repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2beta1_participants_list_suggestions_async.py | Python | apache-2.0 | 1,546 | 0.00194 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | gle-cloud-dialogflow
# [START dialogflow_generated_dialogflow_v2beta1_Participants_ListSuggestions_async]
from google.cloud import dialogflow_v2beta1
async def sample_list_suggestions():
# Create a client
client = dialogflow_v2beta1.ParticipantsAsyncClient()
# Initialize request argument(s)
request... | st
page_result = client.list_suggestions(request=request)
# Handle the response
async for response in page_result:
print(response)
# [END dialogflow_generated_dialogflow_v2beta1_Participants_ListSuggestions_async]
|
sandialabs/BioCompoundML | bcml/Parser/read_training.py | Python | bsd-3-clause | 2,349 | 0 | """
This process takes in the training dataset and outputs
a data structure that includes the name of the molecule,
the predictor, and the CAS number
Attributes:
input_file (str): This is the training file that
is read by the output
Instance (class): This is a private class which
structures each instan... | unt] == self.predictor:
| predictor = item
elif self.weights is True and header[count] == 'Weight':
weight = float(item.rstrip())
elif self.user is True:
compound['userhash'][header[count]] = item.rstrip()
compound[header[... |
PicoGeyer/CS-6250-A5_firewall_test | testing-topo.py | Python | mit | 2,069 | 0.006283 | #!/usr/bin/python
"Assignment 5 - This defines a topology for running a firewall. It is not \
necessarily the topology that will be used for grading, so feel free to \
edit and create new topologies and share them."
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import CPULim... | ass FWTopo(Topo):
''' Creates the following topoplogy:
e1 e2 e3
| | |
\ | /
firwall (s1)
/ | \
| | |
w1 w2 w3
'''
def __init__(self, cpu=.1, bw=10, delay=None, **params):
super(FWTopo,self).__init__()
# Host in link c... | tion
hconfig = {'cpu': cpu}
lconfig = {'bw': bw, 'delay': delay}
# Create the firewall switch
s1 = self.addSwitch('s1')
# Create East hosts and links)
e1 = self.addHost('e1', **hconfig)
e2 = self.addHost('e2', **hconfig)
e3 = self.addHost... |
deka108/mathqa-server | cms/admin.py | Python | apache-2.0 | 1,772 | 0 | """
# Name: cms/admin.py
# Description:
# Created by: Phuc Le-Sanh
# Date Created: N.A
# Last Modified: Nov 21 2016
# Modified by: Phuc Le-Sanh
"""
from django.contrib import admin
from django.contrib | .admin import ModelAdmin
from apiv2.models import *
c | lass QuestionAdmin(ModelAdmin):
fields = ('id', 'content', 'concept', 'is_sample', 'subconcept',
'difficulty_level', 'marks', 'keypoints', 'keywords',
'paper', 'source', 'used_for', 'response_type',
'question_type', 'paper')
empty_value_display = '-empty-'
# from meas... |
mwindau/praktikum | v504/oppellog.py | Python | mit | 701 | 0.012839 | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
u, i=np.genfromtxt('Rohdaten/Daten_1_5.txt', unpack=True)
i=np.log(i)
u=np.log(u)
def f(u, a, b):
return a * u + b
params, covariance = curve_fit(f, u, i)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', err... | i, 'rx', label='Messwerte')
plt.plot(x_plot, f(x_plot, params[0], params[1]), 'b-', label='Ausgleichsgerade')
plt.xlabel('log(U / V)')
plt.ylabel('log(I / mA)')
#plt.xlim(8, 300)
#plt.yscale('log')
#plt.xscale('log')
plt.grid()
plt.legend(loc='best')
| plt.savefig('build/oppellog.pdf')
#
|
Telefonica/vaultier-cli | vaultcli/main.py | Python | gpl-3.0 | 37,793 | 0.005716 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Adrián López Tejedor <[email protected]>
# Óscar García Amor <[email protected]>
#
# Distributed under terms of the GNU GPLv3 license.
from vaultcli.auth import Auth
from vaultcli.client import Client
from vau... |
from zipfile import ZipFile, ZIP_DEFLATED
import argparse
import json
import os
import sys
def get_config_file(args):
if args.config:
return | args.config
else:
config_files = [
os.path.join(os.path.expanduser('~'), '.config/vaultcli/vaultcli.conf'),
os.path.join(os.path.expanduser('~'), '.vaultcli.conf')
]
config_file = [file for file in config_files if os.access(file, os.R_OK)]
if ... |
Smart-Torvy/torvy-home-assistant | homeassistant/components/cover/demo.py | Python | mit | 5,159 | 0 | """
Demo platform for the cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
from homeassistant.components.cover import CoverDevice
from homeassistant.helpers.event import track_utc_time_change
def setup_platform(hass, config, add_d... | return
if self._unsub_listener_cover_tilt is not None:
self._unsub_listener_cover_tilt()
self._unsub_listener_cover_tilt = No | ne
self._set_tilt_position = None
def _listen_cover(self):
"""Listen for changes in cover."""
if self._unsub_listener_cover is None:
self._unsub_listener_cover = track_utc_time_change(
self.hass, self._time_changed_cover)
def _time_changed_cover(self, no... |
plxaye/chromium | src/chrome/test/functional/media/pyauto_media.py | Python | apache-2.0 | 1,125 | 0.007111 | # Copyright (c) 2012 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.
"""PyAuto media test base. Handles PyAuto initialization and path setup.
Required to ensure each media test can load the appropriate libraries. Each
t... | DO(dalecurtis): This should only be added for t | ests which use psutil.
sys.path.append(os.path.normpath(os.path.join(
media_dir, os.pardir, os.pardir, os.pardir, os.pardir,
'third_party', 'psutil')))
_SetupPaths()
import pyauto_functional
Main = pyauto_functional.Main
|
bremond/siconos | Build/tools/publish.py | Python | apache-2.0 | 6,107 | 0.000819 | #!/usr/bin/env python
# documentation publication on http://siconos.gforge.inria.fr
# ./publish [- | r <sha>] [-u <gforge_user>] [-s <src dir ] [-b <build dir>] \
# [-w workdir] [-m]
# -r followed by some git sha
# -u followed by gforge login
# -s followed by src directory
# -b followed by build directory
# -d : publish devel version
# example:
# to update site with current documentation
# ./publish -u br... | ) documentation
# ./publish -r3194 -u bremond [...]
# Note: some rsync error may occurs due to some files modes on remote site
import sys
import os
import shutil
import tempfile
import re
from subprocess import check_call
from getpass import getuser
from getopt import gnu_getopt, GetoptError
#
# exit only if not i... |
RaoUmer/distarray | docs/sphinx/source/conf.py | Python | bsd-3-clause | 8,831 | 0.006455 | # -*- coding: utf-8 -*-
#
# DistArray documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 31 01:11:34 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | ix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a li... | eme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_t... |
dldinternet/aws-cfn-resource-bridge | setup.py | Python | apache-2.0 | 3,161 | 0.001582 | #!/usr/bin/env python
#==============================================================================
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | s.stderr, "Python 2.6+ is required"
sys.exit(1)
rpm_requires = ['python >= 2.6', 'python-daemon', 'python-botocore >= 0.17.0']
dependencies = ['python-daemon>=1.5.2', 'botocore>=0.17.0']
if sys.version_info[:2] == | (2, 6):
# For python2.6 we have to require argparse
rpm_requires.append('python-argparse >= 1.1')
dependencies.append('argparse>=1.1')
_opts = {
'build_scripts': {'executable': '/usr/bin/env python'},
'bdist_rpm': {'requires': rpm_requires}
}
_data_files = [('share/doc/%s-%s' % (name, bridge.__vers... |
timpalpant/calibre | src/calibre/gui2/convert/single.py | Python | gpl-3.0 | 12,211 | 0.004586 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
import cPickle, shutil
from PyQt5.Qt import QAbstractListModel, Qt, QFont, QModelIn... |
if geom:
self.restoreGeometry(geom)
else:
self.resize(self.sizeHint())
def sizeHint(self):
desktop = QCoreApplication.instance().desktop()
geom = desktop.availableGeometry(self)
nh, nw = max(300, geom.height()-50), max(400, geom.width()-70)
r... | at(self):
return unicode(self.input_formats.currentText()).lower()
@property
def output_format(self):
return unicode(self.output_formats.currentText()).lower()
@property
def manually_fine_tune_toc(self):
for i in xrange(self.stack.count()):
w = self.stack.widget(i)
... |
tacitia/ThoughtFlow | project/project/settings.py | Python | mit | 4,859 | 0.00247 | # !/usr/bin/python
import os
# CUSTOM PATH SETTINGS
PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
REPO_DIR = os.path.realpath(os.path.join(PROJECT_DIR, '..'))
HOME_DIR = os.path.realpath(os.path.join(REPO_DIR, '..'))
STATIC_DIR = os.path.realpath(os.path.join(HOME_DIR, 'staticfiles'))
MEDIA_DIR = os.path.r... | 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
| 'context_processors':
(
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
... |
EducatedMachine/pysprintly | api/items.py | Python | mit | 133 | 0 | class Items:
def __init__(self, connection, cache_values=True):
| self.conn = connection
self.cache_values = Tr | ue
|
amw2104/fireplace | tests/test_league.py | Python | agpl-3.0 | 15,470 | 0.028636 | from utils import *
def test_ancient_shade():
game = prepare_empty_game()
shade = game.player1.give("LOE_110")
assert len(game.player1.deck) == 0
shade.play()
assert len(game.player1.deck) == 1
assert game.player1.deck[0].id == "LOE_110t"
game.end_turn()
assert game.player1.hero.health == 30
game.end_turn()... | _061")
sentinel2.play()
game.end_turn(); game.end_turn()
assert sentinel2.atk == sentinel2.health == 4
game.player1.give("CS2_029").play(target=sentinel1)
assert sentinel2.atk == sentinel2.health == 4 + 3
assert wisp.atk == wisp.health == 1
game.player1.give("CS2_029").play(target=sentinel2)
assert wisp.atk ==... | ame = prepare_game()
# kill a Wisp
wisp = game.player1.give(WISP)
wisp.play()
game.player1.give(MOONFIRE).play(target=wisp)
game.end_turn(); game.end_turn()
assert len(game.player1.field) == 0
assert len(game.player2.field) == 0
game.player1.give("LOE_026").play()
assert len(game.player1.field) == 0
assert ... |
kontza/sigal | sigal/plugins/copyright.py | Python | mit | 2,076 | 0 | """Plugin which add a copyright to the image.
Settings:
- ``copyright``: the copyright text.
- ``copyright_text_font``: the copyright text font - either system/user
font-name or absolute path to font.ttf file. If no font is specified, or
specified font is not found, the default font is used.
- ``copyright_text_f... | = settings.get('copyright_text_position',
(5, img.size[1] - text_height))
draw.text((left, top), text, fill=color, font=font)
return img
def register(settings):
if settings.get('copyright'):
signals.img_resized.connect(add_copyright)
else:
logger.warning('C... | t is not set')
|
XiaodunServerGroup/ddyedx | lms/djangoapps/class_dashboard/dashboard_data.py | Python | agpl-3.0 | 15,860 | 0.003279 | """
Computes the data to display on the Instructor Dashboard
"""
from courseware import models
from django.db.models import Count
from django.utils.translation import ugettext as _
from xmodule.course_module import CourseDescriptor
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.inheritanc... | data(section).get('display_name', '')
data = []
c_subsection = 0
fo | r subsection in section.get_children():
c_subsection += 1
c_unit = 0
for unit in subsection.get_children():
c_unit += 1
c_problem = 0
for child in unit.get_children():
# Student data is at the problem level
... |
ajslater/magritte | test.py | Python | gpl-2.0 | 272 | 0 | import sys
fro | m unittest import TestCase
from magritte.cli import main
class TestConsole(TestCase):
def test_basic(self):
sys.argv += ['-V']
with self.assertRaises(SystemExit) as cm:
main()
|
self.assertEqual(cm.exception.code, 0)
|
garlandkr/ansible | lib/ansible/module_common.py | Python | gpl-3.0 | 6,752 | 0.004295 | # (c) 2013-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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) an... | .join(os.path.dirname(this_file), 'module_utils')
self.strip_comments = strip_comments # TODO: implement
# ******************************************************* | ***********************
def slurp(self, path):
if not os.path.exists(path):
raise errors.AnsibleError("imported module support code does not exist at %s" % path)
fd = open(path)
data = fd.read()
fd.close()
return data
def _find_snippet_imports(self, module_... |
jkreft-usgs/PubsWarehouse_UI | server/setup.py | Python | unlicense | 3,994 | 0.001502 | """
Setuptools configuration for Pubs Warehouse.
This setup script requires that static assets have been built into the
`assets/dist` directory prior to the build.
"""
import os
from setuptools import setup, find_packages
def read_requirements():
"""
Get application requirements from
the requirements.tx... | his function in | cludes that file as a data file, then it's
going to be in the distributable.
:param list data_dirs: list of tuples each of the form: (`installation directory`, `source directory`)
the installation directory can be None to preserve the source directory's structure in the wheel's data
directory
... |
Azure/azure-sdk-for-python | sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/operations/_tags_operations.py | Python | mit | 5,614 | 0.004097 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ERIALIZER. | header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
class TagsOperations(object):
"""TagsOperations operations.
You should not instantiate this class directly. Instead, you sh... |
ypu/virt-test | tools/github/cache_populate.py | Python | gpl-2.0 | 718 | 0 | #!/usr/bin/env python
import sys
import os |
import getpass
import datetime
from github import Github
from github_issues import GithubIssues
gh = Github(login_or_token=raw_input("Enter github username: "),
password=getpass.getpass('Enter github password: '),
user_agent='PyGithub/Python')
print "Enter location (<user>/<repo>)",
repo_full... | p() or repo_full_name
print
issues = GithubIssues(gh, repo_full_name)
for issue in issues:
sys.stdout.write(str(issue['number']) + '\n')
sys.stdout.flush()
# make sure cache is cleaned and saved up
del issues
print
|
MaximeGLegault/StrategyIA | ai/STA/Tactic/RotateAroundPosition.py | Python | mit | 1,168 | 0.003425 | # Under MIT license, see LICENS | E.txt
from typing import List
import numpy as np
from RULEngine.Game.OurPlayer import OurPlayer
from RULEngine.Util.Position import Position
from RULEngine.Util.Pose import Pose
from ai.STA.Tactic.Tactic import Tactic
from ai.STA.Tactic.tactic_constants import Flags
from ai.STA.Action.rotate_around import RotateAround... | yer: OurPlayer, target: Pose, args: List[str]=None):
super().__init__(game_state, player, target, args)
def exec(self):
if self.check_success():
self.status_flag = Flags.SUCCESS
else:
self.status_flag = Flags.WIP
ball = self.game_state.get_ball_position().con... |
blitzmann/Pyfa | eos/db/saveddata/databaseRepair.py | Python | gpl-3.0 | 11,132 | 0.004581 | # ===============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
#
# pyfa 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, eithe... | T(*) AS num FROM fits WHERE damagePatternID NOT IN (SELECT ID FROM damagePatterns) OR damagePatternID IS NULL"
results = DatabaseCleanup.ExecuteSQLQuery(saveddata_engine, query)
if results is None:
return
row = results.first()
if row and row['num']:
# Get Unifo... | WHERE name = 'Uniform'"
uniform_results = DatabaseCleanup.ExecuteSQLQuery(saveddata_engine, uniform_query)
if uniform_results is None:
return
rows = uniform_results.fetchall()
if len(rows) == 0:
pyfalog.error("Missing uniform damage pat... |
BhallaLab/moose | moose-gui/suds/reader.py | Python | gpl-3.0 | 5,246 | 0.000191 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will b... | suds library's
caching system.
"""
from suds.cache import Cache, NoCache
from suds.plugin import PluginContainer
from suds.sax.parser import Parser
from suds.store import DocumentStore
from suds.transport import Request
class Reader:
"""
Provides integration with the cache.
@ivar options: An options obj... | ns: I{Options}
"""
def __init__(self, options):
"""
@param options: An options object.
@type options: I{Options}
"""
self.options = options
self.plugins = PluginContainer(options.plugins)
def mangle(self, name, x):
"""
Mangle the name by hash... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.3.0/Lib/test/test_logging.py | Python | mit | 134,314 | 0.003231 | #!/usr/bin/env python
#
# Copyright 2001-2012 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright n... | up the default logging stream to an internal StringIO instance,
so that we can examine log output as we want."""
logger_dict = logging.getLogger().manager.loggerDict
logging._acquireLock() |
try:
self.saved_handlers = logging._handlers.copy()
self.saved_handler_list = logging._handlerList[:]
self.saved_loggers = saved_loggers = logger_dict.copy()
self.saved_level_names = logging._levelNames.copy()
self.logger_states = logger_states = {}
... |
dogebuild/dogebuild | dogebuild/dogefile.py | Python | mit | 6,192 | 0.003068 | import logging
import sys
from functools import reduce
from os.p | ath import relpath
from pathlib import Path
from typing import Dict, List, Any
from argparse import ArgumentParser
from dogebuild.common import DOGE_FILE, DirectoryContext, sanitize_name
from dogebuild.dependencies_functions import resolve_dependency_tree
from dogebuild.dogefile_internals.context import Context, Conte... | ge_file_id: str):
extra = {"doge_file_id": doge_file_id}
super(DogeFileLoggerAdapter, self).__init__(logger, extra)
self.doge_file_id = doge_file_id
def process(self, msg, kwargs):
return f"{self.doge_file_id}: {msg}", kwargs
class DogeFileFactory:
def __init__(self, root_path... |
Akrog/cinder | cinder/tests/__init__.py | Python | apache-2.0 | 1,435 | 0.000697 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a ... | g permissions and limitations
# under the License.
"""
:mod:`cinder.tests` -- Cinder Unittests
=====================================================
.. automodule:: cinder.tests
:platform: Unix
.. moduleauthor:: Jesse Andrews <[email protected]>
.. moduleauthor:: Devin Carlen <[email protected]>
.. module... | Andy Smith <[email protected]>
"""
import eventlet
eventlet.monkey_patch()
# See http://code.google.com/p/python-nose/issues/detail?id=373
# The code below enables nosetests to work with i18n _() blocks
import __builtin__
setattr(__builtin__, '_', lambda x: x)
|
salas106/lahorie | lahorie/plugins/parrot.py | Python | mit | 238 | 0.012605 | # -*- coding: utf8 -*-
"""
The ``parrot plugin
====================
Some can of russian parrot, that ac | t like a russian roulette, randomly repeating some sentence.
May enter in berzek mode, but it is very rare.
"""
| |
ajaygarg84/sugar | extensions/deviceicon/speaker.py | Python | gpl-2.0 | 7,404 | 0 | # Copyright (C) 2008 Martin Dengler
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | rom sugar3.graphics import style
from sugar3.graphics.icon import get_icon_state, Icon
from sugar3.graphics.tray import TrayIcon
from sugar3.graphics.palette import Palette
from sugar3.graphics.palettemenu import PaletteMenuBox
from sugar3.graphics.palettemenu import PaletteMenuItem
from | sugar3.graphics.palettemenu import PaletteMenuItemSeparator
from sugar3.graphics.xocolor import XoColor
from jarabe.frame.frameinvoker import FrameWidgetInvoker
from jarabe.model import sound
_ICON_NAME = 'speaker'
class DeviceView(TrayIcon):
FRAME_POSITION_RELATIVE = 103
def __init__(self):
clie... |
wisechengyi/pants | src/python/pants/backend/python/rules/python_create_binary.py | Python | apache-2.0 | 4,021 | 0.00373 | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from typing import Optional
from pants.backend.python.rules.pex import Pex
from pants.backend.python.rules.pex_from_target_closure import CreatePexFromTa... | EntryPoint, PythonBinarySources
from p | ants.backend.python.rules.targets import targets as python_targets
from pants.backend.python.targets.python_binary import PythonBinary
from pants.build_graph.address import Address
from pants.engine.addressable import Addresses
from pants.engine.legacy.structs import PythonBinaryAdaptor
from pants.engine.parser import ... |
beepscore/google-python-exercises | basic/string_tool.py | Python | apache-2.0 | 2,076 | 0.003372 | #!/usr/bin/env python3 -tt
"""
Utility methods for strings.
"""
class StringTool:
def __init__(self):
pass
def clean_string(self, a_string):
"""
Return string with unwanted punctuation removed.
Currently uses str.replace()
Could make more efficient using regular exp... | aned.replace(';', ' ')
| string_cleaned = string_cleaned.replace(':', ' ')
string_cleaned = string_cleaned.replace(',', ' ')
string_cleaned = string_cleaned.replace('.', ' ')
string_cleaned = string_cleaned.replace('?', ' ')
string_cleaned = string_cleaned.replace('!', ' ')
return string_cleaned... |
sontek/python-driver | tests/integration/cqlengine/statements/test_base_statement.py | Python | apache-2.0 | 983 | 0 | # Copyright 2015 DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# limitations under the License.
from unittest import TestCase
from cassandra.cqlengine.statements import BaseCQLStatement, StatementException
class BaseStatementTest(TestCase):
def test_where_clause_type_checking(self):
""" tests that only assignment clauses can be added to queries """
stmt = ... | seCQLStatement('table', [])
with self.assertRaises(StatementException):
stmt.add_where_clause('x=5')
|
coquelicot/Pooky | pooky/Widgets.py | Python | gpl-3.0 | 2,289 | 0.003058 | # This file is part of Pooky.
# Copyright (C) 2013 Fcrh <[email protected]>
#
# Pooky 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 ver... | rror("Singleton check failed.")
else:
self.__class__.__instance = self
class Palette(SingletonWidget):
def __init__(self, *args):
super(). | __init__(*args)
class Preference(SingletonWidget):
def __init__(self, *args):
super().__init__(*args)
QtGui.QLabel('Almost Empty XD.', self)
self.resize(640, 480)
self.setWindowTitle('Preference')
class About(SingletonWidget):
def __init__(self, *args):
super().__ini... |
maxive/erp | addons/website_sale_link_tracker/controllers/backend.py | Python | agpl-3.0 | 2,123 | 0.002355 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import http
from odoo.addons.website_sale.controllers.backend import WebsiteSaleBackend
from odoo.http import request
class WebsiteSaleLinkTrackerBackend(WebsiteSaleBackend):
@http.route()
def fetch_... | results = super(WebsiteSaleLinkTrackerBackend, self).fetch_dashboard_data(date_from, date_to)
results['dashboards']['sales']['utm_graph'] = self.fetch_utm_data(date_from, date_to)
return results
def fetch_utm_data(self, date_from, date_to):
sale_utm_domain = [
('team_id.t... | orders_data_groupby_campaign_id = request.env['sale.order'].read_group(
domain=sale_utm_domain + [('campaign_id', '!=', False)],
fields=['amount_total', 'id', 'campaign_id'],
groupby='campaign_id')
orders_data_groupby_medium_id = request.env['sale.order'].read_group(... |
danlrobertson/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptmanifest/serializer.py | Python | mpl-2.0 | 4,527 | 0.001546 | from node import NodeVisitor, ValueNode, ListNode, BinaryExpressionNode
from parser import atoms, precedence
atom_names = {v:"@%s" % k for (k,v) in atoms.iteritems()}
named_escapes = set(["\a", "\b", "\f", "\n", "\r", "\t", "\v"])
def escape(string, extras=""):
# Assumes input bytes are either UTF8 bytes or unic... |
if "#" in data or (isinstance(node.parent, ListNode) and
("," in data or "]" in data)):
if " | \"" in data:
quote = "'"
else:
quote = "\""
else:
quote = ""
return [quote + escape(data, extras=quote) + quote]
def visit_AtomNode(self, node):
return [atom_names[node.data]]
def visit_ConditionalNode(self, node):
return ... |
polyaxon/polyaxon | core/polyaxon/polyflow/references/path.py | Python | apache-2.0 | 1,184 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specifi | c language governing permissions and
# limitations under the License.
from marshmallow import fields, validate
import polyaxon_sdk
from polyaxon.polyflow.references.mixin import RefMixin
from polyaxon.schemas.base import BaseCamelSchema, BaseConfig
class PathRefSchema(BaseCamelSchema):
kind = fields.Str(allow_... |
sag-enorman/selenium | py/test/selenium/webdriver/firefox/ff_profile_tests.py | Python | apache-2.0 | 8,464 | 0.001418 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | either express or implied. See the License for the
# specific language governing | permissions and limitations
# under the License.
import base64
import os
import zipfile
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
try:
unicode
except NameError:
unicode = str
from selenium import webdriver
from selenium.webdriver.common.proxy import Pr... |
achon22/cs231nLung | project-a/labels.py | Python | mit | 343 | 0.052478 | #!/usr/bin/env python
def main():
f = open('stage1_solution.csv')
ones = 0
zer | os = 0
total = 0
for line in f:
if line[:3] == 'id,':
continue
line = line.strip().split(',')
label = int(li | ne[1])
if label == 1:
ones += 1
total += 1
zeros = total-ones
print float(zeros)/total
f.close()
if __name__ == '__main__':
main() |
yousrabk/mne-python | mne/viz/tests/test_raw.py | Python | bsd-3-clause | 4,727 | 0 | # Authors: Eric Larson <[email protected]>
#
# License: Simplified BSD
import os.path as op
import warnings
from numpy.testing import assert_raises
from mne import io, read_events, pick_types
from mne.utils import requires_version, run_tests_if_main
from mne.viz.utils import _fake_click
# Set our plotters to ... | otlib.pyplot as plt
raw = _get_raw()
# normal mode
raw.plot_psd(tmax=2.0)
# specific mode
picks = pick_types(raw.info, meg='mag', eeg=False)[:4]
raw.plot_psd(picks=picks, area_mode='range')
ax = plt.axes()
# if ax is supplied, picks must be, too:
assert_raises(ValueError, raw.plot_ps... | ot_psd_topo()
plt.close('all')
run_tests_if_main()
|
netsec-ethz/scion | tools/licensechecker.py | Python | apache-2.0 | 2,566 | 0.001949 | #!/usr/bin/env python3
import sys
import subprocess
license_texts = {
"#":"""
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | nt marker: %s" % first_line
| continue
if license_texts[comment_marker] not in header.decode("utf-8"):
not_ok[f] = "missing licence"
for f, reason in not_ok.items():
print("%s: %s" % (f, reason), file=sys.stderr)
if len(not_ok) > 0:
sys.exit(1)
if __name__ == "__main__":
main()
|
mileswwatkins/billy | billy/tests/fixtures/ex/__init__.py | Python | bsd-3-clause | 1,554 | 0 | metadata = {
"abbreviation": "ex",
"capitol_timezone": "Etc/UTC",
"legislature_name": "Example Legislature",
"lower_chamber_name": "House of Representatives",
"lower_chamber_term": 2,
"lower_chamber_title": "Representative",
"upper_chamber_name": "Senate",
"upper_chamber_term": 6,
"u... | "sessions": [
"S1", "Special1"
],
"start_year": 2011,
"end_year": 2012
},
{
"name": "T2",
"sessions": [
"S2", "Specia | l2"
],
"start_year": 2013,
"end_year": 2014
}
],
"session_details": {
"S0": {"start_date": 1250000000.0, "type": "primary",
"display_name": "Session Zero"},
"S1": {"start_date": 1300000000.0, "type": "primary",
"display_na... |
Eric89GXL/PySurfer | examples/plot_probabilistic_label.py | Python | bsd-3-clause | 1,653 | 0 | """
============================
Display Probabilistic Labels
============================
Freesurfer ships with some probabilistic labels of cytoarchitectonic
and visual areas. Here we show several ways to visualize these labels
to help characterize the location of your data.
"""
from os import environ
from os.path ... | vo", color="#F0F8FF", borders=3, scalar_thresh=.5)
brain.add_label("BA45_exvivo", color="#F0F8FF", alpha=.3, scalar_thresh=.5)
"""
Finally, with a few tricks, you can display the whole probabilistic map.
"""
subjects_dir = environ["SUBJECTS_DIR"]
l | abel_file = join(subjects_dir, "fsaverage", "label", "lh.BA6_exvivo.label")
prob_field = np.zeros_like(brain.geo['lh'].x)
ids, probs = read_label(label_file, read_scalars=True)
prob_field[ids] = probs
brain.add_data(prob_field, thresh=1e-5, colormap="RdPu")
|
LLNL/spack | var/spack/repos/builtin/packages/fasttree/package.py | Python | lgpl-2.1 | 1,234 | 0.001621 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Fasttree(Package):
"""FastTr | ee infers approximately-maximum-likelihood phylogenetic
trees from alignments of nucleotide or protein sequences.
FastTree can handle alignments with up to a million of sequences
in a reasonable amount of time and memory."""
homepage = "http://www.microbesonline.org/fasttree"
url | = "http://www.microbesonline.org/fasttree/FastTree-2.1.10.c"
version('2.1.10', sha256='54cb89fc1728a974a59eae7a7ee6309cdd3cddda9a4c55b700a71219fc6e926d', expand=False, url='http://www.microbesonline.org/fasttree/FastTree-2.1.10.c')
phases = ['build', 'install']
def build(self, spec, prefix):
... |
emilroz/openmicroscopy | components/tools/OmeroPy/src/omero/__init__.py | Python | gpl-2.0 | 3,189 | 0.000314 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Primary OmeroPy types
Classes:
- omero.client -- Main OmeroPy connector object
Copyright 2007, 2008 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
from omero_version import omero_version
... | f no
default is provided, the string must be of the
form: 'Image:1' or 'ImageI:1'. With a default,
a string consisting of just the ID is permissible
but not require | d.
"""
import omero
parts = proxy_string.split(":")
if len(parts) == 1 and default is not None:
proxy_string = "%s:%s" % (default, proxy_string)
parts.insert(0, default)
kls = parts[0]
if not kls.endswith("I"):
kls += "I"
kls = getattr(omero.model, kls, None)
if ... |
madcowfred/evething | thing/views/pi.py | Python | bsd-2-clause | 3,175 | 0.004094 | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | TRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWI | SE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
from django.conf import settings
from django.contrib.auth.decorators import login_required
from thing.models import * # NOPEP... |
drewet/shaderc | glslc/test/expect.py | Python | apache-2.0 | 15,233 | 0.000985 | # Copyright 2015 The Shaderc Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Stdout, NoOutputOnStderr):
"""Mixin class for checking that return code is zero and no output on
stdout and stderr."""
pass
class CorrectObjectFilePreamble(GlslCTest):
"""Provides methods for verifying preamble for a SPV object file."""
def verify_object_file_preamble(self, filename):
"""... | """
def read_word(binary, index, little_endian):
"""Reads the index-th word from the given binary file."""
word = binary[index * 4:(index + 1) * 4]
if little_endian:
word = reversed(word)
return reduce(lambda w, b: (w << 8) | ord(b), word, 0)
... |
BoasWhip/Black | Code/marketData.py | Python | mit | 5,694 | 0.019143 | # -*- coding: utf-8 -*-
import numpy as np
from pandas import read_csv as importDB
import pandas as pd
database = r'\\UBSPROD.MSAD.UBS.NET\UserData\ozsanos\RF\Desktop\Black\stockData.csv'
tickers = ['AAPL','ADBE','ADI','AMD','AXP','BRCM','C','GLD','GOOG','GS','HNZ','HPQ','IBM','MSFT','TXN','XOM']
dateRange = ... | 2011 = True
symbolSet = ['AAPL', 'GOOG', 'IBM', 'MSFT']
weights = [0.5,0.0,0.5,0.0]
print simulate(dateRange[is2011][0], dateRange[is2011][1], symbolSet, weights)
weights = [0.2,0.0,0.8,0.0]
print simulate(dateRange[is2011][0], dateRange[is2011][1], symbolSet, weights)
weights = [0.2,0.2,0.2,0.4]
print simulate(... | , dateRange[is2011][1], symbolSet, weights)
weights = [0.1,0.1,0.8,0.0]
print simulate(dateRange[is2011][0], dateRange[is2011][1], symbolSet, weights)
print('\n')
# Quiz 2
is2011 = False
symbolSet = ['BRCM', 'ADBE', 'AMD', 'ADI']
weights = [0.0,0.2,0.8,0.0]
print simulate(dateRange[is2011][0], dateRange[is201... |
ActiveState/code | recipes/Python/59892_Testing_if_a_variable_is_defined/recipe-59892.py | Python | mit | 190 | 0 | # Ensure variable is defined
try:
x |
except NameEr | ror:
x = None
# Test whether variable is defined to be None
if x is None:
some_fallback_operation()
else:
some_operation(x)
|
ox-it/moxie | moxie/tests/test_cors_views.py | Python | apache-2.0 | 3,333 | 0.0048 | import unittest, json
from moxie.core.app import Moxie
from moxie.core.views import ServiceView
class TestCORSWithCredentials(ServiceView):
cors_allow_headers = 'X-DAVE'
cors_allow_credentials = True
cors_max_age = 20
methods = ['GET', 'OPTIONS', 'PUT']
def handle_request(self):
return ... | ontent(self):
with self.app.test_client() as c:
rv = c.open('/nocreds', method='OPTIONS', headers=[('Accept', 'application/json'), ('Origin', 'foo.domain')])
self.assertEqual(rv.data, '')
def test_actual_content(self):
with self.app.test_client() as c:
rv = c.get... | ual(data['name'], 'Dave')
|
JioCloud/oslo.log | oslo_log/formatters.py | Python | apache-2.0 | 8,844 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ing if the log level is
debug.
For information about what variables are available for the formatter see:
http://docs.python.org/library/logging.html#formatter
If available, uses the context value stored in TLS - local.store.context
"""
def __init__(self, *args, **kwargs):
| """Initialize ContextFormatter instance
Takes additional keyword arguments which can be used in the message
format string.
:keyword project: project name
:type project: string
:keyword version: project version
:type version: string
"""
self.project = ... |
apophys/freeipa | ipalib/install/service.py | Python | gpl-3.0 | 4,662 | 0 | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
Base service installer module
"""
from ipalib.util import validate_domain_name
from ipapython.install import common, core, typing
from ipapython.install.core import group, knob
def prepare_only(obj):
"""
Decorator which makes an inst... | nstall')
@group
class ServiceInstallInterface(common.Installable,
common.Interactive,
core.Composite):
"""
Interface common to all service installers
"""
description = "Basic"
domain_name = knob(
str, None,
description="p... |
"(not necessarily related to the current hostname)",
cli_names='--domain',
)
@domain_name.validator
def domain_name(self, value):
validate_domain_name(value)
servers = knob(
# pylint: disable=invalid-sequence-index
typing.List[str], None,
de... |
hjanime/bcbio-nextgen | bcbio/rnaseq/cufflinks.py | Python | mit | 10,155 | 0.001871 | """Assess transcript abundance in RNA-seq experiments using Cufflinks.
http://cufflinks.cbcb.umd.edu/manual.html
"""
import os
import tempfile
from bcbio.utils import get_in, file_exists, safe_makedir
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import config_utils
from bcbio.provena... | sembly(gtf_file, clean=None, dirty=None):
"""
clean the likely garbage transcripts from the GTF file including:
1. any novel single-exon transcripts
2. any features with an unknown strand
"""
base, ext = os.path.splitext(gtf_file)
db = gtf.get_gtf_db(gtf_file, in_memory=True)
clean = cle... | base + ".dirty" + ext
if file_exists(clean):
return clean, dirty
with open(clean, "w") as clean_handle, open(dirty, "w") as dirty_handle:
for gene in db.features_of_type('gene'):
for transcript in db.children(gene, level=1):
if is_likely_noise(db, transcript):
... |
wrouesnel/ansible | test/runner/lib/sanity/pslint.py | Python | gpl-3.0 | 5,220 | 0.001533 | """Sanity test using PSScriptAnalyzer."""
from __future__ import absolute_import, print_function
import collections
import json
import os
import re
from lib.sanity import (
SanitySingleVersion,
SanityMessage,
SanityFailure,
SanitySuccess,
SanitySkipped,
)
from lib.util import (
SubprocessErro... | path, code = ignore_entry.split(' ', 1)
| if not os.path.exists(path):
invalid_ignores.append((line, 'Remove "%s" since it does not exist' % path))
continue
ignore[path][code] = line
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] in ('.ps1', '.psm1', '.psd1') an... |
sozlukus/sozlukus.com | sozlukus/registration/tests/default_backend.py | Python | mit | 8,430 | 0 | import datetime
from django.conf import settings
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from registration.forms import RegistrationForm
from registration.ba... | 'registration/registration_form.html')
self.failUnless(isinstance(resp.context['form'],
RegistrationForm))
def test_registration(self):
"""
Registration creates a new inactive account and a new profile
with activation key, populates the correct account da... | ent.post(reverse('registration_register'),
data={'username': 'bob',
'email': '[email protected]',
'password1': 'secret',
'password2': 'secret'})
self.assertRedirects(re... |
CareerVillage/slack-moderation | src/accounts/models.py | Python | mit | 446 | 0.002242 | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class AuthToken(models.Model):
"""
Store | auth tokens returned by the moderation backend service (Slack)
"""
service_name = models.TextField()
service_entity_auth_name = models.TextField()
service_entity_auth_i | d = models.TextField()
service_auth_token = models.TextField()
username = models.CharField(max_length=50)
|
marshall/mintest | mintest.py | Python | apache-2.0 | 919 | 0.004353 | #!/usr/bin/env python
#
# mintest - a minimal C unit testing framework, inspired by minunit
#
# Copyright 2013, Marshall Culpepper
# Licensed under the Apache License, Version 2.0
#
# waf tool for configuring and building mintest
import os
this_dir = os.path.abspath(os.path.dirname(__file__))
def options(opt):
o... | t_format = 'MT_OUT_JSON'
cfg.env.append_unique('CFLAGS', ['-DMT_OUT_FORMAT=%s' % out_format])
cfg.env.append_unique('CXXFLAGS', ['-DMT_OUT_FORMAT=%s' % out_format])
cfg.env.append_unique('INCLUDES', [os.path.join(this_dir, 'include')])
def build(bld):
bld.env.MINTEST_SOURCES = bld.root | .ant_glob(os.path.join(this_dir[1:], 'src', '**/*.c'))
|
behas/bitcoingraph | tests/rpc_mock.py | Python | mit | 2,105 | 0 | from bitcoingraph.bitcoind import BitcoinProxy, BitcoindException
from pathlib import Path
import json
TEST_DATA_PATH = "tests/data"
class BitcoinProxyMock(BitcoinProxy):
def __init__(self, host=None, port=None):
super().__init__(host, port)
self.heights = {}
self.blocks = {}
... | f.ge | trawtransaction(tx_id, verbose))
return results
|
Zorro666/renderdoc | docs/python_api/examples/renderdoc/decode_mesh.py | Python | mit | 9,433 | 0.02417 | import sys
# Import renderdoc if not already imported (e.g. in the UI)
if 'renderdoc' not in sys.modules and '_renderdoc' not in sys.modules:
import renderdoc
# Alias renderdoc for legibility
rd = renderdoc
# We'll need the struct data to read out of bytes objects
import struct
# We base our data on a MeshFormat, ... | of the attribute here
# while others will tightly pack
fmt = meshOutputs[i].format
accumOffset += (8 if fmt.compByteWidth > 4 else 4) * fmt.compCount
return meshOutputs
def getIndices(controller, mesh):
# Get the character for the | width of index
indexFormat = 'B'
if mesh.indexByteStride == 2:
indexFormat = 'H'
elif mesh.indexByteStride == 4:
indexFormat = 'I'
# Duplicate the format by the number of indices
indexFormat = str(mesh.numIndices) + indexFormat
# If we have an index buffer
if mesh.indexResourceId != rd.ResourceId.Null():
... |
ChinaMassClouds/copenstack-server | openstack/src/horizon-2014.2/openstack_dashboard/openstack/common/utils.py | Python | gpl-2.0 | 515 | 0 |
def mysql_read():
mysql_info = {}
with open('/etc/openstack.cfg', 'r') as f:
for i in f.readlines():
if i.split('=', 1)[0] in ('DASHBOARD_HOST',
'DASHBOARD_PASS',
'DASHBOARD_NAME',
| 'DASHBOARD_USER',
'DASHBOARD_PORT'):
data = i.split('=', 1)
mysql_info | [data[0]] = data[1].strip()
return mysql_info
|
persepolisdm/persepolis | persepolis/scripts/mac_notification.py | Python | gpl-3.0 | 1,424 | 0.000702 | # -*- coding: utf-8 -*-
# This pr | ogram 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even th... |
stephenrjones/geoq | geoq/mgrs/__init__.py | Python | mit | 230 | 0.008696 | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C- | F600, and
# is subject to the Rig | hts in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
|
asnorkin/sentiment_analysis | site/lib/python2.7/site-packages/scipy/odr/odrpack.py | Python | mit | 41,254 | 0.000654 | """
Python wrappers for Orthogonal Distance Regression (ODRPACK).
Notes
=====
* Array formats -- FORTRAN stores its arrays in memory column first, i.e. an
array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
ef... | t')
if I[3] != 0:
problems.append('WE incorrect')
if I[4] != 0:
problems.append('WD incorrect')
elif I[0] == 4:
problems.append('Error in derivatives')
elif I[0] == 5:
problems.append('Error occurred in callback')
el... | == 6:
problems.append('Numerical error detected')
return problems
else:
return [stopreason]
class Data(object):
"""
The data to fit.
Parameters
----------
x : array_like
Observed data for the independent variable of the regression
y : array_like, opt... |
shahzebsiddiqui/BuildTest | buildtest/cli/__init__.py | Python | gpl-3.0 | 15,098 | 0.002318 | """
buildtest cli: include functions to build, get test configurations, and
interact with a global configuration for buildtest.
"""
import argparse
import os
from termcolor import colored
from buildtest import BUILDTEST_VERSION, BUILDTEST_COPYRIGHT
from buildtest.defaults import BUILD_REPORT
from buildtest.schemas.def... | ge="%(prog)s [options] [COMMANDS]",
epilog=epilog_str,
)
parser.add_argument(
"-V",
"--version",
action="version",
version=f"%(prog)s version {BUILDTEST_VERSION}",
)
parser.add_argument(
"-c", "--config_file", help="Specify alternate configuration file"
... | parsers)
config_menu(subparsers)
report_menu(subparsers)
inspect_menu(subparsers)
schema_menu(subparsers)
cdash_menu(subparsers)
subparsers.add_parser("docs", help="Open buildtest docs in browser")
subparsers.add_parser("schemadocs", help="Open buildtest schema docs in browser")
return... |
agusmakmun/dracos-markdown-editor | martor/fields.py | Python | gpl-3.0 | 535 | 0 | # -*- coding: u | tf-8 -*-
from __future__ import unicode_literals
from django import forms
from .settings import MARTOR_ENABLE_LABEL
from .widgets import MartorWidget
class MartorFormField(forms.CharField):
def __init__(self, *args, **kwargs):
# to setup the editor without label
if not MARTOR_ENABLE_LABEL:
... | artorFormField, self).__init__(*args, **kwargs)
if not issubclass(self.widget.__class__, MartorWidget):
self.widget = MartorWidget()
|
anchor/vaultaire-tools | telemetry/marquise_throughput.py | Python | bsd-3-clause | 14,550 | 0.010584 | #!/usr/bin/env python
'''use marquise_telemetry to build throughput info as visible from the client
e.g.:
$ marquse_telemetry broker | marquise_throughput.py
'''
import sys
from time import *
import os
import fcntl
class TimeAware(object):
'''simple timing aware mixin
The default implementation of o... | bins_to_check = k/self.ticklen
return sum(self.bins[-bins_to_check:])
def mean(self, k=60):
'''return the mean entries per second over the last k seconds
'''
if self.totalticktime < k:
k = self.totalticktime # Only average over t | he time we've been running
bins_to_check = k/self.ticklen
return self.sum(k) / float(bins_to_check) if bins_to_check else 0
@property
def bins(self):
'''get bins in time order, oldest to newest'''
self.check_for_tick_changed()
return self._bins[self.current_bin+1:]+self.... |
jonparrott/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/proto/datatransfer_pb2_grpc.py | Python | apache-2.0 | 16,649 | 0.005346 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.bigquery_datatransfer_v1.proto import datatransfer_pb2 as google_dot_cloud_dot_bigquery_dot_datatransfer__v1_dot_proto_dot_datatransfer__pb2
from google.cloud.bigquery_datatransfer_v1.proto import transfer_pb2 as google... | e transfer of their data from other Google P | roducts into BigQuery.
This service contains methods that are end user exposed. It backs up the
frontend.
"""
def GetDataSource(self, request, context):
"""Retrieves a supported data source and returns its settings,
which can be used for UI rendering.
"""
context.set_code(grpc.StatusCode.UNIMPL... |
codewarrior0/Shiboken | tests/py3kcompat.py | Python | gpl-2.0 | 1,372 | 0.002915 | # -*- coding: utf-8 -*-
#
# This file is part of the Shiboken Python Bindings Generator project.
#
# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
#
# Contact: PySide team <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le... | USA
import sys
IS_PY3K = sys.version_info[0] == 3
if IS_PY3K:
def unicode(s):
return s
def b(s):
return bytes(s, "UTF8")
def l(n):
return n
long = int
else:
def b(s):
return s
def l(n):
return long(n)
unicode = unicode
l | ong = long
|
ninastoessinger/word-o-mat | word-o-mat.roboFontExt/lib/wordomat.py | Python | mit | 30,817 | 0.005584 | # coding=utf-8
#
"""
word-o-mat is a RoboFont extension that generates test words for type testing, sketching etc.
I assume no responsibility for inappropriate words found on those lists and rendered by this script :)
v2.2.4 / Nina Stössinger / 31.05.2015
Thanks to Just van Rossum, Frederik Berlaen, Tobias Frere-Jones... | ModeCallback, sizeStyle="small")
| rePanelOn = 1 if self.matchMode == "grep" else 0
self.g2.matchMode.set(rePanelOn)
# Text/List match mode
self.g2.textMode = Box((padd,29,-padd,133))
labelY = [2, 42]
labelText = ["Require these letters in each word:", "Require one per group in each word:"]
for i in ra... |
pch957/python-bts-v0.9 | scripts/bts_publish_market.py | Python | mit | 8,079 | 0.000124 | #!/usr/bin/env python2
# coding=utf8 sw=1 expandtab ft=python
from __future__ import print_function
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
from autobahn.wamp import auth
from autobahn.twisted.util import sleep
from ... | arket.bts_client.chain_info["block_interval"])
while my_tok | en == Component.task_token:
try:
Component.publish_market.execute()
except Exception as e:
print(e)
now = time.time()
nexttime = int(time.time()/period + 1)*period - now
yield sleep(nexttime+1)
def onLeave(self, details):
... |
Sverchok/SverchokRedux | core/compiler.py | Python | gpl-3.0 | 376 | 0.007979 | from .execute import GraphNode
from . | import preprocess
def compile(layout_dict):
preprocess.proprocess(layout_dict)
# get nodes without any outputs
root_nodes = layout_dict["nodes"].keys() - {l[0] for l in layout_dict["links"]}
graph_dict = {}
ou | t = [GraphNode.from_layout(root_node, layout_dict, graph_dict) for root_node in root_nodes]
return out
|
quimaguirre/diana | diana/toolbox/parse_clinical_trials.py | Python | mit | 12,367 | 0.03105 | ##############################################################################
# Clinical trials parser
#
# eg 2013-2016
##############################################################################
import cPickle, os, re
def main():
#base_dir = "../data/ct/"
base_dir = "/home/eguney/data/ct/"
file_name ... | )
return drug_to_diseases
def get_ct_data(base_dir, includ | e_other_names=True, dump_file=None):
if dump_file is not None and os.path.exists(dump_file):
values = cPickle.load(open(dump_file))
#drug_to_ctids, ctid_to_conditions, ctid_to_values = values
return values
drug_to_ctids = get_interventions(base_dir, include_other_names)
ctid_to_conditions = get_ctid_to_c... |
jmchilton/galaxy-central | galaxy/app.py | Python | mit | 1,636 | 0.017115 | from galaxy import config, tools, jobs, web
import galaxy.model.mapping
class UniverseApplication( object ):
"""Encapsulates the state of a Universe application"""
def __init__( self, **kwargs ):
# Read config file and check for errors
self.config = config.Configuration( **kwargs )
self... | Initialize the tools
self.toolbox = tools.ToolBox( self.config.tool_config, self.config.tool_path )
# Start the job queue
self.job_queue = jobs.JobQueue( self.config.job_queue_workers, self )
self.heartbeat = None
# Start the heartbeat process if configured and available
... | self.heartbeat.start()
def shutdown( self ):
self.job_queue.shutdown()
if self.heartbeat:
self.heartbeat.shutdown() |
okfn/jsontableschema-py | tests/types/test_yearmonth.py | Python | mit | 842 | 0 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
| from tableschema import types
from tableschema.config import ERROR
# Tests
@pytest.mark.parametrize('format, value, result', [
('default', [2000, 10], (2000, 10)),
('default', (2000, 10), (2000, 10)),
('default', '2000-10', (2000, 10)),
('default | ', (2000, 10, 20), ERROR),
('default', '2000-13-20', ERROR),
('default', '2000-13', ERROR),
('default', '2000-0', ERROR),
('default', '13', ERROR),
('default', -10, ERROR),
('default', 20, ERROR),
('default', '3.14', ERROR),
('default', '', ERROR),
])
def test_cast_yearmonth(format, valu... |
gabegaster/python-timer | timer/timer.py | Python | mit | 3,254 | 0.000307 | '''
# Gabe Gaster, 2013
#
# about every minute, eta will report how many iterations
# have been performed and the Expected Time to Completion (the E.T.C.)
#
#####################################################################
#
# Examples:
#
import timer
for stuff in timer.show_progress(range(100)):
# .... a... | cified, look to the length of iterable (if
it's defined in __len__). |
If there is no length, then report number (instead of percent)
done, and report time per iteration (instead of ETA).
"""
name, length = get_name_length(iterable, length)
start = last_update = time.time()
# if the length is unknown, don't estimate completion time, but
# still show periodi... |
asmaps/as_poweradmin | as_poweradmin/main/migrations/0001_initial.py | Python | mit | 4,679 | 0.007908 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CustomerProfile'
db.create_table(u'main_customerprofile',... | '})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}... | enttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.mod... |
Multiscale-Genomics/mg-dm-api | tests/test_meta_modification.py | Python | apache-2.0 | 1,367 | 0.000732 | """
.. See the NOTICE file distributed with this work for additio | nal information
regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
| http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governin... |
KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/core/checks/utils.py | Python | gpl-3.0 | 245 | 0 | import copy
from django.conf import settings
def patch_middleware_message(error):
if settings.MIDDLEWARE is None:
error = copy.copy(error)
error.msg = error.msg.replace('MIDDLEWARE', 'MIDDLEWARE_CLASSES | ')
return error
| |
wendlers/mpfshell | setup.py | Python | mit | 673 | 0 | #!/usr/bin/env python
from setuptools import setup
from mp import version
setup(
name="mpfshell",
version=version.FULL,
description="A simple shell based file explorer for ESP8266 and WiPy "
"Micropython devices.",
author="Stefan Wendler",
author_email="[email protected]",
url="https: | //github.com/wendlers/mpfshell",
download_url="https://github.com/wendlers/mpfshell/archive/0.8.1.tar.gz",
install_requires=["pyserial", "colorama", "websocket_client"],
packages=["mp"],
keywords=["micropython", "shell", "file transfer", "development"],
classifiers=[],
| entry_points={"console_scripts": ["mpfshell=mp.mpfshell:main"]},
)
|
jasonamyers/pynash-click | complex/complex/logger.py | Python | mit | 467 | 0 | import | logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
file_log_handler = logging.FileHandler('combinator-cli.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
format_string = '%(asctime)s - %(name)s - %(levelname)s - %(... | |
cfjhallgren/shogun | examples/undocumented/python/features_dense_io.py | Python | gpl-3.0 | 325 | 0.046154 | #!/usr/bin/env python
parameter_list=[[]]
def features_dense_io():
from shogun import RealFeatu | res, CSVFile
feats=RealFeatures()
f=CSVFile("../data/fm_train_real.dat","r")
f.set_delimiter(" ")
feats.load(f)
return feats
if __name__= | ='__main__':
print('Dense Real Features IO')
features_dense_io(*parameter_list[0])
|
Antiun/stock-logistics-workflow | stock_move_backdating/__openerp__.py | Python | agpl-3.0 | 1,703 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012+ BREMSKERL-REIBBELAGWERKE EMMERLING GmbH & Co. KG
# Author Marco Dieckhoff
# Copyright (C) 2013 Agile Business Group sagl (<h | ttp://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# |
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero G... |
psychopy/psychopy | psychopy/demos/coder/misc/encrypt_data.py | Python | gpl-3.0 | 1,545 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo to illustrate encryption and decryption of a data file using pyFileSec
"""
from pyfilesec import SecFile, GenRSA
import os
# Logging is available, optional:
# from psychopy import logging
# logging.console.setLevel(logging.INFO)
# pfs.logging = logging
# We nee... | :
sf.encrypt(pubkey)
msg = 'ENCRYPT it:\n file name: "%s"\n contents (base64): "%s . . ."'
print(msg % (sf.file, sf.snippet))
pr | int(' is encrypted: %s' % sf.is_encrypted)
# To decrypt the file, use the matching RSA private key (and its passphrase):
sf.decrypt(privkey, passphrase)
msg = 'DECRYPT it:\n file name: "%s"\n contents: "%s"'
print(msg % (sf.file, sf.snippet))
print(' is encrypted: %s' % sf.is_encrypted)
# clean-up the tmp files:
... |
triump0870/movie_task | src/movie/models.py | Python | mit | 719 | 0.006954 | from django.db import models
from django.conf import settings
# Create your models here.
User = settings.AUTH_USER_MODEL
class Genre(models.Mode | l):
genre = models.CharField(max_length=30)
def __unicode__(self):
return self.genre
class Movie(models.Model):
name = models.CharField(max_length=255)
director = models.CharField(max_length=255)
genre = models.ManyToManyField(Genre, null=False, blank=False)
release = models.DateField(... | ,on_delete=models.CASCADE)
def __unicode__(self):
return self.name
|
rasbt/protein-science | scripts-and-tools/strip_h/strip_h.py | Python | gpl-3.0 | 5,260 | 0.009316 | # Sebas | tian Raschka 2014
# Python 3 strip hydrogen atoms from PDB files
#
# run
# ./stip_h.py -h
# for help
#
import os
class Pdb(object):
""" Object that allows operations with protein files in PDB format. """
def __init__( | self, file_cont=[], pdb_code=""):
self.cont = []
self.fileloc = ""
if isinstance(file_cont, list):
self.cont = file_cont[:]
elif isinstance(file_cont, str):
try:
with open(file_cont, 'r') as pdb_file:
self.cont = [row.strip() fo... |
westurner/pkgsetcomp | pkgsetcomp/pyrpo.py | Python | bsd-3-clause | 33,675 | 0.000475 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
"""Search for code repositories and generate reports"""
import datetime
import errno
import logging
import os
import pprint
import re
import subprocess
import sys
from collections import deque, namedtuple
from distutils.util import convert_p... | dtuple
return self
@property
def relpath(self):
here = os.path.abspath(os.path.curdir)
relpath = os.path.relpath(self.fpath, here)
| return relpath
@cached_property
def _namedtuple(cls):
return namedtuple(
''.join((str.capitalize(cls.label), "Rev")),
(f[0] for f in cls.fields))
def unique_id(self):
"""
:returns: str
"""
pass
def status(self):
"""
... |
mfelsche/dwd_weather_data | weather/data/solar.py | Python | apache-2.0 | 1,704 | 0.001763 | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License"... | issions and limitations
# under the License.
#
# However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.
from .base import DWDDataSourcePa | rser
class SolarRadiationParser(DWDDataSourceParser):
NAME = "solar"
def get_name(cls):
return cls.NAME
def extract_data(self, row):
return {
"sunshine_duration": self.get_float(row[3]), # Stundensumme der Sonnenscheindauer in minutes
"diffuse_sky_radiation": sel... |
WenqinSHAO/rtt | localutils/benchmark.py | Python | mit | 18,510 | 0.004646 | """
benchmark.py provides functions for various evaluation tasks in this work
"""
import collections
import sys
import munkres
import numpy as np
def evaluation(fact, detection):
"""classify the detections into true positive, true negative, false positive and false negative
Args:
fact (list of int): ... | return_match (bool): returns the matching tuple idx [(fact_idx, detection_idx),... | ] if set true
Returns:
dict: {'tp':int, 'fp':int, 'fn':int, 'precision':float, 'recall':float, 'dis':float, 'match': list of tuple}
"""
if len(fact) == 0:
summary = dict(tp=None, fp=len(detection), fn=None,
precision=None, recall=None,
dis=None... |
avanzosc/odoo-addons | stock_orderpoint_generation/__manifest__.py | Python | agpl-3.0 | 483 | 0 | # Copyright 2021 Daniel Campos - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.h | tml
{
"name": "Stock Orderpoint Generation",
"version": "14.0.1.0.0",
"license": "AGPL-3",
"depends": [
"stock",
],
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"category": "Custom",
"data": [
"security/ir.model.access.csv",
"wizards/stock_orderp... | t_generator_view.xml",
],
"installable": True,
}
|
sunrin92/LearnPython | 0-ThinkPython/get_wordlist.py | Python | mit | 158 | 0 | def getWordlist(wordtxt):
fin = open(word | txt)
words = []
for line in fin:
word = line.strip()
words.append(word)
retur | n words
|
laborautonomo/pip | pip/vcs/mercurial.py | Python | mit | 5,087 | 0.000197 | import os
import tempfile
import re
from pip.util import call_subprocess
from pip.util import display_path, rmtree
from pip.log import logger
from pip.vcs import vcs, VersionControl
from pip.download import path_to_url
from pip._vendor.six.moves import configparser
class Mercurial(VersionControl):
name = 'hg'
... | full_egg_name = '%s-%s' % (egg_project_name, tag_revs[current_rev])
elif current_rev in branch_revs:
# It's the tip of a branch
full_egg_name = '%s-%s' % (
egg_project_name,
branch_revs[current_rev],
)
else:
full_egg_name ... | .register(Mercurial)
|
ptcrypto/p2pool-adaptive | extra_modules/x11_hash/test.py | Python | gpl-3.0 | 344 | 0.008721 | import quark_hash
import weakref
import binascii
import Str | ingIO
from binascii import unhexlify
teststart = '700000005d385ba114d079970b29a9418fd0549e7d68a95c7f168621a314201000000000578586d149fd07b22f3a8a347c516de7052f034d2b76ff68e0d6ecff9b77a45489e3fd511 | 732011df0731000';
testbin = unhexlify(teststart)
hash_bin = x11_hash.getPoWHash(testbin) |
PDOK/data.labs.pdok.nl | data/bag-brk/modules/FindApartment.py | Python | mit | 492 | 0.002033 | # Initialize the lookup table for apar | tments
import csv
lut = []
reader = csv.DictReader(open('data/Apprechtcomplex-met-Grondpercelen | -mei2017.csv'), fieldnames=['apartment', 'parcel'])
# Populate the lookup table: allows file handle to be released.
for row in reader:
lut.append(row)
def find_apartment(apartment):
parcel_matches = []
for entry in lut:
if entry['apartment'] == apartment:
parcel_matches.append(entry[... |
dypublic/PyConChina2016 | fabfile.py | Python | mit | 690 | 0 | # -*- coding: utf-8 -*-
from os.path import dirname, realpath, join
from fabric.api import local, env
from fabric.contrib.project import rsync_project
env.user = 'imust'
env.hosts = ['119.254.110.163']
VPS_DEPLOY_PATH = '/home/imust/data/www/public/'
PROJECT_ROOT_DIR = realpath(dirname(__file__))
DIST_DIR = join(PRO... | + '/'
| VENV_PYTHON = join(PROJECT_ROOT_DIR, 'venv', 'bin', 'python2')
def clean():
local(u'rm -rf {}'.format(DIST_DIR))
def build():
clean()
local(u'{python} bin/app.py -g'.format(python=VENV_PYTHON))
def deploy_vps():
build()
rsync_project(remote_dir=VPS_DEPLOY_PATH,
local_dir=DIST... |
Southpaw-TACTIC/TACTIC | src/pyasm/application/maya/maya_environment.py | Python | epl-1.0 | 1,612 | 0.003102 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | in this package'''
def set_up(info):
# set up application environment, by getting information from the info
# object. This info object, contains data retrieved from some
# external source
# get the environment | and application
env = AppEnvironment.get()
from maya_app import Maya, Maya85
# detect if this is Maya 8.5 or later
app = None
try:
import maya
app = Maya85()
except ImportError:
from pyasm.application.maya import Maya
app... |
UManPychron/pychron | pychron/dvc/share.py | Python | apache-2.0 | 4,172 | 0.000479 | # ===============================================================================
# Copyright 2015 Jake R | oss
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lic | ense.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the ... |
shubhamdhama/zulip | zproject/dev_settings.py | Python | apache-2.0 | 6,566 | 0.000761 | import os
import pwd
from typing import Optional, Set, Tuple
ZULIP_ADMINISTRATOR = "[email protected]"
# We want LOCAL_UPLOADS_DIR to be an absolute path so that code can
# chdir without having problems accessing it. Unfortunately, this
# means we need a duplicate definition of DEPLOY_ROOT with the one in
# ... | = {
"full_name": "cn",
"avatar": "thumbnailPhoto",
# This won't do much unless one changes | the fact that
# all users have LDAP_USER_ACCOUNT_CONTROL_NORMAL in
# zerver/lib/dev_ldap_directory.py
"userAccountControl": "userAccountControl",
}
elif FAKE_LDAP_MODE == 'b':
LDAP_APPEND_DOMAIN = 'zulip.com'
AUTH_LDAP_USER_ATTR_MAP = {
"full_... |
chienlieu2017/it_management | odoo/addons/procurement/models/procurement.py | Python | gpl-3.0 | 12,497 | 0.002641 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import OperationalError
from odoo import api, fields, models, registry, _
from odoo.exceptions import UserError
import odoo.addons.decimal_precision as dp
PROCUREMENT_PRIORITIES = [('0', 'Not urgent'), (... | :
try:
if procurement._assign():
res = procurement._run()
| if res:
procurement.write({'state': 'running'})
else:
procurement.write({'state': 'exception'})
else:
procurement.message_post(body=_('No rule matching this procurement'))
... |
ongair/yowsup | yowsup/registration/existsrequest.py | Python | mit | 938 | 0.009595 | from yowsup.common.http.warequest import WARequest
from yowsup.common.http.waresponseparser import JSONResponseParser
from yowsup.env import YowsupEnv
class WAExistsReque | st(WARequest):
def __init__ | (self,cc, p_in, idx):
super(WAExistsRequest,self).__init__()
self.addParam("cc", cc)
self.addParam("in", p_in)
self.addParam("id", idx)
self.addParam("lg", "en")
self.addParam("lc", "GB")
self.addParam("token", YowsupEnv.getCurrent().getToken(p_in))
self... |
AloneGu/amira_image_cls | img_cls/model/img_process.py | Python | mit | 6,753 | 0.002369 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: Jackling Gu
@file: img_process.py
@time: 2017-06-13 11:13
"""
from ..util import getcfg, data_load, get_abspath, get_y_labels, preprocess_img
from sklearn.preprocessing import LabelEncoder
from keras.models import load_model, Model
from keras.callbacks import CSVLo... | (self):
| # use data augmentation
datagen = ImageDataGenerator(
shear_range=0.15,
rotation_range=0.15,
zoom_range=0.15,
vertical_flip=True,
horizontal_flip=True) # randomly flip images
# self.model.fit(self.x, self.binary_y, epochs=self.epoch, validat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.