<commit_before># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'conditions': [
    ['sysroot!=""', {
      'variables': {
        'pkg-config': './pkg-config-wrapper "<(sysroot)"',
      },
    }, {
      'variables': {
        'pkg-config': 'pkg-config'
      },
    }],
    [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', {
      'variables': {
        # We use our own copy of libssl3, although we still need to link against
        # the rest of NSS.
        'use_system_ssl%': 0,
      },
    }, {  # OS!="linux"
      'variables': {
        'use_system_ssl%': 1,
      },
    }],
  ],

  'targets': [
    {
      'target_name': 'gtk',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gtk+-2.0 gthread-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gtk+-2.0 gthread-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gtk+-2.0 gthread-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gtkprint',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gtk+-unix-print-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gtk+-unix-print-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gtk+-unix-print-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'nss',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'conditions': [
            ['use_system_ssl==0', {
              'dependencies': [
                '../../net/third_party/nss/ssl.gyp:ssl',
                '../../third_party/zlib/zlib.gyp:zlib',
              ],
              'direct_dependent_settings': {
                'cflags': [
                  # We need for our local copies of the libssl3 headers to come
                  # first, otherwise the code will build, but will fallback to
                  # the set of features advertised in the system headers.
                  # Unfortunately, there's no include path that we can filter
                  # out of $(pkg-config --cflags nss) and GYP include paths
                  # come after cflags on the command line. So we have these
                  # bodges:
                  '-I../net/third_party/nss/ssl',               # for scons
                  '-Inet/third_party/nss/ssl',                  # for make
                  '-IWebKit/chromium/net/third_party/nss/ssl',  # for make in webkit
                  '<!@(<(pkg-config) --cflags nss)',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other nss)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l nss | sed -e "s/-lssl3//")',
                ],
              },
            }, {
              'direct_dependent_settings': {
                'cflags': [
                  '<!@(<(pkg-config) --cflags nss)',
                ],
                'defines': [
                  'USE_SYSTEM_SSL',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other nss)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l nss)',
                ],
              },
            }
          ]]
        }],
      ],
    },
    {
      'target_name': 'freetype2',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags freetype2)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other freetype2)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l freetype2)',
            ],
          },
      }]]
    },
    {
      'target_name': 'fontconfig',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags fontconfig)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other fontconfig)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l fontconfig)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gdk',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gdk-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gdk-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gdk-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gconf',
      'type': 'settings',
      'conditions': [
        ['use_gconf==1 and _toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gconf-2.0)',
            ],
            'defines': [
              'USE_GCONF',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gconf-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gconf-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'x11',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags x11)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other x11)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l x11)',
            ],
          },
      }],
      # When XInput2 is available (i.e. inputproto version is 2.0), the
      # pkg-config command will succeed, so the output will be empty.
      ['"<!@(<(pkg-config) --atleast-version=2.0 inputproto || echo $?)"==""', {
        'direct_dependent_settings': {
          'defines': [
            'HAVE_XINPUT2',
          ],
        },
      }],
      ],
    },
    {
      'target_name': 'xext',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags xext)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other xext)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l xext)',
            ],
          },
      }]]
    },
    {
      'target_name': 'selinux',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'link_settings': {
            'libraries': [
              '-lselinux',
            ],
          },
      }]]
    },
    {
      'target_name': 'gnome-keyring',
      'type': 'settings',
      'conditions': [
        ['use_gnome_keyring==1', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gnome-keyring-1)',
            ],
            'defines': [
              'USE_GNOME_KEYRING',
            ],
            'conditions': [
              ['linux_link_gnome_keyring==0', {
                'defines': ['DLOPEN_GNOME_KEYRING'],
              }],
            ],
          },
          'conditions': [
            ['linux_link_gnome_keyring!=0', {
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other gnome-keyring-1)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l gnome-keyring-1)',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  '-ldl',
                ],
              },
            }],
          ],
        }],
      ],
    },
    {
      'target_name': 'dbus-glib',
      'type': 'settings',
      'direct_dependent_settings': {
        'cflags': [
          '<!@(<(pkg-config) --cflags dbus-glib-1)',
        ],
      },
      'link_settings': {
        'ldflags': [
          '<!@(<(pkg-config) --libs-only-L --libs-only-other dbus-glib-1)',
        ],
        'libraries': [
          '<!@(<(pkg-config) --libs-only-l dbus-glib-1)',
        ],
      },
    },
    {
      'target_name': 'libresolv',
      'type': 'settings',
      'link_settings': {
        'libraries': [
          '-lresolv',
        ],
      },
    },
    {
      'target_name': 'openssl',
      'type': 'settings',
      'conditions': [
        ['use_openssl==1', {
          'direct_dependent_settings': {
            'defines': [
              # OpenSSL support is incomplete: http://crbug.com/62803.
              # Defining USE_OPENSSL disables USE_NSS.
              'USE_OPENSSL',
            ],
            'include_dirs': [
              '<!@(<(pkg-config) --cflags openssl)',
            ],
          },
          'link_settings': {
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l openssl)',
            ],
          },
        },],
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<commit_msg>unit_tests: Fix link error (missing libXi) on Linux<commit_after># Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

{
  'conditions': [
    ['sysroot!=""', {
      'variables': {
        'pkg-config': './pkg-config-wrapper "<(sysroot)"',
      },
    }, {
      'variables': {
        'pkg-config': 'pkg-config'
      },
    }],
    [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', {
      'variables': {
        # We use our own copy of libssl3, although we still need to link against
        # the rest of NSS.
        'use_system_ssl%': 0,
      },
    }, {  # OS!="linux"
      'variables': {
        'use_system_ssl%': 1,
      },
    }],
  ],

  'targets': [
    {
      'target_name': 'gtk',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gtk+-2.0 gthread-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gtk+-2.0 gthread-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gtk+-2.0 gthread-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gtkprint',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gtk+-unix-print-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gtk+-unix-print-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gtk+-unix-print-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'nss',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'conditions': [
            ['use_system_ssl==0', {
              'dependencies': [
                '../../net/third_party/nss/ssl.gyp:ssl',
                '../../third_party/zlib/zlib.gyp:zlib',
              ],
              'direct_dependent_settings': {
                'cflags': [
                  # We need for our local copies of the libssl3 headers to come
                  # first, otherwise the code will build, but will fallback to
                  # the set of features advertised in the system headers.
                  # Unfortunately, there's no include path that we can filter
                  # out of $(pkg-config --cflags nss) and GYP include paths
                  # come after cflags on the command line. So we have these
                  # bodges:
                  '-I../net/third_party/nss/ssl',               # for scons
                  '-Inet/third_party/nss/ssl',                  # for make
                  '-IWebKit/chromium/net/third_party/nss/ssl',  # for make in webkit
                  '<!@(<(pkg-config) --cflags nss)',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other nss)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l nss | sed -e "s/-lssl3//")',
                ],
              },
            }, {
              'direct_dependent_settings': {
                'cflags': [
                  '<!@(<(pkg-config) --cflags nss)',
                ],
                'defines': [
                  'USE_SYSTEM_SSL',
                ],
              },
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other nss)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l nss)',
                ],
              },
            }
          ]]
        }],
      ],
    },
    {
      'target_name': 'freetype2',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags freetype2)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other freetype2)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l freetype2)',
            ],
          },
      }]]
    },
    {
      'target_name': 'fontconfig',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags fontconfig)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other fontconfig)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l fontconfig)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gdk',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gdk-2.0)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gdk-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gdk-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'gconf',
      'type': 'settings',
      'conditions': [
        ['use_gconf==1 and _toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gconf-2.0)',
            ],
            'defines': [
              'USE_GCONF',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other gconf-2.0)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l gconf-2.0)',
            ],
          },
      }]]
    },
    {
      'target_name': 'x11',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags x11)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other x11)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l x11)',
            ],
          },
      }],
      # When XInput2 is available (i.e. inputproto version is 2.0), the
      # pkg-config command will succeed, so the output will be empty.
      ['"<!@(<(pkg-config) --atleast-version=2.0 inputproto || echo $?)"==""', {
        'direct_dependent_settings': {
          'defines': [
            'HAVE_XINPUT2',
          ],
        },
        'link_settings': {
          'ldflags': [
            '<!@(<(pkg-config) --libs-only-L --libs-only-other xi)',
          ],
          'libraries': [
            '<!@(<(pkg-config) --libs-only-l xi)',
          ],
        }
      }],
      ],
    },
    {
      'target_name': 'xext',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags xext)',
            ],
          },
          'link_settings': {
            'ldflags': [
              '<!@(<(pkg-config) --libs-only-L --libs-only-other xext)',
            ],
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l xext)',
            ],
          },
      }]]
    },
    {
      'target_name': 'selinux',
      'type': 'settings',
      'conditions': [
        ['_toolset=="target"', {
          'link_settings': {
            'libraries': [
              '-lselinux',
            ],
          },
      }]]
    },
    {
      'target_name': 'gnome-keyring',
      'type': 'settings',
      'conditions': [
        ['use_gnome_keyring==1', {
          'direct_dependent_settings': {
            'cflags': [
              '<!@(<(pkg-config) --cflags gnome-keyring-1)',
            ],
            'defines': [
              'USE_GNOME_KEYRING',
            ],
            'conditions': [
              ['linux_link_gnome_keyring==0', {
                'defines': ['DLOPEN_GNOME_KEYRING'],
              }],
            ],
          },
          'conditions': [
            ['linux_link_gnome_keyring!=0', {
              'link_settings': {
                'ldflags': [
                  '<!@(<(pkg-config) --libs-only-L --libs-only-other gnome-keyring-1)',
                ],
                'libraries': [
                  '<!@(<(pkg-config) --libs-only-l gnome-keyring-1)',
                ],
              },
            }, {
              'link_settings': {
                'libraries': [
                  '-ldl',
                ],
              },
            }],
          ],
        }],
      ],
    },
    {
      'target_name': 'dbus-glib',
      'type': 'settings',
      'direct_dependent_settings': {
        'cflags': [
          '<!@(<(pkg-config) --cflags dbus-glib-1)',
        ],
      },
      'link_settings': {
        'ldflags': [
          '<!@(<(pkg-config) --libs-only-L --libs-only-other dbus-glib-1)',
        ],
        'libraries': [
          '<!@(<(pkg-config) --libs-only-l dbus-glib-1)',
        ],
      },
    },
    {
      'target_name': 'libresolv',
      'type': 'settings',
      'link_settings': {
        'libraries': [
          '-lresolv',
        ],
      },
    },
    {
      'target_name': 'openssl',
      'type': 'settings',
      'conditions': [
        ['use_openssl==1', {
          'direct_dependent_settings': {
            'defines': [
              # OpenSSL support is incomplete: http://crbug.com/62803.
              # Defining USE_OPENSSL disables USE_NSS.
              'USE_OPENSSL',
            ],
            'include_dirs': [
              '<!@(<(pkg-config) --cflags openssl)',
            ],
          },
          'link_settings': {
            'libraries': [
              '<!@(<(pkg-config) --libs-only-l openssl)',
            ],
          },
        },],
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<|endoftext|>


<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
'''
`Originator` testing

.. note::
    these tests assume that the `external` sip profile's context
    has been assigned to the switchy dialplan.
'''
from __future__ import division
import time
import math
from switchy.apps import dtmf, players

def test_rep_fields(get_orig):
    """Test replacement fields within originate commands
    """
    ret = {'field': 'kitty'}
    orig = get_orig('{field}', rep_fields_func=lambda: ret)
    orig.load_app(players.TonePlay)
    orig.duration = 0  # don't auto-hangup
    # check userpart passthrough
    assert 'sofia/external/{field}' in orig.originate_cmd[0]
    assert orig.rep_fields_func() == ret

    # verify invalid field causes failure
    orig.rep_fields_func = lambda: {'invalidname': 'kitty'}
    orig.start()
    time.sleep(0.05)
    # burst loop thread should fail due to missing 'field' kwarg to str.format
    assert orig.stopped()

    # verify field replacement func
    client = orig.pool.clients[0]
    listener = orig.pool.listeners[0]
    # set dest url and call associating xheader to our replaceable field
    ident = "{}@{}:{}".format('doggy', client.host, 5080)
    client.set_orig_cmd('{field}',
                        xheaders={client.call_tracking_header: "{field}"})
    orig.rep_fields_func = lambda: {'field': ident}
    orig.max_offered += 1
    orig.start()
    time.sleep(0.05)
    assert ident in listener.calls  # since we replaced the call id xheader
    listener.calls[ident].hangup()
    time.sleep(0.05)
    assert orig.count_calls() == 0

def test_dtmf_passthrough(get_orig):
    '''Test the dtmf app in coordination with the originator
    '''
    orig = get_orig('doggy', offer=1)
    orig.load_app(dtmf.DtmfChecker)
    orig.duration = 0
    orig.start()
    checker = orig.pool.clients[0].apps.DtmfChecker['DtmfChecker']
    time.sleep(checker.total_time + 1)
    orig.stop()
    assert not any(
        orig.pool.evals("client.apps.DtmfChecker['DtmfChecker'].incomplete"))
    assert not any(
        orig.pool.evals("client.apps.DtmfChecker['DtmfChecker'].failed"))
    assert orig.state == "STOPPED"

def test_convo_sim(get_orig):
    """Test the `PlayRec` app when used for a load test with the `Originator`
    """
    recs = []

    def count(recinfo):
        recs.append(recinfo)

    orig = get_orig('doggy')
    orig.load_app(
        players.PlayRec,
        ppkwargs={
            'rec_stereo': True,
            'callback': count,
        }
    )
    # manual app reference retrieval
    playrec = orig.pool.nodes[0].client.apps.PlayRec['PlayRec']

    # verify dynamic load settings modify playrec settings
    orig.rate = 20
    orig.limit = orig.max_offered = 100
    playrec.rec_period = 2.0
    assert playrec.iterations * playrec.clip_length + playrec.tail == orig.duration

    orig.start()
    # ensure calls are set up fast enough
    start = time.time()
    time.sleep(float(orig.limit / orig.rate) + 1.0)
    stop = time.time()
    assert orig.pool.count_calls() == orig.limit

    # wait for all calls to end
    orig.waitwhile()
    # ensure number of calls recorded matches the rec period
    assert float(len(recs)) == math.floor((stop - start) / playrec.rec_period)
<commit_msg>Add a dialer state control test<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
'''
`Originator` testing

.. note::
    these tests assume that the `external` sip profile's context
    has been assigned to the switchy dialplan.
'''
from __future__ import division
import time
import math
from switchy.apps import dtmf, players

def test_dialer_state(get_orig):
    """Verify dialer state changes based on its API.
    """
    dialer = get_orig('you', offer=float('inf'))
    dialer.load_app(players.TonePlay)
    dialer.duration = 0  # don't auto-hangup

    # ensure intial state interface
    assert dialer.check_state("INITIAL")

    # verify initial internal event states
    assert not dialer._start.is_set()
    assert not dialer._burst.is_set()
    assert not dialer._exit.is_set()

    dialer.start()
    time.sleep(0.3)
    assert not dialer._start.is_set()
    assert not dialer.stopped()
    assert dialer._burst.is_set()
    assert dialer.check_state("ORIGINATING")

    dialer.hupall()
    dialer.waitforstate('STOPPED', timeout=5)
    assert dialer.check_state("STOPPED")
    assert dialer.stopped()
    assert not dialer._start.is_set()
    assert not dialer._burst.is_set()

def test_rep_fields(get_orig):
    """Test replacement fields within originate commands
    """
    ret = {'field': 'kitty'}
    orig = get_orig('{field}', rep_fields_func=lambda: ret)
    orig.load_app(players.TonePlay)
    orig.duration = 0  # don't auto-hangup
    # check userpart passthrough
    assert 'sofia/external/{field}' in orig.originate_cmd[0]
    assert orig.rep_fields_func() == ret

    # verify invalid field causes failure
    orig.rep_fields_func = lambda: {'invalidname': 'kitty'}
    orig.start()
    time.sleep(0.05)
    # burst loop thread should fail due to missing 'field' kwarg to str.format
    assert orig.stopped()

    # verify field replacement func
    client = orig.pool.clients[0]
    listener = orig.pool.listeners[0]
    # set dest url and call associating xheader to our replaceable field
    ident = "{}@{}:{}".format('doggy', client.host, 5080)
    client.set_orig_cmd('{field}',
                        xheaders={client.call_tracking_header: "{field}"})
    orig.rep_fields_func = lambda: {'field': ident}
    orig.max_offered += 1
    orig.start()
    time.sleep(0.05)
    assert ident in listener.calls  # since we replaced the call id xheader
    listener.calls[ident].hangup()
    time.sleep(0.05)
    assert orig.count_calls() == 0

def test_dtmf_passthrough(get_orig):
    '''Test the dtmf app in coordination with the originator
    '''
    orig = get_orig('doggy', offer=1)
    orig.load_app(dtmf.DtmfChecker)
    orig.duration = 0
    orig.start()
    checker = orig.pool.clients[0].apps.DtmfChecker['DtmfChecker']
    time.sleep(checker.total_time + 1)
    orig.stop()
    assert not any(
        orig.pool.evals("client.apps.DtmfChecker['DtmfChecker'].incomplete"))
    assert not any(
        orig.pool.evals("client.apps.DtmfChecker['DtmfChecker'].failed"))
    assert orig.state == "STOPPED"

def test_convo_sim(get_orig):
    """Test the `PlayRec` app when used for a load test with the `Originator`
    """
    recs = []

    def count(recinfo):
        recs.append(recinfo)

    orig = get_orig('doggy')
    orig.load_app(
        players.PlayRec,
        ppkwargs={
            'rec_stereo': True,
            'callback': count,
        }
    )
    # manual app reference retrieval
    playrec = orig.pool.nodes[0].client.apps.PlayRec['PlayRec']

    # verify dynamic load settings modify playrec settings
    orig.rate = 20
    orig.limit = orig.max_offered = 100
    playrec.rec_period = 2.0
    assert playrec.iterations * playrec.clip_length + playrec.tail == orig.duration

    orig.start()
    # ensure calls are set up fast enough
    start = time.time()
    time.sleep(float(orig.limit / orig.rate) + 1.0)
    stop = time.time()
    assert orig.pool.count_calls() == orig.limit

    # wait for all calls to end
    orig.waitwhile()
    # ensure number of calls recorded matches the rec period
    assert float(len(recs)) == math.floor((stop - start) / playrec.rec_period)
<|endoftext|>


<commit_before>localIP = raw_input("Input your local IP address to Philips Hue Bridge: ")
lampName = raw_input("Input name of your selected Philips Hue lamp: ")
apiKey = raw_input("Input your Darksky API key: ")
latitude = raw_input("Input your latitude: ")
longitude = raw_input("Input your longitude: ")

with open("localconfig.py", "w") as f:
    f.write("#!/usr/bin/env python\n")
    f.write("\n")
    f.write("#IP of bridge\n")
    f.write("bridge = '" + localIP + "'\n")
    f.write("\n")
    f.write("#Name of lamp that will change colour\n")
    f.write("selectedLamp = '" + lampName + "'\n")
    f.write("\n")
    f.write("#Dark sky API key\n")
    f.write("API_KEY = '" + apiKey + "'\n")
    f.write("\n")
    f.write("#GPS position for forecast\n")
    f.write("coordinates = ['" + latitude + "', '" + longitude + "']\n")
    f.write("\n")
    f.write("#Set lamp colors [brightness, hue, saturation]\nrainColor = [120, 45000, 254]\ndefaultColor = [254, 10000, 0]")
<commit_msg>Added snowColor when you create localConfig<commit_after>localIP = raw_input("Input your local IP address to Philips Hue Bridge: ")
lampName = raw_input("Input name of your selected Philips Hue lamp: ")
apiKey = raw_input("Input your Darksky API key: ")
latitude = raw_input("Input your latitude: ")
longitude = raw_input("Input your longitude: ")

with open("localconfig.py", "w") as f:
    f.write("#!/usr/bin/env python\n")
    f.write("\n")
    f.write("#IP of bridge\n")
    f.write("bridge = '" + localIP + "'\n")
    f.write("\n")
    f.write("#Name of lamp that will change colour\n")
    f.write("selectedLamp = '" + lampName + "'\n")
    f.write("\n")
    f.write("#Dark sky API key\n")
    f.write("API_KEY = '" + apiKey + "'\n")
    f.write("\n")
    f.write("#GPS position for forecast\n")
    f.write("coordinates = ['" + latitude + "', '" + longitude + "']\n")
    f.write("\n")
    f.write("#Set lamp colors [brightness, hue, saturation]\nrainColor = [120, 45000, 254]\nsnowColor = [120, 25000, 254]\ndefaultColor = [254, 10000, 0]")
<|endoftext|>


<commit_before># The MIT License (MIT)
# Copyright (c) 2016 satojkovic

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os
from PIL import Image
from collections import defaultdict
from itertools import product
from sklearn.cross_validation import train_test_split
import shutil

CNN_IN_WIDTH = 64
CNN_IN_HEIGHT = 32

DATA_AUG_POS_SHIFT_MIN = -2
DATA_AUG_POS_SHIFT_MAX = 2
DATA_AUG_SCALES = [0.9, 1.1]
DATA_AUG_ROT_MIN = -15
DATA_AUG_ROT_MAX = 15

TRAIN_DIR = 'flickr_logos_27_dataset'
TRAIN_IMAGE_DIR = os.path.join(TRAIN_DIR, 'flickr_logos_27_dataset_images')
CROPPED_AUG_IMAGE_DIR = os.path.join(
    TRAIN_DIR, 'flickr_logos_27_dataset_cropped_augmented_images')
ANNOT_FILE = 'flickr_logos_27_dataset_training_set_annotation.txt'

def parse_annot(annot):
    fn = annot[0].decode('utf-8')
    class_name = annot[1].decode('utf-8')
    train_subset_class = annot[2].decode('utf-8')
    return fn, class_name, train_subset_class

def get_rect(annot):
    rect = defaultdict(int)
    x1, y1, x2, y2 = rect_coord(annot[3:])
    cx, cy, wid, hgt = center_wid_hgt(x1, y1, x2, y2)
    rect['x1'] = x1
    rect['y1'] = y1
    rect['x2'] = x2
    rect['y2'] = y2
    rect['cx'] = cx
    rect['cy'] = cy
    rect['wid'] = wid
    rect['hgt'] = hgt
    return rect

def aug_pos(annot, im):
    aug_pos_ims = []
    aug_pos_suffixes = []

    rect = get_rect(annot)
    for sx, sy in product(
            range(DATA_AUG_POS_SHIFT_MIN, DATA_AUG_POS_SHIFT_MAX),
            range(DATA_AUG_POS_SHIFT_MIN, DATA_AUG_POS_SHIFT_MAX)):
        cx = rect['cx'] + sx
        cy = rect['cy'] + sy
        cropped_im = im.crop((cx - rect['wid'] // 2, cy - rect['hgt'] // 2,
                              cx + rect['wid'] // 2, cy + rect['hgt'] // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_pos_ims.append(resized_im)
        aug_pos_suffixes.append('p' + str(sx) + str(sy))
        cropped_im.close()

    return aug_pos_ims, aug_pos_suffixes

def aug_scale(annot, im):
    aug_scale_ims = []
    aug_scale_suffixes = []

    rect = get_rect(annot)
    for s in DATA_AUG_SCALES:
        w = int(rect['wid'] * s)
        h = int(rect['hgt'] * s)
        cropped_im = im.crop((rect['cx'] - w // 2, rect['cy'] - h // 2,
                              rect['cx'] + w // 2, rect['cy'] + h // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_scale_ims.append(resized_im)
        aug_scale_suffixes.append('s' + str(s))
        cropped_im.close()

    return aug_scale_ims, aug_scale_suffixes

def aug_rot(annot, im):
    aug_rot_ims = []
    aug_rot_suffixes = []

    rect = get_rect(annot)
    for r in range(DATA_AUG_ROT_MIN, DATA_AUG_ROT_MAX):
        rotated_im = im.rotate(r)
        cropped_im = rotated_im.crop(
            (rect['cx'] - rect['wid'] // 2, rect['cy'] - rect['hgt'] // 2,
             rect['cx'] + rect['wid'] // 2, rect['cy'] + rect['hgt'] // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_rot_ims.append(resized_im)
        aug_rot_suffixes.append('r' + str(r))
        rotated_im.close()
        cropped_im.close()

    return aug_rot_ims, aug_rot_suffixes

def crop_logos(annot, im):
    x1, y1, x2, y2 = rect_coord(annot[3:])
    cropped_im = im.crop((x1, y1, x2, y2))
    cropped_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
    cropped_suffix = 'p00'
    return [cropped_im], [cropped_suffix]

def rect_coord(annot_part):
    return list(map(int, annot_part))

def center_wid_hgt(x1, y1, x2, y2):
    cx = x1 + (x2 - x1) // 2
    cy = y1 + (y2 - y1) // 2
    wid = (x2 - x1)
    hgt = (y2 - y1)
    return cx, cy, wid, hgt

def is_skip(annot_part):
    x1, y1, x2, y2 = rect_coord(annot_part)
    _, _, wid, hgt = center_wid_hgt(x1, y1, x2, y2)
    if wid <= 0 or hgt <= 0:
        return True
    else:
        return False

def save_im(annot, cnt, *args):
    fn, class_name, train_subset_class = parse_annot(annot)
    dst_dir = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for i, arg in enumerate(args):
        for im, suffix in zip(arg[0], arg[1]):
            save_fn = '_'.join(
                [fn.split('.')[0], class_name, train_subset_class, str(cnt),
                 suffix]) + os.path.splitext(fn)[1]
            im.save(os.path.join(dst_dir, save_fn))

def close_im(*args):
    for ims in args:
        for im in ims:
            im.close()

def crop_and_aug(annot_train):
    if not os.path.exists(CROPPED_AUG_IMAGE_DIR):
        os.makedirs(CROPPED_AUG_IMAGE_DIR)

    cnt_per_file = defaultdict(int)
    for annot in annot_train:
        # for generating a file name
        fn, _, _ = parse_annot(annot)
        cnt_per_file[fn] += 1

        # skip if width or height equal zero
        if is_skip(annot[3:]):
            print('Skip: ', fn)
            continue

        # open an image
        im = Image.open(os.path.join(TRAIN_IMAGE_DIR, fn))

        # normal cropping
        cropped_ims, cropped_suffixes = crop_logos(annot, im)

        # augment by shifting a center
        shifted_ims, shifted_suffixes = aug_pos(annot, im)

        # augment by scaling
        scaled_ims, scaled_suffixes = aug_scale(annot, im)

        # augment by rotation
        rotated_ims, rotated_suffixes = aug_rot(annot, im)

        # save images
        save_im(annot, cnt_per_file[fn], [cropped_ims, cropped_suffixes],
                [shifted_ims, shifted_suffixes], [scaled_ims, scaled_suffixes],
                [rotated_ims, rotated_suffixes])

        # close image file
        close_im([im], cropped_ims, shifted_ims, scaled_ims, rotated_ims)

    # print results
    org_imgs = [img for img in os.listdir(TRAIN_IMAGE_DIR)]
    crop_and_aug_imgs = [img for img in os.listdir(CROPPED_AUG_IMAGE_DIR)]
    print('original: %d' % (len(org_imgs)))
    print('cropped: %d' % (len(crop_and_aug_imgs)))

    return crop_and_aug_imgs

def do_train_test_split():
    class_names = [cls for cls in os.listdir(CROPPED_AUG_IMAGE_DIR)]
    for class_name in class_names:
        imgs = [img
                for img in os.listdir(
                    os.path.join(CROPPED_AUG_IMAGE_DIR, class_name))]
        # train=0.75, test=0.25
        train_imgs, test_imgs = train_test_split(imgs)
        # move to train or test directory
        os.makedirs(os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'train'))
        os.makedirs(os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'test'))
        for img in train_imgs:
            dst = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'train')
            src = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, img)
            shutil.move(src, dst)
        for img in test_imgs:
            dst = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'test')
            src = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, img)
            shutil.move(src, dst)

def main():
    annot_train = np.loadtxt(os.path.join(TRAIN_DIR, ANNOT_FILE), dtype='a')
    print('train_annotation: %d, %d ' % (annot_train.shape))

    # cropping and data augmentation
    crop_and_aug(annot_train)

    # train_test_split
    do_train_test_split()

if __name__ == '__main__':
    main()
<commit_msg>Add a new method<commit_after># The MIT License (MIT)
# Copyright (c) 2016 satojkovic

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os
from PIL import Image
from collections import defaultdict
from itertools import product
from sklearn.cross_validation import train_test_split
import shutil

CNN_IN_WIDTH = 64
CNN_IN_HEIGHT = 32

DATA_AUG_POS_SHIFT_MIN = -2
DATA_AUG_POS_SHIFT_MAX = 2
DATA_AUG_SCALES = [0.9, 1.1]
DATA_AUG_ROT_MIN = -15
DATA_AUG_ROT_MAX = 15

TRAIN_DIR = 'flickr_logos_27_dataset'
TRAIN_IMAGE_DIR = os.path.join(TRAIN_DIR, 'flickr_logos_27_dataset_images')
CROPPED_AUG_IMAGE_DIR = os.path.join(
    TRAIN_DIR, 'flickr_logos_27_dataset_cropped_augmented_images')
ANNOT_FILE = 'flickr_logos_27_dataset_training_set_annotation.txt'

def parse_annot(annot):
    fn = annot[0].decode('utf-8')
    class_name = annot[1].decode('utf-8')
    train_subset_class = annot[2].decode('utf-8')
    return fn, class_name, train_subset_class

def get_rect(annot):
    rect = defaultdict(int)
    x1, y1, x2, y2 = rect_coord(annot[3:])
    cx, cy, wid, hgt = center_wid_hgt(x1, y1, x2, y2)
    rect['x1'] = x1
    rect['y1'] = y1
    rect['x2'] = x2
    rect['y2'] = y2
    rect['cx'] = cx
    rect['cy'] = cy
    rect['wid'] = wid
    rect['hgt'] = hgt
    return rect

def aug_pos(annot, im):
    aug_pos_ims = []
    aug_pos_suffixes = []

    rect = get_rect(annot)
    for sx, sy in product(
            range(DATA_AUG_POS_SHIFT_MIN, DATA_AUG_POS_SHIFT_MAX),
            range(DATA_AUG_POS_SHIFT_MIN, DATA_AUG_POS_SHIFT_MAX)):
        cx = rect['cx'] + sx
        cy = rect['cy'] + sy
        cropped_im = im.crop((cx - rect['wid'] // 2, cy - rect['hgt'] // 2,
                              cx + rect['wid'] // 2, cy + rect['hgt'] // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_pos_ims.append(resized_im)
        aug_pos_suffixes.append('p' + str(sx) + str(sy))
        cropped_im.close()

    return aug_pos_ims, aug_pos_suffixes

def aug_scale(annot, im):
    aug_scale_ims = []
    aug_scale_suffixes = []

    rect = get_rect(annot)
    for s in DATA_AUG_SCALES:
        w = int(rect['wid'] * s)
        h = int(rect['hgt'] * s)
        cropped_im = im.crop((rect['cx'] - w // 2, rect['cy'] - h // 2,
                              rect['cx'] + w // 2, rect['cy'] + h // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_scale_ims.append(resized_im)
        aug_scale_suffixes.append('s' + str(s))
        cropped_im.close()

    return aug_scale_ims, aug_scale_suffixes

def aug_rot(annot, im):
    aug_rot_ims = []
    aug_rot_suffixes = []

    rect = get_rect(annot)
    for r in range(DATA_AUG_ROT_MIN, DATA_AUG_ROT_MAX):
        rotated_im = im.rotate(r)
        cropped_im = rotated_im.crop(
            (rect['cx'] - rect['wid'] // 2, rect['cy'] - rect['hgt'] // 2,
             rect['cx'] + rect['wid'] // 2, rect['cy'] + rect['hgt'] // 2))
        resized_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
        aug_rot_ims.append(resized_im)
        aug_rot_suffixes.append('r' + str(r))
        rotated_im.close()
        cropped_im.close()

    return aug_rot_ims, aug_rot_suffixes

def crop_logos(annot, im):
    x1, y1, x2, y2 = rect_coord(annot[3:])
    cropped_im = im.crop((x1, y1, x2, y2))
    cropped_im = cropped_im.resize((CNN_IN_WIDTH, CNN_IN_HEIGHT))
    cropped_suffix = 'p00'
    return [cropped_im], [cropped_suffix]

def rect_coord(annot_part):
    return list(map(int, annot_part))

def center_wid_hgt(x1, y1, x2, y2):
    cx = x1 + (x2 - x1) // 2
    cy = y1 + (y2 - y1) // 2
    wid = (x2 - x1)
    hgt = (y2 - y1)
    return cx, cy, wid, hgt

def is_skip(annot_part):
    x1, y1, x2, y2 = rect_coord(annot_part)
    _, _, wid, hgt = center_wid_hgt(x1, y1, x2, y2)
    if wid <= 0 or hgt <= 0:
        return True
    else:
        return False

def save_im(annot, cnt, *args):
    fn, class_name, train_subset_class = parse_annot(annot)
    dst_dir = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for i, arg in enumerate(args):
        for im, suffix in zip(arg[0], arg[1]):
            save_fn = '_'.join(
                [fn.split('.')[0], class_name, train_subset_class, str(cnt),
                 suffix]) + os.path.splitext(fn)[1]
            im.save(os.path.join(dst_dir, save_fn))

def close_im(*args):
    for ims in args:
        for im in ims:
            im.close()

def crop_and_aug(annot_train):
    if not os.path.exists(CROPPED_AUG_IMAGE_DIR):
        os.makedirs(CROPPED_AUG_IMAGE_DIR)

    cnt_per_file = defaultdict(int)
    for annot in annot_train:
        # for generating a file name
        fn, _, _ = parse_annot(annot)
        cnt_per_file[fn] += 1

        # skip if width or height equal zero
        if is_skip(annot[3:]):
            print('Skip: ', fn)
            continue

        # open an image
        im = Image.open(os.path.join(TRAIN_IMAGE_DIR, fn))

        # normal cropping
        cropped_ims, cropped_suffixes = crop_logos(annot, im)

        # augment by shifting a center
        shifted_ims, shifted_suffixes = aug_pos(annot, im)

        # augment by scaling
        scaled_ims, scaled_suffixes = aug_scale(annot, im)

        # augment by rotation
        rotated_ims, rotated_suffixes = aug_rot(annot, im)

        # save images
        save_im(annot, cnt_per_file[fn], [cropped_ims, cropped_suffixes],
                [shifted_ims, shifted_suffixes], [scaled_ims, scaled_suffixes],
                [rotated_ims, rotated_suffixes])

        # close image file
        close_im([im], cropped_ims, shifted_ims, scaled_ims, rotated_ims)

    # print results
    org_imgs = [img for img in os.listdir(TRAIN_IMAGE_DIR)]
    crop_and_aug_imgs = [img for img in os.listdir(CROPPED_AUG_IMAGE_DIR)]
    print('original: %d' % (len(org_imgs)))
    print('cropped: %d' % (len(crop_and_aug_imgs)))

    return crop_and_aug_imgs

def crop_and_aug_with_none(annot_train, annot_query):
    pass

def do_train_test_split():
    class_names = [cls for cls in os.listdir(CROPPED_AUG_IMAGE_DIR)]
    for class_name in class_names:
        imgs = [img
                for img in os.listdir(
                    os.path.join(CROPPED_AUG_IMAGE_DIR, class_name))]
        # train=0.75, test=0.25
        train_imgs, test_imgs = train_test_split(imgs)
        # move to train or test directory
        os.makedirs(os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'train'))
        os.makedirs(os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'test'))
        for img in train_imgs:
            dst = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'train')
            src = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, img)
            shutil.move(src, dst)
        for img in test_imgs:
            dst = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, 'test')
            src = os.path.join(CROPPED_AUG_IMAGE_DIR, class_name, img)
            shutil.move(src, dst)

def main():
    annot_train = np.loadtxt(os.path.join(TRAIN_DIR, ANNOT_FILE), dtype='a')
    print('train_annotation: %d, %d ' % (annot_train.shape))

    # cropping and data augmentation
    crop_and_aug(annot_train)

    # train_test_split
    do_train_test_split()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>"""
cryptography.py
Author: Nils Kingston
Credit: Roger

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
from operator import add
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
a = ""
while a != "q":
    a = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if a == "e":
        encripting = input("What do you want to encript? ")
        jumbler = input("What should the key be? ")
        e_list = []
        for x in encripting:
            e_list.append(associations.find(x))
        j_list = []
        for x in jumbler:
            j_list.append(associations.find(x))
        newlist = []
        for x in range(2):
            newlist.append(e_list[x] + j_list[x])
        print(newlist)

    elif a == "d":
        jumbled_code = input("Message?")
        key = input("Key?")
        list(jumbled_code)
        list(key)
        message = [x1 - x2 for (x1, x2) in zip(jumbled_code, key)]

    elif a == "q":
        print("Goodbye!")
    else:
        print("Did not understand try again")

<commit_msg>Updated from Brython Server: 10/8/2015 2:47:54 PM<commit_after>"""
cryptography.py
Author: Nils Kingston
Credit: Roger

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
from operator import add
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
a = ""
while a != "q":
    a = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if a == "e":
        encripting = input("What do you want to encript? ")
        jumbler = input("What should the key be? ")
        e_list = []
        for x in encripting:
            e_list.append(associations.find(x))
        j_list = []
        for x in jumbler:
            j_list.append(associations.find(x))
        newlist = []
        length = len(e_list)
        for x in range(length):
            newlist.append(e_list[x] + j_list[x])
        print(newlist)

    elif a == "d":
        jumbled_code = input("Message?")
        key = input("Key?")
        list(jumbled_code)
        list(key)
        message = [x1 - x2 for (x1, x2) in zip(jumbled_code, key)]

    elif a == "q":
        print("Goodbye!")
    else:
        print("Did not understand try again")

<|endoftext|>


<commit_before>"""
cryptography.py
Author: <your name here>
Credit: <list sources used, if any>

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
no = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if no == ("q"):
    print ("Goodbye!")
elif no not in ("e", "d", "q"):
     input("Did not understand command, try again:")<commit_msg>Updated from Brython Server: 11/21/2016 1:22:34 PM<commit_after>"""
cryptography.py
Author: kezar
Credit: kotz

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
no = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if no == ("q"):
    print ("Goodbye!")
elif no not in ("e", "d", "q"):
     input("Did not understand command, try again:")<|endoftext|>


<commit_before>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]

i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i not in('e','d','q'):
    print("Did not understand command, try again.")
    i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i=="e":
    message=input("Message: ")
    key=str(input("Key: "))
    m=len(message)
    k=len(key)
    for x in (0,m):
        let.append(associations.find(message[x]))
    for y in range (0,k):
        kelt.append(associations.find(message[y]))
    q=l-k
    kelt.append(associations.find(message[-q]))
    print(kelt)
if i=="d":
    print(let)
if i=="q":
    print("Goodbye!")<commit_msg>Updated from Brython Server: 3/3/2016 2:47:47 PM<commit_after>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]

i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i not in('e','d','q'):
    print("Did not understand command, try again.")
    i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i=="e":
    message=input("Message: ")
    key=str(input("Key: "))
    m=len(message)
    k=len(key)
    for x in (0,m):
        let.append(associations.find(message[x]))
    for y in range (0,k):
        kelt.append(associations.find(message[y]))
    q=l-k
    kelt.append(associations.find(message[1]))
    print(kelt)
if i=="d":
    print(let)
if i=="q":
    print("Goodbye!")<|endoftext|>


<commit_before>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]

i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i not in('e','d','q'):
    print("Did not understand command, try again.")
if i=="e":
    message=input("Message: ")
    key=str(input("Key: "))
    m=len(message)
    k=len(key)
    for x in (0,m):
        let.append(associations.find(message[x]))
    for y in range (0,k):
        kelt.append(associations.find(message[y]))
    q=l-k
    kelt.append(associations.find(message[-q]))
    print(message)
if i=="d":
    print(let)
if i=="q":
    print("Goodbye!")<commit_msg>Updated from Brython Server: 3/3/2016 2:46:08 PM<commit_after>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]

i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i not in('e','d','q'):
    print("Did not understand command, try again.")
    i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
if i=="e":
    message=input("Message: ")
    key=str(input("Key: "))
    m=len(message)
    k=len(key)
    for x in (0,m):
        let.append(associations.find(message[x]))
    for y in range (0,k):
        kelt.append(associations.find(message[y]))
    q=l-k
    kelt.append(associations.find(message[-q]))
    print(message)
if i=="d":
    print(let)
if i=="q":
    print("Goodbye!")<|endoftext|>


<commit_before>import os
import sys
from SCons.Script.SConscript import SConsEnvironment

def CheckPKGConfig(context, version):
	context.Message( 'Checking for pkg-config... ' )
	ret = context.TryAction('pkg-config --atleast-pkgconfig-version=%s' % version)[0]
	context.Result( ret )
	return ret

def CheckPKG(context, name):
	context.Message( 'Checking for %s... ' % name )
	ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0]
	context.Result( ret )
	return ret

def SelectBuildDir(build_dir, platform=None):

	# if no platform is specified, then default to sys.platform
	if not(platform):
		platform = sys.platform

	print "Looking for build directory for platform '%s'" % platform

	# setup where we start looking at first
	test_dir = build_dir + os.sep + platform
	default_dir = build_dir + os.sep + 'linux'

	# we look for a directory named exactly after the
	# platform so that very specific builds can be done
	if os.path.exists(test_dir):
		# make sure it is a directory
		target_dir = test_dir
	else:
		print "Exact match not found, finding closest guess"

		# looks like there isn't an exact match
		# find the closest matching directory
		dirs = os.listdir(build_dir)
		found_match = 0
		for dir in dirs:
			if platform.find(dir) != -1:
				# found a match (hopefully the right one)
				target_dir = build_dir + os.sep + dir
				found_match = 1
				break
		if not(found_match):
			print "No match found, looking for 'default' directory"
			# looks like this platform isn't available
			# try the default target
			if os.path.exists(default_dir):
				target_dir = default_dir
			else:
				# bad, nothing is available, tell the user
				print "No build directories found for your platform '%s'" % platform
			return None

	print "Found directory %s, will build there" % target_dir
	return target_dir

def dist(env, appname=None, version=None):
	"dist target - should be portable"
	import shutil, tarfile
	if not appname: appname=config["name"]
	if not version: version=config["version"]

	# Our temporary folder where to put our files
	TMPFOLDER=appname+'-'+str(version)

	# Remove an old package directory
	if os.path.exists(TMPFOLDER): shutil.rmtree(TMPFOLDER)

	# Copy everything into the new folder
	shutil.copytree('.', TMPFOLDER)

	# Enter into it and remove unnecessary files
	os.chdir(TMPFOLDER)
	#clean up build in tmpdir
	os.popen('scons -Q -c').read()
	for (root, dirs, filenames) in os.walk('.'):
		clean_dirs = []
		for d in dirs:
			if d in ['CVS', 'cache','.svn', '{arch}']:
				shutil.rmtree(os.path.join(root,d))
			elif d.startswith('.'):
				shutil.rmtree(os.path.join(root,d))
			else:
				clean_dirs += d
		dirs = clean_dirs

		to_remove = False
		for f in list(filenames):
			if f.startswith('.'): to_remove = True
			elif f.endswith('~'): to_remove = True
			elif f.endswith('.pyc'): to_remove = True
			elif f.endswith('.pyo'): to_remove = True
			elif f.endswith('.bak'): to_remove = True
			elif f.endswith('.orig'): to_remove = True
			elif f in ['config.log']: to_remove = True
			elif f.endswith('.tar.bz2'): to_remove = True
			elif f.endswith('.zip'): to_remove = True
			elif f.endswith('Makefile'): to_remove = True

			if to_remove:
				os.remove(os.path.join(root, f))
				to_remove = False

	# go back to the root directory
	os.chdir('..')

	tar = tarfile.open(TMPFOLDER+'.tar.bz2','w:bz2')
	tar.add(TMPFOLDER)
	tar.close()
	print 'Your archive is ready -> '+TMPFOLDER+'.tar.bz2'

	if os.path.exists(TMPFOLDER): shutil.rmtree(TMPFOLDER)

	sys.exit(0)

def add_define(env, define, value = 1, quote = -1):
	"""store a single define and its state into an internal list
		for later writing to a config header file"""
	try:
		tbl = env['defines']
	except KeyError:
		tbl = {}
	if not define: raise "define must be .. defined"

	value = env.subst(value) #substitute construction values
	# the user forgot to tell if the value is quoted or not
	if quote < 0:
		if isinstance(value, basestring):
			tbl[define] = '"%s"' % str(value)
		else:
			tbl[define] = value
	elif not quote:
		if isinstance(value, int):
			tbl[define] = int(value)
		else:
			tbl[define] = value
	else:
		tbl[define] = '"%s"' % str(value)
	env['defines'] = tbl

def is_defined(env, define):
	try: return env['defines'].has_key(define)
	except: return None

def get_define(env, define):
	"get the value of a previously stored define"
	try: return env['defines'][define]
	except: return 0

def write_config_header(env, configfile='config.h'):
	"save the defines into a file"
	import re, os
	reg=re.compile('[/\\\\.-]', re.M)

	include_name = '_'.join(reg.split(configfile)).upper()
	inclusion_guard_name = '_%s_OPENSYNC' % (include_name)

	dest = open(configfile, 'w')
	dest.write('/* configuration created by OpenSync build */\n')
	dest.write('#ifndef %s\n#define %s\n\n' % (inclusion_guard_name, inclusion_guard_name))
	try:
		for key, value in env['defines'].iteritems():
			if value is None:
				dest.write('#define %s\n' % key)
			elif isinstance(value, int):
				dest.write('#define %s %i\n' % (key, value))
			elif value:
				dest.write('#define %s %s\n' % (key, value))
			else:
				dest.write('/* #undef %s */\n' % key)
	except KeyError:
		pass
	dest.write('\n#endif /* %s */\n' % (inclusion_guard_name,))
	dest.close()

class opts:
	def __init__(self, env, option_file="config_cache.py", cache_dir="cache"):
		from SCons.Options import Options
		self.env=env
		self.args=self.__makeHashTable(sys.argv)
		self.option_file=os.path.join(cache_dir, option_file)
		self.env['CACHEDIR']=cache_dir
		if not os.path.isdir(env['CACHEDIR']): os.mkdir(env['CACHEDIR'])
		self.opts=Options(self.option_file)

	#TODO: this parser is silly, fix scons command-line handling instead
	def __makeHashTable(self, args):
		table = { }
		for arg in args:
			if len(arg) > 1:
				lst=arg.split('=')
				if len(lst) < 2: continue
				key=lst[0]
				value=lst[1]
				if len(key) > 0 and len(value) >0: table[key] = value
		return table

	def update(self):
		self.opts.Update(self.env, self.args)

	def save(self):
		self.opts.Save(self.option_file, self.env)

	def add(self, key, help="", default=None, validator=None, converter=None, **kw):
		self.opts.Add(key, help, default, validator, converter, **kw)

	def add_options(self, *optlist):
		self.opts.AddOptions(*optlist)

	def generate_help_text(self):
		return self.opts.GenerateHelpText(self.env)

#wrapper methode to initalise and access opts_class object
def get_opts(env, option_file="config_cache.py", cache_dir="cache"):
	if not env.has_key('OPTIONS'):
		env['OPTIONS'] = env.opts_class(env, option_file, cache_dir)
	return env['OPTIONS']

# Since SCons doesn't support versioning, we need to do it for SCons.
# Unfortunately, that means having to do things differently depending
# on platform...
def build_shlib(env, target_name, sources, vnum=None, **kw):
	import SCons.Util
	import re
	platform = env.subst('$PLATFORM')
	shlib_pre_action = None
	shlib_suffix = env.subst('$SHLIBSUFFIX')
	shlib_post_action = None
	shlink_flags = SCons.Util.CLVar(env.subst('$SHLINKFLAGS'))

	if platform == 'posix':
		shlib_post_action = [ 'rm -f $TARGET', 'ln -s ${SOURCE.file} $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*$' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_suffix += '.' + vnum
		shlink_flags += [ '-Wl,-Bsymbolic', '-Wl,-soname=${TARGET.file}' ]
	elif platform == 'aix':
		shlib_pre_action = [
			"nm -Pg $SOURCES > ${TARGET}.tmp1",
			"grep ' [BDT] ' < ${TARGET}.tmp1 > ${TARGET}.tmp2",
			"cut -f1 -d' ' < ${TARGET}.tmp2 > ${TARGET}",
			"rm -f ${TARGET}.tmp[12]" ]
		shlib_pre_action_output_re = [ '$', '.exp' ]
		shlib_post_action = [ 'rm -f $TARGET', 'ln -s $SOURCE $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_suffix += '.' + vnum
		shlink_flags += ['-G', '-bE:${TARGET}.exp', '-bM:SRE']
	elif platform == 'cygwin':
		shlink_flags += [ '-Wl,-Bsymbolic',
				'-Wl,--out-implib,${TARGET.base}.a' ]
	elif platform == 'darwin':
		shlib_suffix = '.' + vnum + shlib_suffix
		shlink_flags += [ '-dynamiclib',
				'-current-version %s' % vnum ]

	lib = env.SharedLibrary(target_name, sources,
				SHLIBSUFFIX=shlib_suffix,
				SHLINKFLAGS=shlink_flags, **kw)

	if shlib_pre_action:
		shlib_pre_action_output = re.sub(shlib_pre_action_output_re[0],
						shlib_pre_action_output_re[1],
						str(lib[0]))
		env.Command(shlib_pre_action_output, [ lib_objs ],
				shlib_pre_action)
		env.Depends(lib, shlib_pre_action_output)
	if shlib_post_action:
		shlib_post_action_output = re.sub(shlib_post_action_output_re[0],
						shlib_post_action_output_re[1],
						str(lib[0]))
		env.Command(shlib_post_action_output, lib, shlib_post_action)
	return lib

def install_shlib(env, destination, lib):
	import re
	platform = env.subst('$PLATFORM')
	shlib_suffix = env.subst('$SHLIBSUFFIX')
	shlib_install_pre_action = None
	shlib_install_post_action = None

	if platform == 'posix':
		shlib_post_action = [ 'rm -f $TARGET',
					'ln -s ${SOURCE.file} $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*$' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_install_post_action = shlib_post_action
		shlib_install_post_action_output_re = shlib_post_action_output_re

	ilib = env.Install(destination,lib)

	if shlib_install_pre_action:
		shlib_install_pre_action_output = re.sub(shlib_install_pre_action_output_re[0],
							shlib_install_pre_action_output_re[1],
							str(ilib[0]))
		env.Command(shlib_install_pre_action_output, ilib,
				shlib_install_pre_action)
		env.Depends(shlib_install_pre_action_output, ilib)
	if shlib_install_post_action:
		shlib_install_post_action_output = re.sub(shlib_install_post_action_output_re[0],
							shlib_install_post_action_output_re[1],
							str(ilib[0]))
		env.Command(shlib_install_post_action_output, ilib,
				shlib_install_post_action)

def exists(env):
	return true

def generate(env):
	SConsEnvironment.dist = dist
	SConsEnvironment.write_config_header = write_config_header
	SConsEnvironment.add_define = add_define
	SConsEnvironment.is_defined = is_defined
	SConsEnvironment.get_define = get_define
	SConsEnvironment.opts_class = opts
	SConsEnvironment.get_opts = get_opts
	SConsEnvironment.build_shlib = build_shlib
	SConsEnvironment.install_shlib = install_shlib

	env.get_opts()
<commit_msg>fix issue when a "=" is in arg:<commit_after>import os
import sys
from SCons.Script.SConscript import SConsEnvironment

def CheckPKGConfig(context, version):
	context.Message( 'Checking for pkg-config... ' )
	ret = context.TryAction('pkg-config --atleast-pkgconfig-version=%s' % version)[0]
	context.Result( ret )
	return ret

def CheckPKG(context, name):
	context.Message( 'Checking for %s... ' % name )
	ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0]
	context.Result( ret )
	return ret

def SelectBuildDir(build_dir, platform=None):

	# if no platform is specified, then default to sys.platform
	if not(platform):
		platform = sys.platform

	print "Looking for build directory for platform '%s'" % platform

	# setup where we start looking at first
	test_dir = build_dir + os.sep + platform
	default_dir = build_dir + os.sep + 'linux'

	# we look for a directory named exactly after the
	# platform so that very specific builds can be done
	if os.path.exists(test_dir):
		# make sure it is a directory
		target_dir = test_dir
	else:
		print "Exact match not found, finding closest guess"

		# looks like there isn't an exact match
		# find the closest matching directory
		dirs = os.listdir(build_dir)
		found_match = 0
		for dir in dirs:
			if platform.find(dir) != -1:
				# found a match (hopefully the right one)
				target_dir = build_dir + os.sep + dir
				found_match = 1
				break
		if not(found_match):
			print "No match found, looking for 'default' directory"
			# looks like this platform isn't available
			# try the default target
			if os.path.exists(default_dir):
				target_dir = default_dir
			else:
				# bad, nothing is available, tell the user
				print "No build directories found for your platform '%s'" % platform
			return None

	print "Found directory %s, will build there" % target_dir
	return target_dir

def dist(env, appname=None, version=None):
	"dist target - should be portable"
	import shutil, tarfile
	if not appname: appname=config["name"]
	if not version: version=config["version"]

	# Our temporary folder where to put our files
	TMPFOLDER=appname+'-'+str(version)

	# Remove an old package directory
	if os.path.exists(TMPFOLDER): shutil.rmtree(TMPFOLDER)

	# Copy everything into the new folder
	shutil.copytree('.', TMPFOLDER)

	# Enter into it and remove unnecessary files
	os.chdir(TMPFOLDER)
	#clean up build in tmpdir
	os.popen('scons -Q -c').read()
	for (root, dirs, filenames) in os.walk('.'):
		clean_dirs = []
		for d in dirs:
			if d in ['CVS', 'cache','.svn', '{arch}']:
				shutil.rmtree(os.path.join(root,d))
			elif d.startswith('.'):
				shutil.rmtree(os.path.join(root,d))
			else:
				clean_dirs += d
		dirs = clean_dirs

		to_remove = False
		for f in list(filenames):
			if f.startswith('.'): to_remove = True
			elif f.endswith('~'): to_remove = True
			elif f.endswith('.pyc'): to_remove = True
			elif f.endswith('.pyo'): to_remove = True
			elif f.endswith('.bak'): to_remove = True
			elif f.endswith('.orig'): to_remove = True
			elif f in ['config.log']: to_remove = True
			elif f.endswith('.tar.bz2'): to_remove = True
			elif f.endswith('.zip'): to_remove = True
			elif f.endswith('Makefile'): to_remove = True

			if to_remove:
				os.remove(os.path.join(root, f))
				to_remove = False

	# go back to the root directory
	os.chdir('..')

	tar = tarfile.open(TMPFOLDER+'.tar.bz2','w:bz2')
	tar.add(TMPFOLDER)
	tar.close()
	print 'Your archive is ready -> '+TMPFOLDER+'.tar.bz2'

	if os.path.exists(TMPFOLDER): shutil.rmtree(TMPFOLDER)

	sys.exit(0)

def add_define(env, define, value = 1, quote = -1):
	"""store a single define and its state into an internal list
		for later writing to a config header file"""
	try:
		tbl = env['defines']
	except KeyError:
		tbl = {}
	if not define: raise "define must be .. defined"

	value = env.subst(value) #substitute construction values
	# the user forgot to tell if the value is quoted or not
	if quote < 0:
		if isinstance(value, basestring):
			tbl[define] = '"%s"' % str(value)
		else:
			tbl[define] = value
	elif not quote:
		if isinstance(value, int):
			tbl[define] = int(value)
		else:
			tbl[define] = value
	else:
		tbl[define] = '"%s"' % str(value)
	env['defines'] = tbl

def is_defined(env, define):
	try: return env['defines'].has_key(define)
	except: return None

def get_define(env, define):
	"get the value of a previously stored define"
	try: return env['defines'][define]
	except: return 0

def write_config_header(env, configfile='config.h'):
	"save the defines into a file"
	import re, os
	reg=re.compile('[/\\\\.-]', re.M)

	include_name = '_'.join(reg.split(configfile)).upper()
	inclusion_guard_name = '_%s_OPENSYNC' % (include_name)

	dest = open(configfile, 'w')
	dest.write('/* configuration created by OpenSync build */\n')
	dest.write('#ifndef %s\n#define %s\n\n' % (inclusion_guard_name, inclusion_guard_name))
	try:
		for key, value in env['defines'].iteritems():
			if value is None:
				dest.write('#define %s\n' % key)
			elif isinstance(value, int):
				dest.write('#define %s %i\n' % (key, value))
			elif value:
				dest.write('#define %s %s\n' % (key, value))
			else:
				dest.write('/* #undef %s */\n' % key)
	except KeyError:
		pass
	dest.write('\n#endif /* %s */\n' % (inclusion_guard_name,))
	dest.close()

class opts:
	def __init__(self, env, option_file="config_cache.py", cache_dir="cache"):
		from SCons.Options import Options
		self.env=env
		self.args=self.__makeHashTable(sys.argv)
		self.option_file=os.path.join(cache_dir, option_file)
		self.env['CACHEDIR']=cache_dir
		if not os.path.isdir(env['CACHEDIR']): os.mkdir(env['CACHEDIR'])
		self.opts=Options(self.option_file)

	#TODO: this parser is silly, fix scons command-line handling instead
	def __makeHashTable(self, args):
		table = { }
		for arg in args:
			if len(arg) > 1:
				lst=arg.split('=', 1)
				if len(lst) < 2: continue
				key=lst[0]
				value=lst[1]
				if len(key) > 0 and len(value) >0: table[key] = value
		return table

	def update(self):
		self.opts.Update(self.env, self.args)

	def save(self):
		self.opts.Save(self.option_file, self.env)

	def add(self, key, help="", default=None, validator=None, converter=None, **kw):
		self.opts.Add(key, help, default, validator, converter, **kw)

	def add_options(self, *optlist):
		self.opts.AddOptions(*optlist)

	def generate_help_text(self):
		return self.opts.GenerateHelpText(self.env)

#wrapper methode to initalise and access opts_class object
def get_opts(env, option_file="config_cache.py", cache_dir="cache"):
	if not env.has_key('OPTIONS'):
		env['OPTIONS'] = env.opts_class(env, option_file, cache_dir)
	return env['OPTIONS']

# Since SCons doesn't support versioning, we need to do it for SCons.
# Unfortunately, that means having to do things differently depending
# on platform...
def build_shlib(env, target_name, sources, vnum=None, **kw):
	import SCons.Util
	import re
	platform = env.subst('$PLATFORM')
	shlib_pre_action = None
	shlib_suffix = env.subst('$SHLIBSUFFIX')
	shlib_post_action = None
	shlink_flags = SCons.Util.CLVar(env.subst('$SHLINKFLAGS'))

	if platform == 'posix':
		shlib_post_action = [ 'rm -f $TARGET', 'ln -s ${SOURCE.file} $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*$' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_suffix += '.' + vnum
		shlink_flags += [ '-Wl,-Bsymbolic', '-Wl,-soname=${TARGET.file}' ]
	elif platform == 'aix':
		shlib_pre_action = [
			"nm -Pg $SOURCES > ${TARGET}.tmp1",
			"grep ' [BDT] ' < ${TARGET}.tmp1 > ${TARGET}.tmp2",
			"cut -f1 -d' ' < ${TARGET}.tmp2 > ${TARGET}",
			"rm -f ${TARGET}.tmp[12]" ]
		shlib_pre_action_output_re = [ '$', '.exp' ]
		shlib_post_action = [ 'rm -f $TARGET', 'ln -s $SOURCE $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_suffix += '.' + vnum
		shlink_flags += ['-G', '-bE:${TARGET}.exp', '-bM:SRE']
	elif platform == 'cygwin':
		shlink_flags += [ '-Wl,-Bsymbolic',
				'-Wl,--out-implib,${TARGET.base}.a' ]
	elif platform == 'darwin':
		shlib_suffix = '.' + vnum + shlib_suffix
		shlink_flags += [ '-dynamiclib',
				'-current-version %s' % vnum ]

	lib = env.SharedLibrary(target_name, sources,
				SHLIBSUFFIX=shlib_suffix,
				SHLINKFLAGS=shlink_flags, **kw)

	if shlib_pre_action:
		shlib_pre_action_output = re.sub(shlib_pre_action_output_re[0],
						shlib_pre_action_output_re[1],
						str(lib[0]))
		env.Command(shlib_pre_action_output, [ lib_objs ],
				shlib_pre_action)
		env.Depends(lib, shlib_pre_action_output)
	if shlib_post_action:
		shlib_post_action_output = re.sub(shlib_post_action_output_re[0],
						shlib_post_action_output_re[1],
						str(lib[0]))
		env.Command(shlib_post_action_output, lib, shlib_post_action)
	return lib

def install_shlib(env, destination, lib):
	import re
	platform = env.subst('$PLATFORM')
	shlib_suffix = env.subst('$SHLIBSUFFIX')
	shlib_install_pre_action = None
	shlib_install_post_action = None

	if platform == 'posix':
		shlib_post_action = [ 'rm -f $TARGET',
					'ln -s ${SOURCE.file} $TARGET' ]
		shlib_post_action_output_re = [
			'%s\\.[0-9\\.]*$' % re.escape(shlib_suffix),
			shlib_suffix ]
		shlib_install_post_action = shlib_post_action
		shlib_install_post_action_output_re = shlib_post_action_output_re

	ilib = env.Install(destination,lib)

	if shlib_install_pre_action:
		shlib_install_pre_action_output = re.sub(shlib_install_pre_action_output_re[0],
							shlib_install_pre_action_output_re[1],
							str(ilib[0]))
		env.Command(shlib_install_pre_action_output, ilib,
				shlib_install_pre_action)
		env.Depends(shlib_install_pre_action_output, ilib)
	if shlib_install_post_action:
		shlib_install_post_action_output = re.sub(shlib_install_post_action_output_re[0],
							shlib_install_post_action_output_re[1],
							str(ilib[0]))
		env.Command(shlib_install_post_action_output, ilib,
				shlib_install_post_action)

def exists(env):
	return true

def generate(env):
	SConsEnvironment.dist = dist
	SConsEnvironment.write_config_header = write_config_header
	SConsEnvironment.add_define = add_define
	SConsEnvironment.is_defined = is_defined
	SConsEnvironment.get_define = get_define
	SConsEnvironment.opts_class = opts
	SConsEnvironment.get_opts = get_opts
	SConsEnvironment.build_shlib = build_shlib
	SConsEnvironment.install_shlib = install_shlib

	env.get_opts()
<|endoftext|>


<commit_before>import logging, urllib2
import lighter.util as util

class Datadog(object):
    def __init__(self, token):
        self._token = token
        self._url = 'https://app.datadoghq.com'
        self._message_attribs = {
            'aggregation_key': 'Lighter Deployment',
            'source_type_name': 'lighter'
        }

    def notify(self, title, message, tags=[], priority='normal', alert_type='info'):
        if not title or not message:
            logging.warn('Datadog title and message required')
            return

        logging.debug("Sending Datadog event: %s", message)
        self._call('/api/v1/events', util.merge(self._message_attribs, {
            'title': title,
            'message': message,
            'tags':tags,
            'priority': priority,
            'alert_type': alert_type
        }))

    def _call(self, endpoint, data):
        if not self._url or not self._token:
            logging.debug('Datadog is not enabled')
            return

        try:
            url = self._url.rstrip('/') + endpoint + '?api_key=' + self._token
            logging.debug('Calling Datadog endpoint %s', endpoint)
            util.jsonRequest(url, data=data, method='POST')
        except urllib2.URLError, e:
            logging.warn(str(e))
            return {}
<commit_msg>Fixed naming in Datadog event<commit_after>import logging, urllib2
import lighter.util as util

class Datadog(object):
    def __init__(self, token):
        self._token = token
        self._url = 'https://app.datadoghq.com'
        self._message_attribs = {
            'aggregation_key': 'Lighter Deployment',
            'source_type_name': 'lighter'
        }

    def notify(self, title, message, tags=[], priority='normal', alert_type='info'):
        if not title or not message:
            logging.warn('Datadog title and message required')
            return

        logging.debug("Sending Datadog event: %s", message)
        self._call('/api/v1/events', util.merge(self._message_attribs, {
            'title': title,
            'text': message,
            'tags':tags,
            'priority': priority,
            'alert_type': alert_type
        }))

    def _call(self, endpoint, data):
        if not self._url or not self._token:
            logging.debug('Datadog is not enabled')
            return

        try:
            url = self._url.rstrip('/') + endpoint + '?api_key=' + self._token
            logging.debug('Calling Datadog endpoint %s', endpoint)
            util.jsonRequest(url, data=data, method='POST')
        except urllib2.URLError, e:
            logging.warn(str(e))
            return {}
<|endoftext|>