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
kubeflow/kubeflow
components/crud-web-apps/volumes/backend/apps/common/status.py
Python
apache-2.0
2,168
0
from kubeflow.kubeflow.crud_backend import api, status def pvc_status(pvc): """ Set the status of the pvc """ if pvc.metadata.deletion_timestamp is not None: return status.create_status(status.STATUS_PHASE.TERMINATING, "Deleting Volume...") if pvc.statu...
eason == "Provisioning": phase = status.STATUS_PHASE.WAITING elif evs[0].reason == "FailedBinding": phase = status.STATUS_PHASE.WARNING elif evs[0].type == "Warning": phase = status.STATUS
_PHASE.WARNING elif evs[0].type == "Normal": phase = status.STATUS_PHASE.READY return status.create_status(phase, msg, state) def viewer_status(viewer): """ Return a string representing the status of that viewer. If a deletion timestamp is set we want to return a `Terminating` state. ...
SwankSwashbucklers/bottle-builder
bottle-builder.py
Python
mit
18,381
0.013111
""" """ ################################################################################ ##### Command Line Interface ################################################### ################################################################################ from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter...
return 'nothing to see here' $ph{Run Server} if args.deploy: run(host=args.ip, port=args.port, server='cherrypy') #deployment else: run(host=args.ip, port=args.port, debug=True, reloader=True) #development """ ) MAIN_ROUTE_TEMPLATE = Template("""\ @route('/${path}') def ${method_name}(): return templat...
e='${template}') """ ) STATIC_ROUTE_TEMPLATE = Template("""\ @get('/${path}') def load_resource(): return static_file('${file}', root='${root}') """ ) WATCH_SASS_SCRIPT = Template("""\ from sys import argv, exit from signal import signal, SIGTERM, SIGINT from shutil import rmtree from subprocess import Popen fr...
simplegeo/sqlalchemy
examples/beaker_caching/model.py
Python
mit
3,110
0.006752
"""Model. We are modeling Person objects with a collection of Address objects. Each Address has a PostalCode, which in turn references a City and then a Country: Person --(1..n)--> Address Address --(has a)--> PostalCode PostalCode --(has a)--> City City --(has a)--> Country """ from sqlalchemy import Column, Int...
# Caching options. A set of three RelationshipCache options # which can be applied to Query(), causing the "l
azy load" # of these attributes to be loaded from cache. cache_address_bits = RelationshipCache("default", "byid", PostalCode.city).\ and_( RelationshipCache("default", "byid", City.country) ).and_( RelationshipCache("default", "byid", Address.post...
kmacinnis/sympy
sympy/core/numbers.py
Python
bsd-3-clause
81,489
0.000577
from __future__ import print_function, division import decimal import math import re as regex import sys from collections import defaultdict from .core import C from .sympify import converter, sympify, _sympify, SympifyError from .singleton import S, Singleton from .expr import Expr, AtomicExpr from .decorators impor...
: return _mpf_zero else: # don't change anything; this should already # be a well formed mpf tuple return mpf rv = mpf_normalize(sign, man, expt, bc, prec, rnd) return rv # TODO: we should use the warnings module _errdict = {"divide": False} def seterr(...
["divide"] != divide: clear_cache() _errdict["divide"] = divide def _as_integer_ratio(p): """compatibility implementation for python < 2.6""" neg_pow, man, expt, bc = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_) p = [1, -1][neg_pow % 2]*man if expt < 0: q = 2**-expt else: ...
our-iot-project-org/pingow-web-service
src/posts/views.py
Python
mit
5,217
0.000767
from django.core import serializers from rest_framework.response import Response from django.http import JsonResponse try: from urllib import quote_plus # python 2 except: pass try: from urllib.parse import quote_plus # python 3 except: pass from django.contrib import messages from django.contrib.co...
ata, parent=parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "c...
"post_detail.html", context) def post_list(request): today = timezone.now().date() queryset_list = Post.objects.active() # .order_by("-timestamp") if request.user.is_staff or request.user.is_superuser: queryset_list = Post.objects.all() query = request.GET.get("q") if query: que...
buzztroll/staccato
staccato/cmd/api.py
Python
apache-2.0
899
0.001112
import eventlet import gettext import sys from staccato.common import config import staccato.openstack.common.wsgi as os_wsgi import staccato.openstack.common.pastedeploy as os_pastedeploy # Monkey patch socket and time eventlet.patcher.monkey_patch(all=False, socket=True, time=True) gettext.install('staccato', unic...
conf) server = os_
wsgi.Service(wsgi_app, conf.bind_port) server.start() server.wait() except RuntimeError as e: fail(1, e) main()
verejnedigital/verejne.digital
data/prod_generation/entity_tools.py
Python
apache-2.0
3,557
0.000562
"""Utility methods for handling Entities. These methods can be shared between entity generation (invoked through the Entities class) at the start of prod data generation, and between post processing methods (such as adding edges between family members and neighbours). """ import codecs import collections import re ...
, # 'titles_suf': titles_suf, # } # Less conservative matching: Find the last token that is a surname, # and take the rest before it
as given names i = len(names) - 1 while (i >= 1) and (names[i] not in surnames): i -= 1 if i >= 1: return ParsedName( titles_prefix=titles_pre, firstnames=names[:i], surname=names[i], titles_suffix=titles_suf ) else: if ver...
leleobhz/scripts
python/chat_back_machine/engine/PyDbLite/MySQL.py
Python
gpl-2.0
11,904
0.015793
"""PyDbLite.py adapted for MySQL backend Differences with PyDbLite: - pass the connection to the MySQL db as argument to Base() - in create(), field definitions must specify a type - no index - the Base() instance has a cursor attribute, so that SQL requests can be executed : db.cursor.execute(an_sql_req...
me) elif mode == "open": return self.open() else: raise IOError,"Base %s already exists" %self.name self.fields = [ f[0] for f in fields ] self.all_fields = ["__id__","__version__"]+self.fields _types = ["INTEGER PRIMARY KEY AUTO_INC...
zip(self.all_fields,_types)] sql = "CREATE TABLE %s (%s)" %(self.name, ",".join(f_string)) self.cursor.execute(sql) return self def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" self._ge...
Accelerite/cinder
cinder/tests/targets/test_tgt_driver.py
Python
apache-2.0
11,627
0.000172
# 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...
' Prevent removal: No\n' ' Readonly: No\n' ' SWP: No\n'
' Thin-provisioning: No\n' ' Backing store type: rdwr\n' ' Backing store path: /dev/stack-volumes-lvmdriver-1/volume-83c2e877-feed-46be-8435-77884fe55b45\n' # noqa ' Backing store flags:\n' ' Account information:\n' ...
michellemorales/OpenMM
models/lfads/utils.py
Python
gpl-2.0
12,183
0.010671
# Copyright 2017 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...
HDF5 format. Args: data_fname: The filename of the file from which to read the data. Returns: A diction
ary whose keys will vary depending on dataset (but should always contain the keys 'train_data' and 'valid_data') and whose values are numpy arrays. """ try: with h5py.File(data_fname, 'r') as hf: data_dict = {k: np.array(v) for k, v in hf.items()} return data_dict except IOError: prin...
antoinecarme/pyaf
tests/artificial/transf_Anscombe/trend_PolyTrend/cycle_0/ar_12/test_artificial_1024_Anscombe_PolyTrend_0_12_20.py
Python
bsd-3-clause
265
0.086792
import pyaf.Bench.TS_datasets as tsds import tests.artifici
al.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length
= 0, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 12);
kaushik94/sympy
sympy/external/tests/test_importtools.py
Python
bsd-3-clause
1,405
0.004982
from sympy.external import import_module from sympy.utilities.pytest import warns # fixes issue that arose in addressing issue 6533 def test_no_stdlib_collections(): ''' make sure we get the right collections when it is not part of a larger list ''' import collections matplotlib = import_module...
llections def test_no_stdlib_collections3(): '''make sure we get the right collections with no catch'''
import collections matplotlib = import_module('matplotlib', __import__kwargs={'fromlist': ['cm', 'collections']}, min_module_version='1.1.0') if matplotlib: assert collections != matplotlib.collections def test_min_module_version_python3_basestring_error(): with warns(UserWarning):...
kinow-io/kinow-python-sdk
kinow_client/models/prepayment_bonus_response.py
Python
apache-2.0
7,163
0.000419
# coding: utf-8 """ Server API Reference for Server API (REST/Json) OpenAPI spec version: 2.0.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class PrepaymentBonusResponse(object): """ NOTE: This cl...
paymentBonusResponse. :type: int """ self._id = id @property def name(self): """ Gets the name of this PrepaymentBonusResponse. :return: The name of this PrepaymentBonusResponse. :rtype: str """
return self._name @name.setter def name(self, name): """ Sets the name of this PrepaymentBonusResponse. :param name: The name of this PrepaymentBonusResponse. :type: str """ self._name = name @property def id_product(self): """ Ge...
viswimmer1/PythonGenerator
data/python_files/31890725/gamestate.py
Python
gpl-2.0
5,483
0.001094
import pygame from pygame.locals import * import random import itertools import state import block import tetros import states from text import Text from colors import Colors from engine import Engine from playfield import Playfield from countdown import Countdown class GameState(state.State): tetro_classes = ...
f.falling_tetro = None break
else: # update row self.falling_tetro.row += 1 # reset counter self.falling_tetro.drop_delay_counter = 0 # new tetro if needed if self.falling_tetro is None: color = random.choice(self.tetro_...
Yelp/pyes
tests/test_facets.py
Python
bsd-3-clause
6,193
0.004198
# -*- coding: utf-8 -*- from __future__ import absolute_import import unittest from .estestcase import ESTestCase from pyes.facets import DateHistogramFacet from pyes.filters import TermFilter, RangeFilter from pyes.query import FilteredQuery, MatchAllQuery, Search from pyes.utils import ESRange import datetime class ...
q = MatchAllQuery() q = FilteredQuery(q, RangeFilter(qrange=ESRange('date', datetime.date(2011, 4, 1), datetime.date(2011, 5, 1), include_upper=False))) q = q.search() q.facet.facets.append(DateHistogramFacet('date_facet', field='date', ...
resultset = self.conn.search(query=q, indices=self.index_name, doc_types=[self.document_type]) self.assertEquals(resultset.total, 2) self.assertEquals(resultset.facets['date_facet']['entries'], [{u'count': 2, u'time': 1301616000000}]) if __name__ == "__main__": unittest.main()
be-cloud-be/horizon-addons
server/addons/project/project.py
Python
agpl-3.0
53,981
0.005131
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import datetime, date from lxml import etree import time from openerp import api from openerp import SUPERUSER_ID from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate ...
isplay.'), } def _get_default_project_ids(self, cr, uid, ctx=None): if ctx is None: ctx = {} default_project_id = ctx.get('default_project_id') return [default_project_id] if default_project_id else None _defaults = { 'sequence': 1, 'project_ids': _get_d...
ault_project_ids, } _order = 'sequence' class project(osv.osv): _name = "project.project" _description = "Project" _inherits = {'account.analytic.account': "analytic_account_id", "mail.alias": "alias_id"} _inherit = ['mail.thread', 'ir.needaction_mixin'] _period_number = 5...
psykohack/crowdsource-platform
crowdsourcing/models.py
Python
mit
21,348
0.001499
from django.contrib.auth.models import User from django.db import models from django.utils import timezone from oauth2client.django_orm import FlowField, CredentialsField from crowdsourcing.utils import get_delimiter import pandas as pd import os class RegistrationModel(models.Model): user = models.OneToOneField(...
el): user_source = models.ForeignKey(UserProfile, related_name='user_source') user_target = models.ForeignKey(UserProfile, related_name='user_target') deleted = models.BooleanField(default=False) created_timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) last_updated = models.DateT
imeField(auto_now_add=False, auto_now=True) class Category(models.Model): name = models.CharField(max_length=128, error_messages={'required': "Please enter the category name!"}) parent = models.ForeignKey('self', null=True) deleted = models.BooleanField(default=False) created_timestamp = models.DateTi...
wizzat/wizzat.py
tests/testcase.py
Python
mit
630
0.022222
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import wizzat.testutil import wizzat.pghelper class DBTestCase(wizzat.testutil.TestCase): db_info = { 'host' : 'localhost', 'port' : 5432, 'user' : 'wizzat', ...
autocommit' : False, } db_mgr = wizzat.pghelper.ConnMgr(db_info, max_ob
js = 3, ) def conn(self, name = 'testconn'): conn = self.db_mgr.name(name) conn.autocommit = True return conn
berquist/programming_party
eric/project12/davidson.py
Python
mpl-2.0
2,084
0.00144
"""A block Davidson solver for finding a fixed number of eigenvalues. Adapted from https://joshuagoings.com/2013/08/23/davidsons-method/ """ import time from typing import Tuple import numpy as np from tqdm import tqdm def davidson(A: np.ndarray, k: int, eig: int) -> Tuple[np.ndarray, np.ndarray]: assert len(A....
range(k, mmax, k)): if m <= k: for j in range(k): V[:, j] = t[:, j] / np.linalg.norm(t[:, j]) theta_old = 1 elif m > k: theta_old = theta[:eig] V, R = np.linalg.qr(V) T = V[:, : (m + 1)].T @ A @ V[:, : (m + 1)] THETA, S = np.lin...
idx = THETA.argsort() theta = THETA[idx] s = S[:, idx] for j in range(k): w = (A - theta[j] * I) @ V[:, : (m + 1)] @ s[:, j] q = w / (theta[j] - A[j, j]) V[:, (m + j + 1)] = q norm = np.linalg.norm(theta[:eig] - theta_old) if norm < tol:...
happz/settlers
tests/units/tournaments/randomized.py
Python
mit
746
0.009383
import tests.units.tournaments import lib.datalayer import g
ames import games.settlers import tournaments import hruntime from tests import * from tests.units.tournaments import create_and_populate_tournament class Tests(TestCase): @classmethod def setup_class(cls): super(Tests, cls).setup_class() hruntime.dbroot = lib.datalayer.Root() hruntime.dbroot.users[...
YSTEM'] = tests.DummyUser('SYSTEM') def test_sanity(self): patched_events = { 'tournament.Created': 2, 'tournament.PlayerJoined': 12, 'game.GameCreated': 8, 'game.PlayerJoined': 4, 'game.PlayerInvited': 8 } with EventPatcherWithCounter(patched_events): T = create_and_...
ecreall/nova-ideo
novaideo/views/smart_folder_management/remove_smart_folder.py
Python
agpl-3.0
2,248
0.00089
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from p...
'removesmartfolder' viewid = 'removesmartfolder' template = 'pontus:templates/views_templates/simple_multipleview.pt' views = (RemoveSmartFolderViewStudyReport, RemoveSmartFolderView) validators = [RemoveSmartFolder.get_validator()] DEFAULTMAPPING_ACTIONS_VIEWS.update( {RemoveSmartFolder: RemoveS...
wMultipleView})
jonathf/matlab2cpp
src/matlab2cpp/rules/_cell.py
Python
bsd-3-clause
495
0.00404
from .variables import * def Cell(node): # cells must stand on own line if node.parent.cls not in ("Assign", "Assigns"): node.auxiliary("cell") return "{", ",", "}" def Assign(node): if node.name == 'var
argin': out = "%(0)s = va_arg(varargin, " + node[0].type + ") ;" else
: out = "%(0)s.clear() ;" # append to cell, one by one for elem in node[1]: out = out + "\n%(0)s.push_back(" + str(elem) + ") ;" return out
FlowFX/unkenmathe.de
src/um/exercises/migrations/0005_auto_20170826_0942.py
Python
agpl-3.0
578
0.00173
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-26 09:42 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [
('exercises', '0004_exercise_author'), ] operations = [ migrations.AlterField(
model_name='exercise', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), ]
gnumdk/eolie
eolie/helper_dbus.py
Python
gpl-3.0
3,499
0
# Copyright (c) 2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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, or # (at your option) any later version. ...
_id as int @param dbus_args as GLib.Variant()/None @param callback as function """ try: bus = El().get_dbus_connection() proxy_bus = PROXY_BUS % page_id Gio.DBusProxy.new(bus, Gio.DBusProxyFlags.NONE, None, proxy_b...
call, dbus_args, callback, *args) except Exception as e: print("DBusHelper::call():", e) def connect(self, signal, callback, page_id): """ Connect callback to object signals @param signal as str @param callback as function ...
projectarkc/arkc-server
arkcserver/pyotp/totp.py
Python
gpl-2.0
2,787
0.001435
from __future__ import print_function, unicode_literals, division, absolute_import import datetime import time import ntplib from pyotp import utils from pyotp.otp import OTP class TOTP(OTP): systime_offset = None def __init__(self, *args, **kwargs): """ @option options [Integer] interval ...
al = kwargs.pop('interval', 30) if self.systime_offset is None: try: c = ntplib.NTPClient() TOTP.systime_offset = int(c.request( 'pool.ntp.org', version=3).offset) except Exception: self.systime_offset = 0 super(...
l be adjusted to UTC automatically @param [Time/Integer] time the time to generate an OTP for @param [Integer] counter_offset an amount of ticks to add to the time counter """ if not isinstance(for_time, datetime.datetime): for_time = datetime.datetime.fromtimestamp(int(for_...
treycucco/py-utils
idb/spreadsheet/csv.py
Python
bsd-3-clause
862
0.012761
import csv from . import WorksheetBase, WorkbookBase, C
ellMode class CSVWorksheet(WorksheetBase): def __init__(self, raw_sheet, ordinal): super().__init__(raw_sheet, ordinal) self.name = "Sheet 1" self.nrows = len(self.raw_sheet) self.ncols = max([len(r) for r in self.raw_sheet]) def parse_cell(self, cell, coords, cell_mode=CellMode.cooked): try:...
f, row_index): return self.raw_sheet[row_index] class CSVWorkbook(WorkbookBase): def iterate_sheets(self): with open(self.filename, "r") as rf: reader = csv.reader(rf) yield list(reader) def get_worksheet(self, raw_sheet, index): return CSVWorksheet(raw_sheet, index)
bdfoster/blumate
tests/components/test_graphite.py
Python
mit
8,152
0
"""The tests for the Graphite component.""" import socket import unittest from unittest import mock import blumate.core as ha import blumate.components.graphite as graphite from blumate.const import ( EVENT_STATE_CHANGED, EVENT_BLUMATE_START, EVENT_BLUMATE_STOP, STATE_ON, STATE_OFF) from tests.common impo...
butes.""" mock_time.return_value = 12345 attrs = {'foo': 1, 'bar': 2.0, 'baz': True,
'bat': 'NaN', } expected = [ 'bm.entity.state 0.000000 12345', 'bm.entity.foo 1.000000 12345', 'bm.entity.bar 2.000000 12345', 'bm.entity.baz 1.000000 12345', ] state = mock.MagicMock(state=0, attributes=attrs) ...
punalpatel/st2
st2reactor/st2reactor/container/manager.py
Python
apache-2.0
6,484
0.002159
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
or(sensor=sensor_obj) return LOG.info('Sensor %s updated. Reloading sensor.', sensor_ref) try: self._sensor_container.remove_sensor(sensor=sensor_obj) except: LOG.exception('Failed to reload sensor %s', sensor_ref) else: self._sensor_conta...
_sensor(self, sensor): if not self._sensors_partitioner.is_sensor_owner(sensor): LOG.info('sensor %s is not supported. Ignoring delete.', self._get_sensor_ref(sensor)) return LOG.info('Unloading sensor %s.', self._get_sensor_ref(sensor)) self._sensor_container.remove_sens...
google/swift-jupyter
test/fast_test.py
Python
apache-2.0
196
0
"""Runs
fast tests.""" import unittest from
tests.kernel_tests import SwiftKernelTests, OwnKernelTests from tests.simple_notebook_tests import * if __name__ == '__main__': unittest.main()
lixiangning888/whole_project
modules/signatures_orignal/banker_cridex.py
Python
lgpl-3.0
2,206
0.00544
# Copyright (C) 2014 Robby Zeitfuchs (@robbyFux) # # 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, or # (at your option) any later version. # # This program is d...
m/analysis/NDU2ZWJjZTIwYmRiNGVmNWI3MDUyMGExMGQ0MmVhYTY/", "https://malwr
.com/analysis/MTA5YmU4NmIwMjg5NDAxYjlhYzZiZGIwYjZkOTFkOWY/"] def run(self): indicators = [".*Local.QM.*", ".*Local.XM.*"] match_file = self.check_file(pattern=".*\\KB[0-9]{8}\.exe", regex=True) match_batch_file = self.check_file(pattern=".*\\\\Te...
georgemarshall/django
django/contrib/gis/db/backends/base/operations.py
Python
bsd-3-clause
6,371
0.002197
from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.measure import ( Area as AreaMeasure, Distance as DistanceMeasure, ) from django.db.utils import NotSupportedError from django.utils.functional import cached_property class Ba...
, compiler): """ Return the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend. """ def transform_value(value, ...
atial_function_name('Transform'), f.srid) if transform_value(value.output_field, f) else '%s' ) if transform_value(value, f): # Add Transform() to the SQL placeholder. return '%s(%s(%%s,%s), %s)' % ( self.spatial_function_name('...
openkamer/openkamer
parliament/migrations/0003_auto_20161126_2342.py
Python
mit
467
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016
-11-26 22:42 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parliament', '0002_auto_20161123_1157'), ] ope
rations = [ migrations.AlterField( model_name='politicalparty', name='name_short', field=models.CharField(max_length=200), ), ]
0--key/lib
portfolio/Python/scrapy/axemusic/tomleemusic_ca.py
Python
apache-2.0
5,954
0.003359
import re import logging import urllib import csv import os import shutil from datetime import datetime import StringIO from scrapy.spider import BaseSpider from scrapy import signals from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.response import get_base_...
et_base_url(response), url) yield Request(url, callback=self.parse_product) next_page = hxs.select(u'//a[@class="smallPrint" and contains(text(),"Next")]/@href').extract() if next_page: url = urljoin_rfc(get_base_url(response), next_page[0]) yield Request(url, callba...
hxs = HtmlXPathSelector(response) product_loader = ProductLoader(item=Product(), selector=hxs) product_loader.add_value('url', response.url) product_loader.add_xpath('name', u'//h1[@class="productDetailHeader"]/text()') if hxs.select(u'//span[@class="productDetailSelling"]/text()'):...
DQE-Polytech-University/Beamplex
src/laserstructure.py
Python
mit
3,771
0.008221
import matplotlib.pyplot as plt #stores information about laser structure #saves refraction and electric field profiles in text and graphic form to HDD class Laser: refraction = [] field = [] gridX = [] gridN = [] field = [] def __init__(self, (wavelength, concentration, thickness...
self.gridX[i]) + ": " + str(self.gridN[i]) + "\n") refractionFile.close() #field profile output def plotField(self): if isinstance(self.gridX, li
st) == False: raise TypeError("self.gridX should be a list") if isinstance(self.field, list) == False: raise TypeError("self.field should be a list") if len(self.gridX) <= 20: raise ValueError("len(self.gridX) out of range") if len(self.field) <= 20: ...
rmit-ir/SummaryRank
summaryrank/__main__.py
Python
mit
2,623
0.000381
""" The main script """ import argparse import summaryrank.features import summaryrank.importers import summaryrank.tools DESCRIPTION = ''' SummaryRank is a set of tools that help producing machine-learned summary/sentence rankers. It supports a wide range of functions such as generating judgments in trec_eval forma...
p), ("import_trec_novelty", summaryrank.importers.import_trec_novelty), ("import_mobileclick", summaryrank.importers.import_mobileclick), ] FEATURE_FUNCTIONS = [ ("gen_term", summaryrank.features.gen_term), ("gen_freqstats", summaryrank.features.gen_freqstats), ("gen_esa", summaryrank.features.gen_...
[ ("describe", summaryrank.tools.describe), ("cut", summaryrank.tools.cut), ("join", summaryrank.tools.join), ("shuffle", summaryrank.tools.shuffle), ("split", summaryrank.tools.split), ("normalize", summaryrank.tools.normalize), ] def _make_command_list(functions): """ Prepare a formatted...
pmverdugo/fiware-validator
validator/tests/api/middleware/test_ssl.py
Python
apache-2.0
1,568
0.000638
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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 ...
"OK" self.item.external.return_value = "OK" observed = self.item.process_request(input) self.assertEqual(expected, observed) def tearDown(self): """ Cleanup the SSLMiddleware instance """ super(SSLMiddlewareTestC
ase, self).tearDown() self.m.UnsetStubs() self.m.ResetAll()
nickgashkov/virtualspace
virtualspace/utils/exceptions.py
Python
mit
290
0
# Copyright (c) 2017 Nick G
ashkov # # Distributed under MIT License. See LICENSE file for details. class ValidationError(Exception): def __init__(self, *args, **kwargs): self.error_dict = kwargs.pop('error_dict') super(ValidationError, self).__init__(*
args, **kwargs)
forYali/yali
yali/gui/ScrBootloader.py
Python
gpl-2.0
4,461
0.003362
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # ...
self.ui.advancedSettingsBox.hide() else: self.ui.advancedSettingsBox.show() def activateChoices(self): for choice in self.bootloader.choices.keys(): if choice == BOOT_TYPE_M
BR: self.ui.installMBR.setText(_("The first sector of")) self.boot_disk = self.bootloader.choices[BOOT_TYPE_MBR][0] # elif choice == BOOT_TYPE_RAID: # self.ui.installPartition.setText("The RAID array where Pardus is installed") # self.boot_partiti...
ajrichards/GenesDI
genesdi/RunMakeFigures.py
Python
gpl-3.0
5,628
0.022388
#!/usr/bin/python # # to run an example # python RunMakeFigures.py -p Demo -i 0 -j 1 -f 3FITC_4PE_004.fcs -h ./projects/Demo # import getopt,sys,os import numpy as np ## important line to fix popup error in mac osx import matplotlib matplotlib.use('Agg') from cytostream import Model import matplotlib.pyplot as plt #...
print "WARNING: RunMakeFigures failed errorchecking" if projectID == None or channel1 ==
None or channel2 == None or selectedFile == None: bad_input() run = False print "WARNING: RunMakeFigures failed errorchecking" if os.path.isdir(homeDir) == False: print "ERROR: homedir does not exist -- bad project name", projectID, homeDir run = False if altDir != None and os.path.isdir(altDir) =...
r0h4n/commons
tendrl/commons/objects/node_context/__init__.py
Python
lgpl-2.1
7,441
0
import json import os import socket import sys import uuid import etcd from tendrl.commons import objects from tendrl.commons.utils import etcd_utils from tendrl.commons.utils import event_utils from tendrl.commons.utils import log_utils as logger NODE_ID = None class NodeContext(objects.BaseObject): def __i...
y curr_tags = [] try: _nc_data = etcd_utils.read( "/nodes/%s/NodeContext/data" % self.node_id ).value curr_tags = json.loads(_nc_data)['tags'] except etcd.EtcdKeyNotFound: pass try: curr_tags = json.loads(curr_...
[] self.tags += NS.config.data.get('tags', []) self.tags += curr_tags self.tags = list(set(self.tags)) self.status = status or "UP" self.sync_status = sync_status self.last_sync = last_sync self.pkey = pkey or self.fqdn self.value = 'nodes/{0}/NodeContext...
jrha/aquilon
build/bootstrap_ms/ms/version/__init__.py
Python
apache-2.0
726
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2011,2013 Contributor # # 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 #...
e 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 governing permissions and # limitations under the License. def addpkg(
*args, **kwargs): pass
xlk521/cloudguantou
friendships/urls.py
Python
bsd-3-clause
252
0.019841
#
coding=utf8 ''' Created on 2012-9-19 @author: senon ''' from django.conf.urls.defaults import patterns, url urlpatterns = patterns('friendships.views', url(r'^concerned_about_friends/', 'concerned_about_friends')
)
jshou/bsi
bsi/bsi_parser.py
Python
mit
930
0.012903
import ply.yacc as yacc from bsi_lexer import tokens from bsi_object import BsiObject from bsi_array import BsiArray def p_object_pairs(p): 'obj : pairs' p[0] = BsiObject() for pair in p[1]: p[0].set(pair[0], pair[1]) def p_pairs_pair(p): 'pairs : pair' p[0] = [p[1]] def p_pairs_pair_pair...
ef p_array_vals(p): 'vals : val vals' p[0] = [p[1]] + p[2] def p_val
_nested_obj(p): 'val : L_BRACE obj R_BRACE' p[0] = p[2] def p_error(p): print p print "Syntax error in input!" bsi_parser = yacc.yacc()
Fokko/incubator-airflow
airflow/task/task_runner/__init__.py
Python
apache-2.0
1,828
0.001094
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation
(ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the ...
# # 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 governing permissions and limitations # under the License....
avedaee/DIRAC
Core/Utilities/Statistics.py
Python
gpl-3.0
2,281
0.021043
################################################################################################## # $HeadURL$ ################################################################################################## """Collection of DIRAC useful statistics related modules. .. warning:: By default on Error they return N...
if len(numbers): numbers = sorted([float(x) for x in numbers]) return sum(numbers)/float(len(numbers)) def getMedian( numbers ): """ Return the median of the list of numbers. :param list numbers: data sample """ # Sort the list and take the middle ele
ment. nbNum = len(numbers) if not nbNum: return copy = sorted( [float(x) for x in numbers] ) if nbNum & 1: # There is an odd number of elements return copy[nbNum//2] else: return 0.5*(copy[nbNum//2 - 1] + copy[nbNum//2]) def getVariance( numbers, posMean='Empty' ): """Determine the mea...
jojoriveraa/titulacion-NFCOW
venv/bin/django-admin.py
Python
apache-2.0
192
0
#!/home/jojoriveraa/Dropbox/Capacit
ación/Platzi/Python-Django/NFCow/venv/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_comma
nd_line()
plaid/plaid-python
plaid/model/transactions_rule_field.py
Python
mit
6,963
0.000718
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal...
properties_type (tuple): A tuple of classes accepted as additional properties values. """
allowed_values = { ('value',): { 'TRANSACTION_ID': "TRANSACTION_ID", 'NAME': "NAME", }, } validations = { } additional_properties_type = None _nullable = False @cached_property def openapi_types(): """ This must be a method beca...
sysid/nbs
lstm/lstm_text_generation.py
Python
mit
3,355
0.000596
'''Example script to generate text from Nietzsche's writings. At least 20 epochs are required before the generated text starts sounding coherent. It is recommended to run this script on GPU, as recurrent networks are quite computationally intensive. If you try this script on new data, make sure your corpus has at le...
p.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 # build the model: a single LSTM print('Build model.
..') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars))) model.add(Activation('softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) def sample(preds, temperature=1.0): # helper function to sample an index ...
ajtowns/bitcoin
test/functional/feature_anchors.py
Python
mit
2,924
0.000684
#!/usr/bin/env python3 # Copyright (c) 2020-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block-relay-only anchors functionality""" import os from test_framework.p2p import P2PInterface ...
block_relay_nodes_port = [] inbound_nodes_port = [] for p in self.nodes[0].getpeerinfo(): addr_split = p["addr"].split(":") if p["connection_type"] == "block-relay-only": block_relay_nodes_port.append(hex(int(addr_split[1]))[2:]) else: ...
") self.stop_node(0) # It should contain only the block-relay-only addresses self.log.info("Check the addresses in anchors.dat") with open(node_anchors_path, "rb") as file_handler: anchors = file_handler.read().hex() for port in block_relay_nodes_port: ...
ray-project/ray
python/ray/tests/test_node_manager.py
Python
apache-2.0
1,376
0.000727
import ray from ray._private.test_utils import run_string_as_driver # This tests the queue transitions for infeasible tasks. This has been an issue # in the past, e.g., https://github.com/ray-project/ray/issues/3275. def test_infeasible_tasks(ray_start_cluster): cluster = ray_start_cluster @ray.remote de...
mat( cluster.address, "{str(2): 1}", " " ) run_string_as_driver(driver_script) # Now add a new node that makes the task feasible
. cluster.add_node(resources={str(2): 100}) # Make sure we can still run tasks on all nodes. ray.get([f._remote(args=[], kwargs={}, resources={str(i): 1}) for i in range(3)]) if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", __file__]))
feer56/Kitsune1
scripts/fix_tb_basedon.py
Python
bsd-3-clause
1,520
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Finds revisions from the Thunderbird migration that don't have based_on set correctly, and are still relavent, and fixes that. Run this script like `./manage.py runscript fix_tb_basedon`. """ import sys from traceback import print_exc from django.db.models import Q ...
total = total def tick(self, incr=1): self.current += incr self.draw() def draw(self): self._wr('{0.current} / {0.total}\r'.format(self)) def _wr(self, s):
sys.stdout.write(s) sys.stdout.flush() def run_(): to_process = list(Document.objects.filter( ~Q(parent=None), current_revision__based_on=None, products__slug='thunderbird')) if len(to_process) == 0: print 'Nothing to do.' prog = Progress(len(to_process)) ...
adalke/rdkit
rdkit/sping/WX/__init__.py
Python
bsd-3-clause
20
0
from pidWX import *
mfraezz/osf.io
addons/wiki/utils.py
Python
apache-2.0
7,955
0.001383
# -*- coding: utf-8 -*- import os from future.moves.urllib.parse import quote import uuid import ssl from pymongo import MongoClient import requests from django.apps import apps from addons.wiki import settings as wiki_settings from addons.wiki.exceptions import InvalidVersionError from osf.utils.permissions import A...
d = get_sharejs_uuid(node, wname) doc_item = db['docs'].find_one({'_id': old_sharejs_u
uid}) if doc_item: doc_item['_id'] = new_sharejs_uuid db['docs'].insert(doc_item) db['docs'].remove({'_id': old_sharejs_uuid}) ops_items = [item for item in db['docs_ops'].find({'name': old_sharejs_uuid})] if ops_items: for item in ops_items: item['_id'] = item['...
WebCampZg/conference-web
cfp/migrations/0005_auto_20150319_0019.py
Python
bsd-3-clause
767
0.002608
# -*- coding: utf-8 -*- from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('cfp', '0004_paperapplication_duration'), ] operations = [ migrations.AlterField( model_name='applicant', n...
e='user', field=models.OneToOneField(related_name='applicant', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE), preserve_default=True, ), migrations.AlterField( model_name='paperapplication', name='applicant', field=models.ForeignKey(rel...
p.Applicant', on_delete=models.CASCADE), preserve_default=True, ), ]
simleo/pydoop
examples/self_contained/vowelcount/__init__.py
Python
apache-2.0
850
0
# BEGIN_COPYRIGHT # # Copyright 2009-2021 CRS4. # # 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 agree...
permissions and limitations # under the License. # # END_COPYRIGHT """ A trivial MapReduce application that counts the occure
nce of each vowel in a text input stream. It is more structured than would be necessary because we want to test automatic distribution of a package rather than a single module. """
catapult-project/catapult
third_party/gsutil/third_party/pyasn1/pyasn1/debug.py
Python
bsd-3-clause
3,361
0.000595
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # import logging from pyasn1 import __version__ from pyasn1 import error from pyasn1.compat.octets import octs2ints __all__ = ['Debug', 'setLogger', 'hexdump'] fl...
r'): NullHandler = logging.NullHandler else: # Python 2.6 and older class NullHandler(logging.Hand
ler): def emit(self, record): pass class Debug(object): defaultPrinter = Printer() def __init__(self, *flags, **options): self._flags = flagNone if 'loggerName' in options: # route our logs to parent logger self._printer = Printer( ...
bobmyhill/burnman
examples/example_perplex.py
Python
gpl-2.0
2,092
0.000478
# This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for # the Earth and Planetary Sciences # Copyright (C) 2012 - 2015 by the BurnMan team, released under the GNU # GPL v2 or later. """ example_perplex --------------- This minimal example demonstrates how burnman can be used to read and interro...
5.e9, 151) temperatures = np.linspace(1600., 1800., 3) T = 1650. entropies = rock.evaluate(['S'], pressures, np.array([T] * len(pressures)))[0] smoothed_entropies = smooth_array(array=entropies, gr
id_spacing=np.array([pressures[1] - pressures[0]]), gaussian_rms_widths=np.array([5.e8])) plt.plot(pressures/1.e9, entropies, label='entropies') plt.plot(pressures/1.e9, smoothed_entropies, label='smoothed entrop...
FrancoisRheaultUS/dipy
dipy/reconst/tests/test_ivim.py
Python
bsd-3-clause
19,029
0
""" Testing the Intravoxel incoherent motion module The values of the various parameters used in the tests are inspired by the study of the IVIM model applied to MR images of the brain by Federau, Christian, et al. [1]. References ---------- .. [1] Federau, Christian, et al. "Quantitative measurement of brain ...
ting for multivoxel data. This is to ensure that the fitting routine takes care of signals packed as 1D, 2D or 3D arrays. """
ivim_fit_multi = ivim_model_trr.fit(data_multi) est_signal = ivim_fit_multi.predict(gtab, S0=1.) assert_array_equal(est_signal.shape, data_multi.shape) assert_array_almost_equal(ivim_fit_multi.model_params, ivim_params_trr) assert_array_almost_equal(est_signal, data_multi) def test_ivim_errors(): ...
SalesforceFoundation/CumulusCI
cumulusci/core/source/github.py
Python
bsd-3-clause
4,708
0.000637
import os import shutil from cumulusci.core.exceptions import DependencyResolutionError from cumulusci.core.github import get_github_api_for_repo from cumulusci.core.github import find_latest_release from cumulusci.core.github import find_previous_release from cumulusci.utils import download_extract_github class Git...
may include one of: - commit: a commit hash - ref: a git ref - branch: a git branch - tag: a git tag - release: "latest" | "previous" | "latest_beta" If none of these are specified, CumulusCI will look for the latest release. If there is no release, it will use t...
""" ref = None if "commit" in self.spec: self.commit = self.description = self.spec["commit"] return elif "ref" in self.spec: ref = self.spec["ref"] elif "tag" in self.spec: ref = "tags/" + self.spec["tag"] elif "branch" in self.spe...
doerlbh/Indie-nextflu
augur/scratch/fitness_nonepitope.py
Python
agpl-3.0
2,409
0.027397
# assign epitope fitness to each node in the phylogeny import time from io_util import * from tree_util import * from date_util import * from seq_util import * import numpy as np from itertools import izip from collections im
port defaultdict def append_nonepitope_sites(viruses): for virus in viruses: sites_ne = nonepitope_sites(virus['seq']) virus['sites_ne'] = sites_ne def remove_nonepitope_sites(viruses): for virus in viruses: virus.pop("sites_ne", None) def remove_no
nepitope_distances(viruses): for virus in viruses: virus.pop("distance_ne", None) def most_frequent(char_list): d = defaultdict(int) for i in char_list: d[i] += 1 return sorted(d.iteritems(), key=lambda x: x[1], reverse=True)[0][0] def consensus_nonepitope(viruses): """Return consensus non-epitope sequence""...
diego-d5000/MisValesMd
env/lib/python2.7/site-packages/django/contrib/gis/geos/base.py
Python
mit
1,714
0.000583
from ctypes import c_void_p from django.contrib.gis.ge
os.error import GEOSException # Trying to import GDAL libraries, if available. Have to place in # try/except since this package may be used outside GeoDjango. try: from django.contrib.gis import gdal
except ImportError: # A 'dummy' gdal module. class GDALInfo(object): HAS_GDAL = False gdal = GDALInfo() # NumPy supported? try: import numpy except ImportError: numpy = False class GEOSBase(object): """ Base object for GEOS objects that has a pointer access propert...
lanpa/tensorboardX
tests/test_record_writer.py
Python
mit
1,257
0.000796
from tensorboardX import SummaryWriter import unittest from tensorboardX.record_writer import S3RecordWriter, make_valid_tf_name, GCSRecordWriter import os import boto3 from moto import mock_s3 os.environ.setdefault("AWS_ACCESS_KEY_ID", "foobar_key") os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "foobar_secret") cl...
ke_valid_tf_name('$ave/&sound') assert newname == '._ave/_sound' def test_record_writer_gcs(self
): pass # we don't have mock test, so expect error here. However, # Travis CI env won't raise exception for the following code, # so I commented it out. # with self.assertRaises(Exception): # writer = GCSRecordWriter('gs://this/is/apen') # writer.write(bytes(4...
hpleva/pyemto
pyemto/system.py
Python
mit
148,431
0.003099
# -*- coding: utf-8 -*- """ Created on Wed Dec 3 14:25:06 2014 @author: Matti Ropo @author: Henrik Levämäki """ from __future__ import print_function import time import os import sys import numpy as np import pyemto.common.common as common class System: """The main class which provides the basis for the pyEMTO...
n :type **kwargs: str,int,float,list(str),list(int),list(float) :returns: None :rtype: None """ if lat is None:
sys.exit('System.bulk(): \'lat\' has to be given!') else: self.lat = lat if latname is None: self.latname = self.lat else: self.latname = latname if latpath is None: self.latpath = "./" else: self.latpath = l...
jefftc/changlab
Betsy/Betsy/modules/plot_prediction.py
Python
mit
2,613
0.003827
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, outfile): from genomicode import mplgraph from genomicode import filelib ...
x('Predicted_class') class_value = [i[index] for i in matrix] label_dict = dict() label_list = [] i = -1 for label in class_value: if
label not in label_dict.keys(): i = i + 1 label_dict[label] = i label_list.append(label_dict[label]) yticks = label_dict.keys() ytick_pos = [label_dict[i] for i in label_dict.keys()] fig = mplgraph.barplot(label_list, ...
iulian787/spack
var/spack/repos/builtin/packages/perl-config-general/package.py
Python
lgpl-2.1
557
0.005386
# Copyright 2013-2020 Lawrence Livermo
re 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 PerlConfigGeneral(PerlPackage): """Config::General - Generic Config Module""" homepage = "https://metacpan.org/pod/Config::...
aabe76343e88095d2296c8a422410fd2a05a1901f2b20e2e1f6fad')
david2777/DavidsTools
Standalone/openPathTool/UI_openPathTool.py
Python
gpl-2.0
3,656
0.003282
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'openPathTool.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(...
e(_fromUtf8("pathInLineEdit")) self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.pathInLineEdit) self.pathOutLineEdit = QtGui.QLineEdit(self.centralwidget) self.pathOutLi
neEdit.setReadOnly(True) self.pathOutLineEdit.setObjectName(_fromUtf8("pathOutLineEdit")) self.formLayout.setWidget(1, QtGui.QFormLayout.SpanningRole, self.pathOutLineEdit) self.buttonLayout = QtGui.QHBoxLayout() self.buttonLayout.setObjectName(_fromUtf8("buttonLayout")) self.exp...
tensorflow/probability
tensorflow_probability/python/sts/components/autoregressive_test.py
Python
apache-2.0
6,809
0.004112
# Copyright 2018 The TensorFlow Probability Authors. # # 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 o...
ressiveState
SpaceModel( num_timesteps=num_timesteps, coefficients=coefficients_order1, level_scale=level_scale, initial_state_prior=tfd.MultivariateNormalDiag( scale_diag=[level_scale])) ar2_ssm = AutoregressiveStateSpaceModel( num_timesteps=num_timesteps, coefficient...
aseciwa/independent-study
scripts/stopWords.py
Python
mit
971
0.008239
# Removing stop words # What to do with the Retweets (RT)? # Make adjust so that the # and @ are attached to their associated word (i.e. #GOP, @twitter) from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import sys def remove_stopwords(tweets): with open(tweets, 'r', buffering=1028) as re...
weets = "/Users/alanseciwa/Desktop/Independent_Study/Sep16-GOP-TweetsONLY/clean_data-TWEETONLY.csv" remove_stopwords(tweets) if __name__ == '__main__':
main() sys.exit()
TexasLAN/texaslan.org
config/wsgi.py
Python
mit
1,450
0
""" WSGI config for Texas LAN Web project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICAT...
o replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or
combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with...
bminchew/PySAR
pysar/polsar/decomp.py
Python
gpl-3.0
6,649
0.025417
""" PySAR Polarimetric SAR decomposition Contents -------- decomp_fd(hhhh,vvvv,hvhv,hhvv,numthrd=None) : Freeman-Durden 3-component decomposition """ from __future__ import print_function, division import sys,os import numpy as np ###===============================================================================...
f matform = 'T') hvhv : ndarray cross-polarized power (2|HV|^2 for matform = 'T') hhhv : ndarray HH.HV* cross-product (or 0.5(HH+VV)(HH-VV)* for matform = 'T') hhvv : ndarray HH.VV* cross
-product (or HV(HH+VV)* for matform = 'T') hvvv : ndarray HV.VV* cross-product (or HV(HH-VV)* for matform = 'T') matform : str {'C' or 'T'} form of input matrix entries: 'C' for covariance matrix and 'T' for coherency matrix ['C'] (see ref. 1) ...
edsuom/sAsync
sasync/test/test_items.py
Python
apache-2.0
12,595
0.006431
# sAsync: # An enhancement to the SQLAlchemy package that provides persistent # item-value stores, arrays, and dictionaries, and an access broker for # conveniently managing database access, table setup, and # transactions. Everything can be run in an asynchronous fashion using # the Twisted framework and its deferred ...
self.failUnless( isinstance(value, MockThing), "Item 'bar' is a '%s', not an instance of 'MockThing'" \ % value) self.failUnless( value.beenThereDoneThat, "Class instance wasn't properly persiste...
lUnlessEqual( value.method(2.5), 5.0, "Class instance wasn't properly persisted with its method") dList = [] for name in ('foo', 'bar'): dList.append(self.i.t.load(name).addCallback(gotValue, name)) return DeferredList(dList) def test_loa...
SimeonRolev/RolevPlayerQT
RolevPlayer/Scrobbler.py
Python
gpl-3.0
1,642
0.003654
import json import time from _md5 import md5 import requests import RolevPlayer as r def now_playing_last_fm(artist, track): update_now_playing_sig = md5(("api_key" + r.API_KEY + "artist" + artist + "method" + "track.updateNowPlaying" + ...
p://ws.audioscrobbler.com/2.0/?method=track.updateNowPlaying" + \ "&api_key=" + r.API_KEY + \ "&api_sig=" + update_now_playing_sig + \ "&artist=" + artist + \ "&format=json" + \ "&sk=" + r.SK + \ "&track=" + track req = requests.post(url).text json_ob...
"artist" + artist + "method" + "track.scrobble" + "sk" + r.SK + "timestamp" + str(ts) + "track" + track + r.SECRET).encode('utf-8')).hexdigest() req =...
tanji/replication-manager
share/opensvc/compliance/com.replication-manager/remove_files.py
Python
gpl-3.0
2,367
0.005492
#!/usr/bin/env python data = { "default_prefix": "OSVC_COMP_REMOVE_FILES_", "example_value": """ [ "/tmp/foo", "/bar/to/delete" ] """, "description": """* Verify files and file trees are uninstalled """, "form_definition": """ Desc: | A rule defining a set of files to remove, fed to the 'remove_files' co...
pattern) return l def fixable(self): return RET_NA def check_file(self, _file): if not os.path.exists(_file): pinfo(_file, "does not exist. on target.") return RET_OK perror(_file, "exists. shouldn't") return RET_ERR def fix_file(self, _file...
ile) and not os.path.islink(_file): shutil.rmtree(_file) else: os.unlink(_file) pinfo(_file, "deleted") except Exception as e: perror("failed to delete", _file, "(%s)"%str(e)) return RET_ERR return RET_OK def check(self...
AversivePlusPlus/AversivePlusPlus
tools/conan/conans/client/new.py
Python
bsd-3-clause
3,503
0.001427
conanfile = """from conans import ConanFile, CMake, tools import os class {package_name}Conan(ConanFile): name = "{name}" version = "{version}" license = "<Put the package license here>" url = "<Package recipe repository url here, for issues about the package>" settings = "os", "compiler", "build_...
code in the folder and use exports instead of retrieving it with this source() method ''' #self.run("git clone ...") or #tools.download("url", "file.zip") #tools.unzip("file.zip" ) def package(self): self.copy("*.h", "includ
e") """ test_conanfile = """from conans import ConanFile, CMake import os channel = os.getenv("CONAN_CHANNEL", "{channel}") username = os.getenv("CONAN_USERNAME", "{user}") class {package_name}TestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "{name}/{version}@%s/%s" % (us...
nkgilley/home-assistant
tests/components/linky/test_config_flow.py
Python
apache-2.0
6,904
0.000145
"""Tests for the Linky config flow.""" from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from h...
"homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) servi
ce_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert resul...
branden/dcos
gen/__init__.py
Python
apache-2.0
29,065
0.002408
"""Helps build config packages for installer-specific templates. Takes in a bunch of configuration files, as well as functions to calculate the values/strings which need to be put into the configuration. Operates strictly: - All paramaters are strings. All things calculated / derived are strings. - Every given pa...
e.parse_str( load_string(extra_filename))) result[name] = result_list return result # Render the Jinja/YAML into YAML, then load the YAML and merge it to make the # final configuration files. def render_templates(template_dict, arguments): rendered_templates = dict() templates ...
lates.items(): full_template = None for template in templates: rendered_template = template.render(arguments) # If not yaml, just treat opaquely. if not name.endswith('.yaml'): # No merging support currently. assert len(templates) == 1...
KanoComputing/kano-toolset
kano/utils/disk.py
Python
gpl-2.0
1,133
0
# disk.py # # Copyright (C) 2014-2016 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Utilities relating to disk manangement from kano.utils.shell import run_cmd def get_free_space(path="/"): """ Returns the amount of free space in certain location in MB :p...
dummy_size, dummy_used, free, dummy_percent, dummy_mp = \ out.split('\n')[1].split() return int(free) / 1024 def get_partition_info(): device = '/dev/mmcblk0' try: cmd = 'lsblk -n -b {} -o SIZE'.format(device) stdout, dummy_stderr, r
eturncode = run_cmd(cmd) if returncode != 0: from kano.logging import logger logger.warning("error running lsblk") return [] lines = stdout.strip().split('\n') sizes = map(int, lines) return sizes except Exception: return []
swarmer/tester
core/migrations/0009_auto_20150821_0243.py
Python
mit
376
0
# -
*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0008_auto_20150819_0050'), ] operations = [ migrations.AlterUniqueTogether( name='test', unique...
), ]
koparasy/faultinjection-gem5
src/arch/x86/isa/insts/general_purpose/data_transfer/xchg.py
Python
bsd-3-clause
3,156
0
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implemen...
Y, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWIS
E) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Gabe Black microcode = ''' # All the memory versions need to use LOCK, regardless of if it was set def macroop XCHG_R_R { # Use the xor trick instead of moves to reduce register pressure. ...
vaibhavi-r/CSE-415
Assignment3/puzzle0.py
Python
mit
129
0.015504
i
mport EightPuzzleWithHeuristics as Problem # puzzle0: CREATE_INITIAL_STATE = lambd
a: Problem.State([0, 1, 2, 3, 4, 5, 6, 7, 8])
wwj718/edx-video
common/djangoapps/student/views.py
Python
agpl-3.0
50,206
0.002769
import datetime import feedparser import json import logging import random import re import string # pylint: disable=W0402 import urllib import uuid import time from django.conf import settings from django.contrib.auth import logout, authenticate, login from django.contrib.auth.models import User from django.con...
tificateStatuses.generating: 'generating', CertificateStatuses.regenerating: 'generating', CertificateStatuses.downloadable: 'ready', CertificateStatuses.notpassing: 'notpassing', CertificateStatuses.restricted: 'restricted',
} status = template_state.get(cert_status['status'], default_status) d = {'status': status, 'show_download_url': status == 'ready', 'show_disabled_download_button': status == 'generating', } if (status in ('generating', 'ready', 'notpassing', 'restricted') and course.end...
noirhat/bin
games/doom/doom-1.py
Python
gpl-2.0
755
0.003974
#!/usr/bin/env python3 from os import environ, system from subprocess import Popen print('\nUltimate Doom (Classic)') print('Link: https://store.steampowered.com/app/2280/Ultimate_Doom/\n') ho
me = environ['HOME'] core = home + '/bin/games/steam-connect/steam-connect-core.py' logo = home + '/bin/games/steam-connect/doom-logo.txt' ga
me = 'doom-1' stid = '2280' proc = 'gzdoom' flag = ' +set dmflags 4521984' conf = ' -config ' + home + '/.config/gzdoom/gzdoom-classic.ini' save = ' -savedir ' + home + '/.config/gzdoom/saves/' + game iwad = ' -iwad DOOM.WAD' mods = ' -file music-doom.zip sprite-fix-6-d1.zip doom-sfx-high.zip speed-weapons.zip' args...
fusionbox/django-importcsvadmin
importcsvadmin/forms.py
Python
bsd-2-clause
3,694
0.000812
import csv from django.db import transaction from django import forms from django.forms.forms import NON_FIELD_ERRORS from django.utils import six from django.utils.translation import ugettext_lazy as _ class CSVImportError(Exception): pass class ImportCSVForm(forms.Form): csv_file = forms.FileField(requir...
i, row) def append_import_error(self, error, rownumber=None, column_name=None): if rownumber is not None: if column_name is not None: # Translators: "{row}", "{column}" and "{error}" # should not be translated
fmt = _("Could not import row #{row}: {column} - {error}") else: # Translators: "{row}" and "{error}" should not be translated fmt = _("Could not import row #{row}: {error}") else: if column_name is not None: raise ValueErro...
XeCycle/indico
indico/MaKaC/services/interface/rpc/offline.py
Python
gpl-3.0
3,627
0.001103
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
ution): return {'conference': object.getConference().getId(), 'co
ntribution': object.getId()} elif isinstance(object, MaKaC.conference.Session): return {'conference': object.getConference().getId(), 'session': object.getId()} elif isinstance(object, MaKaC.conference.SessionSlot): return {'conference': object.getConference().getId(), ...
mholtrop/Phys605
Python/Getting_Started/CSV_Plot.py
Python
gpl-3.0
1,762
0.009081
# # Here is a more complicated example that loads a .csv file and # then creates a plot from the x,y data in it. # The data file is the saved curve from partsim.com of the low pass filter. # It was saved as xls file and then opened in Excel and exported to csv # # First import the csv parser, the numeric tools and plot...
_filter.csv") # # Pass the file to the csv parser # data = csv.reader(f) headers = data.next() units = data.next() # # Here is a "wicked" way in Python that does quicker what the # the more verbose code does below. It is "Matlab" like. # dat = np.array([ [float(z) for z in x] for x in data ]) # put the data in dat as f...
dat[:,1] # select the second column # y2_ar = dat[:,2] # select the third column x_ar = [] # Create a new list (array) called dat to hold the data. y1_ar = [] y2_ar = [] for (x,y1,y2) in data: # Unpack the csv data into x,y1,y2 variables. x_ar.append( float(x)) y1_ar.append(float(y1)) y2_ar.append(fl...
pymir3/pymir3
scripts/ismir2016/birdclef_tza_bands.py
Python
mit
13,712
0.004959
import numpy as np import logging import glob import bandwise_features as BF import time import mir3.modules.features.stats as feat_stats import mir3.modules.tool.to_texture_window as texture_window import remove_random_noise as rrn from multiprocessing import Pool logger = logging.getLogger("birdclef_tza_bands") logg...
f = open(experiment.mirex_scratch_folder + "/" + experiment.output_file, "wb") m.save(f, restore_state=True) f.close() return m def tza_calc_textures(args):
tw = texture_window.ToTextureWindow() feature = args[0] logger.debug("calculating textures for %s", feature.metadata.filename) T0 = time.time() results = tw.to_texture(feature, args[1]) T1 = time.time() logger.debug("texture calculation took %f seconds", T1-T0) return results def tza_bands...
Kami/libcloud
libcloud/test/storage/test_oss.py
Python
apache-2.0
31,715
0.000126
# -*- coding=utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lice...
urn (httplib.OK, body, self.base_headers, httplib.responses[httplib.O
K]) def _list_container_objects_prefix(self, method, url, body, headers): params = {'prefix': self.test.prefix} self.assertUrlContainsQueryParams(url, params) body = self.fixtures.load('list_container_objects_prefix.xml') return (httplib.OK, body, sel...
pybursa/homeworks
s_shybkoy/hw5/hw5_task1.py
Python
gpl-2.0
2,975
0.00041
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" Задание 1: классный Человек. УСЛОВИЕ: Реализовать класс Person, который отображает запись в книге контактов. Класс имеет 4 атрибута: - surname - строка - фамилия контакта (обязательный) - first_name - строка - имя контакта (обязательный) - nickname - строк...
me self.first_name = first_name self.birth_date = res_date if nickname is not None: self.nickname = nickname def get_age(self): u"""Метод класса подсчитывает и выводит количество полных лет""" if self.birth_date is not None: today
_date = datetime.date.today() delta = today_date.year - self.birth_date.year if today_date.month <= self.birth_date.month \ and today_date.day < self.birth_date.day: delta -= 1 print "Age:", delta return str(delta) else: ...
ShaolongHu/lpts
tests/glxgears.py
Python
gpl-2.0
3,938
0.01248
# -*- coding:utf-8 -*- ''' x11perf测试工具执行脚本 ''' import os, shutil, re from test import BaseTest from lpt.lib.error import * from lpt.lib import lptxml from lpt.lib import lptlog from lpt.lib.share import utils from lpt.lib import lptreport import glob glxgears_keys = ["gears"] class TestControl(BaseTest): ...
ic = {}.fromkeys(glxgears_keys, 0) result_lines = utils.read_all_lines(file) for parallel in self.parallels: re_match = "[\d]+ CPUs in
system; running %d parallel copy of tests" % parallel parallel_result_dic = result_dic.copy() for line in result_lines: if re.search(re_match, line, re.I): parallel_index = result_lines.index(line) paralell_result_list = [ self.__get_value...
auduny/home-assistant
tests/components/stream/test_recorder.py
Python
apache-2.0
2,235
0
"""The tests for hls streams.""" from datetime import timedelta from io import BytesIO from unittest.mock import patch from homeassistant.setup import async_setup_component from homeassistant.components.stream.core import Segment from homeassistant.components.stream.recorder import recorder_save_worker import homeassi...
Setup demo track source = generate_h264_video() stream = preload_stream(hass, source) recorder = stream.add_provider('recorder') stream.start() await recorder.recv() # Wait a minute future = dt_util.utcnow() + timedelta(minutes=1) async_fire_time_changed...
generate_h264_video() output = BytesIO() output.name = 'test.mp4' # Run recorder_save_worker(output, [Segment(1, source, 4)]) # Assert assert output.getvalue()
kyclark/metagenomics-book
python/hello/hello_arg3.py
Python
gpl-3.0
251
0
#!/usr/bin/env python3 """hello with args""" import sys import os args = sys.argv if len(args) != 2:
script = os.path.basename(args[0]) print('Usage: {} NAME'.format(script))
sys.exit(1) name = args[1] print('Hello, {}!'.format(name))
egancatriona1/python-jumpstart
apps/06_lolcat_factory/you_try/program.py
Python
mit
1,553
0.000644
import os import platform import subprocess import cat_service from apps.general import headers def main(): headers.print_header('LOLCAT FACTORY') # look for a directory if not there create it dir_path = get_or_create_output_folder() n_cats = get_number_cats() # contact the lol cat api, get binar...
ing up do you need?') if number_files.isnumeric(): n_cats = int(number_files) return n_cats print('That was not a valid number please try again') def download_cats(dir_path, n_cats): for i in range(n_cats): cat_service.get_cat(dir_path, 'lol_cat{}.jpg'.format(i)) ...
arwin': subprocess.call(['open', folder]) elif platform.system() == 'Windows': print('with windows') subprocess.call(['explorer', folder]) elif platform.system() == 'Linux': subprocess.call(['xdg-open', folder]) else: print('Do not support your os "{}"'.format(platfor...
arunchaganty/presidential-debates
django/twit/migrations/0007_retweet.py
Python
mit
697
0.002869
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, mod
els class Migration(migration
s.Migration): dependencies = [ ('twit', '0006_auto_20160419_0248'), ] operations = [ migrations.CreateModel( name='Retweet', fields=[ ('id', models.BigIntegerField(serialize=False, help_text='Unique id that comes from Twitter', primary_key=True)), ...
Hironsan/uecda-pyclient
src/connection.py
Python
mit
1,996
0
# -*- coding: utf-8 -*- import socket import struct
import signal signal.signal(signal.SIGPIPE, signal.SIG_IGN) class Connection(object): """ サーバとの通信用クラス """ BINARY_INT = '!1I' BINARY_TABLE = '!120I' def __init__(self, addr='127.0.0.1', port=42485): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) self.sock.co...
unpacked_value = self._recv_msg(byte_length=4) s = struct.Struct(self.BINARY_INT) integer = s.unpack(unpacked_value) return integer[0] def recv_table(self): unpacked_value = self._recv_msg(byte_length=480) s = struct.Struct(self.BINARY_TABLE) ls = s.unpack(unpacke...
CenterForOpenScience/SHARE
share/transform/chain/__init__.py
Python
apache-2.0
484
0
from share.transf
orm.chain.exceptions import * # noqa from share.transform.chain.links import * # noqa from share.transform.chain.parsers import * # noqa from share.transform.chain.transformer import ChainTransformer # noqa from share.transform.chain.links import Context # Context singleton to be used for parser definitions # Cla...
beni55/sentry
src/sentry/migrations/0015_auto__add_field_message_project__add_field_messagecountbyminute_projec.py
Python
bsd-3-clause
15,392
0.007926
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'GroupedMessage', fields ['checksum', 'logger', 'view'] db.delete_unique('...
'sentry_filtervalue', ['project_id', 'value', 'key']) # Adding field 'MessageFilterValue.project' db.add_column('sentry_messagefiltervalue', 'project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False) # Adding unique constraint on ...
['project_id', 'group_id', 'value', 'key']) # Adding field 'GroupedMessage.project' db.add_column('sentry_groupedmessage', 'project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sentry.Project'], null=True), keep_default=False) # Adding unique constraint on 'GroupedMessage', ...
conejoninja/xbmc-seriesly
servers/wupload.py
Python
gpl-3.0
11,622
0.015835
# -*- coding: utf-8 -*- #------------------------------------------------------------ # seriesly - XBMC Plugin # Conector para Wupload # http://blog.tvalacarta.info/plugin-xbmc/seriesly/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapert...
if header[0]=="location": location1 = header[1] logger.info("location1="+str(header)) # Obtiene la URL final headers = scrapertools.get_headers_from_response(location1) location2 = "" content_disposition = "" for header in headers: l...
if header[0]=="location": location2 = header[1] location = location2 if location=="": location = location1 return [ ["(Premium) [wupload]",location + "|" + "User-Agent="+urllib.quote("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1....
AIESECGermany/gis-hubspot-sync
gis_token_generator.py
Python
gpl-2.0
825
0.004848
import urllib import urllib2 import cookielib import logging class GISTokenGenerator: def __init__(self, email, password): self.cj = cookielib.CookieJar() self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj)) self.email = email self.login_data = urllib.urlencode(...
: password}) def generate_token(self): logging.info('Generating a token for {0}...'.format(self.email)) self.opener.open('https://auth.aiesec.org/users/sign_in', self.login_data) tok
en = None for cookie in self.cj: if cookie.name == 'expa_token': token = cookie.value if token is None: raise Exception('Unable to generate a token for {0}!'.format(self.email)) return token
JQIamo/artiq
artiq/compiler/testbench/perf_embedding.py
Python
lgpl-3.0
2,231
0.001793
import sys, os from pythonparser import diagnostic from ...language.environment import ProcessArgumentManager from ...master.databases import DeviceDB, DatasetDB from ...master.worker_db import DeviceManager, DatasetManager from ..module import Module from ..embedding import Stitcher from ..targets import OR1KTarget fr...
pile(f.read(), f.name, "exec") testcase_vars = {'__name__': 'testbench'} exec(testcase_code, testcase_vars) device_db_path = os.path.join(os.path.dirname(sys.argv[1]), "device_db.py") device_
mgr = DeviceManager(DeviceDB(device_db_path)) dataset_db_path = os.path.join(os.path.dirname(sys.argv[1]), "dataset_db.pyon") dataset_mgr = DatasetManager(DatasetDB(dataset_db_path)) argument_mgr = ProcessArgumentManager({}) def embed(): experiment = testcase_vars["Benchmark"]((device_mgr, da...
listamilton/supermilton.repository
plugin.audio.soundcloud/resources/lib/nightcrawler/core/abstract_context.py
Python
gpl-2.0
10,518
0.001236
import json import os import urllib from ..storage import WatchLaterList, FunctionCache, SearchHistory, FavoriteList, AccessManager from .abstract_settings import AbstractSettings from .. import utils class AbstractContext(object): CACHE_ONE_MINUTE = 60 CACHE_ONE_HOUR = 60 * CACHE_ONE_MINUTE CACHE_ONE_DA...
'movies' CONTENT_TYPE_TV_SHOWS = 'tvshows' CONTENT_TYPE_EPISODES = 'episodes' CONTENT_TYPE_MUSIC_VIDEOS = 'musicvideos' LOG_DEBUG = 0 LOG_INFO = 1 LOG_WARNING = 2
LOG_ERROR = 3 def __init__(self, path=u'/', params=None, plugin_name=u'', plugin_id=u''): if not params: params = {} pass self._path_match = None self._python_version = None self._cache_path = None self._function_cache = None self._search_hi...