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 |
|---|---|---|---|---|---|---|---|---|
upTee/upTee | uptee/wsgi.py | Python | bsd-3-clause | 1,132 | 0.000883 | """
WSGI config for uptee project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should ex | pose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom on... | combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "uptee.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting poin... |
koroshiya/JPyReader | rarfile/setup.py | Python | mit | 961 | 0.023933 | #! /usr/bin/env python
from distutils.core import setup
import rarfile
ver = rarfile.__version__
ldesc = open("README.rst").read().strip()
sdesc = ldesc.split('\n')[0].split(' - ')[1].strip()
setup(
name = "rarfile",
version = ver,
description = sdesc,
long_description = ldesc,
author = "Marko K... | proved :: ISC License (ISCL)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Archiving :: Com | pression",
]
)
|
jordic/django_tiny_shop | demo/ipy_user_conf.py | Python | bsd-3-clause | 632 | 0.001582 | """
Makes IPython import all of your projects models when shell is started.
1. Save as ipy_user_conf.py in project root
2. | ./manage.py shell
3. profit
"""
import IPython.ipapi
ip = IPython.ipapi.get()
def main():
imported = "\nImported models:\n\n"
try:
from django.db.models.loading import get_models
for m in get_models():
try:
ip.ex("from %s import %s" % (m.__module__, m.__name__))
... | except ImportError:
pass
print imported
except ImportError:
pass
main() |
trizt/osquery | tools/formatting/git-clang-format.py | Python | bsd-3-clause | 18,615 | 0.000967 | #!/usr/bin/env python
#
#===- git-clang-format - ClangFormat Git Integration ---------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LLVM-LICENSE.TXT for details.
#
#===---------------------------------... | oved from
args and placed in `dash_dash`.
If "--" is present (i.e., `dash_dash` is non-empty), the argument to its
left (if present) is taken as commit. Otherwise, the first argument is
checked if it is a commit or a file. If commit is not given,
`default_commit` | is used."""
if dash_dash:
if len(args) == 0:
commit = default_commit
elif len(args) > 1:
die('at most one commit allowed; %d given' % len(args))
else:
commit = args[0]
object_type = get_object_type(commit)
if object_type not in ('commit', ... |
Samsung/ADBI | arch/arm/tests/arm_dp_imm.py | Python | apache-2.0 | 1,486 | 0.010767 | import random
from test import *
from branch import *
INSN = 'and eor sub rsb add adc sbc rsc tst teq cmp cmn orr mov bic mvn'.split()
NORN = 'mov m | vn'.split()
NORD = 'cmp cmn tst teq'.split()
def rotate(val, c):
return ((val >> c) | (val << (32 - c))) & 0xffffffff
def test(insn, s, flags, rd, rn, rnval, imm8, rot):
name = 'test_dp_imm_%s' % tn()
cleanup = asm_wrap(name, rd, {rn:rnval}, flags)
print '%s_tinsn:' % name
if 1:... | %i' % (insn, rn, imm8, rot)
else:
print ' %s%s %s, %s, #%i, %i' % (insn, s, rd, rn, imm8, rot)
else:
v = rotate(imm8, rot)
if insn in NORN:
print ' %s%s %s, #%i // %x ror %i ' % (insn, s, rd, v, imm8, rot)
elif insn in NORD:
print ' ... |
tst-ahernandez/earthenterprise | earth_enterprise/src/server/wsgi/serve/snippets/data/metainfo_by_fieldpath.py | Python | apache-2.0 | 24,676 | 0.001621 | #!/usr/bin/python
#
# Copyright 2017 Google 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 a... | age_intl_url:value": {
"abstract_fieldpath": "end_snippet.default_web_page_ | intl_url:value",
"default_value": null,
"description": "Default location of web page.",
"empty_concrete_fieldpath": "end_snippet.default_web_page_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "default_web_page_intl_url:value",
"presence": "... |
hexlism/css_platform | sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/geoa/fields.py | Python | apache-2.0 | 2,340 | 0.005983 | import json
from wtforms.fields import TextAreaField
from shapely.geometry import shape, mapping
from .widgets import LeafletWidget
from sqlalchemy import func
import geoalchemy2
#from types import NoneType
#from .. import db how do you get db.session in a Field?
class JSONField(TextAreaField):
def _value(self):
... |
if valuelist:
value = valuelist[0]
if not value:
self.data = None
return
try:
self.data = self.from_json(value)
except ValueError:
| self.data = None
raise ValueError(self.gettext('Invalid JSON'))
def to_json(self, obj):
return json.dumps(obj)
def from_json(self, data):
return json.loads(data)
class GeoJSONField(JSONField):
widget = LeafletWidget()
def __init__(self, label=None, validators=Non... |
fevxie/odoo-infrastructure | infrastructure/models/server_configuration.py | Python | agpl-3.0 | 964 | 0 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import mo | dels, fields
class server_configuration(models.M | odel):
""""""
_name = 'infrastructure.server_configuration'
_description = 'server_configuration'
name = fields.Char(
string='Name',
required=True
)
distrib_codename = fields.Char(
string='Distribution Codename',
required=True
)
install_command_i... |
reinaldoc/dbsync | source/converter/StringReplace.py | Python | gpl-2.0 | 612 | 0.03268 | """
StringReplace - a converter to replace section(s) of a string to strings passed
as parameters
"""
from util.Strings import Strings
class StringReplace(object):
def __init__(self, data, args=()):
"""
Receive the data to be converted and parameters.
"""
| self.value = data
if not data:
return
try:
s_from = args[0]
s_to = args[1]
self.value = Strings.replace_string(data, s_from | , s_to)
except IndexError:
print("Error: StringReplace takes exactly 2 arguments (%s given): %s" % (len(args), args) )
except Exception, e:
print(e)
def get_value(self):
return self.value
|
hasgeek/funnel | migrations/versions/a23e88f06478_add_commentset_fields.py | Python | agpl-3.0 | 1,439 | 0.00139 | """Add commentset fields.
Revision ID: a23e88f06478
Revises: 284c10efdbce
Create Date: 2021-03-22 02:54:30.416806
"""
from alembic import op
fr | om s | qlalchemy.sql import column, table
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a23e88f06478'
down_revision = '284c10efdbce'
branch_labels = None
depends_on = None
commentset = table(
'commentset',
column('id', sa.Integer()),
column('last_comment_at', sa.TIMESTAMP(timezone=... |
pombredanne/jkarn-pub-test | udfs/python/coffee.py | Python | apache-2.0 | 813 | 0.01353 | from pig_util import outputSchema
COFFEE_SNOB_PHRASES = set((\
'espresso', 'cappucino', 'macchiato', 'latte', 'cortado', 'pour over', 'barista',
'flat white', 'siphon pot', 'woodneck', 'french press', 'arabica', 'chemex',
'frothed', 'la marzocco', 'mazzer', 'la pavoni', 'nespresso', 'rancilio silvia', 'h... | ')
def is_coffee_tweet(text):
"""
Is the given text indicative of coffee snobbery?
"""
if not text:
retu | rn 0
lowercased = set(text.lower().split())
return 1 if any((True for phrase in COFFEE_SNOB_PHRASES if phrase in lowercased)) else 0
|
ulikoehler/entropy-analysis-tools | RandGen/scripts/lc.py | Python | gpl-3.0 | 1,933 | 0.047077 | #!/usr/bin/env python
#This is a runtime-configurable implementation of the
#linear congruentialpseudo-random number generator,
#using the following formula:
#y = (a*z+b) mod m
#where:
#z = the last generate result (or the seed at startup)
#a,b,m = parameters (defaults generated randomly)
#
#Numbers created by the LC a... | "How many random numbers to generate")
parser.add_o | ption("-o",
"--out",
dest="outfileName",
help="Output file")
parser.add_option("-a",
"--parama",
type="long",
dest="a",
help="Parameter a (multiplier)")
parser.add_option("-b",
"--paramb",
type="long",
dest="b",
help="Parameter b (increment)")
parser.add_option("-m",
"--p... |
TOC-Shard/moul-scripts | Python/xUserKIBase.py | Python | gpl-3.0 | 26,723 | 0.007409 | # -*- coding: utf-8 -*-
#==============================================================================#
# #
# Offline KI #
# ... | stPersonOverride()
if not silent: ki.AddChatLine(None, '1st person switchi | ng enabled', 0)
return True
# link commands
if (cmnd == 'hood'):
gender = PtGetLocalAvatar().avatar.getAvatarClothingGroup()
if (gender == 0): hisher = 'his'
elif (gender == 1): hisher = 'her'
else: hisher = 'the'
if not silent: ki.DisplayStatusMessage('%s is link... |
craws/OpenAtlas-Python | openatlas/models/gis.py | Python | gpl-2.0 | 7,414 | 0.000135 | import ast
from typing import Any, Dict, List, Optional
from flask import g, json
from flask_wtf import FlaskForm
from openatlas.database.gis import Gis as Db
from openatlas.models.entity import Entity
from openatlas.models.imports import Project
from openatlas.models.node import Node
from openatlas.util.util import ... | 'properties': {
'objectId': row['object_id'],
'objectName': row['object_name'].replace('"', '\"'),
'objectDescription': object_desc,
'id': | row['id'],
'name': row['name'].replace('"', '\"')
if row['name'] else '',
'description': description,
'shapeType': row['type']}}
if 'types' in row and row['types']:
nodes_list = ast.liter... |
kryptxy/torrench | torrench/modules/limetorrents.py | Python | gpl-3.0 | 7,173 | 0.001673 | """The Pirate Bay Module."""
import logging
import sys
from torrench.utilities.Config import Config
class LimeTorrents(Config):
"""
LimeTorrents class.
This class fetches torrents from LimeTorrents proxy,
and diplays results in tabular form.
All activities are logged and stored in a log file.
... | f.soup.find('table', class_='table2')
if test is not None:
| self.proxy = proxy
print("Pass!")
self.logger.debug("Test passed!")
break
else:
print("Test failed!\nPossibly site not reachable. See logs.")
self.logger.de... |
KrzysztofStachanczyk/Sensors-WWW-website | www/env/lib/python2.7/site-packages/django/urls/base.py | Python | gpl-3.0 | 5,668 | 0.001059 | from __future__ import unicode_literals
from threading import local
from django.utils import six
from django.utils.encoding import force_text, iri_to_uri
from django.utils.functional import lazy
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
from django.utils.translation import override
from .e... | try:
app_list = resolver.app_dict[ns]
# Yes! Path part matches an app in the current Resolver.
if current_ns and current_ns in app_list:
# If we are reversing for a particular app, use that
# namespace.
... | # The name isn't shared by one of the instances (i.e.,
# the default) so pick the first instance as the default.
ns = app_list[0]
except KeyError:
pass
if ns != current_ns:
current_path = None
... |
paris-ci/CloudBot | plugins/password.py | Python | gpl-3.0 | 2,551 | 0.00196 | # import string
import random as std_random
from cloudbot import hook
try:
# noinspection PyUnresolvedReferences
from Crypto.Random import random
gen = random.StrongRandom()
except ImportError:
# Just use the regular random module, not the strong one
gen = std_random.SystemRandom()
with open("da... | easy to remember password with [length] (default 4) commonly used words"""
try:
length = int(text)
except ValueError:
length = 3
if length > 10:
notice("Maximum length is 50 characters.")
return
words = []
# generate password
for x in range(length):
word... | s))
notice("Your password is '{}'. Feel free to remove the spaces when using it.".format(" ".join(words)))
|
3dfxmadscientist/CBSS | openerp/tools/mail.py | Python | agpl-3.0 | 14,926 | 0.00335 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2012-2013 OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | n root.getiterator():
if not node.text:
continue
node.text = _replace_matching_regex(quote_tags, node.text)
# 3. remove blockquotes
quotes = [el for el in root.getiterator(tag='blockquote')]
for node in quotes:
# copy the node tail into parent text
if node.tail:
... | )
# 4. strip signatures
signature = re.compile(r'([-]{2}[\s]?[\r\n]{1,2}[^\z]+)')
for elem in root.getiterator():
if elem.text:
match = re.search(signature, elem.text)
if match:
elem.text = elem.text[:match.start()] + elem.text[match.end():]
if elem.t... |
levilucio/SyVOLT | GM2AUTOSAR_MM/overlap_rules/models/MapVirtualDeviceFAULTY_overlap_MDL.py | Python | mit | 7,044 | 0.006814 | """
__MapVirtualDeviceFAULTY_overlap_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Tue Nov 5 10:14:40 2013
____________________________________________________________________________________________
"""
from stick... | tVisual = True
if(hasattr(self.obj1581, '_setHierarchicalLink')):
self.obj1581._setHierarchicalLink(False)
# MT_pivotOut__
self.obj1581.MT_pivotOut__.setValue('')
self.obj1581.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj1581.MT_subtypeMatching__.setValue(('True', 0))
self... | =====================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint ... |
jledbetter/openhatch | mysite/scripts/clean_data_for_academic_analysis.py | Python | agpl-3.0 | 1,935 | 0.007235 | #!/usr/bin/python
# This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# 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 ... | ty string
### * set the email | column to the empty string
### * delete (from the database) any PortfolioEntry that is_deleted
### * delete (from the database) any Citation that is_deleted
### * delete all WebResponse objects
import mysite.profile.models
import django.contrib.auth.models
### set the email and password columns to the empty string
fo... |
McBen/ingress-intel-total-conversion | buildsettings.py | Python | isc | 2,320 | 0.006466 | # settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... | e/local.properties created as required
'mobile': {
'resourceUrlBase': None,
'distUrlBase': None,
'buildMobile': 'debug',
},
# if you want to publish your own fork of the project, and host it on your own web site
# create a localbuildsettings | .py file containing something similar to this
# note: Firefox+Greasemonkey require the distUrlBase to be "https" - they won't check for updates on regular "http" URLs
#'example': {
# 'resourceBaseUrl': 'http://www.example.com/iitc/dist',
# 'distUrlBase': 'https://secure.example.com/iitc/dist',
... |
OpenC-IIIT/prosfair | gui/gui_basic.py | Python | mit | 23,370 | 0.046598 | import pygame, sys
from pygame.locals import *
import re
import json
import imp
import copy
#chessboard = json.load(open("./common/initial_state.json"))
chessboard1 = json.load(open("./common/initial_state.json"))
chessboard2 = json.load(open("./common/initial_state.json"))
chessboard3 = json.load(open("./common/i... | valid = False
| for x in ['white','black']:
for k in board[x].keys():
if board[x][k][1] == old_x and board[x][k][0] == old_y:
if "bishop" in k:
... |
moiseslorap/RIT | Computer Science 1/Labs/lab9/hashtable.py | Python | mit | 4,321 | 0.010414 | """
description: open addressing Hash Table for CS 141 Lecture
file: hashtable.py
language: python3
author: sps@cs.rit.edu Sean Strout
author: scj@cs.rit.edu Scott Johnson
"""
from rit_lib import *
class HashTable(struct):
"""
The HashTable data structure contains a collection of values
where ea... | size is the number of elements in occupying the hashtable
"""
_slots = ((list, 'table'), (int, 'size'))
def | HashTableToStr(self):
"""
HashTableToStr: HashTable -> String
"""
result = ""
for i in range(len(self.table)):
e = self.table[i]
if not e == None:
result += str(i) + ": "
result += e.EntryToStr() + "\n"
return resul... |
tg-msft/azure-sdk-tools | packages/python-packages/api-stub-generator/tests/docstring_parser_test.py | Python | mit | 7,115 | 0.004498 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from apis... | xtanalytics.DetectLanguageInput`, like
`{"id": "1", "country_hint": "us", "text": "hello world"}`.
:type documents:
list[str] or list[~azure.ai.textanalytics.DetectLanguageInput] or list[dict[str, str]]
:keyword str country_hint: A country hint for the entire batch. Accepts two
... | -1 alpha-2. Per-document
country hints will take precedence over whole batch hints. Defaults to
"US". If you don't want to use a country hint, pass the string "none".
:keyword str model_version: This value indicates which model will
be used for scoring, e.g. "latest", "2019-1... |
lablup/sorna-agent | tests/docker/test_agent.py | Python | lgpl-3.0 | 6,239 | 0.000641 | import signal
from typing import (
Any,
Mapping,
)
from unittest.mock import AsyncMock
from aiodocker.exceptions import DockerError
from ai.backend.common.exception import ImageNotAvailable
from ai.backend.common.types import AutoPullBehavior
from ai.backend.common.docker import ImageRef
from ai.backend.agen... | ocker):
behavior = AutoPullBehavior.DIGEST
inspect_mock = AsyncMock(return_value=digest_matching_image_info)
mocker.patch.object(agent.docker.images, 'inspect', new=inspect_mock)
pull = await agent.check_image(imgref, query_digest, behavior)
assert not pull
inspect_mock.assert_awaited_with(imgre... | GEST
inspect_mock = AsyncMock(return_value=digest_mismatching_image_info)
mocker.patch.object(agent.docker.images, 'inspect', new=inspect_mock)
pull = await agent.check_image(imgref, query_digest, behavior)
assert pull
inspect_mock.assert_awaited_with(imgref.canonical)
@pytest.mark.asyncio
async d... |
mLewisLogic/prism | prism/prism.py | Python | mit | 8,323 | 0.001802 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2012 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import image_util
class Connection(object):
"""Enclosing object through which the system is managed"""
def __init__(self, s3_connection, bucket_name, bucket_url):
"""Set up t... | rivative_spec.get('key_suffix')] = deriv
return derivs
def id_to_key(self, image_id):
"""Combines self.key_prefix with this id"""
return u'{ | key_prefix}{id}'.format(
key_prefix=self.key_prefix,
id=image_id)
def get_url(self, image_id):
"""Get the url, given this hash. Gets default if present and needed"""
key = image_id if image_id else self.default_image
if key:
return u'{bucket_url}{key}'.fo... |
manassolanki/erpnext | erpnext/stock/doctype/material_request/material_request_dashboard.py | Python | gpl-3.0 | 313 | 0.047923 | from frappe import _
def ge | t_data():
return {
'fieldname': 'material_request',
'transactions': [
{
'label': _('Related'),
'items': ['Request for Quotation', 'Supplier Quotation', 'Purchase Order', "Stock Entry"]
} | ,
{
'label': _('Manufacturing'),
'items': ['Work Order']
}
]
} |
kfr2/cmsplugin-biography | cmsplugin_biography/models.py | Python | mit | 2,213 | 0.001808 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from djangocms_text_ckeditor.fields import HTMLField
from easy_thumbnails.alias import aliases
from easy_thumbnails.signals import saved_file
from easy_thumbnails.signal_handlers import gen... | sonBiography)
short_description = HTMLField(blank=True, help_text="If specified, this text will replace the person's normal description.")
event_descrip | tion = HTMLField(blank=True, help_text="If specified, this text will appear after the person's normal description.")
class Meta:
ordering = ('person', )
def __unicode__(self):
return unicode(self.person)
def copy_relations(self, oldinstance):
self.person = oldinstance.person
# G... |
mileistone/test | vedanet/engine/__init__.py | Python | mit | 336 | 0.008929 | """
Lightnet Engine Module |br|
This module contains classes and functions to manage the training of | your networks.
It has an engine, capable of orchestrating your train | ing and test cycles, and also contains function to easily visualise data with visdom_.
"""
#from .engine import *
from ._voc_train import *
from ._voc_test import *
|
jesmorc/Workinout | proyectoP4/urls.py | Python | gpl-3.0 | 1,273 | 0.004713 | # -*- coding: utf-8 -*-
"""proyectoP4 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.h... | rl, patterns
from django.contrib import admin
from Workinout import views
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*)
]
if settings.DEBUG:
| urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
else:
urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}),
)
|
drayanaindra/django-shop | tests/testapp/manage.py | Python | bsd-3-clause | 609 | 0.004926 | #!/usr/bin/env python
import os, sys
from django.core.management import execute_manager
sys.path.insert(0, os.path.abspath('./../../'))
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory conta... | ars you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file_ | _)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
|
eclee25/flu-SDI-exploratory-age | scripts/WIPS2015/WIPS_Bansal2010_hierarchy.py | Python | mit | 1,282 | 0.024961 | #!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 2/6/15
###Function: Redraw figure 4A in Shifting Demographic Landscape (Bansal2010)
###Import data:
###Command Line: python
##############################################
### notes ###
### pack... | #
### functions ###
### import data ###
chi | ldin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/scripts/WIPS2015/importData/child_attack_rate.txt','r')
child=csv.reader(childin, delimiter=' ')
adultin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/scripts/WIPS2015/importData/adult_attack_rate.txt','r')
adult=csv.reader(adultin... |
shubhdev/openedx | common/djangoapps/student/models.py | Python | agpl-3.0 | 67,408 | 0.002077 | """
Models for User Information (students, staff, etc)
Migration Notes
If you make changes to this model, be sure to create an appropriate migration
file and check it in at the same time as your model changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py lms schemamigration student --auto description_of_... | gging.getLogger("audit")
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore # pylint: disable=invalid-name
UNENROLLED_TO_ALLOWEDTOENROLL = 'from unenrolled to allowed to enroll'
ALLOWEDTOENROLL_TO_ENROLLED = 'from allowed to enroll to enrolled'
ENROLLED_TO_ENROLLED = 'from enrolled to enrolled'
ENROLL... | nrolled to enrolled'
ALLOWEDTOENROLL_TO_UNENROLLED = 'from allowed to enroll to enrolled'
UNENROLLED_TO_UNENROLLED = 'from unenrolled to unenrolled'
DEFAULT_TRANSITION_STATE = 'N/A'
TRANSITION_STATES = (
(UNENROLLED_TO_ALLOWEDTOENROLL, UNENROLLED_TO_ALLOWEDTOENROLL),
(ALLOWEDTOENROLL_TO_ENROLLED, ALLOWEDTOENRO... |
ariwaranosai/twitter_bot | twitter_bot/main.py | Python | gpl-2.0 | 1,342 | 0.003726 | #!/usr/bin/env python
#coding=utf-8
# Copyright 2007 Google 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 appl... | e License for the specific language governing permissions and
# limitations under the License.
#
import webapp2
import time
import dbcontroller as dc
import speak
import User
im | port logging
class MainHandler(webapp2.RequestHandler):
def get(self):
list = dc.refresh()
lines = speak.speak(list)
import twitter
for user in User.users:
for i in lines:
str1 = i
logging.log(logging.INFO, u"twitter length is " + \
... |
cloudzfy/euler | src/125.py | Python | mit | 555 | 0.001802 | # The palindromic number 595 is interesting because it can be written
# as the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 +
# 11^2 + 12^2.
# There are exactly eleven palindromes below one-thousand th | at can
# be written as consecutive square sums, and the sum of these palindromes
# is 4164. Note that 1 = 0^2 + 1^2 has not been included as this problem
# is concerned with the squares of positive integers.
# Find the sum of all the numbers less than 10^8 that are both palindromic
# and can | be written as the sum of consecutive squares.
|
abogushov/django-admin-json-editor | example/app/migrations/0002_roles.py | Python | mit | 888 | 0.003378 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-25 13:37
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
depe | ndencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ArrayJSONModel',
fields=[
| ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('roles', django.contrib.postgres.fields.jsonb.JSONField(default=[])),
],
),
migrations.AlterField(
model_name='jsonmodel',
name='data',
... |
javiercantero/streamlink | src/streamlink/plugins/funimationnow.py | Python | bsd-2-clause | 11,232 | 0.002137 | from __future__ import print_function
import logging
import random
import re
from streamlink.compat import urljoin
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import http
from streamlink.plugin.api import useragents
from streamlink.plugin.api import validate
from s... | "success": False,
"error": validate.text},
{"token": validate.text,
"user": {"id": int}}
))
def __init_ | _(self, experience_id):
"""
:param experience_id: starting experience_id, may be changed later
"""
self.experience_id = experience_id
self._language = None
self.cache = {}
self.token = None
def request(self, method, url, *args, **kwargs):
headers = kw... |
flav-io/flavio | flavio/physics/wdecays/test_mW.py | Python | mit | 729 | 0 | import unittest
import flavio
from . import mw
from flavio.physics.zdecays.test_smeftew import ZeroDict
import wilson
par = flavio.default_parameters.get_central_all()
|
class TestMW(unittest.TestCase):
def test_mW_SM(self):
self.assertAlmostEqual(mw.mW_SM(par), 80.3779, delta=0.02)
def test_shifts_sm(self):
C = ZeroDict({})
self.assertEqua | l(mw.dmW_SMEFT(par, C), 0)
def test_obs(self):
w = wilson.Wilson({}, scale=91.1876, eft='SMEFT', basis='Warsaw')
self.assertAlmostEqual(flavio.sm_prediction('m_W'),
par['m_W'], delta=0.03)
self.assertEqual(flavio.sm_prediction('m_W'),
... |
altur13/osu-Assistant | beatmap_processor.py | Python | gpl-3.0 | 1,817 | 0.004403 | #!/usr/bin/env python
import sys
from utils.file_system import *
from calculations.beatmap_metadata import BeatmapMetadat | a
from database.database_wrapper import DatabaseWrapper
def hello(msg):
print("Hello world! " | + msg)
def print_help():
print("Usage: ./beatmap_processor.py [songs_folder]")
print("This script initializes beatmap database with pp calculations")
print("of all standard maps located on [songs_folder]")
exit(1)
if (len(sys.argv) != 2):
print_help()
songs_abs_path = abs_path(sys.argv[1])
print(... |
tectronics/rebuildingtogethercaptain | room/forms.py | Python | apache-2.0 | 7,780 | 0.010154 | # Copyright 2011 Luke Stone
"""Django forms for models."""
# This don't work in appengine, we use djangoforms instead.
# from django.forms import ModelForm
from django import forms # DateField, DateTimeInput
from google.appengine.ext.db import djangoforms
import common
import models
VENDOR_SELECTIONS = (
'H... | d', 'program', 'vendor']
class InKindDonationForm(SiteExpenseForm):
donation_date = forms.DateField(required=True)
donor = forms.CharField(required=True)
donor_phone = forms.CharField(required=True)
description = forms.CharField(required=True, widget=forms.Textarea)
class Meta:
model = mod... | exclude = ['last_editor', 'modified', 'program']
|
michaeldayreads/marathon-bigip-ctlr | common.py | Python | apache-2.0 | 6,679 | 0 | #!/usr/bin/env python3
#
# Copyright 2017 F5 Networks
#
# 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 ... |
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(formatter)
logger. | addHandler(consoleHandler)
logger.propagate = False
def set_marathon_auth_args(parser):
"""Set the authorization for Marathon."""
parser.add_argument("--marathon-auth-credential-file",
env_var='F5_CC_MARATHON_AUTH',
help="Path to file containing a user/pass ... |
ToonTownInfiniteRepo/ToontownInfinite | toontown/minigame/Purchase.py | Python | mit | 34,313 | 0.00204 | from PurchaseBase import *
from otp.nametag.NametagFloat2d import *
from otp.nametag import NametagGlobals
from direct.task.Task import Task
from toontown.toon import ToonHead
from toontown.toonbase import ToontownTimer
from direct.gui import DirectGuiGlobals as DGG
from direct.directnotify import DirectNotifyGlobal
fr... | rewardDoubledJellybeanLabel.hide()
self.countSound = base.loadSfx('phase_3.5/audio/sfx/tick_counter.ogg')
self.overMaxSound = base.loadSfx('phase_3.5/audio/sfx/AV_collision.ogg')
self.celebrateSound = base.loadSfx('phase_4/audio/sfx/MG_win.ogg')
return
def unload(self):
Purc... | stroying head frames')
for headFrame in self.headFrames:
if not headFrame[1].isEmpty():
headFrame[1].reparentTo(hidden)
headFrame[1].des |
joaks1/PyMsBayes | pymsbayes/utils/tempfs.py | Python | gpl-3.0 | 4,956 | 0.004439 | #! /usr/bin/env python
import sys
import os
import tempfile
from pymsbayes.utils.functions import random_str
from pymsbayes.utils.errors import TempFSError
from pymsbayes.utils.messaging import get_logger
_LOG = get_logger(__name__)
class TempFileSystem(object):
"""
A temporary file system that protects aga... | rent = self.base_dir
full_parent = self._check_parent(parent)
return self._make_dir(parent=full_parent, prefix=prefix)
def clear_dir(self, path):
full_path = self._get_full_path(path)
if not full | _path in self.dirs:
raise TempFSError('Temp directory {0!r} is not registered; '
'cannot clear'.format(full_path))
for p in os.listdir(full_path):
path = os.path.join(full_path, p)
if os.path.isfile(path):
self.remove_file(path)
... |
spreg-git/pysal | pysal/spreg/tests/test_twosls.py | Python | bsd-3-clause | 14,374 | 0.018784 | import unittest
import numpy as np
import pysal
from pysal.spreg.twosls import BaseTSLS, TSLS
class TestBaseTSLS(unittest.TestCase):
def setUp(self):
db = pysal.open(pysal.examples.get_path("columbus.dbf"),'r')
self.y = np.array(db.by_col("CRIME"))
self.y = np.reshape(self.y, (49,1))
... | 04], [ 57.5 | 7145851]])
np.testing.assert_array_almost_equal(reg.predy[0:5], predy_5, 7)
q_5 = np.array([[ 5.03], [ 4.27], [ 3.89], [ 3.7 ], [ 2.83]])
np.testing.assert_array_equal(reg.q[0:5], q_5)
self.assertAlmostEqual(reg.sig2n_k, 587.56797852699822, 7)
self.assertAlmostEqual(reg.sig2n, 5... |
yamila-moreno/jannie-5 | examples/bottle-example.py | Python | gpl-3.0 | 520 | 0.003846 | # -* | - coding: utf-8 -*-
from time import sleep
import subprocess
def invoke_rest_api(cmd):
url = 'http://localhost:8080/{}'.format(cmd)
subprocess.call(['curl', url])
def with_api():
# start
invoke_rest_api('start')
invoke_rest_api('takeoff')
sleep(3)
# go forward
invoke_rest_api('go_forw... | _main__":
with_api()
|
faribas/RMG-Py | rmgpy/molecule/draw.py | Python | mit | 68,395 | 0.008217 | #!/usr/bin/env python
# encoding: utf-8
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2009-2011 by the RMG Team (rmg_dev@mit.edu)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of thi... | kipedia.org/wiki/Skeletal_formula>`_ of a wide
variety of organic and inorganic molecules. The general method for creating
these drawings is to utilize the :meth:`draw()` method of the :class:`Molecule`
you wish to draw; this wraps a call to :meth:`MoleculeDrawer.draw()`, where the
molecule drawing algorithm begins. Ad... | s used to create
the drawings. The :class:`MoleculeDrawer` class module will fail gracefully if
Cairo is not installed.
The implementation uses the 2D coordinate generation of rdKit to find coordinates,
then uses Cairo to render the atom.
"""
import math
import numpy
import os.path
import re
import logging
from rmg... |
ariovistus/pyd | examples/rawexample/setup.py | Python | mit | 268 | 0.011194 | from pyd.supp | ort import setup, Extension
projName = 'rawexample'
setup(
name=projName,
version='0.1',
ext_modules=[
Extension(projName, [ | 'rawexample.d'],
raw_only=True,
build_deimos=True,
d_lump=True)
],
)
|
zachriggle/alpha3 | ALPHA3.py | Python | bsd-3-clause | 11,046 | 0.021637 | # Copyright (c) 2003-2010, Berend-Jan "SkyLined" Wever <berendjanwever@gmail.com>
# Project homepage: http://code.google.com/p/alpha3/
# All rights reserved. See COPYRIGHT.txt for details.
import charsets, encode, io
import x86, x64, test
import os, re, sys
#_____________________________________________________... | "Which character casing to use (uppercase, mixedcase, lowercase)."),
(" base address ", "How to determine the base address in the decoder code (each encoder has its own set of "
"valid values)."),
(None, ""),
(None | , "[I/O Setting]"),
(" --input=\"file\"", "Path to a file that contains the shellcode to be encoded (Optional, default is to read "
"input from stdin)."),
(" --output=\"file\"", "Path to a file that will receive the encoded shellcode (Optional, default is to write "
... |
X-Scapin/BlueP | resources/demoprojects/Demo1/car.py | Python | apache-2.0 | 418 | 0.002392 | import sys
from vehicule import Vehicule
class Car(Vehicule):
""" New class Voiture"""
wheel_numbers = 4
def __init__(self, name): |
self.name = name
self.doors = {}
self.default_message = "Hello everybody !"
def print_value(self, sender):
"""DocString : this method print the default value of this insta | nce"""
print(sender + " say : " + self.default_message)
|
icyblade/pynga | setup.py | Python | mit | 1,018 | 0 | from setuptools import setup
about = {}
with open('./pynga/__version__.py', 'r') as f:
exec(f.read(), about)
with open('README.md', 'r') as f:
readme = f.read()
tests_require = [
'pytest>=3.5.0,<3.7.0',
'pytest-flake8>=1.0.0'
]
setup(
name=about['__title__'],
version=about['__version__'],
... | il__'],
description=about['__description__'],
long_description=readme,
long_description_content_type='text/markdown',
classifiers=[
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
install_requires=[
'requests>=2.10.0',
'cacheco... | ts_require=tests_require,
extras_require={
'test': tests_require,
},
python_requires='>=3.6',
)
|
mohamedhagag/community-addons | crm_change_request/models/change_request.py | Python | agpl-3.0 | 3,485 | 0 | # -*- encoding: utf-8 -*-
from openerp.osv import osv, fields
class LeadToChangeRequestWizard(osv.TransientModel):
"""
wizard to convert a Lead into a Change Request and move the Mail Thread
"""
_name = "crm.lead2cr.wizard"
_inherit = 'crm.partner.binding'
_columns = {
"lead_id": fiel... | uest(self, cr, uid, ids, context=None):
# get the wizards and models
wizards = self.browse(cr, uid, ids, context=context)
lead_obj = self.pool["crm.lead"]
cr_obj = self.pool["change.management.change"]
attachment_obj = self.pool['ir.attachment']
for wizard in wizards:
... | partner = self._find_matching_partner(cr, uid, context=context)
if not partner and (lead.partner_name or lead.contact_name):
partner_ids = lead_obj.handle_partner_assignation(
cr, uid, [lead.id], context=context
)
partner = partner_ids[lea... |
datahuborg/datahub | src/core/db/backend/pg.py | Python | mit | 45,439 | 0.000044 | import re
import os
import errno
import shutil
import hashlib
from collections import namedtuple
from uuid import uuid4
import psycopg2
import core.db.query_rewriter
from psycopg2.extensions import AsIs
from psycopg2.pool import ThreadedConnectionPool
from psycopg2 import errorcodes
from core.db.licensemanager import L... | NT_PRIVILEGE):
raise PermissionDenied()
if (e.pgcode == errorcodes.INVALID_PARAMETER_VALUE or
e.pgcode == errorcodes.UNDEFINED_OBJECT):
raise ValueError("Invalid parameter in query.")
if e.pgcod | e == errorcodes.INVALID_SCHEMA_NAME:
error = ('Repo not found. '
'You must specify a repo in your query. '
'i.e. select * from REPO_NAME.TABLE_NAME. ')
raise LookupError(error)
if e.pgcode == errorcodes.UNDEFINED_TABLE:
raise LookupError("Table or view not f... |
kitchenbudapest/vr | hud.py | Python | gpl-3.0 | 4,413 | 0.019035 | ## INFO ########################################################################
## ##
## plastey ##
## ======= ... | ##
######################################################################## INFO ##
# Import python modules
from collections import deque
#------------------------------------------------------------------------------#
class Text:
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
d... | bject
self._text_other = text_other_object
self._get_time = time_getter
self._interval = interval
self._last_time = time_getter()
self._messages = deque()
self._still_empty = True
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -... |
consultit/p3opensteer | samples/python/map_drive.py | Python | lgpl-3.0 | 11,669 | 0.004113 | '''
Created on Jun 26, 2016
@author: consultit
'''
from panda3d.core import TextNode, ClockObject, AnimControlCollection, \
auto_bind, LPoint3f, LVecBase3f, TextureStage, TexGenAttrib
from p3opensteer import OSSteerManager, ValueList_string, ValueList_LPoint3f, \
ValueList_float, OSSteerPlugIn
#
from ... | tex_scale(rttTexStage, 1.0 / 128.0, 1.0 / 128.0)
sceneNP.set_tex_gen(rttTexStage, TexGenAttrib.M_world_position)
sceneNP.set_texture(rttTexStage, texture, 10)
def togglePredictionType():
"""toggle prediction type"""
global steerPlugIn
predictionType = steerPlugIn.get_map_prediction_type()
... | ED_PREDICTION:
steerPlugIn.set_map_prediction_type(OSSteerPlugIn.LINEAR_PREDICTION)
print ("prediction type: linear")
else:
steerPlugIn.set_map_prediction_type(OSSteerPlugIn.CURVED_PREDICTION)
print ("prediction type: curved")
if __name__ == '__main__':
msg = "'map drive... |
MehdiSfr/tensor-flow | tensorflow/python/training/moving_averages.py | Python | apache-2.0 | 11,235 | 0.002225 | # Copyright 2015 Google Inc. 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 law or a... | with ops.op_scope([variable, value, decay], name, "AssignMovingAvg") as name:
with ops.device(variable.device):
decay = ops.convert_to_tensor(1.0 - decay, name="decay")
if decay.dtype != variable.dtype.base_dtype:
decay = math_ops.cast(decay, variable.dtype.base_dtype)
return state_ops.ass... | nentialMovingAverage(object):
"""Maintains moving averages of variables by employing an exponential decay.
When training a model, it is often beneficial to maintain moving averages of
the trained parameters. Evaluations that use averaged parameters sometimes
produce significantly better results than the final... |
Everley1993/Laky-Earo | test/test_diagram.py | Python | apache-2.0 | 4,567 | 0.003065 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import unittest
from earo.event import Event, Field
from earo.handler import Handler, Emittion, NoEmittion
from earo.mediator import Mediator
from earo.context import Context
from earo.processor import Processor, ProcessFlow
from earo.diagram import Diagram
class TestDiagram(... | D])
handler_4 = Handler(EventC, foo)
handler_5 = Handler(EventD, fooEx)
mediator.register_event_handler(
handler_1,
handler_2,
handler_3,
handler_4,
handler_5
)
process_flow = ProcessFlow(mediator, EventA)
diag... | e(diagram_from_json.json)
if __name__ == '__main__':
unittest.main()
|
sa2ajj/DistroTracker | pts/mail/management/commands/pts_dispatch.py | Python | gpl-2.0 | 2,039 | 0 | # Copyright 2013 The Distro Tracker Developers
# See the COPYRIGHT file at the top-level directory of this distribution and
# at http://deb.li/DTAuthors
#
# This file is part of Distro Tracker. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution and at http:/... | os
import sys
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
A Djan | go management command used to invoke the dispatch functionality.
The received message is expected as input on stdin.
"""
input_file = sys.stdin
def handle(self, *args, **kwargs):
logger.info('Processing a received package message')
if six.PY3:
self.input_file = self.input_... |
afg984/pyardrone | pyardrone/navdata/options.py | Python | mit | 14,941 | 0 | '''
This module corresponds to ARDroneLib/Soft/Common/navdata_common.h
'''
import ctypes
import functools
from pyardrone.utils.structure import Structure
uint8_t = ctypes.c_uint8
uint16_t = ctypes.c_uint16
uint32_t = ctypes.c_uint32
int16_t = ctypes.c_int16
int32_t = ctypes.c_int32
bool_t = ctypes.c_uint32 # ARDro... | pressure'
offset_pressure = float32_t
est_z = float32_t
est_zdot = float32_t
est_bias_PWM = float32_t
est_biais_pression = float32_t
offs | et_US = float32_t
prediction_US = float32_t
cov_alt = float32_t
cov_PWM = float32_t
cov_vitesse = float32_t
bool_effet_sol = bool_t
somme_inno = float32_t
flag_rejet_US = bool_t
u_multisinus = float32_t
gaz_altitude = float32_t
Flag_multisinus = bool_t
Flag_multisinus_debut =... |
liukaijv/XlsxWriter | xlsxwriter/test/comparison/test_chart_date04.py | Python | bsd-2-clause | 2,223 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from datetime import date
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(Exc... | date(2013, 1, 9),
date(2013, 1, 10)]
values = [10, 30, 20, 40, 20, 60, 50, 40, 30, 30]
worksheet.write_column('A1', dates, date_format)
worksheet.write_column('B1', values)
chart.add_series({
| 'categories': '=Sheet1!$A$1:$A$10',
'values': '=Sheet1!$B$1:$B$10',
})
chart.set_x_axis({
'date_axis': True,
'minor_unit': 1,
'major_unit': 1,
'minor_unit_type': 'months',
'major_unit_type': 'years',
'num_for... |
dimaleks/uDeviceX | tests/dump/graph.full.py | Python | gpl-3.0 | 371 | 0.008086 | #!/usr/bin/env python
import mirheo as mir
ranks = (1, 1, 1)
domain = (4, 4, 4)
u = mir.Mirheo(ranks, d | omain, debug_level=3, log_filename='log', no | _splash=True)
u.save_dependency_graph_graphml("tasks.full", current=False)
# sTEST: dump.graph.full
# cd dump
# rm -rf tasks.graphml
# mir.run --runargs "-n 1" ./graph.full.py
# cat tasks.full.graphml > tasks.out.txt
|
coz787/conges4ac | actools/cg_minst.py | Python | gpl-2.0 | 12,134 | 0.020277 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''cg_minst.py: conges multi-installer
outil d'installation multiple adapté au portage des applications
conges d'un env vers un autre
'''
import getpass, sys, os, subprocess, pprint, string, re, time
from traceback import print_exc
from cg_lib import exec_sql_file
im... | else :
| break
screfpath = screfpath[0:nj]
if not os.access(screfpath, os.F_OK & os.R_OK) :
print "read acces to %s conges ref path refused" % dcgid['crefpath']
sys.exit(1)
screfpathdbconnect = None
try:
screfpathdbconnect = "%s/%s" % (dcgid['crefpath'],dcgid['cdbcon... |
PALab/PLACE | place/utilities.py | Python | lgpl-3.0 | 3,034 | 0.001648 | """Helper utilities for PLACE data"""
from sys import argv
from os import remove
from os.path import basename, isdir, isfile
from itertools import count
from glob import glob
import numpy as np
def column_renamer():
"""Tool for renaming the columns in a NumPy structured array file"""
if not (len(argv) > 1 and... | le(directory):
"""Pack the individual row files into one NumPy structured array"""
files = sorted(glob('{}/data_*.npy'.format(directory)))
num = len(files)
if num == 0:
print('No PLACE data_*.npy files found in {}'.format(directory))
return
with open(files[0], 'rb') as file_p:
... | row = np.load(file_p)
data[i] = row[0]
with open('{}/data.npy'.format(directory), 'xb') as file_p:
np.save(file_p, data)
for filename in files:
remove(filename)
def multiple_files():
"""Unpack one NumPy structured array into individual row files"""
if not (len(argv) == 2 and i... |
patmarion/director | src/python/director/debugVis.py | Python | bsd-3-clause | 8,815 | 0.005786 | import director.vtkAll as vtk
from director import vtkNumpy as vnp
from director.shallowCopy import shallowCopy
import numpy as np
class DebugData(object):
def __init__(self):
self.append = vtk.vtkAppendPolyData()
def write(self, filename):
writer = vtk.vtkXMLPolyDataWriter()
writer.... | line.SetPoint1(p1)
line.SetPoint2(p2)
line.Update()
poly | Data = line.GetOutput()
if radius > 0.0:
polyData = applyTubeFilter(polyData, radius)
self.addPolyData(polyData, color)
def addPolyLine(self, points, isClosed=False, radius=0.0, color=[1,1,1]):
pts = vnp.getVtkPointsFromNumpy(np.array(points, dtype=np.float64))
polyLine ... |
rado0x54/project-euler | python/problem0052.py | Python | mit | 651 | 0.003072 | #!/usr/bin/env python3
"""Project Euler - Problem 52 Module"""
import pelib
def problem52():
"""Problem 52 - Permuted multiples"""
x = 1
while True:
ss_str_2x = sorted | (set(str(2 * x)) | )
ss_str_3x = sorted(set(str(3 * x)))
ss_str_4x = sorted(set(str(4 * x)))
ss_str_5x = sorted(set(str(5 * x)))
ss_str_6x = sorted(set(str(6 * x)))
if ss_str_2x == ss_str_3x == ss_str_4x == ss_str_5x == ss_str_6x:
#print(x, ss_str_2x)
return x
x += ... |
devs1991/test_edx_docmode | cms/djangoapps/contentstore/views/import_export.py | Python | agpl-3.0 | 21,168 | 0.002646 | """
These views handle all actions in Studio related to import and exporting of
courses
"""
import base64
import logging
import os
import re
import shutil
import tarfile
from path import Path as path
from tempfile import mkdtemp
from django.conf import settings
from django.contrib.auth.decorators import login_required... | ng, 0)
# If the course has an entrance exam then remove it and its corresponding milestone.
# current course state before import.
if root_name == COURSE_ROOT:
if courselike_module. | entrance_exam_enabled:
remove_entrance_exam_milestone_reference(request, courselike_key)
log.info(
"entrance exam milestone content reference for course %s has been removed",
courselike_module.id
... |
rdio/translate-toolkit | filters/test_checks.py | Python | gpl-2.0 | 65,604 | 0.005247 | # -*- coding: utf-8 -*-
from py.test import mark
from translate.filters import checks
from translate.lang import data
from translate.storage import po, xliff
def strprep(str1, str2, message=None):
return data.normalized_unicode(str1), data.normalized_unicode(str2), data.normalized_unicode(message)
def passes(... | r1, str2, message=None):
"""returns whether the given strings fail on the given test, handling only SeriousFilterFailures"""
str1, str2, message = strprep(str1, str2, message)
try:
filterresult = filterfunction(str1, str2)
except checks.SeriousFilterFailure, e:
if message:
ex... | e.encode('utf-8')
else:
filterresult = False
return not filterresult
def test_defaults():
"""tests default setup and that checks aren't altered by other constructions"""
stdchecker = checks.StandardChecker()
assert stdchecker.config.varmatches == []
mozillachecker = checks.Mozi... |
laurentb/mpdat | mpdat/process.py | Python | mit | 735 | 0.001361 | from os.path import dirname
"""
Process MPDatClient responses
"" | "
def get_files_and_dirs_from_db(items):
"""
Returns (files, directories) from a source with files and directories mixed.
"""
files = []
dirs = []
for item in items:
if "directory" in item:
dirs.append(item["directory"])
elif "file" in item:
fi | les.append(item["file"])
return (files, dirs)
def process_song(item):
"""
Adds a "dir" attribute to songs, change "pos" to int
"""
if "file" in item:
item["dir"] = dirname(item["file"])
if "pos" in item:
item["pos"] = int(item["pos"])
if "time" in item:
item["time"... |
rasmadeus/rasmadeus.ru | rapp/article/views.py | Python | gpl-3.0 | 1,716 | 0.001748 | from django.http import HttpResponse
from django.template.loader import get_template
from rapp.article.models import Article
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
def _get_greeting(request):
return request.user.username if request.user.is_authenticated()... | greeting(request),
'article': _get_default_common_data()
}
return HttpResponse(template.render(context, request))
def code_404_view(request): |
template = get_template('404.html')
context = {
'greeting': _get_greeting(request),
'article': _get_default_common_data()
}
return HttpResponse(template.render(context, request))
class ArticleDetailView(DetailView):
model = Article
context_object_name = 'article'
def get_... |
Zuiev/shipping-cost | app.py | Python | apache-2.0 | 2,545 | 0.009037 | #!/usr/bin/env python
import urllib
import json
import os
import smtplib
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=... | "speech": speech,
"displayText": speech,
#"data": {},
# "contextOut": [],
"source": "apiai-onlinestore-shipping"
}
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print "Starting app on port %d" % port
app.run(debug=T | rue, port=port, host='0.0.0.0')
|
msegado/edx-platform | lms/djangoapps/shoppingcart/tests/test_reports.py | Python | agpl-3.0 | 12,763 | 0.004154 | # -*- coding: utf-8 -*-
"""
Tests for the Shopping Cart Models
"""
import datetime
from textwrap import dedent
import pytest
import pytz
from django.conf import settings
from mock import patch
import six
from six import StringIO
from six import text_type
from course_modes.models import CourseMode
from shoppingcart.... | und.refund_requested_time = self.test_time
second_refund.save()
self | .CORRECT_REFUND_REPORT_CSV = dedent(u"""
Order Number,Customer Name,Date of Original Transaction,Date of Refund,Amount of Refund,Service Fees (if any)
3,King Bowsér,{time_str},{time_str},40.00,0.00
4,Súsan Smith,{time_str},{time_str},40.00,0.00
""".format(time_str=str(sel... |
Hao-Liu/avocado | selftests/functional/test_utils.py | Python | gpl-2.0 | 4,216 | 0.001186 | import os
import sys
import time
import tempfile
import shutil
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
else:
import unittest
from avocado.utils import process
FAKE_VMSTAT_CONTENTS = """#!/usr/bin/python
import time
import random
import signal
import sys
class FakeVMStat(object):
... | = self.get_bo()
m_in = self.get_in()
cs = self.get_cs()
us = self.get_us()
sy = self.get_sy()
m_id = self.get_id()
wa = self.get_wa()
st = self.get_st()
print("%2d %2d %2d %7d %6d %7d %1d %1d %2d %3d %4d %2d %2d... | me.sleep(self.interval)
if __name__ == '__main__':
vmstat = FakeVMStat(interval=float(sys.argv[1]))
vmstat.start()
"""
FAKE_UPTIME_CONTENTS = """#!/usr/bin/python
if __name__ == '__main__':
print("17:56:34 up 8:06, 7 users, load average: 0.26, 0.20, 0.21")
"""
class ProcessTest(unittest.TestCase):
... |
AugustG98/NWT-Bot | NWT-Bot/books.py | Python | mit | 5,132 | 0.049493 | bookprefix = {
'Genesis' : '1',
'genesis' : '1',
'Gen' : '1',
'gen' : '1',
'Exodus' : '2',
'exodus' : '2',
'Exo' : '2',
'exo' : '2',
'Ex' : '2',
'ex' : '2',
'Leviticus' : '3',
'leviticus' : '3',
'Lev' : '3',
'lev' : '3',
'Numbers' : '4',
'numbers' : '4',
... | Tim' : '54',
'1tim' : '54',
'2Timothy' : '55',
'2timothy' : '55',
'2Tim' : '55',
'2tim' : '55',
'Titus' : '56',
'titus' : '56',
'Philemon' : '57',
'philemon' : '57',
'Philem' : '57',
' | philem' : '57',
'Hebrews' : '58',
'hebrews' : '58',
'Heb' : '58',
'heb' : '58',
'James' : '59',
'james' : '59',
'Jas' : '59',
'jas' : '59',
'1Peter' : '60',
'1peter' : '60',
'1Pet' : '60',
'1pet' : '60',
'2Peter' : '61',
'2peter' : '61',
'2Pet' : '61',
'2p... |
humdings/zipline | tests/utils/test_cache.py | Python | apache-2.0 | 2,166 | 0 | from unittest import TestCase
from pandas import Timestamp, Timedelta
from zipline.utils.cache import CachedObject, Expired, ExpiringCache
class CachedObjectTestCase(TestCase):
def test_cached_object(self):
expiry = Timestamp('2014')
before = expiry - Timedelta('1 minute')
after = expir... | ache.set('foo', 1, expiry_1)
cache.set('bar', 2, expiry_2)
self.assertEqual(cache.get('fo | o', before_1), 1)
# Unwrap on expiry is allowed.
self.assertEqual(cache.get('foo', expiry_1), 1)
with self.assertRaises(KeyError) as e:
self.assertEqual(cache.get('foo', after_1))
self.assertEqual(e.exception.args, ('foo',))
# Should raise same KeyError after deleti... |
warmersun/lessonplan2 | warmersun_lessonplans_site/lessonplan/migrations/0003_homepage.py | Python | gpl-2.0 | 816 | 0.002451 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0001_squashed_0016_change_page_url_path_to_text_field'),
('lessonplan', '0002_auto_2... | ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Pa | ge')),
('body', wagtail.wagtailcore.fields.RichTextField(blank=True)),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
|
thom-at-redhat/cfme_tests | fixtures/log.py | Python | gpl-2.0 | 4,066 | 0.003443 | import collections
import pytest
from utils import log
#: A dict of tests, and their state at various test phases
test_tracking = collections.defaultdict(dict)
# | Expose the cfme logger as a fixture for convenience
@pytest.fixture(scope='session')
def logger():
return log.logger
@pytest.mark.hookwrapper
def pytest_runtest_setup(item):
path, lineno, domaininfo = item.location
logger().info(log.format_marker(_format_nodeid(item.nodeid), mark="-"),
extra={'so... | ).info(log.format_marker('Starting new test run', mark="="))
expression = config.getvalue('keyword') or False
expr_string = ', will filter with "%s"' % expression if expression else ''
logger().info('Collected %i items%s' % (len(items), expr_string))
@pytest.mark.hookwrapper
def pytest_runtest_logreport(r... |
yunity/yunity-core | karrot/utils/serializers.py | Python | agpl-3.0 | 97 | 0 | from rest_framework import serializers |
class EmptySerializer(serializers.Serializer):
| pass
|
tariqdaouda/pyGeno | pyGeno/tools/parsers/CSVTools.py | Python | apache-2.0 | 10,715 | 0.052543 | import os, types, collections
class EmptyLine(Exception) :
"""Raised when an empty or comment line is found (dealt with internally)"""
def __init__(self, lineNumber) :
message = "Empty line: #%d" % lineNumber
Exception.__init__(self, message)
self.message = message
def __str__(self) :
return self.message... | ator = '"', lineSeparator = '\n') :
"""Loads a CSV file"""
self.filename = filePath
f = open(filePath)
if lineSeparator == '\n' :
lines = f.readlin | es()
else :
lines = f.read().split(lineSeparator)
f.flush()
f.close()
lines = lines[skipLines:]
self.lines = []
self.comments = []
for l in lines :
if len(l) != 0 and l[0] != "#" :
self.lines.append(l)
elif l[0] == "#" :
self.comments.append(l)
self.separator = separator
self.line... |
egabancho/invenio-ext | invenio_ext/template/config.py | Python | gpl-2.0 | 947 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014, 2015 CERN.
#
# Invenio 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 optio... | not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 3 | 30, Boston, MA 02111-1307, USA.
"""Jinja2 configuration."""
from __future__ import unicode_literals
JINJA2_EXTENSIONS = [
'jinja2.ext.do',
]
"""List of automatically loaded extensions."""
|
statmuse/bagelbot | check_attendance.py | Python | mit | 6,699 | 0.003583 | #!/usr/bin/env python
"""
Bagelbot script for checking for attendance for an upcoming bagelbot meeting.
"""
import logging
import sys
import time
from datetime import datetime, timedelta
from config import ATTENDANCE_TIME_LIMIT
from utils import YES, NO, initialize, nostdout, download_shelve_from_s3, upload_shelve_to_... | ,
)
parsed_args = parser.parse_args()
if parsed_args.from_cron:
with nostdout():
main(parsed_args)
else:
| main(parsed_args)
|
vishnubob/pyscad | tests/test_radial_resolution.py | Python | mit | 692 | 0.001445 | from boiler import *
class TestRadialResolution(unittest.TestCase):
def test_cylinder_radial_resolution_scad(self):
c = Cylinder(h=10, r=20, fn=10, fa=1)
answer = "cylinder(r=20.0, h=10.0, center=false, $fn=10.0);"
code_compare(c.render_scad(), answer)
c.fn = 0
answer = "cyl... | );"
code_compare(c.render_scad(), answer)
c.fs = 3
answer = "cylinder(r=20.0, h=10.0, center=false, $fa=1.0, $fs=3.0);"
code_compare(c.render_scad(), answer)
c.fs = 2
c.fa = 2
answer = "cylinder(r=20.0, h=1 | 0.0, center=false);"
code_compare(c.render_scad(), answer)
|
shuhaowu/wrtfreezer | setup.py | Python | agpl-3.0 | 408 | 0.002451 | #!/usr/bin/env python
from distutils.core import setup
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="wrtfreezer",
version="0.1",
description="A simple utility to mass build OpenWRT images.",
author="Shuh | ao Wu",
license="AGPL",
| url="https://github.com/shuhaowu/wrtfreezer",
packages=["wrtfreezer"],
scripts=["wrtbuild"],
requires=requirements,
)
|
hiteshgarg14/Django-Social-Website | bookmarks/account/urls.py | Python | mit | 1,562 | 0.014085 | from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
urlpatterns = [
# previous login view
# url(r'^login/$', views.user_login, name='login'),
# login / logout urls
url(r'^login/$', auth_views... | set_done'),
url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$',\
auth_views.password_reset_confirm,name='password_reset_confirm'),
url(r'^password-reset/complete/$',auth_views.password_reset_complete,name='password_reset_complete'),
# register
url(r'^register/$', views.re... | me='edit'),
url(r'^users/$', views.user_list, name='user_list'),
url(r'^users/follow/$', views.user_follow, name='user_follow'),
url(r'^users/(?P<username>[-\w]+)/$', views.user_detail, name='user_detail'),
]
|
condad/google-objects | setup.py | Python | apache-2.0 | 1,680 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
from setuptools import setup
from setuptools import find_packages
with io.open('README.md', 'rt', encoding='utf8') as f:
README = f.read()
if sys.argv[-1] == 'test':
os.system('python -sm unittest discover tests "*_te | st.py"')
sys.exit(0)
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist')
os.system('twine upload dist/*')
sys.exit(0)
VERSION = '0.0.7'
REQUIRES = ['google-api-python-client>=1.5.3', 'pandas>=0.22.0', 'fire>=0.1.3']
GI | THUB_URL = 'https://github.com/condad/google-objects'
setup(
name='google_objects',
packages=find_packages(),
version=VERSION,
description="A simple OO wrapper around Google's python API client",
long_description=README,
long_description_content_type='text/markdown',
author='Connor Sullivan... |
grcanosa/my-telegram-bot | src/mybot/handler/piropos.py | Python | gpl-3.0 | 833 | 0.040816 | #!/usr/bin/python3
import emoji
import random;
from .phraselist import PhraseList;
#from ..data.teletokens import CID;
from telegram import Bot,Update;
class PiropoList(PhraseList):
def __init__(self,cmdget | = "",
cmdadd="",
filename ="",
updater=None,
userR = None,
priority = 50):
super().__init__(cmdget=cmdget,cmdadd=cmdadd,filename=filename,updater=updater,userR=userR,priority=priority);
def get_ma... | eja de pedir piropos";
#return "BQADBAADKgAD15TmAAFDS0IqiyCZgwI","audio"
#return "AwADBAADJwAD15TmAAG3Lbh5kdhR6QI","voice"
return text,"message";
|
mkouhei/hatena2rest | setup.py | Python | gpl-3.0 | 2,308 | 0.004333 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012 Kouhei Maeda <mkouhei@palmtb.net>
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 3 of the License,... | 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. I... | Status :: 3 - Alpha",
"Intended Audience :: Information Technology",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Site Management",
"Topic :: Text Processing :: Markup",
"Topic :: Text Processin... |
huanqi/leetcode-python | implement_strstr/solution.py | Python | bsd-2-clause | 483 | 0 | class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
n = len(haystack)
m = len(needle)
for i in range(n + 1 - m):
matched = True
for k in range(m):
... | break
if | matched:
return i
return -1
|
errror/SlackRTMBot | slott/plugins/ping/__init__.py | Python | lgpl-3.0 | 63 | 0.015873 | #!/usr/bin/env py | thon3
print('ping/__init__.py')
import ping
| |
gilleshenrard/ikoab_elise | api/views.py | Python | mit | 2,172 | 0.00046 | from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fs... | serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
re | turn Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
e-mission/e-mission-server | emission/analysis/modelling/tour_model/get_users.py | Python | bsd-3-clause | 1,172 | 0.007679 | import emission.analysis.modelling.tour_model.data_preprocessing as preprocess
# to determine if the user is valid:
# valid user should have >= 10 trips for further analysis and the proportion of filter_trips is >=50%
def valid_user(filter_trips,trip | s):
valid = False
if len(filter_trips) >= 10 and len(filter_trips) / len(trips) >= 0.5:
valid = True
return valid
# - user_ls: a list of strings representing short user names, such as [user1, user2, user3...]
# - v | alid_user_ls: a subset of `user_ls` for valid users, so also string representation of user names
# - all_users: a collection of all user ids, in terms of user id objects
def get_user_ls(all_users,radius):
user_ls = []
valid_user_ls = []
for i in range(len(all_users)):
curr_user = 'user' + str(i + 1)... |
sinhrks/chainer | tests/cupy_tests/sorting_tests/test_search.py | Python | mit | 4,156 | 0 | import unittest
from cupy import testing
@testing.gpu
class TestSearch(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_allclose()
def test_argmax_all(self, xp, dtype):
a = testing.shaped_random((2, 3), xp, dtype)
return a.argmax()
... | py_cupy_allclose()
def test_argmax_axis1(self, xp, dtype):
a = testing.shaped_random((2, 3, 4), xp, dtype)
return a.argmax(axis=1)
@testing.for_all_dtypes()
@testing.nu | mpy_cupy_allclose()
def test_argmax_axis2(self, xp, dtype):
a = testing.shaped_random((2, 3, 4), xp, dtype)
return a.argmax(axis=2)
@testing.for_all_dtypes()
@testing.numpy_cupy_allclose()
def test_argmin_all(self, xp, dtype):
a = testing.shaped_random((2, 3), xp, dtype)
... |
rigetticomputing/pyquil | pyquil/parser.py | Python | apache-2.0 | 1,511 | 0 | ##############################################################################
# Copyright 2016-2018 Rigetti Computing
#
# 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... | uil))
def parse(quil: str) -> List[AbstractInstruction]:
"""
Parse a raw Quil program and return a corresponding list of PyQuil objects.
:param str quil: a single or multiline Quil program
:return: list of instructions
| """
p = run_parser(quil)
return p
|
greggyNapalm/lunaport_client | lunaport_client/tests/test_server_resource.py | Python | apache-2.0 | 1,964 | 0.00611 | #import sys
#sys.path.append('../')
import responses
import requests
#from lunaport_client import LunaportClinetv1
#import lunaport_client as lc
#print lc.__version__
#import .. lunaport_client
#from ..lunaport_client import LunaportClinet
#from lunaport_client import LunaportClinet as lunac
#lunac = lunaport_client... | /twitter.com/api/1/foobar',
body='{"error": "not found"}', status=404,
content_type='application/json')
resp = requests.get('http://twitter.com/api/1/foobar')
assert resp.json() == {"error": "not found"}
assert len(responses.calls) == 1
assert responses.calls[0].re... | f test_my_YYY():
responses.add(responses.GET, 'http://twitter.com/api/1/foobar',
body='{"error": "not found"}', status=404,
content_type='application/json')
resp = requests.get('http://twitter.com/api/1/foobar')
assert resp.json() == {"error": "not found"}
assert l... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/bin/2.78/scripts/addons/rigify/rigs/pitchipoy/tentacle.py | Python | gpl-3.0 | 16,078 | 0.020152 | import bpy
from ...utils import copy_bone
from ...utils import strip_org, make_deformer_name, connected_children_names
from ...utils import make_mechanism_name, put_bone, create_sphere_widget
from ...utils import create_widget, create_circle_widget
from ...utils import MetarigError
from rna_ | prop_ui import rna_i | dprop_ui_prop_get
script = """
controls = [%s]
master_name = '%s'
if is_selected( controls ):
layout.prop( pose_bones[ master_name ], '["%s"]', slider = True )
layout.prop( pose_bones[ master_name ], '["%s"]', slider = True )
"""
class Rig:
def __init__(self, obj, bone_name, params):
self... |
bl4ckdu5t/registron | tests/interactive/test_ipython.py | Python | mit | 441 | 0.004535 | #--------------------------------------------------------- | --------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------... | mbed
embed()
|
online-behaviour/machine-learning | getTweetText.py | Python | apache-2.0 | 1,768 | 0.010181 | #!/usr/bin/python3 -W all
"""
getTweetText.py: extract tweet text from json file
usage: getTweetText.py < file
20170418 erikt(at)xs4all.nl
"""
import csv
import json
import re
import sys
# command name for error messages
COMMAND = sys.argv[0]
patternNewline = re.compile("\n")
# open csv output
with sys.s... | "in_reply_to_status_id_str" in jsonLine["retweeted_status"]:
replyId = jsonLine["retweeted_status"]["in_reply_to_status_id_str"]
screenName = jsonLine["user"]["screen_ | name"]
date = jsonLine["created_at"]
text = jsonLine["text"]
text = patternNewline.sub(" ",text)
outFile.writerow([thisId,replyId,date,screenName,text])
csvfile.close()
|
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/distutils/command/bdist_dumb.py | Python | mit | 5,127 | 0.00195 | """distutils.command.bdist_dumb
Implements the Distutils 'bdist_dumb' command (create a "dumb" built
distribution -- i.e., just an archive to be unpacked under $prefix or
$exec_prefix)."""
__revision__ = "$Id$"
import os
from sysconfig import get_python_version
from distutils.util import get_platform
from distutil... | nstall_base),
repr(install.install_platbase)))
else:
archive_root = os.path.join(self.bdist_dir,
ensure_relative(install.install_base))
# Make the archive
filename = self.make_archiv | e(pseudoinstall_root,
self.format, root_dir=archive_root,
owner=self.owner, group=self.group)
if self.distribution.has_ext_modules():
pyversion = get_python_version()
else:
pyversion = 'any'
self.di... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatterternary/_selectedpoints.py | Python | mit | 435 | 0.002299 | import _plotly_utils.basevalidators
class SelectedpointsValidator(_plotly_utils.basevalidators.AnyValidator):
def | __init__(
self, plotly_name="selectedpoints", parent_name="scatterternary", **kwargs
):
super(SelectedpointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
| **kwargs
)
|
nkgilley/home-assistant | tests/components/juicenet/__init__.py | Python | apache-2.0 | 40 | 0 | """Te | sts for | the JuiceNet component."""
|
hacktoberfest17/programming | hello_world/python/hello_world_py3.py | Python | gpl-3.0 | 23 | 0.043478 | pr | int ("Hello World | !")
|
errbotio/errbot | errbot/templates/initdir/example.py | Python | gpl-3.0 | 667 | 0.001499 | from errbot import BotPlugin, botcmd
class Example(BotPlugin):
"""
This is a very basic plugin to try out your new installation and get you started.
Feel free to tweak me to experiment with Errbot.
You can find me in your init directory in the subdirectory plugins.
"""
@botcmd # flags a comm... | tweak me to experiment with Errbot.
You can | find me in your init directory in the subdirectory plugins.
"""
return "It *works*!" # This string format is markdown.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.