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
zillow/ctds
tests/test_cursor_fetchmany.py
Python
mit
6,714
0.002681
import ctds from .base import TestExternalDatabase class TestCursorFetchMany(TestExternalDatabase): '''Unit tests related to the Cursor.fetchmany() method. ''' def test___doc__(self): self.assertEqual( ctds.Cursor.fetchmany.__doc__, '''\ fetchmany(size=self.arraysize) Fetc...
with connection.cursor() as cursor: self.assertRaises(ctds.InterfaceError, cursor.fetchmany) def test_fetchmany(self): with self.connect() as connection: with connection.cursor() as cursor: cursor.execute( ''' DECLAR...
INSERT INTO @{0}(i) VALUES (1),(2),(3); SELECT * FROM @{0}; SELECT i * 2 FROM @{0}; '''.format(self.test_fetchmany.__name__) ) self.assertEqual([tuple(row) for row in cursor.fetchmany()], [(1,)]) ...
damouse/pyparted
src/parted/filesystem.py
Python
gpl-2.0
3,706
0.001619
# # filesystem.py # Python bindings for libparted (built on top of the _ped Python module). # # Copyright (C) 2009-2011 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2,...
ther) def __ne__(self, other): if hash(self) == hash(other): return False
if type(self) != type(other): return True return self.type != other.type or self.geometry != other.geometry def __str__(self): s = ("parted.FileSystem instance --\n" " type: %(type)s geometry: %(geometry)r checked: %(checked)s\n" " PedFileSystem: %(p...
campadrenalin/python-libdeje
deje/quorum.py
Python
gpl-3.0
5,211
0.005181
''' This file is part of python-libdeje. python-libdeje is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. python-libdeje is distribute...
OR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with python-libdeje. If not, see <http://www.gnu.org/licenses/>. ''' import datetime from persei import * from ejtp.identity import Identity DEFAULT_D...
elf, action, qs = None, signatures = {}): self.action = action self.qs = qs self.signatures = {} self.sent = False for identity in signatures: self.sign(identity, signatures[identity]) if qs: qs.register(self) @property d...
litedesk/litedesk-lib-active_directory
src/litedesk/lib/active_directory/classes/__init__.py
Python
apache-2.0
608
0
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs) # # 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 Licen
se at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language gove...
5j9/yadkard
lib/waybackmachine.py
Python
gpl-3.0
4,099
0
"""Define related tools for web.archive.org (aka Wayback Machine).""" import logging from threading import Thread from datetime import date from urllib.parse import urlparse from regex import compile as regex_compile from requests import ConnectionError as RequestsConnectionError from lib.commons import dict_to_sfn_...
BroadException try: original_dict.update(original_url_dict(ogurl)) except ( ContentTypeError, ContentLengthError, StatusCodeError, RequestsConnectionError, ): pass except Exception: logger.exception( 'There was an unexpected error in wa...
al_url_dict(url: str): """Retuan dictionary only containing required data for og:url.""" d = {} # Creating a thread to request homepage title in background hometitle_list = [] # A mutable variable used to get the thread result home_title_thread = Thread( target=get_home_title, args=(url, ho...
victor-cortez/Heimdall
mergesort/mergesort.py
Python
mit
807
0.019827
def merge(a,b): pa,pb = 0,0 lis = [] pa,pb = [0,le
n(a) > 0],[0,len(b) > 0] la,lb = len(a),len(b) for i in range(la + lb): if pa[1] is True: ta = a[pa[0]] else: ta = float("inf") if pb[1] is True: tb = b[pb[0]] else: tb = float("inf") if tb < ta: lis.append(tb) ...
pa[0] = pa[0] + 1 if pa[0] >= la: pa[1] = False return lis def mergesort(lista): if len(lista) <= 1: return lista a,b = [],[] for i in range(len(lista)): [a,b][i%2].append(lista[i]) return merge(mergesort(a),mergesort(b))
ivano666/tensorflow
tensorflow/python/kernel_tests/pad_op_test.py
Python
apache-2.0
6,742
0.006526
# 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...
[[1, 0], [2, 3], [0, 2]]) def testFloatTypes(self): for t in [np.float32, np.float64, np.complex64]: self._testAll(np.random.rand(2, 5).astype(t), [[1, 0], [2, 0]]) def testShapeFunctionEdgeCases(self): # Unknown p
addings shape. inp = tf.constant(0.0, shape=[4, 4, 4, 4]) padded = tf.pad(inp, tf.placeholder(tf.int32)) self.assertEqual([None, None, None, None], padded.get_shape().as_list()) # Unknown input shape. inp = tf.placeholder(tf.float32) padded = tf.pad(inp, [[2, 2], [2, 2]]) self.assertEqual([...
momikey/pyrge
setup.py
Python
lgpl-2.1
744
0.034946
from distutils.core import setu
p import sys, os DATA_FILES = ['README', 'LICENSE'] ASTEROID_PNGS = ['large.png', 'medium.png', 'small.png', 'ship.png'] INVASION_PNGS = ['ship.png', 'alien.png'] TUTORIALS = ['examples/tutorial/'+t for t in os.listdir('examples/tutorial/')] DATA_FILES += TUTORIALS setup( name='pyrge', version='0.6', author="Mi...
potterpcs.net", url="http://github.com/momikey/pyrge", packages = ['pyrge', 'pyrge.examples.asteroid', 'pyrge.examples.invasion'], package_dir = {'pyrge': ''}, package_data = {'pyrge': DATA_FILES, 'pyrge.examples.asteroid': ['*.png'], 'pyrge.examples.invasion': ['*.png']...
Signbank/FinSL-signbank
signbank/dictionary/urls.py
Python
bsd-3-clause
4,038
0.009163
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.urls import path from django.views.generic.base import RedirectView from django.contrib.auth.decorators import permission_required, login_required # Views from . import adminviews from . import publicviews from . import update from . import de...
e='manage_lexi
cons'), # Apply for lexicon permissions path('lexicons/apply/', login_required(views.ApplyLexiconPermissionsFormView.as_view()), name='apply_lexicon_permissions'), # Create path('advanced/gloss/create/', views.create_gloss, name='create_gloss'), # Urls used to update data path('update/...
hms-dbmi/fourfront
src/encoded/commands/create_mapping_on_deploy.py
Python
mit
5,218
0.001916
import argparse import structlog import logging from pyramid.paster import get_app from snovault.elasticsearch.create_mapping import run as run_create_mapping from dcicutils.log_utils import set_logging from dcicutils.deployment_utils import CreateMappingOnDeployManager log = structlog.getLogger(__name__) EPILOG = _...
xcept Exception as e: log.error("Exception encountered while gatheri
ng deployment information or running create_mapping") log.error("%s: %s" % (e.__class__.__name__, e)) exit(1) def main(): parser = argparse.ArgumentParser( # noqa - PyCharm wrongly thinks the formatter_class is specified wrong here. description="Create Elasticsearch mapping on deployment"...
kklmn/xrt
examples/withRaycing/01_SynchrotronSources/undulatorTapering.py
Python
mit
4,236
0.001416
# -*- coding: utf-8 -*- __author__ = "Konstantin Klementiev", "Roman Chernikov" __date__ = "08 Mar 2016" import pickle import numpy as np import matplotlib.pyplot as plt import os, sys; sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore import xrt.backends.raycing as raycing import xrt.backends.raycin...
ax.plot(e*1e-3, f/max(f), 'g', label='calculated by YAUP/XOP', lw=2) theta, fl = np.loadtxt("thetaexafssc1an_zn_hgap_00002r2.fio.gz", skiprows=113, usecols=(0, 5), unpack=True) si_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) E = rm.ch / (2 * si_1.d * np.sin(np.radians(theta))) a...
legend(loc='lower center') fig1.savefig('compareTaper.png') plt.show() if __name__ == '__main__': main()
toumorokoshi/tornado-transmute
tornado_transmute/__init__.py
Python
mit
189
0
from transmute_core import * # from
.handler import convert_to_handler # from .route import route from .route_set import RouteSet from .url import u
rl_spec from .swagger import add_swagger
azumimuo/family-xbmc-addon
plugin.video.dragon.sports/lib/utils/github/Comparison.py
Python
gpl-2.0
6,448
0.002792
# -*- coding: utf-8 -*- # Copyright 2012 Vincent Jacques # vincent@vincent-jacques.net # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License # as published by the Free Softwar...
attributes["commits"] self._commits = None if attributes["commits"] is None else [ Commit.Commit(self._requester, element, completed=False) for element in attri
butes["commits"] ] if "diff_url" in attributes: # pragma no branch assert attributes["diff_url"] is None or isinstance(attributes["diff_url"], (str, unicode)), attributes["diff_url"] self._diff_url = attributes["diff_url"] if "files" in attributes: # pragma no branc...
eruvanos/openbrokerapi
tests/test_last_binding_operation.py
Python
mit
2,530
0.005138
import http from openbrokerapi.service_broker import LastOperation, OperationState from tests import BrokerTestCase class LastBindingOperationTest(BrokerTestCase): def setUp(self): self.broker.service_id.return_value = 'service-guid-here' def test_last_operation_called_just_with_required_fields(self...
self.broker.last_binding_operation.assert_called_once_with('here-instance_id', 'binding_id', 'service-guid-here operation-data', "", "456") def test_returns_200_with_given_state(self): self.broker.last_binding_operation.return_valu...
e-guid-here%20operation-data' response = self.client.get( '/v2/service_instances/here-instance_id/service_bindings/binding_id/last_operation?%s' % query, headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header }) se...
jalilm/ryu
ryu/tests/unit/packet/test_igmp.py
Python
apache-2.0
34,411
0
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # # 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 appli...
ok_(i) eq_(i.proto, inet.IPPROTO_IGMP) g = self.find_protocol(p, "ig
mp") ok_(g) eq_(g.msgtype, self.msgtype) eq_(g.maxresp, self.maxresp) eq_(g.csum, checksum(self.buf)) eq_(g.address, self.address) def test_to_string(self): igmp_values = {'msgtype': repr(self.msgtype), 'maxresp': repr(self.maxresp), ...
google-research/football
gfootball/env/gym_test.py
Python
apache-2.0
1,391
0.005751
# coding=utf-8 # Copyright 2019 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
re__ import division from __future__ import print_function import unittest import gym from absl.testing import parameterized class GymTest(
parameterized.TestCase): @parameterized.parameters(('scoring'), ('scoring,checkpoints')) def test_environment(self, rewards): # Tests it is possible to create and run an environment twice. for _ in range(2): env = gym.make('gfootball:GFootball-11_vs_11_easy_stochastic-SMM-v0', st...
sfairhur/pycbc
pycbc/strain/strain.py
Python
gpl-3.0
78,684
0.003978
#Copyright (C) 2013 Alex Nitz # # 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 distributed in the h...
t series is downsampled accordingly. If omitted, the Nyquist frequency is used. output_intermedia
tes : {bool, False} Save intermediate time series for debugging. """ # don't waste time trying to optimize a single FFT pycbc.fft.fftw.set_measure_level(0) if high_freq_cutoff: strain = resample_to_delta_t(strain, 0.5 / high_freq_cutoff, method='ldas...
tedunderwood/character
oldcode/combine_hathi_summaries.py
Python
mit
1,368
0.009503
# combine_all_summaries # this fuses the summary files from pre23_hathi, # post22_hathi, and chicago, to create a file # where there is only one entry for each # char, auth, date tuple import csv from collections import Counter counts = dict() columns = ['characters', 'speaking', 'agent', 'mod', 'patient', 'poss', ...
ilepath, counts): with open(filepath, encoding = 'utf-8') as f: reader = csv.DictReader(f) for row in reader: triplet = (row['chargender'], row['authgender'], row['date']) if triplet not in counts: counts[triplet] = Counter() for col in columns: ...
d2counts('post22hathi/corrected_post22_summary.csv', counts) add2counts('pre23hathi/corrected_pre23_hathi_summary.csv', counts) with open('corrected_hathi_summaries.csv', mode = 'w', encoding = 'utf-8') as f: writer = csv.DictWriter(f, fieldnames = fieldnames) writer.writeheader() for triplet, colcounts in...
rdevon/cortex
cortex/built_ins/networks/fully_connected.py
Python
bsd-3-clause
863
0
'''Simple dense network encoders ''' import logging import torch.nn as nn from .base_network import BaseNet logger = logging.getLogger('cortex.arch' + __name__) class FullyConnectedNet(BaseNet): def __init__(self, dim_in, dim_out=None, dim_h=64, dim_ex=None, nonlinearity='ReLU', n_levels=N...
im_h, dim_ex=dim_ex, **layer_args) self.add_output_layer(dim_in, dim_out)
RDFLib/rdflib
test/test_n3.py
Python
bsd-3-clause
8,671
0.001845
import os import pytest from rdflib.graph import Graph, ConjunctiveGraph import unittest from rdflib.term import Literal, URIRef from rdflib.plugins.parsers.notation3 import BadSyntax, exponent_syntax import itertools from urllib.error import URLError from test import TEST_DIR test_data = """ # Definitions of term...
Literal("Foo")) in g) self.assertTrue((URIRef("http://example.com/doc/ba
r"), None, None) in g) self.assertTrue((URIRef("http://example.com/doc/doc2/bing"), None, None) in g) self.assertTrue((URIRef("http://test.com/bong"), None, None) in g) def testBaseExplicit(self): """ Test that the n3 parser supports resolving relative URIs and that base wil...
mezz64/home-assistant
homeassistant/components/freedompro/sensor.py
Python
apache-2.0
3,148
0.000318
"""Support for Freedompro sensor.""" from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callb...
umiditySensor": SensorStateClass.MEASUREMENT, "lightSensor": None, } UNIT_MAP = { "temperatureSensor": TEMP_CELSIUS, "
humiditySensor": PERCENTAGE, "lightSensor": LIGHT_LUX, } DEVICE_KEY_MAP = { "temperatureSensor": "currentTemperature", "humiditySensor": "currentRelativeHumidity", "lightSensor": "currentAmbientLightLevel", } SUPPORTED_SENSORS = {"temperatureSensor", "humiditySensor", "lightSensor"} async def async_se...
vrcmarcos/django-http-model
core/urls.py
Python
mit
876
0
"""core URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls i
mport url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from test_app import views as test_app_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test_app/companies/', test_app_views.companies_li...
nealegibson/Infer
src/MCMC_BGibbs.py
Python
gpl-3.0
7,699
0.039356
import numpy as np np.seterr(divide='ignore') #ignore errors in log division np.seterr(all='ignore') #ignore errors in log division import sys import time ########################################################################################## def BGMCMC(LogPosterior,gp,post_args,ch_len,ep,gibbs_index,chain_file...
=0)[q])/(i-ch_len/5+1)) for q in range(no_steps)])+"\b]" print ("\rComputing Chain %d: '%s' %-20s t = %dm %.2fs%s" % (n+1,chain,'#'*(i/(ch_len/20)+1),ts // 60., ts % 60.,a_str),) print (a_str2,) sys.stdout.flush(); ########################################################################################## def ...
enames,ch_len,posterior,adapt_limits,glob_limits,gp,ep,gibbs): print ("Infer.BGMCMC runnning...") print ("Blocked Gibbs MCMC parameters:") print (" No Chains: %d" % len(ch_filenames)) print (" Chain Length: %d" % ch_len) if(adapt_limits[2]): print (" Relative-step adaption limits: (%d,%d,%d)" % (adapt_limits...
tempbottle/concoord
concoord/threadingobject/dboundedsemaphore.py
Python
bsd-3-clause
1,447
0.001382
""" @author: Deniz Altinbuken, Emin Gun Sirer @note: Bounded Semaphore Coordination Object @copyright: See LICENSE """ from threading import Lock from concoord.exce
ption import * class DBoundedSemaphore(): def __init__(self, count=1): if count < 0: raise ValueError self.__count = int(count) self.__queue = []
self.__atomic = Lock() self._initial_value = int(count) def __repr__(self): return "<%s count=%d init=%d>" % (self.__class__.__name__, self.__count, self._initial_value) def acquire(self, _concoord_command): with self.__atomic: self.__count -= 1 if self.__cou...
vanant/googleads-dfa-reporting-samples
python/v2.1/get_files.py
Python
apache-2.0
2,171
0.005988
#!/usr/bin/python # # Copyright 2014 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 b...
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 # limi
tations under the License. """This example illustrates how to get a list of all the files for a profile. Tags: files.list """ __author__ = ('api.jimper@gmail.com (Jonathon Imperiosi)') import argparse import sys from apiclient import sample_tools from oauth2client import client # Declare command-line flags. argpa...
karllessard/tensorflow
tensorflow/python/distribute/v1/cross_device_ops_test.py
Python
apache-2.0
34,390
0.006077
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
value, devices): """Create a faked Mirrored object for testing. All components of the returned Mirrored have the same objects, which is not true in reality. """ devices = _get_devices(devices) values = [] for d in devices: with ops.device(d): values.append(array_ops.identity(value)) return di...
ed_slices(values, indices, dense_shape, device): with ops.device(device): tensor = ops.IndexedSlices( values=constant_op.constant(values), indices=constant_op.constant(indices), dense_shape=constant_op.constant(dense_shape)) return tensor def _make_mirrored_indexed_slices(devices, valu...
jencce/stuff
py/first.py
Python
gpl-2.0
123
0
#! /usr/bin/env python current =
u'b' print ord(current) print ord('a') print ord('1') print ord('\n') ip 1 2 3
./first.py
mldbai/mldb
testing/MLDB-2107-scalar-format.py
Python
apache-2.0
2,377
0.00589
# # MLDB-2107-scalar-format.py # Mathieu Marquis Bolduc, 2017-01-10 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # from mldb import mldb, MldbUnitTest, ResponseException class MLDB2107ScalarFormatTest(MldbUnitTest): # noqa @classmethod def setUpClass(cls): ds = mldb....
lect x,y from (select false as x, 1 as y)", format='atom').json() def test_error_rows(self): msg = "Query with atom format return
ing multiple rows" with self.assertRaisesRegex(ResponseException, msg): n = mldb.get('/v1/query', q="select x from ds", format='atom').json() def test_multiple_rows_limit(self): n = mldb.get('/v1/query', q="select x from ds limit 1", format='atom').json() self.assertEqual('B', n...
sietse/pyietflib
TestSuite/rfc2045TestSuite/__init__.py
Python
apache-2.0
1,363
0.004402
#!/usr/bin/env python # -*- coding: UTF-8 -*- #----------------------------------------------------------------------------- """IETF RFC 2046 Language Tag Specification unit test suite.""" __author__ = ('Lance Finn Helsten',) __ver
sion__ = '1.0' __copyright__ = """Copyright 2011 Lance Finn Helsten (helsten@ac
m.org)""" __license__ = """ 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 distri...
mikeireland/chronostar
projects/scocen/print_components_overlaps_table_for_paper.py
Python
mit
1,817
0.017611
""" Print data for table `componentsoverlaps.tex` in the paper Numbers of members Ages, crossing time """ import numpy as np from astropy.table import Table, unique ############################################ # Some things are the same for all the plotting scripts and we put # this into a single library to avoid c...
D not in ['H', 'I', 'B']: # Not ScoCen if pmin_membership==0.5: total50+=len(t) e
lif pmin_membership==0.8: total80+=len(t) elif pmin_membership==0.9: total90+=len(t) age = c['Age'] crossing_time = c['Crossing_time'] # %.0f does the roundup properly while %d rounds everything down! line += '%0.f & %.0f '%(age, crossi...
Weasyl/misaka
misaka/constants.py
Python
mit
406
0.002463
# -*- coding: utf-8 -*- import sys from inspect import getmembers from ._hoedown import lib def _set_constants(): is_int = lambda n: isinstance(n, int) for name, value in getmembers(lib, is_int): if not name.startswith('HOEDOWN_'): continue setattr(sys.modules[__name__]
, name[8:]
, value) if not hasattr(sys.modules[__name__], 'EXT_TABLES'): _set_constants()
zaycev/n7
n7/web/urls.py
Python
mit
586
0.001706
#!/usr/bin/env python # coding: utf-8 # Copyright (C) USC Information Sciences Institute # Author: Vladimir M. Zaytsev <zaytsev@usc.edu> # URL: <http://nlg.isi.edu/> # For more information, see README.md # For license information, see LICENSE from django.conf.urls import url from django.conf.urls import patterns
from django.shortcuts import redirect urlpatterns = patterns( "", url(r"^$", "n7.web.
n7.views.demo", name="demo"), url(r"^triples/$", "n7.web.n7.views.trainer", name="trainer"), url(r"^novels/$", "n7.web.n7.views.trainer_add", name="trainer_post"), )
pankajp/pyface
pyface/ui/qt4/code_editor/gutters.py
Python
bsd-3-clause
3,820
0.003141
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------...
painter.fillRect(event.rect(), self.background_color) cw = self.parent() block = cw.firstVisibleBlock() blocknum = block.blockNumber() top = cw.blockBoundingGeometry(block).translated( cw.contentOffset()).top() bottom = top + int(cw.blockBoundingRect(block).height()...
ent.rect().top(): painter.setPen(QtCore.Qt.black) painter.drawText(0, top, self.width() - 2, self.fontMetrics().height(), QtCore.Qt.AlignRight, str(blocknum + 1)) block = block.next() top = bottom ...
sharkspeed/dororis
packages/python/flask/flask-dog-book/5-chapter/main.py
Python
bsd-2-clause
2,710
0.001864
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask, render_template, session, redirect, url_for, flash from flask_wtf import FlaskForm from flask_bootstrap import Bootstrap from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_sqlalchemy impo...
db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) def __repr__(self): return '<User %r>' % self.username # View Functions @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): old_name =...
rname=form.name.data).first() if user is None: user = User(username=form.name.data) db.session.add(user) session['known'] = False else: session['known'] = True session['name'] = form.name.data form.name.data = '' return redirect(url...
rjschwei/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/models/availability_set.py
Python
mit
3,239
0.001544
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ult Domain count. :type platform_fault_domain_count: int :par
am virtual_machines: A list of references to all virtual machines in the availability set. :type virtual_machines: list of :class:`SubResource <azure.mgmt.compute.models.SubResource>` :ivar statuses: The resource status information. :vartype statuses: list of :class:`InstanceViewStatus <azure...
Lilykos/invenio
invenio/modules/jsonalchemy/jsonext/engines/sqlalchemy.py
Python
gpl-2.0
5,159
0.002714
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014 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 option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a...
n, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """SQLAlchemy storage engine implementation.""" import six from flask.helpers import locked_cached_property from werkzeug import import_string from invenio.modules.jsonalchemy.storage import Storage class SQLAlchemyStorage(Storage): """Implem...
yongwen/teletraan
deploy-board/deploy_board/webapp/helpers/tags_helper.py
Python
apache-2.0
1,031
0.007759
# Copyright 2016 Pinterest, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
ava class TagValue(object): BAD_BUILD="BAD_BUILD" GOOD_BUILD="GOOD_
BUILD" def get_latest_by_target_id(request, target_id): return deploy_client.get("/tags/targets/%s/latest" % target_id, request.teletraan_user_id.token)
hamukichi/ironpycompiler
ironpycompiler/detect.py
Python
mit
11,741
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module for detecting where the IronPython executables exist. """ import itertools import os import glob # Original modules from . import exceptions from . import constants from . import datatypes from . import process def search_ipy_reg(regkeys=None, executable=co...
hon and their locations :rtype: dict :raises ironpycompiler.exceptions.IronPyth
onDetectionError: if IronPython cannot be found .. versionadded:: 0.9.0 .. versionchanged:: 1.0.0 Validates the found executables using :func:`validate_pythonexe`. The parameter ``detailed`` was added. """ ipydirpaths = []...
freizeitnerd/sprinkler
www/cgi-bin/cgi-switch-valve.py
Python
mit
222
0.040541
#!/usr/bin/python def renderJson(status, body) print "Status: ", status print "Co
ntent-Type: application/json" print "C
ontent-Length: %d" % (len(body)) print "" print body renderJson("200 OK", "{foo: 'bar'}")
TelematicaUSM/EduRT
backend_modules/__init__.py
Python
agpl-3.0
902
0
# -*- coding: UTF-8 -*- # COPYRIGHT (c) 2016 Cristóbal Ganter # # GNU AFFERO GENERAL PUBLIC LICENSE # Version 3, 19 November 2007 # # 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, eit...
ogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # a...
from controller import MSGHandler from src.load import load_wsclasses load_wsclasses(__name__, MSGHandler)
magenta-aps/mox
oio_rest/oio_rest/utils/encode_token.py
Python
mpl-2.0
893
0
# Copyright (C) 2015-2019 Magenta ApS, https://magenta.dk. # Contact: info@magenta.dk. # # Th
is Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import shutil import os import tempfile from base64 import b64encode import gzip # Outputs the Authorization hea...
ssertion token if len(sys.argv) > 1: assertion_file = sys.argv[1] else: assertion_file = 'test_auth_data/sample-saml2-assertion.xml' (handle, tmpfilename) = tempfile.mkstemp('.gz') with open(assertion_file, 'rb') as f_in, gzip.open(tmpfilename, "wb") as f_out: shutil.copyfileobj(f_in, f_out) with open(t...
achilleas-k/gnome15
src/gnome15/util/g15os.py
Python
gpl-3.0
4,161
0.006008
# Gnome15 - Suite of tools for the Logitech G series keyboards and headsets # Copyright (C) 2010 Brett Smith <tanktarta@blueyonder.co.uk> # Copyright (C) 2013 Nuno Araujo <nuno.araujo@russo79.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publi...
import errno if exc.errno == errno.EEXIST: pass else: raise def full_path_of_program(program_name): """ Search for program_name in all the directories declared in the PATH environment variable Keyword arguments: program_name: the name of the program to search for ...
in PATH. """ for dir in os.environ['PATH'].split(':'): full_path = os.path.join(dir, program_name) if os.path.exists(full_path): return full_path return None def is_program_in_path(program_name): """ Checks if a program_name is available in PATH environment variable ...
dimka665/vk
vk/__init__.py
Python
mit
113
0
fr
om .session import API, UserAPI, CommunityAPI __version__ = '3.0-dev' __all__ = (API, UserAPI, CommunityAPI)
zeeman/cyder
cyder/cydhcp/build/builder.py
Python
bsd-3-clause
5,264
0.00057
from __future__ import unicode_literals import os import shlex import subprocess import sys import syslog import time from traceback import format_exception from cyder.base.mixins import MutexMixin from cyder.base.utils import ( copy_tree, dict_merge, Logger, run_command, set_attrs, shell_out) from cyder.base.vcs...
message) raise if self.check_file: self.check_syntax() self.log_info('DHCP build successful') def push(self, sanity_check=True): self.repo.reset_and_pull() try: copy_tree(s
elf.stage_dir, self.prod_dir) except: self.repo.reset_to_head() raise self.repo.commit_and_push('Update config', sanity_check=sanity_check) def error(self): ei = sys.exc_info() exc_msg = ''.join(format_exception(*ei)).rstrip('\n') self.log_err( ...
endlessm/chromium-browser
third_party/chromite/scripts/cros_env_whitelist.py
Python
bsd-3-clause
469
0.002132
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a B
SD-style license that can be # found in the LICENSE file. """Print the environment whitelist.""" from __future__ import print_function import sys from chromite.lib import constants ass
ert sys.version_info >= (3, 6), 'This module requires Python 3.6+' def main(_argv): print(' '.join(constants.CHROOT_ENVIRONMENT_WHITELIST))
divio/cmsplugin-blog
cmsplugin_blog/migrations/0015_auto__add_field_latestentriesplug.py
Python
bsd-3-clause
7,566
0.008062
# 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): # Adding field 'LatestEntriesPlugin.tagged' db.add_column('cmsplugin_latestentriesplugin', 'tagged', self.gf('djan...
ield', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerFi
eld', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields....
adityahase/frappe
frappe/boot.py
Python
mit
10,547
0.025505
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals from six import iteritems, text_type """ bootstrap client session """ import frappe import frappe.defaults import frappe.desk.desk_page from frappe.desk.form.load import get_me...
e def get_column(doctype): column = "`tabPage`.title as title" if doctype == "Report": column = "`tabReport`.`name` as title, `tabReport`.ref_doctype, `tabReport`.report_type" return column def load_translations(bootinfo): messages = frappe.get_lang_dict("boot") bootinfo["lang"] = frappe.lang # load transl...
{k:v for k, v in iteritems(messages) if k!=v} bootinfo["__messages"] = messages def get_fullnames(): """map of user fullnames""" ret = frappe.db.sql("""select `name`, full_name as fullname, user_image as image, gender, email, username, bio, location, interest, banner_image, allowed_in_mentions from tabUser wh...
Ryszard-Ps/rsr-calculator
rsr_calculator/version.py
Python
gpl-3.0
77
0
# -*- coding: utf-8 -*-
"""#Versión de la calculadora.""" v
ersion = '1.0.0'
killpanda/Ailurus
ailurus/fedora/apps_eclipse.py
Python
gpl-2.0
7,840
0.008291
#coding: utf-8 # # Ailurus - a simple application installer and GNOME tweaker # # Copyright (C) 2009-2010, Ailurus developers and Ailurus contributors # Copyright (C) 2007-2010, Trusted Digital Technology Laboratory, Shanghai Jiao Tong University, China. # # Ailurus is free software; you can redistribute it and/or modi...
dropins/MTJ/' self.paths = [ s
elf.path ] def install(self): make_sure_installed() path = A+'/support/MTJ_urls' with open(path) as f: urls = f.readlines() urls = [u.strip() for u in urls] f = R(urls).download() run_as_root('mkdir -p '+self.path) run_as_root("unzip -qo %s -d %s"%...
osspeak/osspeak
osspeak/pyautogui/__init__.py
Python
mit
36,647
0.002483
# PyAutoGUI: Cross-platform GUI automation for human beings. # BSD license # Al Sweigart al@inventwithpython.com (Send me feedback & suggestions!) """ IMPORTANT NOTE! To use this module on Mac OS X, you need the PyObjC module installed. For Python 3, run: sudo pip3 install pyobjc-core sudo pip3 install pyobjc...
gui_java as platformModule raise NotImplementedError('Jython is not yet supported by PyAutoGUI.') elif sys.platform == 'darwin': from . import _pyautogui_osx as platformModule elif sys.platfo
rm == 'win32': from . import _pyautogui_win as platformModule else: from . import _pyautogui_x11 as platformModule # TODO: Having module-wide user-writable global variables is bad. It makes # restructuring the code very difficult. For instance, what if we decide to # move the mouse-related functions to a sepa...
web-izmerenie/avto-lux161
avto-lux/app/core/routes/testroute.py
Python
agpl-3.0
162
0.012346
# -*- coding: utf-8 -*- f
rom .base import BaseHandler class TestRoute(BaseHandler): def get(self, file): return self
.render(str(file) + '.jade', show_h1=1)
ezeakeal/educube_client
educube/client.py
Python
gpl-3.0
2,664
0.003378
#!/usr/bin/env python import os import sys import json import click import serial import pkg_resources import serial.tools.list_ports import logging.config from educube.web import server as webserver import logging logger = logging.getLogger(__name__) plugin_folder = os.path.join(os.path.dirname(__file__), 'commands...
except serial.serialutil.SerialException as e: raise click.BadParameter("Serial not readable: %s" % e) ############################## # COM
MANDS ############################## def get_serial(): ports = serial.tools.list_ports.comports() suggested_educube_port = ports[-1] return suggested_educube_port.device def get_baud(): ports = serial.tools.list_ports.comports() suggested_educube_port = ports[-1] if suggested_educube_port.desc...
fbarreir/panda-server
pandaserver/test/deleteJobs.py
Python
apache-2.0
5,897
0.010005
import os import re import sys import time import fcntl import types import shelve import random import datetime import commands import threading import userinterface.Client as Client from dataservice.DDM import ddm from dataservice.DDM import dashBorad from taskbuffer.OraDBProxy import DBProxy from taskbuffer.TaskBuff...
metaATableName = "ATLAS_PANDAARCH.metaTable_ARCH" # time limit timeLimit = datetime.datetime.utcnow() - datetime.timedelta(days=3) # delete _logger.debug("get PandaIDs for Delete") sql = "SELECT COUNT(*) FROM ATLAS_PANDA.j
obsArchived4 WHERE modificationTime<:modificationTime" varMap = {} varMap[':modificationTime'] = timeLimit status,res = taskBuffer.querySQLS(sql,varMap) if res != None: tmpTotal = res[0][0] else: tmpTotal = None maxBunch = 1000 nBunch = 500 tmpIndex = 0 while True: sql = "SELECT PandaID,modificationTime FR...
lelit/doit
tests/test_cmdparse.py
Python
mit
5,264
0.009878
import pickle import pytest from doit.cmdparse import DefaultUpdate, CmdParseError, CmdOption, CmdParse class TestDefaultUpdate(object): def test(self): du = DefaultUpdate() du.set_default('a', 0) du.set_default('b', 0) assert 0 == du['a'] assert 0 == du['b'] ...
t 1 == du['b'] def test_add_defaults(self): du = DefaultUpdate() du.add_defaults({'a': 0
, 'b':1}) du['c'] = 5 du.add_defaults({'a':2, 'c':2}) assert 0 == du['a'] assert 1 == du['b'] assert 5 == du['c'] # http://bugs.python.org/issue826897 def test_pickle(self): du = DefaultUpdate() du.set_default('x', 0) dump = pickle.dumps(du,2) ...
TSDBBench/Overlord
vagrant_files/generator/files/databases/opentsdb_cl5_rf1.py
Python
apache-2.0
6,981
0.010314
#!/usr/bin/env python2 # -*- coding: utf-8 -*- __author__ = 'Andreas Bader' __version__ = "0.01" # db_folders -> List of DB Folder (for space check) # db_client -> name of ycsb client # db_args -> special ycsb arguments for this db # db_name -> name of this db (e.g. for workload file) # db_desc -> more detailed name/...
run after ycsb (all vms or local) (without ycsb, sync or space diff or poweroff commands!) # prerun_master -> list of commands to run before ycsb
(only on master(first=ID 0) vm or local)) (without ycsb, sync or space diff or poweroff commands!) # postrun_master -> list of commands to run after ycsb (only on master(first=ID 0) vm or local)) (without ycsb, sync or space diff or poweroff commands!) # prerun_slaves -> list of commands to run before ycsb (only on sla...
Mirantis/pumphouse
pumphouse/tasks/node.py
Python
apache-2.0
19,990
0.00005
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, ...
(akscram): The source of the configuration is the first # node with the `co
mpute` role. compute_nodes = [info for info in nodes_infos.values() if "compute" in info["roles"]] if not compute_nodes: raise exceptions.Conflict("There is no any compute nodes in " "environment %r" % (e...
titilambert/teeawards
old/jobs/suicides/suicides.py
Python
agpl-3.0
4,168
0.003599
from datetime import datetime from pymongo import DESCENDING from libs.lib import tee_db from libs.statisticator import Job class SuicidesJob(Job): def __init__(self): """ Job to get player suicides Collection name: kill_results Struture: {'player': STR , ...
]}, sort=[{'when', DESCENDING}], ) # Set new suicides self.results['suicides'] += suicides.count() # Se
t last event date if suicides.count() > 0: self.results['last_event_date'] = suicides[0]['when'] self.results['date'] = datetime.now() # Save to mongo self.save_results_to_cache() # Change status self.status = 'done'
LCAV/pyroomacoustics
pyroomacoustics/tests/test_issue_162.py
Python
mit
663
0
import
numpy as np import pyroomacoustics as pra def compute_rir(order): fromPos = np.zeros((3)) toPos = np.ones((3, 1)) roomSize = np.array([3, 3, 3]) room = pra.ShoeBox(roomSize, fs=1000, absorption=0.95, max_order=order) room.add_source(fromPos) mics = pra.MicrophoneArray(toPos, room.fs) room...
compute_rir(15) def test_issue_162_max_order_31(): compute_rir(31) def test_issue_162_max_order_32(): compute_rir(32) def test_issue_162_max_order_50(): compute_rir(50) def test_issue_162_max_order_75(): compute_rir(75)
sdiehl/rpygtk
rpygtk/ui/about.py
Python
gpl-3.0
1,127
0.00976
# Copyright 2009-2010 Stephen Diehl # # This file is part of RPyGTK and distributed under the terms # of the GPLv3 license. See the file LICENSE in the RPyGTK # distribution for full details. import sys import pygtk pygtk.require("2.0") import gtk import gtk.glade import config from ui import window class About(win...
ight("Copyr
ight \302\251 2009-2010 Stephen Diehl") self.window.set_logo(gtk.gdk.pixbuf_new_from_file('/usr/share/icons/gnome/scalable/categories/applications-utilities.svg'))
santisiri/popego
envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/cred/portal.py
Python
bsd-3-clause
5,185
0.001157
# -*- test-case-name: twisted.test.test_newcred -*- # Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ The point of integration of application and authentication. """ from twisted.internet import defer from twisted.internet.defer import maybeDeferred from twisted.python import fai...
faces that can be used to login.""" return self.checkers.keys() def registerChecker(self, checker, *credentialInterfaces): if not credentialInterfaces: credentialInterfaces = checker.credentialInterfaces for credentialInterface in credentialInterfaces: self.checkers[...
credentials.ICredentials @param mind: an object which implements a client-side interface for your particular realm. In many cases, this may be None, so if the word 'mind' confuses you, just ignore it. @param interfaces: list of interfaces for the perspective that the mind wish...
mark-me/Pi-Jukebox
venv/Lib/site-packages/mutagen/musepack.py
Python
agpl-3.0
9,468
0
# -*- coding: utf-8 -*- # Copyright (C) 2006 Lukas Lalinsky # Copyright (C) 2012 Christoph Reiter # # 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 yo...
< 7) | (c[0] & 0x7F) if not c[0] & 0x80: return num, i + 1 if limit > 0: raise ValueError return 0, 0 def _calc_sv8_gain(gain): # 64.82 taken from mpcdec return 64.82 - gain / 256.0 def _calc_sv8_peak(peak): return (10 ** (pe
ak / (256.0 * 20.0)) / 65535.0) class MusepackInfo(StreamInfo): """MusepackInfo() Musepack stream information. Attributes: channels (`int`): number of audio channels length (`float`): file length in seconds, as a float sample_rate (`int`): audio sampling rate in Hz bitrat...
hemmerling/codingdojo
src/game_of_life/python_coderetreat_berlin_2014-09/python_legacycrberlin03/gol03.py
Python
apache-2.0
554
0.01444
#-----------
-------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Administrator # # Created: 08/10/2011 # Copyright: (c) Administrator 2011 # Licence: <your licence> #------------------------------------------------------------------------------- ...
griddata = if __name__ == '__main__': pass
weidel-p/nest-simulator
pynest/nest/tests/test_onetooneconnect.py
Python
gpl-2.0
3,758
0.000532
# -*- coding: utf-8 -*- # # test_onetooneconnect.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 Li...
connections = nest.GetConnections(pre) weights = connections.get("weight") self.assertEqual(weights, [2.0, 3.0]) def test_ConnectPrePostWD(self): """Connect pre to post with a weight and delay""" pre = nest.Create("iaf_psc_alpha", 2) post = nest.Create("iaf_psc_alpha", 2...
nest.Connect(pre, post, conn_spec={"rule": "one_to_one"}, syn_spec={"weight": 2.0, "delay": 2.0}) connections = nest.GetConnections(pre) weights = connections.get("weight") delays = connections.get("delay") self.assertEqual(weights, [2.0, 2.0]) self.assertEq...
fhats/py_razor_client
py_razor_client/razor_client.py
Python
mit
4,490
0.000668
# -*- coding: utf-8 -*- """Contains a quick-and-dirty client for talking to a Razor server. Rather than enumerating an API that has lots of warning labels and stickers cautioning that the API might change frequently, I'm letting the razor server drive. This class will, when given a host and port, ask razor for its API...
d_method(collection_name, lambda *args, **kwargs: self._get_collection(collection_url, *args, **kwargs)) self.collections.add(collection_name) def _bind_command(self, command): command_name = command['name'] command_url = command['id'] # Sanitize the command name so that it maps to...
(self._execute_command, command_url)) self.commands.add(command_name) def _bind_method(self, method_name, method): setattr(self, method_name, method) def _get_collection(self, url, *item): if item: item_path = '/'.join(item) total_item_path = '/'.join((url, item...
Azure/azure-sdk-for-python
sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2021_01_01/operations/_object_replication_policies_operations.py
Python
mit
21,178
0.004675
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
t_name", account_name, 'str', max_length=24, min_length=3), "subscr
iptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version...
GaneshmKumar/Alertify
alertify/alertify.py
Python
mit
3,659
0.004373
# @Author: ganeshkumarm # @Date: 2016-11-19T19:20:11+05:30 # @Last modified by: ganeshkumarm # @Last modified time: 2016-11-19T19:20:45+05:30 #Built in modules import os import sys import time import subprocess import datetime import platform from win10toast import ToastNotifier #Used defined module import except...
== 0: s = 59 m -= 1 def sleep_time(self, notify_time): try:
time.sleep(notify_time * 60) except Exception, e: print e def sendNotification(self, message, start_time): try: end_time = datetime.datetime.now() diff_time_in_delta = end_time - start_time diff_time_in_mins = divmod(diff_time_in_delta.days * 86400 ...
googleapis/python-websecurityscanner
samples/generated_samples/websecurityscanner_v1beta_generated_web_security_scanner_get_finding_sync.py
Python
apache-2.0
1,523
0.001313
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
the following: # python3 -m pip install google-cloud-websecurityscanner # [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync] from google.cloud import websecurityscanner_v1beta def sample_get_finding(): # Create a client client = websecurityscanner_v1beta.WebSecurityScannerClie...
Request( name="name_value", ) # Make the request response = client.get_finding(request=request) # Handle the response print(response) # [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_sync]
Johnzero/titanium-websocket
flask/InitTestWebSocketServer.py
Python
apache-2.0
5,551
0.014747
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2013-06-25 21:56:55 # @Author : Xero # @Link : https://github.com/Johnzero # @Version : $Id$ import socket,threading,struct,sys,base64,hashlib from time import sleep # If flash Socket The policy that is sent to the clients. POLICY = """<cross-d...
if(szBuf == False): try : clientpool.remove(connection) for connect in clientpool: self.SendData(str(connection.getpeernam
e())+" quit!",connect) except ValueError:pass break else: head = '\x81' if len(szBuf) < 126: head += struct.pack('B', len(szBuf)) elif len(szBuf) <= 0xFFFF: head += struct.pack('!B...
sebastian-software/jasy
jasy/vcs/Repository.py
Python
mit
3,416
0.001756
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # import os import jasy.core.Console as Console import jasy.core.Util as Util import jasy.vcs.Git as Git import jasy.vcs.Svn as Svn def isUrl(url): """ Figures out whether the given string is a valid Git repository URL. :param url: URL t...
l: string """ revision = None if Git.isUrl(url):
version = Git.expandVersion(version) revision = Git.update(url, version, path, update) return revision def getRevision(path=None): """Returns the current revision of the repository in the given path.""" old = os.getcwd() revision = None if path is not None: os.chdir(path) ...
pombredanne/MOG
nova/conductor/manager.py
Python
apache-2.0
39,345
0.000686
# Copyright 2013 IBM Corp. # # 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...
llowed_updates:
LOG.error(_("Instance update attempted for " "'%(key)s' on %(instance_uuid)s"), {'key': key, 'instance_uuid': instance_uuid}) raise KeyError("unexpected update keyword '%s'" % key) if key in datetime_fields and isinstance(value, bas...
ken0nek/Software2
140519/test-student.py
Python
mit
393
0.007634
#-*- coding:utf-8 -*- class Student: def __init__(self, name): self.name = name def setGrade(self, grade):
sel
f.grade = grade def main(): s1 = Student("yamada") s2 = Student("suzuki") s1.setGrade(1) s2.setGrade(2) format = "student name = {0} ({1})" print format.format(s1.name, s1.grade) print format.format(s2.name, s2.grade) main()
HewlettPackard/python-proliant-sdk
examples/Redfish/ex15_set_uid_light.py
Python
apache-2.0
2,217
0.014885
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 requ...
": # When running on the server locally use the following commented values # iLO_htt
ps_url = "blobstore://." # iLO_account = "None" # iLO_password = "None" # When running remotely connect using the iLO secured (https://) address, # iLO account name, and password to send https requests # iLO_https_url acceptable examples: # "https://10.0.0.100" # "https://f250asha....
phase-dev/phase
libphase/dialogs.py
Python
gpl-3.0
3,325
0.032782
""" Copyright 2014 This file is part of Phase. Phase 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. Phase is distributed in the hope that...
y this software") response=dialog.run() dialog.destroy() return response def exit_warning(): dialog= Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL| Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.NONE, None) dialog.set_default_response(Gtk.ResponseType.OK) dialog.add_bu...
set_markup("<b>Save and Exit?</b>\n\nIf you don't save, all changes will be permanently lost.") response=dialog.run() dialog.destroy() return response
lehmannro/translate
storage/poxliff.py
Python
gpl-2.0
14,996
0.001467
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2006-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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; e...
if not self.hasplural(): # return super(PoXliffUnit, self).getlanguageNodes() # else: # return self.units[0].getlanguageNodes() def setsource(self, source, sourcelang="en"): # TODO: consider changing from plural to singular, etc. self._rich_source = None if not h...
else: target = self.target for unit in self.units: try: self.xmlelement.remove(unit.xmlelement) except xml.dom.NotFoundErr: pass self.units = [] for s in source.strings: newunit = xlif...
kedz/cuttsum
trec2015/sbin/cross-validation/best-feats.py
Python
apache-2.0
1,444
0.006233
import sys import os import pandas as pd from collections import defaultdict import numpy as np dirname = sys.argv[1] path = os.path.join(dirname, "weights.tsv") with open(path ,"r") as f: df = pd.read_csv(f, sep="\t") df = df[df["iter"] == 5] fc2r = defaultdict(list) features = set() for event, event_df in df....
[["name", "weight", "rank"]].iterrows(): clazz = "NEXT" feature = row["name"] rank = row["rank"] fc2r[(feature, clazz)].append(rank) features.add(feature) f2d = {} for feature in features: sel_u = np.mean(fc2r[(feature, "SELECT")]) next_u = np.mean(fc2r[(feature, "NEXT")...
sel_u, next_u) f2d[feature] = diff print feat_diff = sorted(f2d.items(), key=lambda x: x[1]) for feat, diff in feat_diff[-50:]: print feat
wettenhj/pyupdater-wx-demo
wxupdatedemo/tests/test_run_update_available.py
Python
apache-2.0
4,840
0.001653
""" Test ability to run PyUpdaterWxDemo and confirm that an update is available. We don't want this test to be dependent on having a client_config.py (created by pyupdater init), so we set the WXUPDATEDEMO_TESTING environment variable before loading the wxupdatedemo.config module or the run module. """ # pylint: disab...
} } } }, "latest": { APP_NAME: { "stable": { "mac": UPDATE_VERSION_PYU_FORMAT, "win": UPDATE_VERS
ION_PYU_FORMAT, "nix32": UPDATE_VERSION_PYU_FORMAT, "nix64": UPDATE_VERSION_PYU_FORMAT } } } } # Generated by "pyupdater keys -c": # These keys are only used for automated testing! # DO NOT SHARE YOUR PRODUCTION PRIVATE_KEY !!! PUBLIC_KEY = "12y2oHGB2oroRQJkR73CJNaFeQy776oXsUrqWaAEiZU" PRIV...
cwisecarver/osf.io
api/preprint_providers/serializers.py
Python
apache-2.0
3,317
0.000904
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField, ShowIfVersion, DevOnly class PreprintProviderSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'name', 'descri...
l=True), min_version='2.0', max_version='2.3' ) social_facebook = ShowIfVersion( ser.CharField(required=False, allow_null=True), min_version='2.0', max_version='2.3' ) social_instagram
= ShowIfVersion( ser.CharField(required=False, allow_null=True), min_version='2.0', max_version='2.3' ) class Meta: type_ = 'preprint_providers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def get_preprints_url(self, obj): return absolute_r...
fengsp/flask-snippets
templatetricks/override_autoescaped.py
Python
bsd-3-clause
570
0.005263
# -*- coding: utf-8 -*- """ templatetricks.override_autoescaped ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Override which templates are autoescaped http://flask.pocoo.org/snippets/41/ """ import os import sys sys.path.
insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from flask import Flask class JHtmlEscapingFlask(Flask): def select_jinja_autoescape(self, filename): if filename.endswith('.jhtml'): return True return Flask.s
elect_jinja_autoescape(self, filename) app = JHtmlEscapingFlask(__name__)
uogbuji/akara
test/test_pipeline.py
Python
apache-2.0
3,268
0.009486
import hashlib import urllib2 from test_services import GET from akara import pipeline def test_pipeline_missing_stages(): for stages in (None, [], ()): try: pipeline.register_pipeline("blah", stages=stages) except TypeError: pass else: raise AssertErro...
nt(result) > 30, "What?! Did you
remove elements from the registry?"
atztogo/phonopy
phonopy/qha/core.py
Python
bsd-3-clause
40,784
0.00076
"""Core routines for QHA.""" # Copyright (C) 2012 Atsushi Togo # All rights reserved. # # This file is part of phonopy. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain ...
han' or 'birch_murnaghan'. t_max: float Maximum temperature to be calculated. This has to be not
greater than the temperature of the third element from the end of 'temperatre' elements. If max_t=None, the temperature of the third element from the end is used. energy_plot_factor: float This value is multiplied to energy like values only in plotting. """...
hpcloud-mon/monasca-events-api
monasca_events_api/v2/common/schemas/stream_definition_request_body_schema.py
Python
apache-2.0
1,965
0
# Copyright 2015 Hewlett-Packard # # 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, ...
0)), voluptuou
s.Optional('actions_enabled'): bool} request_body_schema = voluptuous.Schema(stream_definition_schema, required=True, extra=True) def validate(msg): try: request_body_schema(msg) except Exception as ex: LOG.debug(ex) raise exceptions.ValidationE...
memsharded/conan
conans/server/launcher.py
Python
mit
2,666
0.002626
#!/usr/bin/python import os from conans import SERVER_CAPABILITIES, REVISIONS from conans.paths import conan_expand_user from conans.server.conf import get_server_store from conans.server.crypto.jwt.jwt_credentials_manager import JWTCredentialsManager from conans.server.crypto.jwt.jwt_updown_manager import JWTUpDownA...
updown_auth_manager=updown_auth_manager) server_capabilities = SERVER_CAPABILITIES server_capabilities.append(REVISIONS) self.server = ConanServer(server_config.port, credential
s_manager, updown_auth_manager, authorizer, authenticator, server_store, server_capabilities) if not self.force_migration: print("***********************") print("Using config: %s" % server_config.config_filename) ...
pcchenxi/baseline
baselines/test.py
Python
mit
435
0.006897
import tensorflow as tf sess=tf.Session() #First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('./baselines/ppo1/model/rl/model.cptk.meta') saver.rest
ore(sess, './baselines/ppo1/model/rl/model.cptk') graph = tf.get_default_graph() value_w = graph.get_tensor_by_name("pi/vffinal/w:0") # print(sess.run('pi/vffinal/w:0')) summary_writer = tf.summary.FileWriter('./baselines/ppo1/log', sess.graph)
dickrd/cla_tool
setup.py
Python
apache-2.0
492
0
from distutils.core import setup from setuptools import find_packages setup( name='cla_tool', version='1.2.0', packages=fi
nd_packages(exclude=['res']), url='https://github.com/dickrd/cla_tool', license='Apache License 2.0', author='DickRD', author_email='dickdat
a7@gmail.com', description='Chinese language analyze tools.', scripts=['bin/cla'], install_requires=['gensim', 'jieba', 'sklearn'], tests_require=['pytest'], test_suite="pytest" )
alexforencich/python-ivi
ivi/agilent/agilentBase8590A.py
Python
mit
2,338
0.005988
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2013-2017 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
lyzer driver" self._identity_sup
ported_instrument_models = ['8590A', '8590B', '8591A', '8592A', '8592B', '8593A', '8594A', '8595A'] def _display_fetch_screenshot(self, format='bmp', invert=False): if self._driver_operation_simulate: return b'' #if format not in S...
siosio/intellij-community
python/helpers/tests/generator3_tests/data/SkeletonGeneration/skeleton_not_regenerated_for_failed_module_on_same_generator_version/failing.py
Python
apache-2.0
97
0.010309
# Actually a correct module to check
that we don't even at
tempt to regenerate a skeleton for it.
wingtk/gvsbuild
gvsbuild/projects/grpc.py
Python
gpl-2.0
2,081
0.000481
# Copyright (C) 2016 - Yevgen Muntyan # Copyright (C) 2016 - Ignacio Casal Quinteiro # Copyright (C) 2016 - Arnavion # # 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 t...
class Grpc(GitRepo, CmakeProject): def __init__(self):
Project.__init__( self, "grpc", repo_url="https://github.com/grpc/grpc.git", fetch_submodules=True, tag="v1.12.0", dependencies=["go", "nuget", "protobuf", "perl", "zlib", "nasm"], patches=["0001-removing-extra-plugins.patch"], ...
spacy-io/spaCy
spacy/lang/ru/lemmatizer.py
Python
mit
6,165
0.000974
from typing import Optional, List, Dict, Tuple from thinc.api import Model from ...pipeline import Lemmatizer from ...symbols import POS from ...tokens import Token from ...vocab import Vocab PUNCT_RULES = {"«": '"', "»": '"'} class RussianLemmatizer(Lemmatizer): _morph = None def __init__( self,...
analyses) == 1: return analyses[0].normal_form return string def oc2ud(oc_tag: str) -> Tuple[str, Dict[str, str]]: gram_map = { "_POS": { "ADJF": "ADJ", "ADJS": "ADJ", "ADVB": "ADV", "Apro": "DET", "COMP": "ADJ", # Can also b...
", "INTJ": "INTJ", "NOUN": "NOUN", "NPRO": "PRON", "NUMR": "NUM", "NUMB": "NUM", "PNCT": "PUNCT", "PRCL": "PART", "PREP": "ADP", "PRTF": "VERB", "PRTS": "VERB", "VERB": "VERB", }, ...
SPIhub/hummingbird
src/backend/lcls.py
Python
bsd-2-clause
28,140
0.00398
# -------------------------------------------------------------------------------------- # Copyright 2016, Benedikt J. Daurer, Filipe R.N.C. Maia, Max F. Hantke, Carl Nettelblad # Hummingbird is distributed under the terms of the Simplified BSD License. # ----------------------------------------------------------------...
taSource(dsrc) self.run = self.data_source.runs().next() self.timestamps = self.run.times() if self.N is not None: self.timestamps = self.timesta
mps[:self.N] self.timestamps = self.timestamps[ipc.mpi.event_reader_rank()::ipc.mpi.nr_event_readers()] else: self.times = None self.fiducials = None self.i = 0 if not dsrc.startswith('shmem='): self.event_slice = slice(ipc.mpi.event_re...
Jackson-Y/Machine-Learning
text/feature_extraction.py
Python
mit
828
0.002778
# -*- coding: utf-8 -*- ''' Description: Extract the feature from the text in English. Version
: python3 ''' from sklearn.feature_extraction.text import CountVectorizer VECTORIZER = CountVectorizer(min_df=1) # 以下代码设置了特征提取方法的参数(以1-2个单词作为滑动窗口大小,以空格作为单词的分割点,最小词频为1) # 详细参考API介绍: # http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction # VECTORIZER = CountVectorizer(ngram_range=...
.', 'And the third one.', 'Is this the first document?' ] X = VECTORIZER.fit_transform(CORPUS) FEATURE_NAMES = VECTORIZER.get_feature_names() print(FEATURE_NAMES)
julianwang/cinder
cinder/openstack/common/scheduler/filters/__init__.py
Python
apache-2.0
1,389
0
# Copyright (c) 2011 OpenStack Foundation. # 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...
lters.""" def _filter_one(self, obj, filter_properties): """Return True if the object passes the filter, otherwise False.""" return self.host_passes(obj, filter_properties) def host_passes(self, host_state, filter_pr
operties): """Return True if the HostState passes the filter, otherwise False. Override this in a subclass. """ raise NotImplementedError() class HostFilterHandler(base_filter.BaseFilterHandler): def __init__(self, namespace): super(HostFilterHandler, self).__init__(BaseHos...
jordanemedlock/psychtruths
temboo/core/Library/GitHub/GistsAPI/Gists/__init__.py
Python
apache-2.0
1,595
0.00627
from temboo.Library.GitHub.GistsAPI.Gists.CheckGist import CheckGist, CheckGistInputSet, CheckGistResultSet
, CheckGistChoreographyExecution from temboo.Library.GitHub.GistsAPI.Gists.CreateGist import CreateGist, CreateGistInputSet, CreateGistResultSet, CreateG
istChoreographyExecution from temboo.Library.GitHub.GistsAPI.Gists.DeleteGist import DeleteGist, DeleteGistInputSet, DeleteGistResultSet, DeleteGistChoreographyExecution from temboo.Library.GitHub.GistsAPI.Gists.GetGist import GetGist, GetGistInputSet, GetGistResultSet, GetGistChoreographyExecution from temboo.Library....
sergecodd/FireFox-OS
B2G/gecko/testing/marionette/client/marionette/tests/unit/test_cookies.py
Python
apache-2.0
3,426
0.005546
import calendar import time import random from marionette_test import MarionetteTestCase class CookieTest(MarionetteTestCase): def setUp(self): MarionetteTestCase.setUp(self) test_url = self.marionette.absolute_url('test.html') self.marionette.navigate(test_url) self.COOKIE_A = {"...
self.marionette.add_cookie(self.COOKIE_A) cookie_returned = str(self.marionette.execute_script("return document.cookie")) print cookie_returned self.a
ssertTrue(self.COOKIE_A["name"] in cookie_returned) self.marionette.delete_all_cookies() self.assertFalse(self.marionette.get_cookies()) def testDeleteCookie(self): self.marionette.add_cookie(self.COOKIE_A) cookie_returned = str(self.marionette.execute_script("return document.cookie...
beeftornado/sentry
src/sentry/migrations/0072_alert_rules_query_changes.py
Python
bsd-3-clause
4,530
0.003311
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-05-01 23:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import sentry.db.models.fields.bounded import sentry.db.models.fields.foreignkey class Migration(mig...
migrations.AlterField( model_name='alertrule', name='dataset', field=models.TextField(null=True), ), migrations.AlterField( model_name='alertrule', name='query', field=models.TextField(null=True), ), migratio...
model_name='alertrule', name='time_window', field=models.IntegerField(null=True), ), migrations.AlterField( model_name='querysubscription', name='aggregation', field=models.IntegerField(default=0, null=True), ), migrations.Alte...
apllicationCOM/youtube-dl-api-server
youtube_dl_server/youtube_dl/extractor/puls4.py
Python
unlicense
3,103
0.001289
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, unified_strdate, int_or_none, ) class Puls4IE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?puls4\.com/video/[^/]+/play/(?P<id>[0-9]+)' _TESTS = [{ '...
'description': v.get('videotitle'), 'duration': int_or_none(v.get('videoduration') or v.get('episoded
uration')), 'upload_date': unified_strdate(v.get('clipreleasetime')), 'uploader': v.get('channel'), } result['formats'] = formats return result
JanX2/LaunchAtLoginHelper
setup.py
Python
mit
738
0.00542
import sys, os import plistlib urlScheme = sys.argv[1] bundleIdentifier = sys.argv[2] directory = os.path.dirname(os.path.abspath(__file__)) stringsOutput = os.path.join(directory, 'LLStrings.h') infoPlistOutput = os.path.join(directory, 'LaunchAtLoginHelper/LaunchAtLoginHelper-Info.plist') infoPlist = plistlib.read...
') as strings: strings.write("""// strings used by LLManager and LaunchAtLoginHelper // #define LLURLScheme @"%(urlScheme)s" #define LLHelperBundleIdentifier @"%(bundleIdentifier)s" """%locals()) infoPlist['
CFBundleIdentifier'] = bundleIdentifier plistlib.writePlist(infoPlist, infoPlistOutput)
intuition-io/intuition
intuition/__init__.py
Python
apache-2.0
541
0
''' Intuition ---- Intuition is an engine, some building bricks and a set of tools meant to let yo
u efficiently and intuitively make your own automated quantitative trading system. It is designed to let traders, developers and scientists explore, improve and deploy market technical hacks. :copyright (c) 2014 Xavier Bruhiere :license: Apache 2.0, see LICENSE for more details. ''' __project__ = 'intuition' ...
hiere' __licence__ = 'Apache 2.0' __version__ = '0.4.0'
PhilHarnish/forge
src/puzzle/examples/mim/p1_3.py
Python
mit
1,874
0.001067
from puzzle.puzzlepedia import puzzle def get(): return puzzle.Puzzle('Puzzle 1.3: The Missing Painting', SOURCE) SOURCE = """ name in {Beth, Charles, David, Frank, Jessica, Karen, Taylor} job in {attorny, banker, composer, de
corator, entrepreneur, filmmaker, gerontologist} start in {boathouse, cottage, garden, lighthouse, mansion, pond, windmill} status in {crime, innocent} # Setup: only one crime was committed. sum([n.crime for n in name]) == 1 #2 boathouse.crime or cottage.crime or lighthouse.crime or windmill.crime #4 if entrepreneur...
rime #5 not gerontologist.crime #6 Karen == decorator #7 entrepreneur == cottage or entrepreneur == mansion or entrepreneur == pond filmmaker == cottage or filmmaker == mansion or filmmaker == pond gerontologist == cottage or gerontologist == mansion or gerontologist == pond #8 if charles.crime: not cottage.crime...
ArielInfante/HappyHour-Flask
app/users/forms.py
Python
mit
3,344
0.002691
from flask_wtf import Form from wtforms import StringField, PasswordField, SubmitField, BooleanField, RadioField, TextAreaField, FileField from wtforms.validators import InputRequired, Length, Email, Regexp from flask_wtf.file import FileRequired, FileAllowed class SignUpForm(Form): username = StringField('Userna...
Regexp('^[A-Za-z][A-Za-z ]*[A-Za-z]$', 0, "Your name must only have letters") ]) email = StringField('Email', validators=[ InputRequired(message="Email is required"), Email(message="Th
is is not a valid email") ]) password = PasswordField('Password', validators=[ InputRequired(message="Password is required"), Length(min=6, message="The password is not long enough") ]) accept_tos = BooleanField("Accept Terms of Service", validators=[ InputRequired(message="You h...
franklingu/leetcode-solutions
questions/convert-a-number-to-hexadecimal/Solution.py
Python
mit
1,481
0.003381
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '...
mple 2: Input: -1 Output: "ffffffff" """ class Solution(object): def toHex(self, num): """ :type num: int :rtype: str """ curr = [] ret = [] for i in xrange(32): curr.append(str(num & 0x01)) num = num >> 1 if len...
ret.append(chr(ord('a') + n - 10)) curr = [] cleaned = [] is_ok = False for i, n in enumerate(reversed(ret)): if n != '0': is_ok = True if is_ok: cleaned.append(n) if not cleaned: return '0' ...