content stringlengths 4 20k |
|---|
# coding=utf-8
"""
Celery configuration file
"""
import os
__author__ = 'Rizky Maulana Nugraha <<EMAIL>>'
__date__ = '12/30/15'
# This is a default value
BROKER_URL = os.environ.get('INASAFE_REALTIME_BROKER_HOST')
CELERY_RESULT_BACKEND = BROKER_URL
CELERY_ROUTES = {
'realtime.tasks.flood': {
'queue': '... |
"""Model for workflow states."""
__all__ = [
'WorkflowState',
'WorkflowStateManager',
]
from mailman.database.model import Model
from mailman.database.transaction import dbconnection
from mailman.interfaces.workflow import IWorkflowState, IWorkflowStateManager
from sqlalchemy import Column, Unicode
from ... |
import sys, os
import MySQLdb
from tcga_utils.mysql import *
#########################################
def main():
db = connect_to_mysql()
cursor = db.cursor()
db_name = 'COAD'
table = 'somatic_mutations'
db_names = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD","ESCA", "FPPP", "G... |
from tempfile import NamedTemporaryFile
from typing import IO
import pytest
from flask import g
from abilian.core.models.subjects import User
from abilian.core.sqlalchemy import SQLAlchemy
from abilian.sbe.apps.communities.models import READER, Community
from abilian.sbe.apps.communities.views.wizard import (
wiz... |
# Dice bitch
# V1.7
# Now stdout output
# V1.5
# Added fudge dice
# fattredd
import random
# A single roll. Given as a string '2d6'
def roll(s):
dice = s.split('d')
if not len(dice) == 2:
return []
if dice[0] == '':
dice[0] = 1
out = []
if dice[1] == 'f':
for i in range(int(dice[0])):
r... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from translate.storage import po
from django.utils import simplejson
import sys, os, re, urllib
from htmlentitydefs import name2codepoint
def htmldecode(text):
"""Decode HTML entities in the given text."""
if type(text) is unicode:
uchr = u... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import re
from django.apps import AppConfig
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from utilities.configurations import Config
from jinja2 import FileSystemLoader, Environment
impor... |
from enigma import eCableScan, eDVBFrontendParametersCable
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Plugins.Plugin import PluginDescriptor
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.NimManager import nimmanager
from Components.c... |
from pecan import hooks
class UserFilterHook(hooks.PecanHook):
# we do this at the very end to ensure user-defined filters
# don't impact things like pagination and notification hooks
priority = 90
def after(self, state):
user_fields = state.request.params.getall('fields')
if not use... |
"""Script for testing qa.qa_config"""
import unittest
from qa import qa_config
import testutils
class TestTestEnabled(unittest.TestCase):
def testSimple(self):
for name in ["test", ["foobar"], ["a", "b"]]:
self.assertTrue(qa_config.TestEnabled(name, _cfg={}))
for default in [False, True]:
se... |
# -*- coding: utf-8 -*-
"""
Implementation of http://elementalselenium.com/tips/25-tables
"""
import unittest
from selenium import webdriver
class Tables(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def tearDown(self):
self.driver.quit()
def test_sort_number_c... |
# coding=utf-8
"""
An example collector that verifies the answer to life, the universe, and
everything does not change.
#### Dependencies
* A sane universe
#### Customizing a collector
Diamond collectors run within the diamond process and collect metrics that can
be published to a graphite server.
Collectors are... |
import contextlib
import json
import MySQLdb as mysql
import os
import shutil
import subprocess
import time
import urllib2
import uuid
from vtdb import cursor
from vtdb import dbexceptions
from vtdb import tablet as tablet_conn
import cases_framework
import environment
import framework
import tablet
import utils
cl... |
import os
from virtinst import VirtualDevice
from virtinst.xmlbuilder import XMLProperty
class VirtualFilesystem(VirtualDevice):
virtual_device_type = VirtualDevice.VIRTUAL_DEV_FILESYSTEM
_target_props = ["dir", "name", "file", "dev"]
TYPE_MOUNT = "mount"
TYPE_TEMPLATE = "template"
TYPE_FILE = ... |
#Setup parameters for FT950
import serial
import time
import FT950SMtoSP
debug0 = True
debug1 = True #Preamp 2!!!! UNCAL!!!
debug2 = False #report smeter value
def debugPrint(level,debugStr):
if ((level==0 and debug0) or
(level==1 and debug1) or
(level==2 and debug2)):
print('Debug',level,... |
"""
raven.core.processors
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import re
from raven.utils import varmap
from raven.utils import six
class Processor(object):
def _... |
from django.conf.urls import patterns, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^login/$', 'adminapi.apps.adminapi.views.handle_login', name='adminapi_handle_login'),
url(r'^logout/$', 'adminapi.apps.adminapi.views.handle_logout', name='adminap... |
from CIM15.IEC61970.SCADA.RemotePoint import RemotePoint
class RemoteSource(RemotePoint):
"""Remote sources are state variables that are telemetered or calculated within the remote unit.Remote sources are state variables that are telemetered or calculated within the remote unit.
"""
def __init__(self, sen... |
"""
enchant.utils: Misc utilities for the enchant package
========================================================
This module provides miscellaneous utilities for use with the
enchant spellchecking package. Currently available functionality
includes:
* string/unicode compatibility wrappers
*... |
from __future__ import unicode_literals
from django.contrib.auth.models import Group
import json
__all__ = (
"Flow"
)
"""
Workflow.py utilise a .json file per each form flow linked to the app_type category on the application. The json config contains a list of routes (also maybe called steps).
All routes st... |
import subprocess
import numpy as np
from s2plib import common
def geodetic_to_geocentric(lat, lon, alt):
"""
Converts WGS84 ellipsoidal coordinates to geocentric cartesian coordinates.
Args:
lat: latitude, in degrees between -90 and 90
lon: longitude, between -180 and 180
alt: alt... |
#!/usr/bin/env python3
"""
Writes mean round count data in tabular format.
"""
__author__ = "Todd Shore <<EMAIL>>"
__copyright__ = "Copyright 2018 Todd Shore"
__license__ = "Apache License, Version 2.0"
import argparse
import csv
import statistics
import sys
from typing import Iterable, Sequence
import pandas as p... |
'''
Custom namespace to be used in TALES expressions, like eg.
tal:content="somedate/opencore:pretty_date"
See http://wiki.zope.org/zope3/talesns.html
and http://www.openplans.org/projects/opencore/how-to-create-a-tales-namespace
'''
from Products.CMFCore.utils import getToolByName
from opencore.project.utils import... |
"""
Module containing all of the datatypes written and read from the datastore.
"""
from collections import namedtuple
import copy
import json
import re
from pycalico import netns
from netaddr import IPAddress, IPNetwork
from pycalico.util import generate_cali_interface_name, validate_characters, \
validate_ports... |
from re import sub,search
import getapi,pools,vicp
ly_lt344_pool = pools.pool()
# Available channels
valid_channels = ["M1","M2","M3","M4","C1","C2","C3","C4","TA","TB","TC","TD"]
# Put serialized API in memory if not called via import
if __name__ == '__main__':
global api; api = getapi.load_api(__file__)
# Fun... |
"""
.. _ex-xdawn-denoising:
===============
XDAWN Denoising
===============
XDAWN filters are trained from epochs, signal is projected in the sources
space and then projected back in the sensor space using only the first two
XDAWN components. The process is similar to an ICA, but is
supervised in order to maximize th... |
from PyQt5.QtCore import QDate, Qt, pyqtSignal
from PyQt5.QtWidgets import QDataWidgetMapper
from PyQt5.QtWidgets import QFormLayout, QVBoxLayout, QHBoxLayout
from PyQt5.QtWidgets import QWidget, QLineEdit, QDateEdit, QTimeEdit, QPushButton, QLabel
from tasks.model import TaskModel
class TaskView(QWidget):
close... |
from .. import Provider as InternetProvider
class Provider(InternetProvider):
user_name_formats = (
'{{last_name_female}}.{{first_name_female}}',
'{{last_name_male}}.{{first_name_male}}',
'{{last_name_male}}.{{first_name_male}}',
'{{first_name_male}}.{{last_name_male}}',
'{... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import numpy as np
# uses from outside: max_idx, flooded, color_order, opposite_points, trinities_by_idx, colors, flow_upper_bound
def find_colors(cur_idx):
global max_cur
max_cur = max(cur_idx, max_cur)
if cur... |
from typing import Optional
from django.contrib.auth.base_user import AbstractBaseUser
from ..order.models import Order, OrderLine
from . import CustomerEvents
from .models import CustomerEvent
UserType = AbstractBaseUser
def customer_account_created_event(*, user: UserType) -> Optional[CustomerEvent]:
return ... |
import json
import urllib2
import cookielib
from voodoo.gen.coordinator.CoordAddress import CoordAddress
from voodoo.sessions.session_id import SessionId
from weblab.core.reservations import Reservation
from weblab.data.command import Command, NullCommand
from weblab.data.experiments import ReservationResult, RunningR... |
import os
from urllib import quote as url_quote
from filecmp import dircmp as DirCompare
from tempfile import mkdtemp
from shutil import copy
from random import randrange, choice
from twisted.python import log
from twisted.trial import unittest
from twisted.internet.defer import Deferred
from twisted.web2.dav.fileop i... |
"""
Support for Dutch Smart Meter Requirements.
Also known as: Smartmeter or P1 port.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.dsmr/
Technical overview:
DSMR is a standard to which Dutch smartmeters must comply. It specifies that
the smar... |
# -*- coding: utf-8 -*-
"""
wakatime.languages.templates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Templates.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
from ..compat import u
""" If these keywords are found in the so... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.preview.deployed_devices.fleet import FleetList
class DeployedDevices(Version):
def __init__(self, domain):
"""
Initial... |
#coding=utf8
'''
@originalAuthor BearChild
@translator SnowOnion
http://blog.csdn.net/keshuai19940722/article/details/18894143
这样的话就可以让每个数都做为一个元素,然后保证第一个比第二个大即可,像滚雪球一样一直和下一个元素相连接,变大。但是因为题目有一个要求,就是说元素不可以为0,所以所有的0都要归结到前面第一个非0元素,这样就导致在滚雪球的时候碰到一个比自己大的雪球,即当前位置的0非常多,记得重新计数。
@status AC
'''
# num=''
c=[]
v=[]
def init():
... |
#!/usr/bin/python
# install chrome and xvfb to run e2e test with selenium
import sys
import os
import json
import time
import subprocess
import pexpect
GOOLGE_CHROME_REPO = '''[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/\$basearch
enabled=1
gpgcheck=1
'''
BOOTSTRAP_NODE_VE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pathlib
import logging
import yaml
from ybk.log import LogFormatter
conf = None
def setup_config(args=None):
global conf
if not conf:
conf = load_config()
if args:
for field in ['loglevel', 'port', 'mongodb_url',
... |
from tempest.lib.services.network import base
class MeteringLabelRulesClient(base.BaseNetworkClient):
def create_metering_label_rule(self, **kwargs):
"""Create metering label rule.
For a full list of available parameters, please refer to the official
API reference:
https://docs.o... |
import logging
import os
from pathlib import Path
import pycodestyle
import shutil
import tempfile
import unittest
from os import path
from time import sleep
from mock import MagicMock
from golem.core.common import get_golem_path, is_windows
from golem.model import Database
from golem.ethereum import Client
class ... |
import abc
import logging
import re
from typing import Tuple
from ..helpers import get_resp_defn
from .protocol_helpers import BigHex2Short, BigHex2Float # noqa: F401
from .protocol_helpers import LittleHex2Float, LittleHex2UInt, LittleHex2Short # noqa: F401
from .protocol_helpers import Hex2Ascii, Hex2Int, Hex2Str ... |
"""
Defines the URL routes for this app.
"""
from django.conf import settings
from django.conf.urls import url
from ..profile_images.views import ProfileImageView
from .accounts.views import AccountDeactivationView, AccountViewSet
from .preferences.views import PreferencesDetailView, PreferencesView
from .verificatio... |
# coding=utf-8
"""
Esse arquivo tem a finalidade de servir de ~cola~ para o desenvolvimento
do desafio, assim como exemplificar o uso de algumas funcionalidades
que não abordaremos diretamente.
"""
import logging
class Cola(object):
def numbers_and_aritmetics_operations(self):
exponecial = 2**3 ... |
import errno
import shutil
import stat
import grp
import pwd
try:
import selinux
HAVE_SELINUX=True
except ImportError:
HAVE_SELINUX=False
def get_state(path):
''' Find out current state '''
if os.path.lexists(path):
if os.path.islink(path):
return 'link'
elif os.path.is... |
#!/usr/bin/python3
# -*- coding=utf-8 -*-
import sys
from telnetlib import Telnet
import re
import time
def TelnetClient(ip, username, password, enable, *cmds):
tn = Telnet(ip, 23)
reply = tn.expect([], timeout=1)[2].decode().strip()
print(reply)
tn.write(username.encode())
tn.write... |
import numpy as np
def gaussian_function(mu, P, feat, peak):
"""
Generates an N-dimensional Gaussian using the feature matrix feat,
centered at mu, with precision matrix P and with intensity peak.
Parameters
----------
mu : numpy.ndarray
Centers of gaussians array.
P : numpy.ndarr... |
import random
import math
import numpy as np
def create_dict_xy_coord(p):
return '{"x": ' + str(p[0]) + ',"y": ' + str(p[1]) + '}'
def create_dict_labels(axis,loc,lab,offsetx=None,offsety=None):
text = '{"axis": "' + axis + '", "pos": ' + str(loc) + ', "lab": "' + lab + '" '
if offsetx is not None:
... |
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'wsconn.html'
def get_context_data(self, **kwargs):
if self.request.user.is_... |
"""OTAA devices to be pre-provisioned in the database.
Make columns devaddr nwkskey appskey nullable; deveui non-nullable.
Revision ID: 99f8aa50ac47
Revises: 282e6b269222
Create Date: 2017-02-20 10:01:14.549853
"""
from alembic import op
from sqlalchemy.sql import table, column
import sqlalchemy as sa
# revision id... |
from __future__ import unicode_literals
import frappe
import unittest
class TestLeavePolicy(unittest.TestCase):
def test_max_leave_allowed(self):
random_leave_type = frappe.get_all("Leave Type", fields=["name", "max_leaves_allowed"])
if random_leave_type:
random_leave_type = random_leave_type[0]
leave_type... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import argparse
import numpy as np
from phonopy.file_IO import parse_FORCE_CONSTANTS, write_FORCE_CONSTANTS
from vasp.poscar import Poscar
from .fc_analyzer_base imp... |
from collections import OrderedDict
import logging
import six
import pandas as pd
import py_entitymatching as em
from py_entitymatching.evaluation.evaluation import eval_matches
from py_entitymatching import DTMatcher
from py_entitymatching.debugmatcher.debug_gui_utils import _get_code_vis, _get_metric,\
_get_da... |
"""Heap queue algorithm (a.k.a. priority queue).
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting
property of a heap is that a[0] is always its smallest element.
Usag... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# chessboard
#
'''
For special chessboard problem.
'''
class ChessBoard():
'''
Class for base chessboard.
row:the chessboard row num.
col:the chessboard col num.
'''
def __init__(self, row=1, col=1):
self._row = ro... |
import requests
import random
_USER_AGENTS = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/601.1.10 (KHTML, like Gecko) Version/8.0.5 Safari/601.1.10",
"Mozilla/5.0 (... |
#!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Pelix demo: Android Compass, using Kivy
Based on the "compass" example of the Kivy project.
:author: Thomas Calmant
:copyright: Copyright 2013, isandlaTech
:license: GPLv2
:version: 0.1
:status: Alpha
"""
# Module version
__version_info__ = (0, 1, 0)
__version__ ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
description = "Manage and load Budget Data Packages"
with open('README.rst') as readme:
long_description = readme.read()
setup(
name = 'budgetdatapackage',
version ... |
CHUNKSIZE = 1 << 26
GETDIR_FLAG_WITHATTR = 0x01
GETDIR_FLAG_ADDTOCACHE = 0x02
# type for readdir command
TYPE_FILE = 'f'
TYPE_SYMLINK = 'l'
TYPE_DIRECTORY = 'd'
TYPE_FIFO = 'q'
TYPE_BLOCKDEV = 'b'
TYPE_CHARDEV = 'c'
TYPE_SOCKET = 's'
TYPE_TRASH = 't'
TYPE_SUSTAINED = 'r'
TYPE_UNKNOWN = '?'
ERROR_MAX = 38
ERROR_LOCKE... |
from Graph import Graph
class UndirectGraph( Graph ):
def __init__( self ):
super( UndirectGraph,self ).__init__()
def connect( self, vertexA,vertexB,label = None ):
if super().connect( vertexA,vertexB,label ) == False:
return False
self.graph[vertexB][vertexA] = label
... |
import sys
import math
import matrix
import pickle
#globals()['something'] = 'bob'
def main():
read_file(sys.argv[1])
def read_file(lines):
global frames,currentframe
f = open(lines,'r')
l = f.readlines();
while(not done):
print "Frame " + str(currentframe)
for line in l:
doline(line)
def is_number(s):
... |
"""
EasyBuild support for ictce compiler toolchain (includes Intel compilers (icc, ifort), Intel MPI,
Intel Math Kernel Library (MKL), and Intel FFTW wrappers).
@author: Stijn De Weirdt (Ghent University)
@author: Kenneth Hoste (Ghent University)
"""
from easybuild.toolchains.compiler.inteliccifort import IntelIccIfo... |
import warnings
from gtfsobjectbase import GtfsObjectBase
import problems as problems_module
import util
class Stop(GtfsObjectBase):
"""Represents a single stop. A stop must have a latitude, longitude and name.
Callers may assign arbitrary values to instance attributes.
Stop.ParseAttributes validates attribute... |
from __future__ import absolute_import
import os
from PyQt5.QtCore import QThread
from pyinotify import ProcessEvent, IN_CREATE, IN_DELETE, IN_DELETE_SELF, \
IN_MODIFY, WatchManager, Notifier, ExcludeFilter
from ninja_ide.tools.logger import NinjaLogger
logger = NinjaLogger('ninja_ide.core.fi... |
import asyncore
import email.utils
import socket
import threading
import smtpd
import smtplib
import StringIO
import sys
import time
import select
from unittest import TestCase
from test import test_support
HOST = test_support.HOST
def server(evt, buf, serv):
serv.listen(5)
evt.set()
try:
conn, a... |
from tempest_lib.common.utils import data_utils
from tempest.api.identity import base
from tempest import test
class RolesV3TestJSON(base.BaseIdentityV3AdminTest):
@classmethod
def resource_setup(cls):
super(RolesV3TestJSON, cls).resource_setup()
for _ in range(3):
role_name = da... |
#!/usr/bin/python
from __future__ import print_function
import argparse, glob, itertools, re, shutil, os, sys
config_reg = re.compile('.*\/\/\s*(?P<name>\S+):\s*(?P<value>.*)$')
class Tester:
def __init__(self,args,test):
self.args = args
self.test = test
self.update = args.updateref
self.confi... |
import os
import json
import errno
from . import __version__
from .compat import is_windows
DEFAULT_CONFIG_DIR = os.environ.get(
'HTTPIE_CONFIG_DIR',
os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie')
)
class BaseConfigDict(dict):
name = None
helpur... |
import mock
import mox
from oslo.config import cfg
from heat.common import exception
from heat.openstack.common import importutils
from heat.tests.common import HeatTestCase
from heat.tests import utils
from .. import client as heat_keystoneclient # noqa
class KeystoneClientTest(HeatTestCase):
"""Test cases fo... |
import unittest, sys, os
sys.path.insert(0, os.path.abspath('.'))
import csv_map_converter
from csv_map_converter.models.fields import *
class Product(object):
enabled = BooleanField()
name = StringField()
price = IntField()
labels = ListField(StringField())
label = ListField(StringField(... |
"""An estimator is a rule for calculating an estimate of a given quantity.
# Estimators
* **Estimators** are used to train and evaluate TensorFlow models.
They support regression and classification problems.
* **Classifiers** are functions that have discrete outcomes.
* **Regressors** are functions that predict conti... |
'''
Copyright 2015, 2016 University College London.
This file is part of PyORACC.
PyORACC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
# -*- coding:utf-8 -*-
# Cyril Fournier
# 15/01/2016
from wx import WXK_UP, WXK_DOWN, WXK_RIGHT, WXK_LEFT
######################
# Usefull functions
######################
def getKey(d, value):
"""
Return the list of keys corresponding to the value 'value'.
If no key correspond to the value, return an empty list... |
class trie:
def __init__(self):
self.root = dict()
self.root['_end_'] = -1
self.root['_max_'] = -1
def add_string(self,s,priority):
current_dict = self.root
for letter in s:
if letter in current_dict:
current_dict = current_dict[letter]
... |
from __future__ import print_function, division, absolute_import
from flask_classful import FlaskView
from flask import request, current_app
from marvin.web.web_utils import parseSession, update_allowed, updateGlobalSession, check_access
import marvin
from brain.api.general import BrainGeneralRequestsView
from brain.ut... |
import pandas as pd
import numpy as np
import warnings
from functools import partial, wraps
def _recursive_apply(f, l):
if isinstance(l, (list, tuple)):
out = [_recursive_apply(f, l_) for l_ in l]
if isinstance(l, tuple):
out = tuple(out)
return out
else:
return f(l... |
# encoding: UTF-8
"""
Author: KeKe
Please install tiger-api before use.
pip install tigeropen
"""
from copy import copy
from datetime import datetime
from multiprocessing.dummy import Pool
from queue import Empty, Queue
import functools
import traceback
import pandas as pd
from pandas import DataFrame
from tigeropen... |
"""Test version bits warning system.
Generate chains with block versions that appear to be signalling unknown
soft-forks, and test that warning alerts are generated.
"""
from test_framework.mininode import *
from test_framework.test_framework import PlanbcoinTestFramework
from test_framework.util import *
import re
f... |
import os
migrated = False
def migrateSupport(oldAppName, newAppName):
print('Checking Miro preferences and support migration...')
global migrated
migrated = False
from AppKit import NSBundle
prefsPath = os.path.expanduser('~/Library/Preferences').decode('utf-8')
newDomain = NSBundle.mainBu... |
import gfootball_engine as libgame
e_PlayerRole_GK = libgame.e_PlayerRole.e_PlayerRole_GK
e_PlayerRole_CB = libgame.e_PlayerRole.e_PlayerRole_CB
e_PlayerRole_LB = libgame.e_PlayerRole.e_PlayerRole_LB
e_PlayerRole_RB = libgame.e_PlayerRole.e_PlayerRole_RB
e_PlayerRole_DM = libgame.e_PlayerRole.e_PlayerRole_DM
e_PlayerRo... |
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
plt.ion()
plt.close('all')
from config import *
def plot_all(dim):
d_full = pd.read_csv('results/full.csv')
d_sparse = pd.read_csv('results/sparse.csv')
d_vff = pd.read_csv('results/vff.csv')
bullet = ['o', 'X', 'D', 'P', 'H',... |
from __future__ import unicode_literals, absolute_import
import ctypes
import sys
import re
def ValidHandle(value, func, arguments):
if value == 0:
raise ctypes.WinError()
return value
#import serial
from ardublocklyserver.pyserialports.serial_to_bytes import to_bytes
from ardublocklyserver.pyserialpo... |
"""Cell to run odm_slam."""
import os
from opendm import log
from opendm import io
from opendm import system
from opendm import context
from opendm import types
class ODMSlamStage(types.ODM_Stage):
"""Run odm_slam on a video and export to opensfm format."""
def process(self, args, outputs):
tree = o... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - run standalone server, optionally daemonizing it
@copyright: 2008 MoinMoin:ForrestVoight
@license: GNU GPL, see COPYING for details.
"""
import os
import sys
import signal
from MoinMoin.script import MoinScript
from MoinMoin.util.daemon import Daem... |
import getpass
import pytest
from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session
from TCLIService import TCLIService
from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
USER_NAME = getpass.getuser()
PROXY_USER = "proxy_user_name"
PROXY_USER_WITH_COMMA = "proxy_user,name_2"
PROXY_USER... |
{
"name": "Account Invoice Extended",
"version": "2.0.1.1",
"author": "Didotech SRL",
"website": "http://www.didotech.com",
"category": 'Accounting & Finance',
"description": """
Module adds extra functionality to account_invoice:
- possibility to filter invoices by year
... |
"""
Django settings for cloudbuster project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... |
from lib import aa
import aatw
from aatw import TYPE, EXTENSION
import targets
from targets import _
NAME = _('ASCII Art Presentation Web')
TAGS = aatw.TAGS.copy()
TAGS['bar1'] = aa.line(targets.AA['bar1'], targets.CONF['width'] - 2)
TAGS['bar2'] = aa.line(targets.AA['bar2'], targets.CONF['width'] - 2)
if not targets... |
from Tkinter import *
import webbrowser
class Application(Frame):
def __init__(self, master):
""" Initialize the Frame """
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
# Title label
self.instruction = Label(self, text = "PyCaesar", font=("arial",17,"bold"))
... |
from AbstractPowerCalculator import AbstractPowerCalculator
from LinearInterpolationPowerCalculator import interp
'''
CycleOps Fluid2 power calculator.
'''
class CycleOpsFluid2PowerCalculator(AbstractPowerCalculator):
def __init__(self):
super(CycleOpsFluid2PowerCalculator, self).__init__()
self.w... |
#!/usr/bin/env python
#
# L. Brodeau, 2017
#
# Compute curl, aka relative vorticity from 2D vector on a lat-lon spherical
# grid a la ECMWF
#
import sys
import numpy as nmp
from netCDF4 import Dataset
import string
import barakuda_tool as bt
cv_wmod='wspd10m'
if len(sys.argv) != 4:
print 'Usage: '+sys.argv[0]+... |
import contextlib
import logging
import os
from typing import FrozenSet, List
from typing import Dict # noqa: F401
import snapcraft.plugins
from snapcraft import ProjectOptions
from snapcraft.internal import elf
from snapcraft.internal import errors
logger = logging.getLogger(__name__)
def is_go_based_plugin(plug... |
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from imagekit.models import ImageS... |
from flask import Response, Blueprint
from flask import g, render_template, url_for
from flask import request, abort, redirect
from flask.ext import login
from flask.ext.security import current_user, roles_accepted
from app.models import Patch, PatchState
from app.slugify import slugify
from app import db
bp = Blue... |
#bprop.py
import numpy as np
#Array of layer sizes
ls = np.array([2, 4, 4, 1])
n = len(ls)
#List of weight matrices (each a numpy array)
W = []
#Initialize weights to small random values
for i in range(n - 1):
W.append(np.random.randn(ls[i], ls[i + 1]) * 0.1)
#List of bias vectors initialized to small random values... |
from pymongo import errors
from anubis import db
from anubis import error
from anubis.model import builtin
from anubis.util import argmethod
from anubis.util import validator
PROJECTION_PUBLIC = {'uid': 1}
@argmethod.wrap
async def add(domain_id: str, owner_uid: int,
roles=builtin.DOMAIN_SYSTEM['roles... |
import sys, os, popen2, random
#jobs_per_file = 10
jobs_per_file = 4
max_l1 = 10 # Don't do any parsing with an l1 above this value
from variables import *
from host import *
host = get_host()
if len(sys.argv) < 4:
sys.stderr.write("Incorrect call.\n")
sys.stderr.write("USAGE: make-condor-parser-submit.py paramete... |
{
'name': 'VAT Number Validation',
'version': '1.0',
'category': 'Accounting',
'description': """
VAT validation for Partner's VAT numbers.
=========================================
After installing this module, values entered in the VAT field of Partners will
be validated for all supported countries. ... |
from django.db import connection
from django.db import models
class Database(models.Model):
name = models.TextField(blank=False, db_index=True)
description = models.TextField(blank=True, db_index=True)
url = models.URLField(max_length=300)
def __unicode__(self):
return '<Database %s "%s">' % ... |
from builtins import object
import logging
import sys
logger = logging.getLogger(__name__)
class Printer(object):
"""Class to print messages to the console"""
def __init__(self, msg, progress_bar=False, current=100, total=100):
if progress_bar is True:
if int(current / total * 100) < 100... |
from __future__ import print_function
"""
This tool takes data from stdin and validates it as iCalendar data suitable
for the server.
"""
from calendarserver.tools.cmdline import utilityMain, WorkerService
from twisted.internet.defer import succeed
from twisted.python.text import wordWrap
from twisted.python.usage im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.