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
uclouvain/OSIS-Louvain
base/tests/factories/group_element_year.py
Python
agpl-3.0
2,912
0.002061
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
r # (at your option) any later version. # # This program is distributed in the hope that it wil
l 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. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this progr...
chemlab/chemlab
chemlab/core/spacegroup/crystal.py
Python
gpl-3.0
7,982
0.003884
# Adapted from ASE https://wiki.fysik.dtu.dk/ase/ # # # Copyright (C) 2010, Jesper Friis # (see accompanying license files for details). """ A module for chemlab for simple creation of crystalline structures from knowledge of the space group. """ import numpy as np from collections import Counter from .spacegroup ...
=ondublicates, # symprec=symprec) # symbols = parse_symbols(symbols) # symbols = [symbols[i] for i in kinds] # if cell is None: # cell = cellpar_to_cell(cellpar, ab_normal, a_direction) # info = dict(spacegroup=sg) # if primitive_cell: #
info['unit_cell'] = 'primitive' # else: # info['unit_cell'] = 'conventional' # if 'info' in kwargs: # info.update(kwargs['info']) # kwargs['info'] = info # atoms = ase.Atoms(symbols, # scaled_positions=sites, # cell=cell, # ...
DarkPurpleShadow/ConnectFour
urwid/lcd_display.py
Python
bsd-3-clause
16,440
0.003343
#!/usr/bin/python # -*- coding: utf-8 -*- # # Urwid LCD display module # Copyright (C) 2010 Ian Ward # # This library 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 2.1...
set_input_timeouts(self, *args): pass def reset_default_terminal_palette(self, *args): pass def run_wrapper(self,fn): return fn() def draw_screen(self, xxx_todo_changeme, r ): (cols, rows) = xxx_todo_changeme pass def clear(self): pass def get...
CFLCDScreen(LCDScreen): """ Common methods for Crystal Fontz LCD displays """ KEYS = [None, # no key with code 0 'up_press', 'down_press', 'left_press', 'right_press', 'enter_press', 'exit_press', 'up_release', 'down_release', 'left_release', 'right_release', 'enter_relea...
edx/ecommerce
ecommerce/core/migrations/0007_auto_20151005_1333.py
Python
agpl-3.0
780
0.002564
# -*- coding: utf-8 -*- from django.db import migrations def cre
ate_switch(apps, schema_editor): """Create the async_order_fulfillment switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.get_or_create(name='async_order_fulfillment', defaults={'active': False}) def delete_switch(apps, schema_editor): """Delete the asyn...
lment').delete() class Migration(migrations.Migration): dependencies = [ ('core', '0006_add_service_user'), ('waffle', '0001_initial'), ] operations = [ migrations.RunPython(create_switch, reverse_code=delete_switch), ]
zfrxiaxia/Code-zfr
visualgo数据结构/01_sort.py
Python
gpl-3.0
1,847
0.045529
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Created on Sun Sep 18 20:24:29 2016 """ list1 = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48] list2 = [1,1,1,1,1,1,1,1] list3 = [1,2,3,4,5,6,7,8] list4 = [2,3,6,7,5,2,2,2] list5 = [8,7,6,5,4,3,2,1] #检查函数 def check(func): print sort_bubble(list1)==func(lis...
en(left) and r<len(right): if left[l] < right[r]: result.append(left[l]) l += 1 else: result.appen
d(right[r]) r += 1 result += right[r:] result+= left[l:] return result #
timevortexproject/timevortex
features/__init__.py
Python
mit
23
0
"""Features
modules"""
destijl/grr
grr/lib/aff4_objects/hardware.py
Python
apache-2.0
334
0.005988
#!/usr/bin/env python """AFF4 objects for managing Chipsec responses.""" from grr.client.components.chipsec_support.actions import chipsec_types from grr.lib.aff4_objects import collects class ACPITabl
eDataC
ollection(collects.RDFValueCollection): """A collection of ACPI table data.""" _rdf_type = chipsec_types.ACPITableData
arenadata/ambari
ambari-server/src/main/resources/stacks/BigInsights/4.2.5/services/HDFS/package/alerts/alert_checkpoint_time.py
Python
apache-2.0
10,596
0.014062
#!/usr/bin/env python """ 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")...
See the License for the specific language governing permissions and limitations under the License. """ import time import urllib2 import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set. import logging import traceback from resource_management.l...
l_namenode_addresses from resource_management.libraries.functions.curl_krb_request import curl_krb_request from resource_management.libraries.functions.curl_krb_request import DEFAULT_KERBEROS_KINIT_TIMER_MS from resource_management.libraries.functions.curl_krb_request import KERBEROS_KINIT_TIMER_PARAMETER from resourc...
dhyams/SALib
SALib/analyze/__main__.py
Python
lgpl-3.0
1,927
0.011936
from sys import exit import argparse import sobol, morris, extended_fast parser = argparse.ArgumentParser(description='Perform sensitivity analysis on model output') parser.add_argument('-m', '--method', type=str, choices=['sobol', 'morris', 'fast'], required=True) parser.add_argument('-p', '--paramfile', type...
args.column, calc_second_order, num_resamples = args.sobol_bootstrap_resamples, delim = args.delimiter) elif args.method == 'morris': if args.m
orris_model_input is not None: morris.analyze(args.paramfile, args.morris_model_input, args.model_output_file, args.column, delim = args.delimiter) else: print "Error: model input file is required for Method of Morris. Run with -h flag to see usage." exit() elif args.method == 'fast': ...
MadManRises/Madgine
shared/bullet3-2.89/examples/pybullet/examples/fileIOPlugin.py
Python
mit
457
0.017505
impo
rt pybullet as p import time p.connect(p.GUI) fileIO = p.loadPlugin("fileIOPlugin") if (fileIO >= 0): p.executePluginCommand(fileIO, "pickup.zip", [p.AddFileIOAction, p.ZipFileIO]) objs = p.loadSDF("pickup/model.sdf") dobot = objs[0] p.changeVisualShape(dobot, -1, rgbaColor=[1, 1, 1, 1]) else: print("fileIO...
e) while (1): p.stepSimulation() time.sleep(1. / 240.)
vegarang/devilry-django
devilry/utils/tests/__init__.py
Python
bsd-3-clause
81
0.024691
fro
m streamable_archive_tests import * from delivery_collection_tests import
*
rosudrag/eve-wspace
evewspace/account/models.py
Python
gpl-3.0
4,390
0.003189
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # 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 ...
harid, charname, shipname, shiptype): """ Updates the cached locations dict for this
user. """ current_time = time.time() user_cache_key = 'user_%s_locations' % self.user.pk user_locations_dict = cache.get(user_cache_key) time_threshold = current_time - (60 * 15) location_tuple = (sys_id, charname, shipname, shiptype, current_time) if user...
goldhand/django-nupages
tests/test_models.py
Python
bsd-3-clause
1,041
0.024976
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-nupages ------------ Tests for `django-nupages` models module. """ import os import shutil import unittest from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.sites.models import Site
from nupages import models from nupages import views class
TestNupages(unittest.TestCase): def create_page( self, title="Test Page", description="yes, this is only a test", content="yes, this is only a test", custom_template="", site=Site.objects.create(domain="127.0.0.1:8000", name="127.0.0.1:8000")): return models.Page.objects.create( title=title, ...
simone-campagna/statcode
lib/python/statcode/project_file.py
Python
apache-2.0
5,340
0.004307
#!/usr/bin/env python3 # # Copyright 2013 Simone Campagna # # 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 ...
ines += 1 self.file_stats = FileStats(li
nes=num_lines, bytes=num_bytes) except (OSError, IOError) as e: self.filetype = FileTypeClassifier.FILETYPE_UNREADABLE self.file_stats = FileStats() try: self.file_stats.bytes += os.stat(self.filepath).st_size except: ...
Clivern/PyLogging
examples/custom_actions.py
Python
mit
773
0.01423
import pylogging import os # Logs Dir Absolute Path logs_path = os.path.dirname(os.path.abspath(__file__)) + '/logs/' # Create Logger Instance logger = pylogging.PyLogging(LOG_FILE_PATH = logs_path) def customAction1(type, msg): # Custom
Action Goes Here pass # Add Action actionIden1 = logger.addAction(customAction1) def customAction2(type, msg): # Custom Action Goes Here pass # Add Action actionIden2 = logger.addAction(customAction2) # To Remove Action1 logger.removeAction(actionIden1) # Log Info Message logger.info("Info Message") # Log War...
al("Critical Message.") # Log Normal Message logger.log("Normal Log Message.")
NetstationMurator/django-treenav
treenav/forms.py
Python
bsd-3-clause
2,787
0.001794
from django import forms from django.core.urlresolvers import reverse, NoReverseMatch from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.core.validators import URLValidator from treenav.models import MenuItem from mptt.forms import TreeNodeChoic...
f): super(MenuItemFormMixin, self).clean() content_type = self.cleaned_data['content_type'] object_id = self.cleaned_data['object_id'] if (content_type and not object_id) or (not content_type and object_id): raise forms.ValidationError( "Both 'Content type' an...
try: obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist, e: raise forms.ValidationError(str(e)) try: obj.get_absolute_url() except AttributeError, e: raise forms.ValidationError(str(e)) ...
ratschlab/ASP
examples/undocumented/python_modular/kernel_combined_modular.py
Python
gpl-2.0
1,900
0.036842
from tools.load import LoadMatrix from numpy import double lm=LoadMatrix() traindat = double(lm.load_numbers('../data/fm_train_real.dat')) testdat = double(lm.load_numbers('../data/fm_test_real.dat')) traindna = lm.load_dna('../data/fm_train_dna.dat') testdna = lm.load_dna('../data/fm_test_dna.dat') parameter_list =...
ombinedFeatures() subkfeats_train=RealFeatures(fm_train_real) subkfeats_test=RealFeatures(fm_test_real) subkernel=GaussianKernel(10, 1.1) feats_train.append_feature_obj(subkfeats_train) feats_test.append_feature_obj(subkfeats_test) kernel.append_kernel(subkernel) subkfeats_train=StringCharFeatures(fm_train_dna...
) feats_train.append_feature_obj(subkfeats_train) feats_test.append_feature_obj(subkfeats_test) kernel.append_kernel(subkernel) subkfeats_train=StringCharFeatures(fm_train_dna, DNA) subkfeats_test=StringCharFeatures(fm_test_dna, DNA) subkernel=LocalAlignmentStringKernel(10) feats_train.append_feature_obj(subkfe...
AdamStone/cryptrade
cryptrade/trading.py
Python
unlicense
30,686
0.000293
""" Tools for handling trade data, candle data, and simulating trades. """ from __future__ import division import os import csv import time from datetime import datetime, timedelta import itertools import traceback from decimal import Decimal, getcontext getcontext().prec = 8 from utilities import (TRADES, CANDLES, u...
or trade in self.tradesource.trades if trade['timestamp'] >= self.active_candle[0]] def update(self):
""" Checks for new trades and updates the candle data. """ new_trades = self.tradesource.new_trades if new_trades: self.active_trades += [{'timestamp': int(trade['timestamp']), 'price': Decimal(trade['price']),
opensemanticsearch/open-semantic-search-apps
src/annotate/urls.py
Python
gpl-3.0
494
0.01417
from django.conf.urls import url from annotate import views urlpatterns = [ url(r'^$', vi
ews.IndexView.as_view(), name='index'), url(r'^create$', views.create_annotation, name='create'), url(r'^edit$', views.edit_annotation, name='edit'), url(r'^json$', views.export_json, name='export_json'), url(r'^rdf$', views.export_rdf, name='export_rdf'), url(r'^(?P<pk>\d+)/update$', views.update_annotatio
n, name='update'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), ]
bzennn/blog_flask
python/lib/python3.5/site-packages/pilkit/processors/__init__.py
Python
gpl-3.0
386
0
# flake8: noqa """ PILKit image processors. A processor accepts an image, does some stuf
f, and returns the result. Processors can do anything with the image you want, but their responsibilities should be limited to image manipulations--the
y should be completely decoupled from the filesystem. """ from .base import * from .crop import * from .overlay import * from .resize import *
alexwaters/python-readability-api
examples/read-bookmarks.py
Python
mit
2,034
0.002458
#!/usr/bin/env python # -*- coding: utf-8 -*- """ read-bookmark.py ~~~~~~~~~~~~~~~~ This module is an example of how to harness the Readability API w/ oAuth. This module expects the following environment variables to be set: - READABILITY_CONSUMER_KEY - READABILITY_CONSUMER_SECRET - READABILITY_ACCESS_TOKEN - READA...
following to get your access tokens:: $ ./login-xauth.py <username> <password> """ import sys from HTMLParser import HTMLParser from ext import setup_rdd class MLStripper(HTMLParser): """HTMLParser w/ overrides for stripping text out.""" def __init__(self): self.reset() self.
fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ' '.join(self.fed) def strip_tags(html): """A super low-tech and debatably irresponsible attempt to turn HTML into plain text.""" s = MLStripper() s.feed(html) data = s.get_data() for s i...
mdiller/MangoByte
cogs/utils/metastats.py
Python
mit
738
0.004065
def get_h
ero_winrate(hero): """returns hero winrate from list of meta heroes""" if hero['pro_pick'] == 0: return 0 else: return hero.get('pro_win', 0) / hero.get('pro_pick', 1) def get_hero_pick_percent(hero, heroes): return hero.get('pro_pick', 0) / get_total_pro_games(heroes) def get_hero_ban_percent(hero,...
total += hero.get('pro_pick', 0) # sums total games in the list total = total/10 return total def get_hero_pickban_percent(hero, heroes): return ( hero.get('pro_pick', 0) + hero.get('pro_ban', 0) ) / get_total_pro_games(heroes)
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/nltk/corpus/reader/reviews.py
Python
apache-2.0
12,534
0.002074
# Natural Language Toolkit: Product Reviews Corpus Reader # # Copyright (C) 2001-2017 NLTK Project # Author: Pierpaolo Pantone <24alsecondo@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ CorpusReader for reviews corpora (syntax based on Customer Review Corpus). - Customer Review C...
eting product from the same brand. Note: Some of the files (e.g. "ipod.txt", "Canon PowerShot SD500.txt") do not provide separation between different reviews. This is due to the fact that the dataset w
as specifically designed for aspect/feature-based sentiment analysis, for which sentence-level annotation is sufficient. For document- level classification and analysis, this peculiarity should be taken into consideration. """ from __future__ import division from six import string_types import re from n...
yiwen-luo/LeetCode
Python/read-n-characters-given-read4-ii-call-multiple-times.py
Python
mit
1,921
0.006247
# Time: O(n) # Space: O(1) # # The API: int read4(char *buf) reads 4 characters at a time from a file. # # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. # # By using the read4 API, implement the function int read(char *buf, int n) ...
uf, a list of characters # @return an integer # def read4(buf): class Solution(object): def __init__(self): self.__buf4 = [''] * 4 self.__i4 = 0 self.__n4 = 0 def read(self, buf, n): """ :type buf: Destination buffer (List[str]) :type n: Maximum number o...
self.__i4 < self.__n4: # Any characters in buf4. buf[i] = self.__buf4[self.__i4] i += 1 self.__i4 += 1 else: self.__n4 = read4(self.__buf4) # Read more characters. if self.__n4: self.__i4 = 0 ...
sthyme/ZFSchizophrenia
BehaviorAnalysis/mergingbehaviordata/lmmanalysisave_septcut4and2ifsame.py
Python
mit
13,435
0.026424
#!/usr/bin/python import os,sys,glob,re import numpy as np import scipy from scipy import stats import datetime import time from datetime import timedelta #import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt #from matplotlib import colors as c #from matplotlib import cm from scipy.stats.kde impor...
1 start","Dark flash block 1 end","Dark flash block 2 start","Dark flash block 2 end"]] stimcombos = { #"Day light flash and weak tap": ["106106"], #"Night light flash and weak tap": ["night1061
06"], "Night tap habituation": ["nighttaphab102", "nighttaphab1"], "Day tap habituation 1": ["adaytaphab102", "adaytaphab1"], "Day tap habituation 3": ["cdaytaphab102", "cdaytaphab1"], "Day tap habituation 2": ["bdaytaphab102", "bdaytaphab1"], "Day light flash": ["lightflash104"], #"Day light flash": ["lightflash...
aferr/LatticeMemCtl
src/mem/ruby/network/garnet/fixed-pipeline/GarnetRouter_d.py
Python
bsd-3-clause
2,044
0.001468
# Copyright (c) 2008 Princeton University # Copyright (c) 2009 Advanced Micro Devices, Inc. # All rights reserved. # # Redistrib
ution 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 the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the abo...
following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROV...
culturagovbr/sistema-nacional-cultura
adesao/migrations/0019_auto_20181005_1645.py
Python
agpl-3.0
8,604
0.005811
# Generated by Django 2.0.8 on 2018-10-05 19:45 from django.db import migrations from django.core.exceptions import ObjectDoesNotExist def cria_sistema_cultura(apps, schema_editor): erros = [] SistemaCultura = apps.get_model('adesao', 'SistemaCultura') Municipio = apps.get_model('adesao', 'Municipio') ...
telefone_dois=municipio.telefone
_dois, telefone_tres=municipio.telefone_tres, email_institucional=municipio.email_institucional_prefeito, tipo_funcionario=3, termo_posse=municipio.termo_posse_prefeito, rg_copia=municipio.rg_copia_prefeito, cpf_copia=munici...
terhorstd/nest-simulator
pynest/examples/hh_psc_alpha.py
Python
gpl-2.0
2,263
0
# -*- coding: utf-8 -*- # # hh_psc_alpha.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 License, o...
uilibrium state nest.SetStatus(sd, {'n_events': 0}) # then reset spike counts
nest.Simulate(simtime) # another simulation call to record firing rate n_events = nest.GetStatus(sd, keys={'n_events'})[0][0] amplitudes[i] = amp event_freqs[i] = n_events / (simtime / 1000.) plt.plot(amplitudes, event_freqs) plt.show()
JackDanger/sentry
src/sentry/south_migrations/0212_auto__add_organizationoption__add_unique_organizationoption_organizati.py
Python
bsd-3-clause
40,363
0.008052
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'OrganizationOption' db.create_table('sentry_organizationo...
('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), ...
th': '32'}) }, 'sentry.broadcastseen': { 'Meta': {'unique_together': "(('broadcast', 'user'),)", 'object_name': 'BroadcastSeen'}, 'broadcast': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [],
robertapengelly/ppa-helper
ppa_helper/compat.py
Python
gpl-3.0
3,031
0.002639
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 # ...
kwargs = lambda kwargs: kwargs if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3 compat_get_terminal_size = shutil.get_terminal_size else: _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines']) def compat_g
et_terminal_size(fallback=(80, 24)): columns = compat_getenv('COLUMNS') if columns: columns = int(columns) else: columns = None lines = compat_getenv('LINES') if lines: lines = int(lines) else: lines = None if colum...
i-rabot/tractogithub
tracformatter/trac/tests/functional/compat.py
Python
bsd-3-clause
650
0.003077
#!/usr/bin/python import os import shutil from trac.util.compat import close_fds # On Windows, shutil.rmtree doesn't remove
files with the read-only # attribute set, so this function explicitly removes it on every error # before retrying. Even on Linux, shutil.rmtree chokes on read-only # directories, so we use this version in all cases. # Fix from http://bitten.edgewall.org/changeset/521 def rmtree(root): """Catch shutil.rmtree...
le_error(fn, path, excinfo): os.chmod(path, 0666) fn(path) return shutil.rmtree(root, onerror=_handle_error)
rectory-school/rectory-apps
courseevaluations/migrations/0005_auto_20151208_1014.py
Python
mit
877
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('academics', '0016_student_auth_key'), ('courseevaluations', '0004_auto_20151208_1004'), ] operations = [ migrations....
model_name='multiplechoicequestionanswer', name='student', ), migrations.AddField( model_name='evaluable', name='student', field=models.ForeignKey(to='academ
ics.Student', default=None), preserve_default=False, ), ]
mhoffma/micropython
tests/thread/thread_qstr1.py
Python
mit
825
0.004848
# test concurrent interning of strings # # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread # function to check the interned string def check(s, val): assert type(s) == str assert int(s) == val # main thread function def th(base, n): for i in range(n): # this...
_thread.allocate_lock() n_thread = 4 n_finished = 0 n_qstr_per_t
hread = 100 # make 1000 for a more stressful test (uses more heap) # spawn threads for i in range(n_thread): _thread.start_new_thread(th, (i * n_qstr_per_thread, n_qstr_per_thread)) # busy wait for threads to finish while n_finished < n_thread: pass print('pass')
mice-software/maus
src/common_py/calibration/get_kl_calib.py
Python
gpl-3.0
3,304
0.003329
# This file is part of MAUS: http://micewww.pp.rl.ac.uk/projects/maus # # MAUS 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. # # MAUS is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the imp...
copy of the GNU General Public License # along with MAUS. If not, see <http://www.gnu.org/licenses/>. # """ Get KL calibrations from DB """ import cdb import json from Configuration import Configuration from cdb._exceptions import CdbPermanentError class GetCalib: """ Evaluator class to evaluate mathematic...
aericson/Djax
pax/library.py
Python
bsd-3-clause
3,541
0.017509
""" Client for the library API. """ class LibraryClient(object): """ Library API client. """ def __init__(self,axilent_connection): self.content_resource = axilent_connection.resource_client('axilent.library','content') self.api = axilent_connection.http_client('axilent.library') ...
h Axilent. """ return self.api.ping(project=project,content_type=content_type) def index_content(self,project,content_type,content_key): """ Forces re-indexing of the specified content item. """ response = self.api.indexcontent(content_key=content_key, ...
roject=project, content_type=content_type) return response['indexed'] def tag_content(self,project,content_type,content_key,tag,search_index=True): """ Tags the specified content item. """ response = self.api.tagcontent(project=pr...
texnofobix/pyhwtherm
example.py
Python
mit
739
0.014885
import pyhwtherm mytest = pyhwtherm.PyHWTherm( username="someuser@example.com", password="mysecretpassword", deviceid=123456 ) print "login successful: ",mytest.login() print "Get thermostat data:",
mytest.updateStatus() beforeChange = mytest.status print "Status: ", beforeChange mytest.tempHold("11:00",cool=78,heat=68) mytest.submit() print "Get thermostat data:", mytest.updateStatus() afterChange = mytest.status print "heat >>",beforeChange['latestData']['uiData']['HeatSetpoint'],"->",afterChange['latestData'...
", mytest.logout()
54Pany/gum
data/libdbs.py
Python
gpl-3.0
1,870
0.002674
#!/usr/bin/env python # encoding: utf-8 import sqlite3 from sys import version_info if version_info >= (3, 0, 0): def listkey(dicts): return list(dicts.keys())[0] else: def listkey(dicts): return dicts.keys()[0] class sqlitei: '''Encapsulation sql.''' def __init__(self, path): ...
e): '''Select table str, column list, dump dict.''' columns = ','.join(column) sql = 'select ' + columns + ' from ' + table dumps = [] if dump: dumpname = listkey(dump) sql += ' where ' + dumpname + '=?' dumps.append(dump[dumpname]) ...
dump dict.''' columns = [] columnx = '' for c in column: columnx += c + '=?,' columns.append(column[c]) dumpname = listkey(dump) sql = 'update ' + table + ' set '+ columnx[:-1] + ' where ' + dumpname + '=?' columns.append(dump[dumpname]) re...
postlund/home-assistant
homeassistant/components/insteon/sensor.py
Python
apache-2.0
876
0.001142
"""Support for INSTEON dimmers via PowerLinc Modem.""" import logging from homeassistant.helpers.entity import Entity from .insteon_entity import InsteonEntity _LOGGER =
logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the INSTEON device class for the hass platform.""" insteon_modem = hass.data["insteon"].get("modem") address = discovery_info["address"] device = insteon_modem.devices[addre
ss] state_key = discovery_info["state_key"] _LOGGER.debug( "Adding device %s entity %s to Sensor platform", device.address.hex, device.states[state_key].name, ) new_entity = InsteonSensorDevice(device, state_key) async_add_entities([new_entity]) class InsteonSensorDevice...
panchr/wire
wire/tests/sqlstring_test.py
Python
gpl-3.0
1,665
0.027628
import unittest import wire class TestSQLString(unittest.TestCase): def setUp(self): '''Sets up the test case''' self.sql = wire.SQLString def test_pragma(self): '''Tests the PRAGMA SQL generation''' self.assertEqual(self.sql.pragma("INTEGRITY_CHECK(10)"), "PRAGMA INTEGRITY_CHECK(10)") self.assertEqual(s...
elf.sql.dropTable("some_other_table"), "DROP TABLE some_other_table") def test_renameTable(self): '''Tests the ALTER TABLE RENAME SQL generation''' s
elf.assertEqual(self.sql.rename("orig_table", "new_table"), "ALTER TABLE orig_table RENAME TO new_table") if __name__ == '__main__': unittest.main()
boada/vpCluster
data/boada/analysis_all/MLmethods/plot_massComparison_scatter.py
Python
mit
1,151
0.002606
from glob import glob import pylab as pyl import h5py as hdf files = glob('ML_predicted_masses*') # get the power law masses with hdf.File('../results_cluster.hdf5', 'r') as f: dset = f[f.keys()[0]] results = dset.value # make a figure f = pyl.figure(figsize=(6, 6 * (pyl.sqrt(5.) - 1.0) / 2.0)) ax = f.add_su...
68a6', '#e24a33'], ['$ML_{\sigma, N_{gals}}$, Flat HMF', '$ML_{\sigma, N_{gals}}
$']): if i == 0: i += 1 continue with hdf.File(f, 'r') as f1: dset = f1[f1.keys()[0]] ML = dset.value ax.errorbar(results['MASS'], ML['ML_pred'], xerr=results['MASS_err'], yerr=ML['ML_pred_err'], fmt='o', ...
haochi/json-stable-stringify-python
tests/test_stringify.py
Python
mit
1,700
0.004118
import unittest from .context import json_stable_stringify_python as stringify class TestStringify(unittest.TestCase): def test_simple_object(self): node = {'c':6, 'b': [4,5], 'a': 3, 'z': None} actual = stringify.stringify(node) expected = '{"a":3,"b":[4,5],"c":6,"z":null}' self.as...
'{"a":{"b":{"c":[1,2,3,null]}}}' self.assertEqual(actual, expected) def test_array_with_objects(self): node = [{'z': 1, 'a': 2}] actual = stringify.stringify(
node) expected = '[{"a":2,"z":1}]' self.assertEqual(actual, expected) def test_nested_array_objects(self): node = [{'z': [[{'y': 1, 'b': 2}]], 'a': 2}] actual = stringify.stringify(node) expected = '[{"a":2,"z":[[{"b":2,"y":1}]]}]' self.assertEqual(actual, expected) ...
dulaccc/Accountant
accountant/settings/common.py
Python
mit
5,873
0.000851
""" Django settings for accountant project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import os import sys from decimal import Decimal import accounting V...
TICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "djangobower.finders.BowerFinder", ) # Media files MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL =...
media/' # Bower config BOWER_COMPONENTS_ROOT = os.path.abspath(os.path.join(BASE_DIR, 'components')) BOWER_INSTALLED_APPS = ( 'modernizr', 'jquery', 'bootstrap', ) # Select 2 AUTO_RENDER_SELECT2_STATICS = False SELECT2_BOOTSTRAP = True # Custom User LOGIN_REDIRECT_URL = 'connect:getting-started' L...
dcm-oss/blockade
blockade/tests/util.py
Python
apache-2.0
1,956
0.001022
############################################################################## # # Copyright Zope Foundation and Contributors
. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #...
###################################################################### import time class Wait(object): class TimeOutWaitingFor(Exception): "A test condition timed out" timeout = 9 wait = .01 def __init__(self, timeout=None, wait=None, exception=None, getnow=(lambda: time.t...
ratschlab/ASP
examples/undocumented/python_modular/graphical/multiclass_qda.py
Python
gpl-2.0
3,312
0.038647
""" Shogun demo Fernando J. Iglesias Garcia """ import numpy as np import matplotlib as mpl import pylab import util from scipy import linalg from shogun.Classifier import QDA from shogun.Features import RealFeatures, MulticlassLabels # colormap cmap = mpl.colors.LinearSegmentedColormap('color_classes', {'red': ...
# Correctly classified tp = (y == y_pred) tp0, tp1, tp2 = tp[y == 0], tp[y == 1], tp[y == 2] X0_tp, X1_tp, X2_tp = X0[tp0], X1[tp1], X2[tp2] # Misclassified X0_fp, X1_fp, X2_fp = X0[tp0 != True], X1[tp1 != True], X2[tp2 != True] # Class 0 data pylab.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color = cols[0]) pylab.p...
p[:, 1], 's', color = cols[0]) m0 = qda.get_mean(0) pylab.plot(m0[0], m0[1], 'o', color = 'black', markersize = 8) # Class 1 data pylab.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color = cols[1]) pylab.plot(X1_fp[:, 0], X1_fp[:, 1], 's', color = cols[1]) m1 = qda.get_mean(1) pylab.plot(m1[0], m1[1], 'o', color = 'blac...
houqp/floyd-cli
floyd/client/version.py
Python
apache-2.0
580
0
from floyd.client
.base import FloydHttpClient from floyd.model.versi
on import CliVersion from floyd.log import logger as floyd_logger class VersionClient(FloydHttpClient): """ Client to get API version from the server """ def __init__(self): self.url = "/cli_version" super(VersionClient, self).__init__(skip_auth=True) def get_cli_version(self): ...
Ymir-RPG/ymir-api
run.py
Python
apache-2.0
70
0
from ymir import ap
p app.run(debug=True, host='0.0.0.0', port=2841
)
eLRuLL/scrapy
scrapy/__init__.py
Python
bsd-3-clause
1,151
0.007819
""" Scrapy - a web crawling and web scraping framework written for Python """ __all__ = ['__version__', 'version_info', 'twisted_version', 'Spider', 'Request', 'FormRequest', 'Selector', 'Item', 'Field'] # Scrapy version import pkgutil __version__ = pkgutil.get_data(__package__, 'VERSION').decode('ascii')....
uires Python 3.5" % __version__) sys.exit(1) # Ignore noisy twisted deprecation warnings import
warnings warnings.filterwarnings('ignore', category=DeprecationWarning, module='twisted') del warnings # Apply monkey patches to fix issues in external libraries from scrapy import _monkeypatches del _monkeypatches from twisted import version as _txv twisted_version = (_txv.major, _txv.minor, _txv.micro) # Declare ...
mivanov-utwente/t4proj
t4proj/apps/stats/models.py
Python
bsd-2-clause
481
0.002079
from django.db.models import Transfor
m from django.db.models import DateTimeField, TimeField from django.utils.functional import cached_property class TimeValue(Transform): lookup_name = 'time' function = 'ti
me' def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return 'TIME({})'.format(lhs), params @cached_property def output_field(self): return TimeField() DateTimeField.register_lookup(TimeValue)
trabacus-softapps/docker-edumedia
additional_addons/Edumedia_India/ed_sale.py
Python
agpl-3.0
56,005
0.017034
from openerp.osv import fields,osv import time import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ from openerp import pooler from openerp import netsvc import base64 from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from openerp.addons.Edumedi...
'cap3_text':fields.text('Caption Text',size=500), 'cap4_terms' : fields.char('Caption 4',size=100), 'cap4_text':fields.text('Caption Text',size=500), 'ed_type':fields.
selection([('so','Sale Order'),('crm','CRM')],'Type'), 'ed_license':fields.selection(config.CLASS_STD,'License',readonly=True ,states={'draft': [('readonly', False)]}), 'rsn_reject' : fields.text('Relationship Manager Remarks',readonly=True ,states={'draft': [('readonly', False)]}), ...
booski/hostdb9
dns_reader.py
Python
gpl-2.0
1,853
0.001619
# coding=utf-8 import sys def read(client, vlans, cnames, print_warnings): lines = [] if cnames: for cname in client.list_cnames(): lines.append('cname\t' + cname['name']) lines.append('target\t' + cname['canonical']) lines.append('') for vlan in client.list_vla...
mes) > 1: extra = '\t# additional names: ' + ', '.join(names[1:]) if print_warnings: print('Warning! '+ addr + ' has several names. ' + 'Adding extra names as file comment.', file=sys.stderr) ...
tra: append_line += extra lines.append(append_line) (comment, aliases) = client.get_host_info(name) if comment: lines.append('comment\t' + comment) for alias in aliases: lines.append('alias\t' + a...
Azure/azure-sdk-for-python
sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2020_04_01/aio/operations/_managed_clusters_operations.py
Python
mit
54,887
0.005265
# 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 ...
if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(
get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerService/managedClusters'} # type: ignore @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIt...
bgroff/kala-app
django_kala/api/basecamp_classic/companies/parsers.py
Python
mit
2,236
0
""" Provides XML parsing support. """ from django.conf import settings from rest_framework.exceptions import ParseError from rest_framework.parsers import BaseParser import defusedxml.ElementTree as etree class XMLCompanyParser(BaseParser): """ XML company parser. """ media_type = 'application/xml' ...
ag == 'city': data['city'] = str(field.text) if field.tag == 'state': data['state'] = st
r(field.text) if field.tag == 'country': data['country'] = str(field.text) if field.tag == 'time-zone-id': data['timezone'] = str(field.text) if field.tag == 'locale': data['locale'] = str(field.text) return data
PAIR-code/interpretability
text-dream/python/helpers/setup_helper.py
Python
apache-2.0
3,457
0.010703
# Copyright 2018 Google LLC. 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...
BertTokenizer.from_pretrained(model_config) # Load pre-trained model (weights) model = modeling.BertForMaskedLM.from_pretrained('bert-base-uncased') _ = model.eval() # Set up the device in use device = torch.device
('cuda:0' if torch.cuda.is_available() else 'cpu') print('device : ', device) model = model.to(device) # Initialize the embedding map embedding_map = embeddings_helper.EmbeddingMap(device, model.bert) return tokenizer, model, device, embedding_map
md1024/rams
uber/tests/models/test_attendee.py
Python
agpl-3.0
16,952
0.001829
from uber.tests import * class TestCosts: @pytest.fixture(autouse=True) def mocked_prices(self, monkeypatch): monkeypatch.setattr(c, 'get_oneday_price', Mock(return_value=10)) monkeypatch.setattr(c, 'get_attendee_price', Mock(return_value=20)) def test_badge_cost(self): assert 10 ...
is_unpaid for status in [c.NEED_NOT_PAY, c.PAID_BY_GROUP, c.REFUNDED]: assert not Attendee(paid=status).is_unpaid # we may eventually want to make this a little more explicit; # at the moment I'm basically just testing an implementation detail def test_is_unassigned(): assert Attendee().is_unassigned ...
endee().is_dealer assert Attendee(ribbon=c.DEALER_RIBBON).is_dealer assert Attendee(badge_type=c.PSEUDO_DEALER_BADGE).is_dealer # not all attendees in a dealer group are necessarily dealers dealer_group = Group(tables=1) assert not Attendee(group=dealer_group).is_dealer def test_is_dept_head(): ...
gst/amqpy
amqpy/consumer.py
Python
mit
2,846
0.000351
from abc import ABCMeta, abstractmethod class AbstractConsumer(metaclass=ABCMeta): """ This class provides facilities to create and manage queue consumers. To create a consumer, subclass this class and override the :meth:`run` method. Then, instantiate the class with the desired parameters and call ...
me()` internally. After the queue consumer is created, :attr:`self.consumer_tag` is set to the server-assigned consumer tag if a tag was not specified initially. """ self.consumer_tag = self.channel.basic_consume( self.queue, self.consume
r_tag, self.no_local, self.no_ack, self.exclusive, callback=self.start, on_cancel=self.cancel_cb) def cancel(self): """Cancel the consumer """ self.channel.basic_cancel(self.consumer_tag) @abstractmethod def run(self, msg): """Consumer callback This met...
DavidYen/YEngine
ypy/path_help.py
Python
mit
129
0.03876
imp
ort os def NormalizedJoin( *args ): "Normalizes and joins directory nam
es" return os.path.normpath(os.path.join(*args))
stweil/letsencrypt
certbot-dns-route53/tests/dns_route53_test.py
Python
apache-2.0
9,471
0.00095
"""Tests for certbot_dns_route53._internal.dns_route53.Authenticator""" import unittest from botocore.exceptions import ClientError from botocore.exceptions import NoCredentialsError try: import mock except ImportError: # pragma: no cover from unittest import mock # type: ignore from certbot import errors fr...
"Id": "EXAMPLE", "Name": "example.com", "Config": { "PrivateZone": False } } FOO_EXAMPLE_COM_ZONE = { "Id": "FOO",
"Name": "foo.example.com", "Config": { "PrivateZone": False } } def setUp(self): from certbot_dns_route53._internal.dns_route53 import Authenticator s...
data-tsunami/museo-cachi
cachi/migrations/0008_auto__del_field_piezaconjunto_fragmentos.py
Python
gpl-3.0
15,336
0.007303
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'PiezaConjunto.fragmentos' db.delete_column(u'cachi_piez...
els.fields.DateField', [], {}), 'fragmento': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'fichas_tecnicas'", 'to': u"orm['cachi.
Fragmento']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inscripciones_marcas': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'observacion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})...
forkbong/qutebrowser
qutebrowser/utils/usertypes.py
Python
gpl-3.0
16,178
0.000124
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
._idx = self._items.index(self._default) return self.curitem() class PromptMode(enum.Enum): """The mode of a Question.""" yesno = enum.auto() text = enum.auto() user_pwd = enum.auto() alert = enum.auto() download = enum.auto() class ClickTarget(enum.Enum): """How to open a cli...
uto() #: Open the link in a new background tab window = enum.auto() #: Open the link in a new window hover = enum.auto() #: Only hover over the link class KeyMode(enum.Enum): """Key input modes.""" normal = enum.auto() #: Normal mode (no mode was entered) hint = enum.auto() #: Hint mode (sh...
timrae/anki
aqt/main.py
Python
agpl-3.0
39,738
0.000906
# Copyright: Damien Elmes <anki@ichi2.net> # -*- coding: utf-8 -*- # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html import re import signal import zipfile from send2trash import send2trash from aqt.qt import * from anki import Collection from anki.utils import isWin, isMac, intTime, spl...
) d.connect(f.add, SIGNAL("clicked()"), self.onAddProfile) d.connect(f.rename, SIGNAL("clicked()"), self.on
RenameProfile) d.connect(f.delete_2, SIGNAL("clicked()"), self.onRemProfile) d.connect(d, SIGNAL("rejected()"), lambda: d.close()) d.connect(f.profiles, SIGNAL("currentRowChanged(int)"), self.onProfileRowChange) self.refreshProfilesList() # raise first, for osx ...
gslab-econ/gslab_python
gslab_make/dir_mod.py
Python
mit
9,540
0.005346
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, Logic...
hidden .csv file: warning if (not filename.startswith('.')) and (ext == '.csv'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_csv_file % (filename, manifestlog) print >> LO...
'.txt'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_txt_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_txt_file % (filename, manifestlog) except: print_e...
namlook/MongoLite
mongolite/schema_document.py
Python
bsd-3-clause
17,726
0.002369
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Nicolas Clairon # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above cop...
bj_optional = attrs.get('optional', {}).copy() attrs['optional'] = parent.optional.copy() attrs['optional'].update(obj_optional) if hasattr(parent, 'default_values'): if parent.default_values: obj_default_values = at...
opy() attrs['default_values'] = parent.default_values.copy() attrs['default_values'].update(obj_default_values) if hasattr(parent, 'skeleton') or hasattr(parent, 'optional'): if attrs.get('authorized_types'): attrs['authorized_types...
googleads/google-ads-python
google/ads/googleads/v9/services/services/conversion_value_rule_set_service/transports/__init__.py
Python
apache-2.0
1,117
0
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
onValueRuleS
etServiceGrpcTransport # Compile a registry of transports. _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ConversionValueRuleSetServiceTransport]] _transport_registry["grpc"] = ConversionValueRuleSetServiceGrpcTransport __all__ = ( "ConversionValueRuleSetServiceTransport", "ConversionVa...
tzpBingo/github-trending
codespace/python/tencentcloud/sqlserver/v20180328/models.py
Python
mit
284,748
0.002484
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
:type UserName: str :param DBPrivileges: 账号权限变更信息 :type DBPrivileges: list of DBPrivilegeModifyInfo """ self.UserName = None self.DBPrivileges = None def _deserialize(self, params): self.UserName = params.get("UserName") if params.get("DBPrivileges") i...
obj = DBPrivilegeModifyInfo() obj._deserialize(item) self.DBPrivileges.append(obj) memeber_set = set(params.keys()) for name, value in vars(self).items(): if name in memeber_set: memeber_set.remove(name) if len(memeber_set) > 0: ...
yrobla/pyjuegos
pgzero/music.py
Python
lgpl-3.0
2,526
0.000396
from pygame.mixer import music as _music from .loaders import ResourceLoader from . import constants __all__ = [ 'rewind', 'stop', 'fadeout', 'set_volume', 'get_volume', 'get_pos', 'set_pos', 'play', 'queue', 'pause', 'unpause', ]
_music.set_endevent(constants.MUSIC_END) class _MusicLoader(ResourceLoader): """Pygame's music API acts as a singleton with one 'current' track. No objects are returned that represent different tracks, so this loader can't return anything use
ful. But it can perform all the path name validations and return the validated path, so that's what we do. This loader should not be exposed to the user. """ EXTNS = ['mp3', 'ogg', 'oga'] TYPE = 'music' def _load(self, path): return path _loader = _MusicLoader('music') # State of w...
sethlaw/sputr
tests/xss_test.py
Python
gpl-3.0
3,768
0.005308
from .requests_test import RequestsTest import copy import sys class XSSTest(RequestsTest): def test(self): if self.DEBUG: print("Run the XSS Tests") passed = 0 failed = 0 messages = [] url = self.domain['protocol'] + self.domain['host'] + self.config['path'] print(...
+ p + ")") if self.config['method'] == 'GET': if self.DEBUG: print("Using GET " + self.config['path']) data = copy.deepcopy(self.config['params']) data[k] = data[k] + p res = self.get(url, params=data) if...
k) failed = failed + 1 result = 'ERROR' else: if 'testpath' in self.config: res = self.get(self.domain['protocol'] + self.domain['host'] + self.config['testpath']) if self.DEBU...
emilssolmanis/tapes
tapes/local/timer.py
Python
apache-2.0
702
0
import
contextlib from time import time from .meter import Meter from .stats import Stat from .histogram import Histogram class Timer(Stat): def __init__(self): self.count = 0 self.meter = Meter() self.histogram = Histogram() super(Timer, self).__init__() @contextlib.contextmanager...
start_time = time() try: yield finally: self.update(time() - start_time) def update(self, value): self.meter.mark() self.histogram.update(value) def get_values(self): values = self.meter.get_values() values.update(self.histogram.ge...
dsumike/adventofcode
python/11p2.py
Python
mit
1,491
0.032193
#!/usr/bin/env python import re letters = 'abcdefghijklmnopqrstuvwxyz' with open("../input/11.txt") as fileobj: password = fileobj.readline().strip() print password def rules(pass
word): rules = [ rule1, rule2, rule3 ] if all(rule(password) for rule in rules): return True else: return False def rule1(password): # Rule 1: in the range of A-Z, must have 3 consecutive letters # Check A-X for [abc, bcd, ..., wzy, xyz] for i in range(24):
if letters[i:i+3] in password: return True # else rule 1 failed return False def rule2(password): # Rule 2: No i, o, l if 'i' in password or 'o' in password or 'l' in password: return False return True def rule3(password): # Rule 3: Password must contain at least 2 different, non-overlapping pairs of le...
ismail-s/warehouse
tests/unit/i18n/test_init.py
Python
apache-2.0
1,632
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
ludeme(): config_settings = {} config = pretend.stub( add_request_method=pretend.call_recorder(lambda f, name, reify: None), get_settings=lambda: config_settings, ) i18n.includeme(config) assert config.add_request_method.calls == [ pretend.call(i18n._locale, name="locale", ...
n.filters:format_datetime", }, "jinja2.globals": { "l20n": "warehouse.i18n.l20n:l20n", }, }
developerworks/horizon
horizon/tests/authors_tests.py
Python
apache-2.0
2,188
0.001371
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # Copyright 2012 Nebula 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...
port unittest def parse_mailmap(mailmap='.mailmap'): mapping = {} if os.path.exists(mailmap): fp = open(mailmap, 'r')
for l in fp: l = l.strip() if not l.startswith('#') and ' ' in l: canonical_email, alias = l.split(' ') mapping[alias] = canonical_email return mapping def str_dict_replace(s, mapping): for s1, s2 in mapping.iteritems(): s = s.replace(s1, s2) ...
stephenfin/patchwork
patchwork/api/event.py
Python
gpl-2.0
3,356
0
# Patchwork - automated patch tracking system # Copyright (C) 2017 Stephen Finucane <stephen@that.guru> # # SPDX-License-Identifier: GPL-2.0-or-later from collections import OrderedDict from rest_framework.generics import ListAPIView from rest_framework.serializers import ModelSerializer from rest_framework.serialize...
, 'project', 'date'] for field in [x for x in data]:
if field not in kept_fields: del data[field] elif field in self._category_map[instance.category]: field_name = 'check' if field == 'created_check' else field payload[field_name] = data.pop(field) data['payload'] = payload return data ...
ljwolf/pysal
pysal/contrib/gwr/tests/test_gwr.py
Python
bsd-3-clause
45,280
0.009408
""" GWR is tested against results from GWR4 """ import unittest import pickle as pk from pysal.contrib.gwr.gwr import GWR from pysal.contrib.gwr.sel_bw import Sel_BW from pysal.contrib.gwr.diagnostics import get_AICc, get_AIC, get_BIC, get_CV from pysal.contrib.glm.family import Gaussian, Poisson, Binomial import nump...
ck([rural, pov, black]) self.BS_F = pysal.open(pysal.examples.get_path('georgia_BS_F_listwise.csv')) self.BS_NN = pysal.open(pysal.examples.get_path('georgia_BS_NN_listwise.csv')) self.GS_F = pysal.open(pysal.examples.get_path('georgia_GS_F_li
stwise.csv')) self.GS_NN = pysal.open(pysal.examples.get_path('georgia_GS_NN_listwise.csv')) self.MGWR = pk.load(open(pysal.examples.get_path('FB.p'), 'r')) self.XB = pk.load(open(pysal.examples.get_path('XB.p'), 'r')) self.err = pk.load(open(pysal.examples.get_path('err.p'), 'r')) ...
Vdragon/git-cola
cola/difftool.py
Python
gpl-2.0
6,355
0.000157
from __future__ import division, absolute_import, unicode_literals from qtpy import QtWidgets from qtpy.QtCore import Qt from . import cmds from . import gitcmds from . import hotkeys from . import icons from . import qtutils from . import utils from .i18n import N_ from .widgets import completion from .widgets impor...
ext=None): """Show
a diff dialog for diff expressions""" dlg = Difftool(parent, expr=expr, hide_expr=hide_expr, focus_tree=focus_tree, context=context) if create_widget: return dlg dlg.show() dlg.raise_() return dlg.exec_() == QtWidgets.QDialog.Accepted class Difftool(s...
thePetrMarek/SequenceOfDigitsRecognition
sequences_of_variable_length/deep_localization_weighted_loss_variable_length_deeper.py
Python
mit
7,054
0.00241
import tensorflow as tf ''' Model for sequence classification and localization with weighted loss ''' class DeepLocalizationWeightedLossVariableLengthDeeper: def get_name(self): return "deep_localization_weighted_loss_variable_length_6" def input_placeholders(self): inputs_placeholder = tf.p...
, [1, 2, 2, 1], [1, 2, 2, 1]) reshaped = tf.reshape(max_pool6, [-1, 1024]) logits = [] gru = tf.contrib.rnn.GRUCell(576) state = gru.zero_state(tf.shape(reshaped)[0], tf.float32) with tf.variable_sco
pe("RNN"): for i in range(5): if i > 0: tf.get_variable_scope().reuse_variables() output, state = gru(reshaped, state) number_logits = self._fully_connected(output, 576, 11) logits.append(number_logits) fc_posit...
n3011/deeprl
train_dqn.py
Python
mit
1,042
0.00096
# -------------------------------------------------------------------# # Released under the MIT license (https://opensource.org/licenses/MIT) # Contact: mrinal.haloi11@gmail.com # Enhancement Copyright 2016, Mrinal Haloi # -------------------------------------------------------------------# import random import os impo...
onfig import cfg # Set random seed tf.set_random_seed(123) random.seed(12345) def main(_): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4) with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess: if cfg.env_type == 'simple': env = SimpleGymEnvironment(cf...
tmp/model_dir'): os.mkdir('/tmp/model_dir') solver = Solver(cfg, env, sess, '/tmp/model_dir') solver.train() if __name__ == '__main__': tf.app.run()
firebitsbr/termineter
framework/modules/get_modem_info.py
Python
gpl-3.0
3,174
0.015123
# framework/modules/get_modem_info.py # # Copyright 2011 Spencer J. McIntyre <SMcIntyre [at] SecureState [dot] net> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the...
ne_ctl.answer_bit_ra
te info['Dial Delay'] = telephone_ctl.dial_delay if len(telephone_ctl.prefix_number): info['Prefix Number'] = telephone_ctl.prefix_number keys = info.keys() keys.sort() self.frmwk.print_status('General Information:') fmt_string = " {0:.<38}.{1}" for key in keys: self.frmwk.print_status(fmt_strin...
ray-project/ray
rllib/utils/exploration/slate_soft_q.py
Python
apache-2.0
1,483
0.000674
from typing import Union from ray.rllib.models.action_dist import ActionDistribution from ray.rllib.utils.annotations import override from ray.rllib.uti
ls.exploration.exploration import TensorType from ray.rllib.utils.exploration.soft_q import SoftQ from ray.rllib.utils.framework import try_import_tf, try_import_torch tf1, tf, tfv = try_import_tf() torch, _ = try_import_torch() class SlateSoftQ(SoftQ): @override(SoftQ) def get_exploration_action( se...
istribution, timestep: Union[int, TensorType], explore: bool = True, ): assert ( self.framework == "torch" ), "ERROR: SlateSoftQ only supports torch so far!" cls = type(action_distribution) # Re-create the action distribution with the correct temperature...
pligor/predicting-future-product-prices
04_time_series_prediction/data_providers/price_history_pack.py
Python
agpl-3.0
2,640
0.003788
import numpy as np class PriceHistoryPack(object): def __init__(self, input_seq_len, num_features, target_seq_len): super(PriceHistoryPack, self).__init__() self.sku_ids = [] self.XX = np.empty((0, input_seq_len, num_features)) self.YY = np.empty((0, target_seq_len)) self.s...
, seqLens, seqMask = np.array(self.sku_ids), self.XX, self.YY, np.array( self.sequence_lens), self.seq_mask if fraction is None: return skuIds, xx, yy, seqLens, seqMask else: random_state = np.random if random_state is None el
se random_state cur_len = len(skuIds) assert cur_len == len(xx) and cur_len == len(yy) and cur_len == len(seqLens) and cur_len == len(seqMask) random_inds = random_state.choice(cur_len, int(cur_len * fraction)) return skuIds[random_inds], xx[random_inds], yy[random_inds...
hakril/PythonForWindows
tests/test_midl.py
Python
bsd-3-clause
380
0.013158
import windows.generat
ed_def as gdef def test_format_charactere_values(): assert gdef.FC_ZERO == 0 assert gdef.FC_PAD == 0x5c assert gdef.FC_PAD == 0x5c assert gdef.FC_SPLIT_DEREFERENCE == 0x74 assert gdef. FC_SPLIT_DIV_2 == 0x75 as
sert gdef.FC_HARD_STRUCT == 0xb1 assert gdef.FC_TRANSMIT_AS_PTR == 0xb2 assert gdef.FC_END_OF_UNIVERSE == 0xba
jansohn/pyload
module/plugins/hoster/HighWayMe.py
Python
gpl-3.0
2,588
0.008114
# -*- coding: utf-8 -*- import re from module.plugins.internal.MultiHoster import MultiHoster, create_getInfo from module.plugins.internal.SimpleHoster import seconds_to_midnight class HighWayMe(MultiHoster): __name__ = "HighWayMe" __type__ = "hoster" __version__ = "0.15" __status__ = "testin...
.log_warning(_("Hoster temporarily unavailable, waiting 1 minute and retry")) self.retry(5, 60, _("Hoster is temporarily unavailable")) def handle_premium(self, pyfile): for _i in xrange(5): self.html = self.load("https://high-way.me/load.php",
get={'link': self.pyfile.url}) if self.html: self.log_debug("JSON data: " + self.html) break else: self.log_info(_("Unable to get API data, waiting 1 minute and retry")) self.retry(5, 60, _("Unable to get API data")) self.che...
wevoice/wesub
apps/activity/migrations/0002_auto__add_activitymigrationprogress.py
Python
agpl-3.0
21,651
0.00799
# -*- coding: 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 model 'ActivityMigrationProgress' db.create_table('activity_activitymigrationprogress', ( ...
ser': {
'Meta': {'object_name': 'CustomUser', '_ormbases': ['auth.User']}, 'autoplay_preferences': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'award_points': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'biography': ('django.db.models.fields.TextField...
kozyarchuk/NCT-workers
tests/perf/pscrap.py
Python
gpl-2.0
1,216
0.011513
from nct.utils.alch import Session, LSession from nct.domain.instrument import Instrument import random import functools import time from nct.deploy.deploy import Deployer import cProfile INSTRUMENTS = ['GOOGL.O', 'TWTR.N', 'GS.N', 'BAC.N', 'IBM.N'] def profile_method(file_name = None): def gen_wrapper(func): ...
cProfile.runctx('f(*args,**kwargs)', globals(), locals(), file_name) print("Done writing") return wrapper return gen_wrapper def time_it(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.time() func(*args,**kwargs) print("It took {}".f...
s = LSession() name = INSTRUMENTS[int(random.random()*100)%len(INSTRUMENTS)] instr_id = s.query(Instrument).filter_by(name=name).one().id for _ in range(10000): s.query(Instrument).get(instr_id) s.close() import sys print (sys.version) Deployer(LSession).deploy() print ("Deployed") for _ in ra...
mcmaxwell/idea_digital_agency
idea/feincms/module/extensions/ct_tracker.py
Python
mit
255
0
# flake8: noqa from
__future__ import absolute_import, unicode_literals import warnings from feincms.extensions.ct_tracker import * warnings.warn( 'Import %s from feincms.extensions.%s' % (__name__, __name__), DeprecationWarning, stacklev
el=2)
Ripsnorta/pyui2
widgets/formpanel.py
Python
lgpl-2.1
7,289
0.006311
# pyui2 # Copyright (C) 2001-2002 Sean C. Riley # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # bu...
ewLabel, (0,num,1,fieldSpan) ) self.addChild( newWidget, (1,num,2,fieldSpan) ) self.__dict__["label_%s" % fieldName] = newLabel self.__dict__["widget_%s" % fi
eldName] = newWidget num = num + fieldSpan self.pack() def populate(self, object): """populate the data fields from the supplied object """ self.object = object for fieldType, fieldName, fieldLabel, fieldSpan, fieldDefault in self.fieldList: ...
pglivebackup/pgchain
pgchain.py
Python
mit
26,324
0.02454
#!/bin/python import sys,os,sqlite3,time,ntpath,psycopg2,grp,pwd from random import randint class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033...
----------------------" + color.END print color.BOLD + " PGCHAIN Help" + color.END print color.BOLD + " ----------------------------------------------------------------------------------------" + color.END print "" print " " + color.UNDERLINE + "General PGCHAIN Usage Syntax:" + color.END
print " ./pgchain.py [COMMAND] [ARGUMENTS]" print "" print " " + color.UNDERLINE + "Available Commands:" + color.END print " " + color.BOLD + "base-backup " + color.END + " - Creates a base backup of the local PostgreSQL cluster." print " " + color.BOLD + "get-wal " + color.END + " ...
allotria/intellij-community
python/testData/debug/stepping/test_smart_step_into_native_function_in_return.py
Python
apache-2.0
99
0
def f(s): s = s[::-1] return s
.swapcase() result = f(f(f(f(f('abcdef'))))) # break
point
bbengfort/TextBlob
textblob/nltk/chat/__init__.py
Python
mit
1,546
0.001294
# Natural Language Toolkit: Chatbots # # Copyright (C) 2001-2013 NLTK Project # Authors: Steven Bird <stevenbird1@gmail.com> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT # Based on an Eliza implementation by Joe Strout <joe@strout.net>, # Jeff Epler <jepler@inetnebr.com> and Jez Higgins <je...
e or the windows IDLE GUI. """ from __future__ import print_function from .util import Chat from .eliza import eliza_chat from .iesha import iesha_chat from .rude import rude_chat from .suntsu import suntsu_chat from .zen import zen_chat bots = [ (eliza
_chat, 'Eliza (psycho-babble)'), (iesha_chat, 'Iesha (teen anime junky)'), (rude_chat, 'Rude (abusive bot)'), (suntsu_chat, 'Suntsu (Chinese sayings)'), (zen_chat, 'Zen (gems of wisdom)')] def chatbots(): import sys print('Which chatbot would you like to talk to?') botcount = len(bot...
jarv/cmdchallenge-site
lambda_src/runcmd/dockerpycreds/__init__.py
Python
mit
116
0.008621
# flake8: noqa from .store import S
tore from .errors import StoreError, CredentialsNotFound from .constants import *
kumar303/rockit
vendor-local/boto/rds/dbsnapshot.py
Python
bsd-3-clause
2,724
0.001468
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # 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 rights to use, copy, modi...
ame, value, connection): if name == 'Engine': self.engine = value elif name == 'InstanceCreateTime': self.instance_create_time = value elif name == 'SnapshotCreateTime': self.snapshot_create_time = value elif name == 'DBInstan
ceIdentifier': self.instance_id = value elif name == 'DBSnapshotIdentifier': self.id = value elif name == 'Port': self.port = int(value) elif name == 'Status': self.status = value elif name == 'AvailabilityZone': self.availabili...
ArcticWarriors/scouting-app
ScoutingWebsite/Scouting2017/view/submissions/submit_bookmark.py
Python
mit
299
0
''' Created on Mar 1, 2017 @author: PJ ''' from Scouting2017.model.reusable_models import Team from BaseScouting.views.submissions.submit_bookmark import BaseUpdateBookmarks class UpdateBookmarks2017(BaseUpdateBookmarks): def __init__(self)
: BaseUpdateBookmarks.__init__(self, Team)
jamespcole/home-assistant
homeassistant/components/ring/sensor.py
Python
apache-2.0
6,215
0
""" This component provides HA sensor support for Ring Door Bell/Chimes. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.ring/ """ from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import ...
device_state_attributes(self): """Return the state attributes.""" attrs = {} attrs[ATTR_ATTRIBUTION] = ATTRIBUTION attrs['device_id'] = self._data.id a
ttrs['firmware'] = self._data.firmware attrs['kind'] = self._data.kind attrs['timezone'] = self._data.timezone attrs['type'] = self._data.family attrs['wifi_name'] = self._data.wifi_name if self._extra and self._sensor_type.startswith('last_'): attrs['created_at'] = ...
ctu-osgeorel/gdal-vfr
vfr2pg.py
Python
mit
5,000
0.0034
#!/usr/bin/env python3 ############################################################################### # # VFR importer based on GDAL library # # Author: Martin Landa <landa.martin gmail.com> # # Licence: MIT/X # ############################################################################### """ Imports VFR data to P...
on='store_true', help="List existing layers in output database and exit") parser.add_argument("--file", help="Path to xml.gz|zip or URL list file") parser.add_argument("--date", help="Date in for
mat 'YYYYMMDD'") parser.add_argument("--type", help="Type of request in format XY_ABCD, eg. 'ST_UKSH' or 'OB_000000_ABCD'") parser.add_argument("--layer", help="Import only selected layers separated by comma (if not given all layers are processed)") parser.add...
mfitzp/padua
padua/utils.py
Python
bsd-2-clause
9,476
0.004538
import numpy as np import scipy as sp import scipy.interpolate import requests from io import StringIO def qvalues(pv, m = None, verbose = False, lowmem = False, pi0 = None): """ Copyright (c) 2012, Nicolo Fusi, University of Sheffield All rights reserved. Estimates q-values from p-values Args ...
_ids(s) ) return list(set(protein_list)) def get_shortstr(s): """ Return the first part of a string before a semicolon. Extract the first, highest-ranked protein ID from a string containing protein IDs in MaxQuant output for
mat: e.g. P07830;P63267;Q54A44;P63268 :param s: protein IDs in MaxQuant format :type s: str or unicode :return: string """ return str(s).split(';')[0] def get_index_list(l, ms): """ :param l: :param ms: :return: """ if type(ms) != list and type(ms) != tuple: ms =...
stscieisenhamer/glue
glue/core/qt/message_widget.py
Python
bsd-3-clause
1,541
0
from __future__ import absolute_import, division, print_func
tion import os from time import ctime from qtpy import QtWidgets from glue import core from glue.utils.qt import load_ui class MessageWidget(QtWidgets.QWidget, core.hub.HubListener): "
"" This simple class displays all messages broadcast by a hub. It is mainly intended for debugging """ def __init__(self): QtWidgets.QWidget.__init__(self) self.ui = load_ui('message_widget.ui', self, directory=os.path.dirname(__file__)) self.ui.messageTable.se...
annegabrielle/secure_adhoc_network_ns-3
ns3_source_code/ns-3.10/bindings/python/apidefs/gcc-LP64/ns3_module_nix_vector_routing.py
Python
gpl-2.0
11,439
0.012763
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## ipv4-nix-vector-routing.h: ns3::Ipv4NixVectorRouting [class] module.add_class('Ipv4NixVectorRouting', parent=root_module['ns3::Ipv4RoutingProtocol']) typ...
orRouting::FlushGlobalNixRoutingCache() [member function] cls.add_method('FlushGlobalNixRoutingCache', 'void', []) ## ipv4-nix-vector-routing.h: static ns3::TypeId ns3::Ipv4NixVectorRouting::G
etTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', ...
oscarlab/betrfs
benchmarks/aging/mailserver/mailserver-aging.py
Python
gpl-2.0
2,672
0.030689
#!/usr/bin/python import imaplib import sys import random import os import threading import time import types import subprocess SERVER = "localhost" USER = ["ftfstest1", "ftfstest2", "ftfstest3", "ftfstest4", "ftfstest5", "ftfstest6", "ftfstest7", "ftfstest8", "ftfstest9", "ftfstest10", "ftfstest11", "ftfstest12", "ft...
ser): t[i].join() t2 = time.time() n
_op_total = 0 for i in range(n_user) : n_op_total = n_op_total + n_op_thread[i] print "This experiment took %f seconds" % (t2 - t1) print "%d ops are executed (%f op/s)" % (n_op_total, n_op_total / (t2 - t1)) f.write("Time\t") f.write(str(t2 - t1) + '\t') f.write("Nops\t") f.write(str(n_op_total) + '\n') sys.exit(0)
vdmann/cse-360-image-hosting-website
src/mvp_landing/urls.py
Python
mit
1,288
0.003882
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin # not sure about line 7 admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^dropzone-drag-drop/$', inc...
rl(r'^$', 'signups.views.home', name='home'), url(r'^register/$', 'drinker.views.DrinkerRegistration'), url(r'^login/$', 'drinker.views.LoginRequest'), url(r'^logout/$', 'drinker.views.LogOutRequest'), url(r'^index/filter/$', 'filter.views.changeBright'), # Uncomment the admin/doc line below to ena...
min documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # not sure if I need an actual url wrapper in this code. # url(r'^admin/varnish/', include('varnishapp.urls')), ) if settings.DEBUG: # urlpatterns add STATIC_URL and serves the STATIC_ROOT file urlpatterns += sta...
dongjinleekr/wpdb
wpdb.py
Python
apache-2.0
16,291
0.008348
from sqlalchemy import Column, MetaData, Table from sqlalchemy import DateTime, Integer, String, Text from sqlalchemy import ForeignKeyConstraint, UniqueConstraint from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import backref, dynamic_loader, mapper, relation from sqlalchemy.orm.colle...
nt(['parent'], ['%s_term_taxonomy.term_taxonomy_id' % prefix]), ) term_relationships = Table('%s_term_relationships' % prefix, metadata, Column('object_id', Integer(), primary_key=True, nullable=False), Column('term_taxonomy_id', Integer(), primary_key=True, nullable=False), ForeignKeyConstraint(['term...
Column('meta_id', Integer(), primary_key=True, nullable=False), Column('post_id', Integer(), primary_key=False, nullable=False), Column('meta_key', String(length=255), primary_key=False), Column('meta_value', Text(length=None), primary_key=False), ForeignKeyConstraint(['post_id'], ['%s_posts.ID' % pre...
natict/roomservice
roomservice/mysql.py
Python
mit
1,306
0
import pymysql from flask_restful import Resource from flask import abort ALLOWED_SHOW = ('processlist', 'databases', 'plugins', 'privileges') class Mysql(Resource): def __init__(self): self.connection = pymysql.connect(user='root') self.cursor = self.connection.cursor() def _execute(self, s...
desc_id = tuple(x[0] for x in self.cursor.description) query_result = self.cursor.fetchall() results = [dict(zip(desc_id, item)) for item in query_result] return results def get(self, cmd): if cmd in ALLOWED_SHOW: return self._execute('show ' + cmd) else: ...
abort(400, e.args) return self._execute('show tables') def post(self, dbname): try: self.cursor.execute('create database ' + dbname) except pymysql.ProgrammingError as e: abort(400, e.args) def delete(self, dbname): try: self.cur...
phase/ApplePi
fastmc/auth.py
Python
mit
7,818
0.004861
# -*- coding: utf-8 -*- # # Copyr
ight (c) 2014, Florian Wesch <fw@dividuum.de> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright # notice, this list of ...
the following disclaimer in the # documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNES...