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
dan-passaro/django-recommend
simplerec/quotes/tests.py
Python
mit
2,071
0
"""Tests for the Quotes app.""" import pytest from django.core import exceptions from . import models @pytest.mark.django_db def test_quote_similarity_pk_order(): """Pairs of quotes must be ordered by PK.""" # Small/big in terms of their IDs. small_quote = models.Quote.objects.create(cont
ent='foo', pk=500) big_quote = mod
els.Quote.objects.create(content='bar', pk=505) # Wrong order raises an exception. with pytest.raises(exceptions.ValidationError): models.QuoteSimilarity.objects.create( quote_1=big_quote, quote_2=small_quote, score=0.3) # Good order works fine. models.QuoteSimilarity.objects.creat...
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_LinearTrend/cycle_5/ar_/test_artificial_32_RelativeDifference_LinearTrend_5__0.py
Python
bsd-3-clause
273
0.084249
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_l
ength = 5, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order =
0);
addiks/gmattermost
src/Application.py
Python
gpl-3.0
3,930
0.003562
# Copyright (C) 2017 Gerrit Addiks <gerrit@addiks.net> # https://github.com/addiks/gedit-phpide # # 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 o...
th this program. If not, see <http://www.gnu.org/licenses/>. import gi gi.require_version('Notify', '0.7') from gi.repository import Gio, Gtk, Notify from os.path import dirname import os from .Controller.TeamsListController import TeamsListController f
rom .Controller.IndicatorController import IndicatorController from .Model.ProfileModel import ProfileModel from .Model.CacheModel import CacheModel from Mattermost.ServerModel import ServerModel class Application(Gtk.Application): __profileModel = None # ProfileModel __cacheModel = None # CacheModel __ind...
a-shar/web_tech
ask/qa/forms.py
Python
bsd-3-clause
1,986
0.002672
# coding=utf-8 from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from qa.models import Question, Answer class AskForm(forms.Form): title = forms.CharField(max_length=1024, label="Заголовок вопроса") text = forms.CharField(widget=forms...
stion(self): # return self.cleaned_data["question"] # # def clean_text(self): # text = self.cleaned_data['text'] # if not text: # raise forms.ValidationError(u'Ответ не может быть пустым', code=13) # return text # # def save(self): # answer = Answer(**...
(UserCreationForm): class Meta: model = User fields = ("username","email",)
alvaroribas/modeling_TDs
data_converter.py
Python
mit
7,982
0.017665
######## Script to convert IRS spectra into pseudophotometric ######## datapoints for modeling the TDs import asciitable import numpy as np import matplotlib.pyplot as plt import pyfits from scipy import interpolate def remove_duplicates_func(seq): """ This function takes a list and returns the same without d...
# Derredening data # Mathis1
990 extinction law for spitzer (Rv=5) mathis_lmb=[2.2,3.4,5.,7.,9.,9.7,10.,12.,15.,18.,20.,25.,35.] mathis_alambda_aj=[0.382,0.182,0.095,0.07,0.157,0.2,0.192,0.098,0.053,0.083,0.075,0.0048,0.013] mathis_interpol=interpolate.interp1d(mathis_lmb,mathis_alambda_aj,kind='linear') #McClure2009 extinction law (lmb in micron...
mitou/meikan
updater.py
Python
mit
3,661
0.001173
# -*- coding: utf-8 -*- """ kintone上のデータを、バックアップを取ってから一括アップデートするスクリプト オプション指定なし→ローカルキャッシュを用いてDry Run -r(--real) →最新のデータを取得してバックアップし、更新 -f(--from-backup) →-rで問題が起きたとき用。バックアップを指定して、そのデータを元に更新する。 """ from cache import get_all, get_app import time import argparse from render import pretty def concat_lines(x, y): if...
all(cache=False, name=dumpdir) elif args.from_backup: xs = get_all(cache=True, name=args.from_backup) else: xs = get_all(cache=True) if not args.converter: to_add, to_update = convert(xs, args) else: import imp info = imp.find_module('converter/' + args.converter...
d_module('m', *info) to_add, to_update = m.convert(xs, args) print "{} items to update, {} items to add".format(len(to_update), len(to_add)) # when recover from backup we need to ignore revision if args.from_backup: for x in xs: x.revision = -1 # ignore revision if args.re...
shengshuyang/StanfordCNNClass
shadow_project/extract_patches.py
Python
gpl-3.0
1,314
0.010654
import matplotlib.pyplot as plt import matplotlib.image as mpimg import nump
y as np import os from math import sqrt from os.path import expanduser def extract_patches(path, filename, out_path, patch_size, stride, visualize): img = mpimg.imread(path+filename) nRows, nCols, nColor = img.shape psx, psy = patch_size patches = [] for r in xrange(psy/2+1, nRows - psy/2 -...
rkashapov/buildbot
master/buildbot/changes/github.py
Python
gpl-2.0
10,700
0.000093
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
prnumber = pr['number'] revision = pr['head']['sha'] # Check to see if the branch is set or matches if self.branches is
not None and base_branch not in self.branches: continue if (self.pullrequest_filter is not None and not self.pullrequest_filter(pr)): continue current = yield self._getCurrentRev(prnumber) if not current or current[0:12] != revisio...
mlperf/training_results_v0.6
Google/benchmarks/transformer/implementations/tpu-v3-512-transformer/transformer/data_generators/translate_test.py
Python
apache-2.0
2,128
0.007049
"""Translate generators test.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tarfile import tensorflow as tf from data_generators import text_problems from data_generators import translate class TranslateTest(tf.test.Te...
et[1] ] with tf.gfile.Open(en_file, "w") as en_f: with tf.gfile.Open(de_file, "w") as de_f: start = i * 10 end = start + 10 for en_line, de_line in data[start:end]: en_f.write(en_lin
e) en_f.write("\n") de_f.write(de_line) de_f.write("\n") with tarfile.open(os.path.join(tmp_dir, tar_file), "w:gz") as tar_f: tar_f.add(en_file, os.path.basename(en_file)) tar_f.add(de_file, os.path.basename(de_file)) cls.tmp_dir = tmp_dir cls.data = d...
boniatillo-com/PhaserEditor
docs/v2/conf.py
Python
epl-1.0
4,869
0.001643
# -*- coding: utf-8 -*- # # Phaser Editor documentation build configuration file, created by # sphinx-quickstart on Thu May 25 08:35:14 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file....
'2.1.7' # The full version, including alpha/beta/rc tags. release = u'2.1.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext
catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', ...
aaronsw/watchdog
vendor/rdflib-2.4.0/rdflib/syntax/serializers/__init__.py
Python
agpl-3.0
449
0.004454
from rdflib import URIRef class Serializer(object): def __init__(self, store): self.store = store self.encoding = "UTF-8" self.base = None def serialize(self, stream, base=None, encoding=None, **args): """Abstract method""" def re
lativize(self, uri): base
= self.base if base is not None and uri.startswith(base): uri = URIRef(uri.replace(base, "", 1)) return uri
dhamaniasad/gpicsync
geonames.py
Python
gpl-2.0
6,231
0.027283
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################### # # A tool to search for geonames metadata either: # - the path of a geocoded picture # - by giving a latitude and longitude values (decimal degrees format) # # (c) francois.schnell francois.schne...
return (self.nearbyPlaceLat,self.nearbyPlaceLon) def findOrientation(self): debug=False nearbyPlaceLat=float(self.findNearbyPlaceLatLon()[0]) nearbyPlacelon=float(self.findNearbyPlaceLatLon()[1])
deltaLat=float(self.lat)-nearbyPlaceLat deltaLon=float(self.long)-nearbyPlacelon situation="" if debug==True: print "nearbyPlaceLat, nearbyPlacelon", nearbyPlaceLat,nearbyPlacelon print "GPS lat,lon",self.lat, self.long print "deltaLat, deltaLon", deltaLat, ...
shivaenigma/pycoin
pycoin/networks/__init__.py
Python
mit
426
0.004695
from .registry import ( # noqa register_network, network_for_netcode, network_codes, network_prefixes, network_name_for_netcode, subnet_name_for_netcode, full_
network_name_for_netcode, wif_prefix_for_netcode, address_prefix_for_netcode, pay_to_script_prefix_for_netcode, prv32_prefix_for_netcode, pub32_prefix_for_netcode, bech32_hrp_for_netcode, pay_
to_script_wit_for_netcode, address_wit_for_netcode )
KRHS-GameProgramming-2014/Arkansas-Smith
StartBlock.py
Python
bsd-2-clause
390
0.087179
import pygame class StartBlock(pygame.sprite.Spri
te): def __init__(self, pos = [0,0]): pygame.sprite.Sprite.__init__(self, self.containers) self.image = pygame.image.load("Art/EnterBlock.png") self.rect = self.image.get_rect() self.place(pos) self.living = True def place(self, pos): self.rect.topleft = po
s def update(*args): self = args[0]
pritha-srivastava/sm
drivers/lvhdutil.py
Python
lgpl-2.1
13,256
0.005432
#!/usr/bin/python # # Copyright (C) Citrix Systems Inc. # # This program 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; version 2.1 only. # # This program is distributed in the hope that it will be u...
size)) vhdutil.setSizeVirt(path, size, jFile) def _tryAcquire(lock): """We must give up if the SR is locked because it could be locked by the coalesce thread trying to acquire the VDI lock we're holding, so as to avoid deadlock
""" for i in range(LOCK_RETRY_ATTEMPTS): gotLock = lock.acquireNoblock() if gotLock: return time.sleep(1) raise util.SRBusyException() def attachThin(journaler, srUuid, vdiUuid): """Ensure that the VDI LV is expanded to the fully-allocated size""" lvName = LV_PREFIX[...
h31nr1ch/Mirrors
c/OtherProblems/patinhos-2334.py
Python
gpl-3.0
123
0.02439
while(True): n=int(input())
if n==-1: break elif n==0: print("0")
else: print(n-1)
parisots/population-gcn
fetch_data.py
Python
gpl-3.0
2,398
0.00417
# Copyright (C) 2017 Sarah Parisot <s.parisot@imperial.ac.uk>, , Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # 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 ...
from nilearn import datasets import ABIDEParser as Reader import os import shutil # Selected pipeline pipeline = 'cpac'
# Input data variables num_subjects = 871 # Number of subjects root_folder = '/path/to/data/' data_folder = os.path.join(root_folder, 'ABIDE_pcp/cpac/filt_noglobal') # Files to fetch files = ['rois_ho'] filemapping = {'func_preproc': 'func_preproc.nii.gz', 'rois_ho': 'rois_ho.1D'} if not os.path.ex...
yogesh2021/qds-sdk-py
qds_sdk/commands.py
Python
apache-2.0
47,582
0.003363
""" The commands module contains the base definition for a generic Qubole command and the implementation of all the specific commands """ from qds_sdk.qubole import Qubole from qds_sdk.resource import Resource from qds_sdk.exception import ParseError from qds_sdk.account import Account from qds_sdk.util import GentleO...
def get_jobs_id(cls, id): """ Fetches information about the hadoop jobs which were started by this command id. This information is only available for commands which have completed (i.e. Status = 'done', 'cancelled' or 'error'.) Also, the cluster which ran this command should be r...
e.agent() r = conn.get_raw(cls.element_path(id) + "/jobs") return r.text def get_results(self, fp=sys.stdout, inline=True, delim=None, fetch=True): """ Fetches the result for the command represented by this object get_results will retrieve results of the command and write ...
deisi/home-assistant
homeassistant/components/frontend/version.py
Python
mit
226
0
""
"DO NOT MODIFY. Auto-generated by build_frontend script.""" CORE = "7d80cc0e4dea6bc20fa2889be0b3cd15" UI = "805f8dda70419b26daabc8e8f625127f" MAP = "c922306de24140afd14f857f927bf8f0
" DEV = "b7079ac3121b95b9856e5603a6d8a263"
mozilla/firefox-flicks
flicks/videos/migrations/0020_auto__add_field_video2013_created.py
Python
bsd-3-clause
7,284
0.008375
# -*- 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 field 'Video2013.created' db.add_column('videos_video2013', 'created', self.g...
', [], {'blank': 'True'}), 'filename': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'processed': ('django.db.model
s.fields.BooleanField', [], {'default': 'False'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'user_notified': ('django.db.models.fields.BooleanField', [], {'defaul...
T3CHNOLOG1C/Kurisu
addons/memes.py
Python
apache-2.0
7,307
0.001096
import discord from discord.ext import commands from sys import argv class Memes: """ Meme commands """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) async def _meme(self, ctx, msg): author = ctx.message.author if...
True) async def lucina2(self, ctx): """Memes.""" await self._meme(ctx, "http://i.imgur.com/ZPMveve.jpg") @commands.command(pass_context=True, hidde
n=True) async def xarec(self, ctx): """Memes.""" await self._meme(ctx, "http://i.imgur.com/A59RbRT.png") @commands.command(pass_context=True, hidden=True) async def clap(self, ctx): """Memes.""" await self._meme(ctx, "http://i.imgur.com/UYbIZYs.gifv") @commands.command(...
2014c2g12/c2g12
wsgi/w2/c2_w2.py
Python
gpl-2.0
9,606
0.005416
########################### 1. 導入所需模組 import cherrypy import os ########################### 2. 設定近端與遠端目錄 # 確定程式檔案所在目錄, 在 Windows 有最後的反斜線 _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) # 設定在雲端與近端的資料儲存目錄 if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # 表示程式在雲端執行 download_root_dir = os.environ['OP...
def get_prog(ev): # ajax can only read data from server _nam
e = '/brython_programs/'+doc["filename"].value try: editor.setValue(open(_name, encoding="utf-8").read()) doc["result"].html = doc["filename"].value+" loaded!" except: doc["result"].html = "can not get "+doc["filename"].value+"!" editor.scrollToRow(0) ...
keras-team/keras
keras/initializers/__init__.py
Python
apache-2.0
7,577
0.007523
# Copyright 2015 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...
OCAL.ALL_OBJECTS['OrthogonalV2'] = initializers_v2.Orthogonal LOCAL.ALL_OBJECTS['RandomNo
rmalV2'] = initializers_v2.RandomNormal LOCAL.ALL_OBJECTS['RandomUniformV2'] = initializers_v2.RandomUniform LOCAL.ALL_OBJECTS['TruncatedNormalV2'] = initializers_v2.TruncatedNormal LOCAL.ALL_OBJECTS['VarianceScalingV2'] = initializers_v2.VarianceScaling LOCAL.ALL_OBJECTS['ZerosV2'] = initializers_v2.Zeros #...
Micronaet/micronaet-addons-private
task_manager/wizard/wizard_report.py
Python
agpl-3.0
11,463
0.015354
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # Copyright (C) 2004-2012 Micronaet srl. All Rights Reserved # d$ # # This pr...
ist') wiz_proxy=self.browse(cr, uid, ids)[0] printsock = xmlrpclib.ServerProxy('http://loc
alhost:8069/xmlrpc/report') #domain = self._get_filter_from_wizard(cr, uid, ids, with_partner=False, context=context) for partner in wiz_proxy.partner_ids: #self.pool.get('intervention.report').search(cr, uid, domain, order=order, context=context) # get intervent_ids for this partner ...
rwl/PyCIM
CIM14/IEC61968/Customers/CustomerAccount.py
Python
mit
3,833
0.002087
# Copyright (C) 2010-2011 Richard Lincoln # # 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, modify, merge, publish...
ansactions", "CustomerAgreem
ents"] _many_refs = ["PaymentTransactions", "CustomerAgreements"] def getPaymentTransactions(self): """All payment transactions for this customer account. """ return self._PaymentTransactions def setPaymentTransactions(self, value): for x in self._PaymentTransactions: ...
sveinugu/gtrackcore
gtrackcore/input/core/GenomeElement.py
Python
gpl-3.0
7,445
0.009268
from gtrackcore.track.core.GenomeRegion import GenomeRegion from gtrackcore.util.CommonConstants import BINARY_MISSING_VAL from gtrackcore.util.CommonFunctions import isNan from gtrackcore.util.CustomExceptions import NotSupportedError class GenomeElement(GenomeRegion): @staticmethod def createGeFromTrackEl(tr...
lf.val is not None else '') def __repr__(self): return str(self) def toStr(self): #self.start+1 because we want to show 1-indexed, end inclu
sive output return (str(self.genome) + ':' if not self.genome is None else '')\ + (str(self.chr) + ':' if not self.chr is None else '')\ + (str(self.start+1) if not self.start is None else '')\ + ('-' + str(self.end) if not self.end is None else '')\ + ((' (Pos)' ...
gw0/pelican-plugins
video_privacy_enhancer/video_privacy_enhancer.py
Python
agpl-3.0
7,716
0.008683
""" Video Privacy Enhancer -------------------------- Authored by Jacob Levernier, 2014 Released under the GNU AGPLv3 For more information on this plugin, please see the attached Readme.md file. """ """ SETTINGS """ # Do not use a leading or trailing slash below (e.g., use "images/video-thumbnails"): output_direct...
actual vid
eo embed match it (so that it's a seamless transition). This can be handled with CSS in both cases, so I haven't hard-coded it here: 1280 W x 720 H 853 W x 480 H 640 W x 360 H 560 W x 315 H Here's an example to add to your CSS file: ``` /* For use with the video-privacy-enhancer Pelican plugin */ img....
rosmo/ansible
lib/ansible/modules/files/patch.py
Python
gpl-3.0
7,109
0.002532
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Luis Alberto Perez Lazaro <luisperlazaro@gmail.com> # Copyright: (c) 2015, Jakub Jirutka <jakub@jirutka.cz> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future...
ATION = r''' --- module: patch author: - Jakub Jirutka (@jirutka) - Luis Alberto Perez Lazaro (@luisperlaz) version_added: '1.9' description: - Apply patch files using the GNU patch tool. short_description: Apply patch files using the GNU patch tool options: basedir: description
: - Path of a base directory in which the patch file will be applied. - May be omitted when C(dest) option is specified, otherwise required. type: path dest: description: - Path of the file on the remote machine to be patched. - The names of the files to be patched are usually taken fr...
bolkedebruin/airflow
tests/providers/apache/livy/operators/test_livy.py
Python
apache-2.0
6,889
0.003048
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
ith(BATCH_ID, retry_args=None) mock_dump_logs.assert_called_with(BATC
H_ID) assert mock_livy.call_count == 3 @patch( 'airflow.providers.apache.livy.operators.livy.LivyHook.dump_batch_logs', return_value=None, ) @patch('airflow.providers.apache.livy.operators.livy.LivyHook.get_batch_state') def test_poll_for_termination_fail(self, mock_livy, mock_d...
bohlian/frappe
frappe/www/qrcode.py
Python
mit
1,245
0.026506
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from urlparse import parse_qs from frappe.twofactor import get_qr_svg_code def get_context(context): context.no_cache = 1 context.qr_code_us...
frappe.throw(_('Not Permitted'), frappe.PermissionError) user = frapp
e.get_doc('User',user) svg = get_qr_svg_code(totp_uri) return (user,svg)
XefPatterson/INF8225_Project
Model/queues.py
Python
mit
3,465
0.001154
import tensorflow as tf import os def create_single_queue(bucket_id, filename, batch_size, buckets): """ Return a shuffle_queue which output element from {bucket_id} bucket :param bucket_id: int :param filename: str :param batch_size: int :param buckets: list :return: """ file_name...
} # Parse a single example context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized=serialized_example,
context_features=context_features, sequence_features=sequence_features ) batch_size = batch_size capacity = 10 * batch_size min_after_dequeue = 9 * batch_size # Basically, pad question with zeros if shorter than buckets[bucket_id][0] length_question = context_parsed["length_qu...
saltstack/salt-pylint
saltpylint/checkers.py
Python
apache-2.0
646
0.001548
# -*- coding: utf-8 -*- ''' saltpylint.checkers ~~~~~~~~~~~~~~~~~~~~ Works around older astroid versions ''' # Import python libs from __future__ import absolute_import # Import pylint libs import astroid from pylint.checkers import BaseChecker as _Ba
seChecker # Imported to avoid needing a separate import from pylint.checkers from pylint.checkers import utils class
BaseChecker(_BaseChecker): def __init__(self, *args, **kwargs): super(BaseChecker, self).__init__(*args, **kwargs) if hasattr(self, 'visit_call') and not hasattr(astroid, 'Call'): setattr(self, 'visit_callfunc', self.visit_call)
skyoo/jumpserver
apps/perms/serializers/asset/permission.py
Python
gpl-2.0
2,536
0.000394
# -*- coding: utf-8 -*- # from rest_framework import serializers from django.utils.translation import ugettext_lazy as _ from orgs.mixins.serializers import BulkOrgResourceModelSerializer from perms.models import AssetPermission, Action __all__ = [ 'AssetPermissionSerializer', 'ActionsField', ] class Actio...
ed', 'date_start', 'comment' ] m2m_fields = [ 'users', 'user_groups', 'assets', 'nodes', 'system_users', 'users_amount', 'user_groups_amount', 'assets_amount', 'nodes_amount', 'system_users_amount', ] fields = small_fields + m2m_fields ...
s valid')}, 'actions': {'label': _('Actions')}, 'users_amount': {'label': _('Users amount')}, 'user_groups_amount': {'label': _('User groups amount')}, 'assets_amount': {'label': _('Assets amount')}, 'nodes_amount': {'label': _('Nodes amount')}, 's...
endlessm/chromium-browser
third_party/chromite/third_party/infra_libs/test/utils_test.py
Python
bsd-3-clause
1,350
0.006667
# -*- encoding: utf-8 -*- # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest import infra_libs DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') class ...
_directory() as tempdir: self.assertTrue(os.path.isdir(tempdir)) # Create
a non-empty file to check that tempdir deletion works. with open(os.path.join(tempdir, 'test_tempdir_no_error.txt'), 'w') as f: f.write('nonsensical content') raise _UtilTestException() # And everything should have been cleaned up afterward self.assertFalse(os.path.isdir(tempdir))
TomBaxter/waterbutler
tasks.py
Python
apache-2.0
3,064
0.002937
import os from invoke import task WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE') def monkey_patch(ctx): # Force an older cacert.pem from certifi v2015.4.28, prevents an ssl failure w/ identity.api.rackspacecloud.com. # # SubjectAltNameWarning: Certificate for identity.api.rackspacecloud.com has no `subj...
file) if WHEELHOUSE_PATH: cmd += ' --no-index --find-links={}'.format(WHEELHOUSE_PATH) ctx.run(cmd, pty=pty) @task def flake(ctx): """ Run style and syntax checker. Follows options defined in setup.cfg """ ctx.run('flake8 .', pty=True) @task def mypy(ctx): """ Check python t...
Follows options defined in setup.cfg """ ctx.run('mypy waterbutler/', pty=True) @task def test(ctx, verbose=False, types=False): flake(ctx) if types: mypy(ctx) cmd = 'py.test --cov-report term-missing --cov waterbutler tests' if verbose: cmd += ' -v' ctx.run(cmd, pty=True)...
silky/PeachPy
examples/nmake/transpose4x4-opt.py
Python
bsd-2-clause
1,848
0.000541
# This file is part of Peach-Py package and is licensed under the Simplified BSD license. # See license.rst for the full text of the license. from peachpy.x86_64 import * from peachpy import * matrix = Argument(ptr(float_)) with Function("transpose4x4_opt", (matrix,)): reg_matrix = GeneralPurposeRegister64() ...
0], xmm_rows[1]) # xmm_rows[2] = ( m20, m30, m21, m31 ) UNPCKLPS(xmm_rows[2], xmm_rows[3]) # xmm_rows[1] = ( m02, m12, m03, m13 ) UNPCKHPS(xmm_temps[0], xmm_rows[1]) xmm_rows[1] = xmm_temps[0] # xmm_rows[3] = ( m22, m32, m23, m33 ) UNPCKHPS(xmm_temps[1], xmm_rows[3]) xmm_rows[3] = xmm_...
m01, m11 ) MOVAPS(xmm_temps[0], xmm_rows[0]) # xmm_temps[1] = ( m02, m12, m03, m13 ) MOVAPS(xmm_temps[1], xmm_rows[1]) # xmm_rows[0] = ( m00, m10, m20, m30 ) MOVLHPS(xmm_rows[0], xmm_rows[2]) MOVUPS([reg_matrix], xmm_rows[0]) # xmm_rows[2] = ( m01, m11, m21, m31 ) MOVHLPS(xmm_rows[2],...
BradburyLab/show_tv
show_tv/app/models/dvr_reader.py
Python
gpl-3.0
3,838
0.003672
# coding: utf-8 from .dvr_base import DVRBase import api import struct from io import BytesIO from tornado import gen @gen.engine def call_dvr_cmd(dvr_reader, func, *args, callback, **kwargs): stream = yield gen.Task(api.connect, dvr_reader.host, dvr_reader.port) if stream: def on_result(data): ...
f load(self, r_t_p, startstamp, stream, callback): ''' ''' self.l.debug('[DVRReader] load start >>>>>>>>>>>>>>>') if isinstance(startstamp, str): startstamp = int(startstamp) self.l.debug('[DVRReader] => asset = {0}'.format(r_t_p)) self.l.debug('[DVRReader] ...
format(startstamp)) pack = pack_read_cmd(self.commands['load'], r_t_p, startstamp, '') yield gen.Task(stream.write, pack) data = yield gen.Task(stream.read_bytes, 8, streaming_callback=None) length = struct.unpack('=Q', data)[0] self.l.debug('[DVRReader]') self.l.debug(...
JetChars/vim
vim/bundle/python-mode/pymode/libs3/rope/base/pycore.py
Python
apache-2.0
15,520
0.000451
import bisect import difflib import sys import warnings import rope.base.oi.doa import rope.base.oi.objectinfo import rope.base.oi.soa from rope.base import ast, exceptions, taskhandle, utils, stdmods from rope.base.exceptions import ModuleNotFoundError from rope.base.pyobjectsdef import PyModule, PyPackage, PyClass i...
. """ return PyModule(self, code, resource, force_errors=force_errors) def get_string_scope(self, code, resource=None): """Returns a `Scope` object for the given code""" return self.get_string_module(code, resource).get_scope()
def _invalidate_resource_cache(self, resource, new_resource=None): for observer in self.cache_observers: observer(resource) def _find_module_in_folder(self, folder, modname): module = folder packages = modname.split('.') for pkg in packages[:-1]: if module.i...
friedrichromstedt/moviemaker3
moviemaker3/stacks/weighted.py
Python
mit
1,580
0.00443
from fframework import asfunction from moviemaker3.stacks.stack import Stack class WeightedStack(Stack): """Elements in the WeightedStack should return (*weight*, *layer*); *layer* and *weight* are extracted by indexing (tuple assignment). You might use ``fframework.compound()`` to generate tuple Functi...
together. Note that if all weights are zero, the result is undefined. The start value for summing up the layers
is *self.zero_layer*. The start value for summing up the weights is *self.zero_weight*. Both are evaluated with *ps*.""" sumlayer = self.zero_layer(ps) weightsum = self.zero_weight(ps) for layer in self.elements: (weight, layer) = layer(ps) # We don't...
aknackiron/testdroid-samples
appium/sample-scripts/python/testdroid_ios.py
Python
apache-2.0
5,790
0.0038
## ## For help on setting up your machine and configuring this TestScript go to ## http://docs.bitbar.com/testing/appium/ ## import os import time import unittest from time import sleep from appium import webdriver from device_finder import DeviceFinder def log(msg): print (time.strftime("%H:%M:%S") + ": " + msg...
cloud['testdroid_apiKey'] = testdroid_apiKey desired_capabilities_cloud['testdroid_target'] = 'ios' desired
_capabilities_cloud['testdroid_project'] = testdroid_project_name desired_capabilities_cloud['testdroid_testrun'] = testdroid_testrun_name desired_capabilities_cloud['testdroid_device'] = testdroid_device desired_capabilities_cloud['testdroid_app'] = testdroid_app desired_capabilities_cl...
Radagast-red/golem
tests/golem/network/p2p/test_node.py
Python
gpl-3.0
1,163
0
import unittest from golem.network.p2p.node import Node def is_ip_address(address): """ Check if @address is correct IP address :param address: Address to be checked :return: True if is correct, false otherwise """ from ipaddress import ip_address, AddressValueError try: # will rai...
dress)) return True except (Value
Error, AddressValueError): return False class TestNode(unittest.TestCase): def test_str(self): n = Node(node_name="Blabla", key="ABC") self.assertNotIn("at", str(n)) self.assertNotIn("at", "{}".format(n)) self.assertIn("Blabla", str(n)) self.assertIn("Blabla", "{}"....
LandRegistry/drv-flask-based-prototype
service/api_client.py
Python
mit
898
0.001114
import math from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS SEARCH_RESULTS_PER_PAGE = 20 def get_title(title_number): return SELECTED_FULL_RESULTS.get(title_number) def _get_titles(page_number): nof_results = len(ALL_TITLES) number_pages = math.ceil(nof_resu...
'page_number': page_number, 'titles': ALL_TITLES[start_index:end_index], } def get_titles_by_postcode(postcode, page_number): return _get_titles(page_number) def get_titles_by_address(address, page_number): return _get_titles(page_number) def get_official_copy_data(tit
le_number): return OFFICIAL_COPY_RESULT
eagleamon/home-assistant
homeassistant/components/media_player/__init__.py
Python
apache-2.0
28,502
0.000035
""" Component to interface with various media players. For more details about this component, please refer to the documentation at https://home-assistant.io/components/media_player/ """ import asyncio from datetime import timedelta import functools as ft import hashlib import logging import os from random import Syste...
DIA_PLAYER_SCHEMA.extend({ vol.Required(ATTR_INPUT_SOURCE): cv.string, }) MEDIA_PLAYER_PLAY_MEDIA_SCHEMA = MEDIA_PLAYER_SCHEMA.extend({ vol.Required(ATTR_MEDIA_CONTENT_TYPE): cv.string, vol.Required(ATTR_MEDIA_CONTENT_ID): cv.string, vol.Optional(ATTR_MEDIA_ENQUEUE): cv.boolean, }) SERVICE_TO_METHOD =...
, SERVICE_TOGGLE: {'method': 'async_toggle'}, SERVICE_VOLUME_UP: {'method': 'async_volume_up'}, SERVICE_VOLUME_DOWN: {'method': 'async_volume_down'}, SERVICE_MEDIA_PLAY_PAUSE: {'method': 'async_media_play_pause'}, SERVICE_MEDIA_PLAY: {'method': 'async_media_play'}, SERVICE_MEDIA_PAUSE: {'method'...
janpipek/boadata
boadata/commands/boaview.py
Python
mit
911
0.001098
#!/usr/bin/env python3 import sys import click from boadata import __version__ from boadata.cli import try_load, try_apply_sql, qt_app @click.command() @click.version_option(__version__) @click.argument("uri") @click.option("-s", "--sql", required=False, help="SQL to run on the object.") @click.option("-t", "--type...
lue is not None} do = try_load(uri, type, parameters=param
eter) do = try_apply_sql(do, kwargs) with qt_app(): from boadata.gui.qt import DataObjectWindow window = DataObjectWindow(do) window.show() window.setWindowTitle(do.uri) if __name__ == "__main__": run_app()
thinkopensolutions/l10n-brazil
financial/models/financial_document_type.py
Python
agpl-3.0
599
0
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from __future__ import division, print_function, unicode_literals from odoo import fields, models class Financial
DocumentType(models.Model): _name = b'financial.document.type' _description = 'Financial Document Type' name = fields.Char( string='Document Type', size=30, required=True, index=True, ) account_id = fields.Many2one( c
omodel_name='financial.account', string='Account', ondelete='restrict', )
curtisallen/Alarmageddon
alarmageddon/validations/cassandra.py
Python
apache-2.0
4,308
0.001625
"""Convenience Validations for working with Cassandra""" from fabric.operations import run from alarmageddon.validations.validation import Priority from alarmageddon.validations.ssh import SshValidation def _get_percentage(text): """Converts strings like '12.2' or '32.4%' into floating point numbers.""" tex...
number_nodes: The expected number of cassandra nodes in the ring. :param owns_threshold: The maximum percentage of the ring owned by a node. :param priority: The Priority level of this validation. :param timeout: How long to attempt to connect to the host. :param hosts: The hosts to connect to. ...
ion Cassandra clusters. """ def __init__(self, ssh_context, service_state="UN", number_nodes=5, owns_threshold=40, priority=Priority.NORMAL, timeout=None, hosts=None): super(CassandraStatusValidation,self).__init__(ssh_context, ...
stefraynaud/spanlib
scripts/quickview.py
Python
lgpl-2.1
398
0.017588
######################### # Simple netcdf plotter # ######################### # Needed modules import vcs, sys, cdms # Arguments if len(s
ys.argv) < 3: print 'Usage: python quickview.py <filename> <varname>' sys.exit(1) filename = sys.argv[1] varname = sys.argv[2] # Open netcdf file f
=cdms.open(filename) # Read our variable s=f(varname) # Create vcs canvas x=vcs.init() # Plot it x.plot(s)
mlperf/training_results_v0.6
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/solver/lr_scheduler.py
Python
apache-2.0
2,161
0.000925
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved. from bisect import bisect_right import torch # FIXME ideally this would be achieved with a CombinedLRScheduler, # separating MultiStepLR with WarmupLR # but the current LRSchedul...
s = warmup_iters self.warmup_method = warmup_method super(WarmupMultiStepLR, self).__init__(optimizer, last_epoch) d
ef get_lr(self): warmup_factor = 1 # optional offset to each base_lr delta = 0. if self.last_epoch < self.warmup_iters: if self.warmup_method == "constant": warmup_factor = self.warmup_factor elif self.warmup_method == "linear": al...
msegado/edx-platform
pavelib/paver_tests/test_database.py
Python
agpl-3.0
8,779
0.002962
""" Tests for the Paver commands for updating test databases and its utility methods """ import os import shutil import tarfile from tempfile import mkdtemp from unittest import TestCase import boto from mock import call, patch, Mock from pavelib import database from pavelib.utils import db_utils from pavelib.utils...
est-db.sh --calculate_migrations'.format(Env.REPO_ROOT)), call('{}/scripts/reset-test-db.sh --rebuild_cache --use-existing-db'.format(Env.REPO_ROOT)) ] _mock_sh.assert_has_calls(calls) @patch.object(database, 'CACHE_BUCKET_NAME', 'test_bucket') @patch.object(db_ut
ils, 'CACHE_FOLDER', mkdtemp()) @patch.object(db_utils, 'FINGERPRINT_FILEPATH', os.path.join(mkdtemp(), 'fingerprint')) @patch.object(db_utils, 'sh') def test_updated_db_cache_pushed_to_s3(self, _mock_sh): """ Assuming that the computed db cache file fingerprint is different than the...
junkoda/fs2
test/test_pm_force.py
Python
gpl-3.0
990
0
# # Test PM for
ce parallelisation: # check force does not depend on number of MPI nodes import fs import numpy as np import h5py import pm_setup # read reference file # $ python3 create_force_h5.py to create file = h5py.File('force_%
s.h5' % fs.config_precision(), 'r') ref_id = file['id'][:] ref_force = file['f'][:] file.close() # compute PM force fs.msg.set_loglevel(0) particles = pm_setup.force() particle_id = particles.id particle_force = particles.force # compare two forces if fs.comm.this_node() == 0: assert(np.all(particle_id == ref_...
gencer/python-phonenumbers
python/phonenumbers/shortdata/region_LY.py
Python
apache-2.0
556
0.008993
"""Auto-generated file, do not edit by hand. LY metadata""" from ..ph
onemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_LY = PhoneMetadata(id='LY', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2}', possible_length=(3,)), emergency=PhoneNumberDesc(national_number_pattern='19[013]', example_nu...
ort_data=True)
jamarrange/sort
build/fileSort/Arranger.py
Python
mit
12,285
0.003093
''' |-------------------------------------------------------------------------- | | Jam arrange: GUI linked to arrangement algorithm | Author: Victor Motha | Copyright 2016 | Objective: Sort through audio files and sort them according to artist names. | Current stable version: 0.0.4 | ''' ''' |------------------------...
ist of all known meta-data, for later use | when creating song storage folders.
| ''' def music_handling(self, audio_file_deets): artist_names = [] for i in range(len(audio_file_deets[0])): ''' |-------------------------------------------------------------------------- | Potential Bug: Unicode Testing Required |---------------...
Lorquas/subscription-manager
test/rhsmlib_test/test_products.py
Python
gpl-2.0
14,073
0.001279
from __future__ import print_function, division, absolute_import # Copyright (c) 2017 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNES...
ime.datetime.now() + datetime.timedelta(days=265) NO_CONTENT_JSON = [{ "id": "4028fa7a5da1fbc201
5da203aba209b7", "uuid": "57b7dbff-9489-43ac-991a-b848324b423a", "name": "localhost.localdomain", "username": "admin", "entitlementStatus": "valid", "serviceLevel": "", "releaseVer": { "releaseVer": None }, "idCert": { "key": "FAKE RSA PRIVATE KEY", "cert": "FAKE ...
ivngithub/testproject
config.py
Python
mit
1,559
0.000641
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True ...
' + str( Config.SQL_PASSWORD) + '@localhost/testproject' class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.en...
oductionConfig, 'default': DevelopmentConfig }
m00dawg/holland
holland/core/log.py
Python
bsd-3-clause
1,274
0.007849
import os import sys import logging __all__ = [ 'clear_root_handlers', 'setup_console_logging', 'setup_file_logging' ] DEFAULT_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S' DEFAULT_LOG_FORMAT = '%(asctime)s [%(levelname)s] %(message)s' DEFAULT_LOG_LEVEL = logging.INFO class NullHandler(logging.Handler): def ...
ng.getLogger() root.setLevel(level) handler = logging.StreamHandl
er() formatter = logging.Formatter(format, datefmt) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def setup_file_logging(filename, level=DEFAULT_LOG_LEVEL, format=DEFAULT_LOG_FORMAT, datefmt=DEFAULT_DATE_FORMA...
libvirt/libvirt-test-API
libvirttestapi/repos/domain/hostname.py
Python
gpl-2.0
1,070
0.000935
# Copyright (
C) 2010-2012 Red Hat, Inc. # This work is licensed under the GNU GPLv2 or later. # To test "virsh hostname" command from libv
irttestapi.utils import process required_params = () optional_params = {} VIRSH_HOSTNAME = "virsh hostname" def hostname(params): """check virsh hostname command """ logger = params['logger'] ret = process.run(VIRSH_HOSTNAME, shell=True, ignore_status=True) if ret.exit_status: logger.er...
lcvisser/task-chrono
util.py
Python
mit
4,240
0.004953
# -*- coding: utf-8 -*- # Copyright (c) 2014 Ludo Visser # # task-chrono is distributed under the terms and conditions of the MIT license. # The full license can be found in the LICENSE file. import numpy import os import StringIO as sio # Useful enumeration class class Enum: def __init__(self, *sequential, **n...
_BLUE) ax.plot(x[M:], sigma_minus[M:], color=LIGHT_
BLUE) ax.plot(x[M:], sigma_plus[M:], color=LIGHT_BLUE) ax.fill_between(x[M:], y1=sigma_minus[M:], y2=sigma_plus[M:], color=LIGHT_BLUE) ax.bar(lbe[M:], errors[M:], w, color=colors[M:], alpha=0.4) # Create labels for x, task in enumerate(tasks[M:]): ax.text(x+M...
SGenheden/Scripts
Membrane/build_lipid.py
Python
mit
3,765
0.007437
# Author: Samuel Genheden, samuel.genheden@gmail.com """ Program to build lipids from a template, similarly to MARTINI INSANE Is VERY experimental! """ import argparse import os import xml.etree.ElementTree as ET import numpy as np from sgenlib import pdb class BeadDefinition(object): def __init__(self): ...
me = None self.beads = [] self.headname = [] self.tailname = [] self.head = [] self.tail = [] def make(self, bd=3.0): struct = pdb.PDBFile() res = pdb.Residue() for i, bead in enumerate(self.beads):
atom = pdb.Atom() atom.idx = i atom.serial = i + 1 atom.name = bead.name atom.resname = self.name atom.residue = 1 atom.set_xyz(bead.xyz*bd) res.atoms.append(atom) struct.atoms.append(atom) struct.residues...
quantopian/zipline
zipline/assets/asset_db_schema.py
Python
apache-2.0
4,743
0
import sqlalchemy as sa # Define a version number for the database generated by these writers # Increment this version number any time a change is made to the schema of the # assets database # NOTE: When upgrading this remember to add a downgrade in: # .asset_db_migrations ASSET_DB_VERSION = 7 # A frozenset of the n...
Text), sa.Column('start_date', sa.Integer, default=0, nullable=False), sa.Column('end_date', sa.Integer, nullable=False), sa.Column('first_t
raded', sa.Integer), sa.Column('auto_close_date', sa.Integer), sa.Column('exchange', sa.Text, sa.ForeignKey(exchanges.c.exchange)), ) equity_symbol_mappings = sa.Table( 'equity_symbol_mappings', metadata, sa.Column( 'id', sa.Integer, unique=True, nullable=False, ...
zubie7a/Algorithms
CodeSignal/Arcade/The_Core/Level_03_Corner_Of_Zeros_And_Ones/017_Kill_Kth_Bit.py
Python
mit
492
0
# https://app.codesignal.com/arcade/code-arcade/corn
er-of-0s-and-1s/b5z4P2r2CGCtf8HCR def killKthBit(n, k): # Use bit operators to turn off the k-th bit from the right. # First create a value with the bit at the position turned on # and everything else off. Then flip that value so all bits # are 1 except the one in position. Then, 'bitwise and' with ...
untouched except the one in # the desired position. return n & ~(1 << (k - 1))
tdda/tdda
tdda/constraints/db/constraints.py
Python
mit
17,342
0.000115
# -*- coding: utf-8 -*- """ TDDA constraint discovery and verification is provided for a number of DB-API (PEP-0249) compliant databases, and also for a number of other (NoSQL) databases. The top-level functions are: :py:func:`tdda.constraints.discover_db_table`: Discover constraints from a single databas...
A database table name, to be checked. *constraints_path*: The path to a JSON .tdda file (possibly generated by the discover_constraints
function, below) containing constraints to be checked. Optional Inputs: *epsilon*: When checking minimum and maximum values for numeric fields, this provides a tolerance. ...
etscrivner/pymemcache
pymemcache/errors.py
Python
bsd-3-clause
465
0
# -*- coding: utf-8 -*- """ pymemcach
e.errors ~~~~~~~~~~~~~~~~~ Exceptions base classes for pymemcache """ class Error(Exception): """Base exception for all pymemcache errors""" class ConnectionError(Error): """Base class for any socket-level connection issues""" class RequestError(Error): """Base class for errors related to the...
nts""" class ResponseError(Error): """Base class for errors related to responses"""
frederick623/HTI
omm/merge_csv.py
Python
apache-2.0
3,078
0.022092
import sqlite3 import csv def csv_to_arr(csv_file, start=1, has_header=True): arr = [] with open(csv_file, 'rU') as f: reader = csv.reader(f) arr = list(reader) if arr == []: return header = "" if has_header: header = ','.join(arr[0]) arr = arr[start:] return header, arr else: return arr[start:...
s_20170427_old.csv") conn, cur = db
_cur() create_tbl(cur, "new", new_header, new_arr) create_tbl(cur, "old", old_header, old_arr) # print new_header cur.execute("""select new.TRADEID,new.PORTFOLIOID,new.BROKEREXCHANGEID,new.MIC,new.USERID,new.IMSID,new.ORDERID,new.WAY,new.QUANTITY,new.PRICE,new.TIMESTAMP,new.IMSUSERID,new.USERDATA,old.MARKETDATA,new.E...
lindzey/pelican-plugins
render_math/math.py
Python
agpl-3.0
14,090
0.003123
# -*- coding: utf-8 -*- """ Math Render Plugin for Pelican ============================== This plugin allows your site to render Math. It uses the MathJax JavaScript engine. For markdown, the plugin works by creating a Markdown extension which is used during the markdown compilation stage. Math therefore gets treated...
d isinstance(value, bool): if value and BeautifulSoup is None: print("BeautifulSoup4 is needed for summaries to be processed by render_math\nPlease install it") value = False mathjax_se
ttings[key] = value if key == 'responsive' and isinstance(value, bool): mathjax_settings[key] = 'true' if value else 'false' if key == 'force_tls' and isinstance(value, bool): mathjax_settings[key] = 'true' if value else 'false' if key == 'responsive_break' and ...
worldforge/cyphesis
data/rulesets/basic/scripts/mind/goals/common/common.py
Python
gpl-2.0
3,486
0.002008
# This file is distributed under the terms of the GNU General Public license. # Copyright (C) 1999 Aloril (See the file COPYING for details). import time from mind.Goal import Goal # goals for minds def false(_): return False def true(_): return True class Delayed(Goal): """Will delay execution of sub goal...
def __init__(self, sub_goals, desc="Executed once after a delay"): Goal.__init__(self, desc=desc, sub_goals=[OneShot(sub_goals=[Delayed(time=time.time() + 1, sub_go
als=sub_goals)])]) class Condition(Goal): """ A conditional goal which first executes a function, and then sets the subgoals to one of two possibilities. If the condition function returns None then none of the subgoals will be executed. """ def __init__(self, condition_fn, goals_true, goals_false...
emulbreh/shrubbery
shrubbery/authentication/__init__.py
Python
mit
172
0.011628
from shrubbery.authentication.contexts imp
ort AuthenticationContext, ModelAuthenticationContext from shrubbery.authentication.exceptions import AuthenticationErr
or, Http403
friedue/AlleleSpecific
individualScripts/removeNegValuesMOD.py
Python
mit
2,375
0.025684
#!/usr/bin/python import sys, getopt def main(argv): try: opts, args = getopt.getopt(argv,"hi:o:",["help","mpileupfile=","jfile=","snpfile=","ofile="]) except getopt.GetoptError: print 'removeNegValuesMOD.py -i <infile> -o <output_file>' sys.exit(2) ...
sys.exit() elif
opt in ("-i", "--infile"): infile = open( arg, 'r') elif opt in ("-o", "--ofile"): outputfile = open( arg, "w") for line in infile: entry=line.rstrip().split("\t") if(len(entry) == 9): start = entry[3] end = entry[4] if(start[0] == "-" an...
willkg/redminelib
redminelib/tests/test716.py
Python
mit
1,444
0
####################################################################### # This file is part of redminel
ib. # # Copyright (C) 2011 Will Kahn-Greene # # redminelib is distributed under the MIT license. See the file # COPYING for distribution details. ####################################################################### from redminelib.redmine import RedmineScraper from redminelib.tests import get_testdata import os ...
"716.html")).read() issue = rs.parse_issue(data) # extracted eq_(issue["id"], "716") eq_(issue["title"], u'Apache FCGI documentation In Manual') eq_(issue["author"], u"Sam Kleinman") eq_(issue["creation-date"], "12/20/2011 10:23 am") eq_(issue["last-updated-date"], "12/22/2011 06:29 pm") ...
qilicun/python
python3/tutorials/filepath.py
Python
gpl-3.0
65
0.015385
#!/usr/bin/env python3
from pathlib import Path
p = Path('.')
adfernandes/intelhex
intelhex/compat.py
Python
bsd-3-clause
5,035
0.002383
# Copyright (c) 2011, Bernhard Leiner # Copyright (c) 2013-2018 Alexander Belchenko # 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...
n = 2 asbytes = str
asstr = str array_tobytes = array.array.tostring IntTypes = (int, long) StrType = basestring UnicodeType = unicode #range_g = xrange # range generator def range_g(*args): # we want to use xrange here but on python 2 it does not work with long ints try: return xr...
ilia-novikov/xcos-gen
hdl_block.py
Python
gpl-3.0
1,461
0.000684
""" This file is part of xcos-gen. xcos-gen 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. xcos-gen is distribute...
hat it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO
SE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with xcos-gen. If not, see <http://www.gnu.org/licenses/>. Author: Ilia Novikov <ilia.novikov@live.ru> """ from block import Block class HdlBlock: def __init__(self,...
bistromath/gr-smartnet
src/python/smartnet2decode.py
Python
gpl-3.0
13,591
0.033037
#!/usr/bin/env python """ This program decodes the Motorola SmartNet II trunking protocol from the control channel Tune it to the control channel center freq, and it'll spit out the decoded packets. In what format? Who knows. Based on your AIS decoding software, which is in turn based on the gr-pager code and the...
ation 4000, #deviation 3000, #audio passband 4000, #audio stopband 1, #gain 75e-6) #deemphasi
s constant #the filtering removes FSK data woobling from the subaudible channel (might be able to combine w/lpf above) self.audiofilttaps = gr.firdes.high_pass(1, self.audiorate, 300, 50, gr.firdes.WIN_HANN) self.audiofilt = gr.fir_filter_fff(1, self.audiofilttaps) self.audiogain = gr.multiply_const_ff(opt...
rituven/winston
core/Events.py
Python
apache-2.0
163
0.006135
c
lass Events(object): """ Events Enum """ UI_BTN_PRESSED = 100 UI_BTN_RELEASED = 101 UI_BTN_CLICKED = 102 SET_UI_BTN_STATE =
150
natea/Miro-Community
localtv/search/tests.py
Python
agpl-3.0
10,029
0.001197
from django.contrib.auth.models import User from localtv.tests import BaseTestCase from localtv import models from localtv.playlists.models import Playlist from localtv import search class SearchTokenizeTestCase(BaseTestCase): """ Tests for the search query tokenizer. """ def assertTokenizes(self, qu...
""" Search should search the user who submitted videos. """ video = models.Video.objects.get(pk=20) video.user = User.objects.get(username='superuser') video.user.username = 'SuperUser' video.user.first_name = 'firstname' video.user.last_name = 'lastname' ...
s.Video.objects.get(pk=47) video2.authors = [video.user] video2.save() self._rebuild_index() self.assertEquals(self.search('superuser'), [video2, video]) self.assertEquals(self.search('firstname'), [video2, video]) self.assertEquals(self.search('lastname'), [video2, vid...
emmanuj/dials_shortest_path
graph.py
Python
mit
1,382
0.015195
#Graph data structure for input graph
from node import Node class Graph: def __init__(self, n): self.numnodes = n self.vertices = [] #container for nodes self.edges = [] for i in range(0,n): self.vertices.append(Node(i)) self.edges.append([]) self.max_edge_l = 0 self.source = None...
self.edges[head].append((tail, edge_length)) # edges are a tuple of tail and edge length if edge_length > self.max_edge_l: self.max_edge_l= edge_length def neighbors(self, i): return self.edges[i] def vertices(self): return self.vertices def max_edge_length(self): ...
Paricitoi/python_4_eng
python_week1/v2/week1_ex8v2.py
Python
gpl-3.0
321
0.034268
#!/u
sr/bin/env python from ciscoconfparse import CiscoConfParse def main(): cisco_cfg = CiscoConfParse("cisco_ipsec.txt") cr_map_list = cisco_cfg.find_objects(r"^crypto map CRYPTO") for item in cr_map_list: print item.text for child in item.children: pr
int child.text if __name__ == "__main__": main()
openstack/designate
designate/quota/__init__.py
Python
apache-2.0
966
0
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hpe.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in
compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either e...
ed. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from oslo_log import log as logging from designate.quota import base LOG = logging.getLogger(__name__) def get_quota(): quota_driver = cfg.CONF.quota_driver LOG.debug("Loa...
karantan/singer-getting-started
src/main.py
Python
mit
617
0
from datetime import datetime from datetime import timezone imp
ort singer import urllib.request def my_ip(): now = datetime.now(timezone.utc).isoformat() schema = { 'properties': { 'ip': {'type': 'string'}, 'timestamp': {'type': 'string', 'format': 'date-time'}, }, } with urllib.request.urlopen('http://icanhazip.com') as...
ode('utf-8').strip() singer.write_schema('my_ip', schema, 'timestamp') singer.write_records('my_ip', [{'timestamp': now, 'ip': ip}]) if __name__ == "__main__": my_ip()
Oizopower/Whitecoin-ABE
Abe/DataStore.py
Python
agpl-3.0
122,759
0.001662
# Copyright(C) 2011,2012,2013,2014 by Abe developers. # DataStore.py: back end database access for Abe. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publi
c License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of #
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with this program. If not, see # <http://www.gnu.org/licenses/agpl.html>. # This module combines three functions th...
gengwg/leetcode
211_add_and_search_word.py
Python
apache-2.0
2,673
0.001122
# 211. Add and Search Word - Data structure design # # Design a data structure that supports the following two operations: # # void addWord(word) # bool search(word) # # search(word) can search a literal word or a regular expression string containing # only letters a-z or .. A . means it can represent any one letter. #...
dfs def find(self, node, word): if word == '': # termination condition return node.isWord if word[0] == '.': # if . loop over all children for x in node.children: # if any of children returns true, return true if x and
self.find(node.children[x], word[1:]): return True else: # normal find child = node.children.get(word[0]) if child: return self.find(child, word[1:]) return False # Your WordDictionary object will be instantiated and called as such: # obj =...
muendelezaji/workload-automation
wlauto/workloads/camerarecord/__init__.py
Python
apache-2.0
1,671
0.001197
# Copyright 2013-2015 ARM Limited # # Licensed under
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is dis...
e the License for the specific language governing permissions and # limitations under the License. # from wlauto import UiAutomatorWorkload, Parameter class Camerarecord(UiAutomatorWorkload): name = 'camerarecord' description = """ Uses in-built Android camera app to record the video for given interval ...
jdasinger/random
copy_rds.py
Python
gpl-3.0
1,743
0.004016
# # Code per http://blog.powerupcloud.com/2016/03/26/automating-rds-snapshots-with-aws-lambda/ # import boto3 import botocore import datetime import re SOURCE_REGION = 'us-east-1' TARGET_REGION = 'us-west-1' iam = boto3.client('iam') instances = ['<instance name>'] # convert to command line argument print('Loading f...
ON) try: response = target.copy_db_snapshot( SourceDBSnapshotIdentifier=source_snap_arn, TargetDBSnapshotId
entifier=target_snap_id, CopyTags=True) print(response) except botocore.exceptions.ClientError as e: raise Exception("Could not issue copy command: %s" % e)
demharters/git_scripts
my_elbow_angle_tcr_imgt.py
Python
apache-2.0
7,744
0.02079
''' More information at: http://www.pymolwiki.org/index.php/elbow_angle Calculate the elbow angle of an antibody Fab complex and optionally draw a graphical representation of the vectors used to determine the angle. NOTE: There is no automatic checking of the validity of limit_l and limit_h values or of the assignm...
l = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h) ch_sel = 'polymer and %s and chain %s and not resi 1-127 and not resi 1001D and not resi 1001C and not resi 1001B and not resi 1001A and not resi 1001' % (obj, heavy) v_sel = '(('+vl_sel+') or ('+vh_sel+'))' c_sel = '(('+cl_sel+') o...
))' # create temp objects cmd.create(vl,vl_sel) cmd.create(vh,vh_sel) cmd.create(cl,cl_sel) cmd.create(ch,ch_sel) # superimpose vl onto vh, calculate axis and angle Rv = calc_super_matrix(vl,vh) angle_v,direction_v,point_v = transformations.rotation_from_matrix(Rv) ...
pyql/PyQL
yaccer.py
Python
gpl-3.0
9,082
0
# Define the grammar for the Pythonic Query Language. # the smallest unit is a term # between any two terms there can be: # a COMMA - delimits fields and defines explicit query groups: # a, b, c @ d>1, 2, 3 # a CONJUCTION - python in fields and acts as delimitor for conditions: # ...
] = [p
[1]] else: p[0] = p[1] + [[(Term(p[2], None, 'COMPARATOR'),)]] + p[3] # top-level query # build parser with start=query def p_query(p): """query : base_query | base_query QUESTION_MARK fields""" p[0] = p[1] if len(p) == 4: p[0].arguments = p[3] def p_base_query(p): "...
ProjectSWGCore/NGECore2
scripts/mobiles/generic/faction/imperial/imp_warant_officer_ii_1st_class_33.py
Python
lgpl-3.0
1,458
0.028121
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from resources.datatables import FactionStatus from java.util import Vector def addTemplate(co...
tes = Vector() weapontemplate = WeaponTemplate('object/weapon/ranged/carbine/shared_carbine_e11.iff', WeaponType.CARBINE, 1.0, 15, 'energy') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('rangedShot') mobileTemplate...
nt_offi_1st_class_ii_33', mobileTemplate) return
yolanother/ubuntumobidev_ubiquity
tests/test_install_misc.py
Python
gpl-3.0
4,712
0
#! /usr/bin/python3 import os import shutil import tempfile import unittest from ubiquity import install_misc class InstallMiscTests(unittest.TestCase): def setUp(self): self.source = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.source) self.target = tempfile.mkdtemp() ...
local/share/man"))) self.assertTrue( os.path.isfile(self.target_path("usr/local/share/man/file"))) def test_remove_target_backs_up_non_empty_directory(self): with open(self.source_path("source-file-target-non-empty-dir"), "w"):
pass os.mkdir(self.target_path("source-file-target-non-empty-dir")) tp = self.target_path("source-file-target-non-empty-dir/file") with open(tp, "w"): pass self.try_remove_target("source-file-target-non-empty-dir") self.assertFalse(os.path.exists( sel...
flarn2006/TPPStreamerBot
tppsb.py
Python
mit
10,064
0.029213
#!/usr/bin/python import sys import re import thread import urllib from time import sleep from datetime import datetime, timedelta import requests import praw from prawcore.exceptions import * import irc.bot # Begin configurable parameters identity = { # Make sure to set these if they aren't already! 'reddit_cli...
er == 'aissurtievos' and not msg.startswith('`'): upd = '' if upd != '': # Message is from a monitored user. # First, see if the message is a reply to another user, so we can pull their message. mentionedUser = findUsernameInMsg(msg) if menti
onedUser != '' and mentionedUser in prevMsgs and mentionedUser not in modList: # We've got a match! But let's make sure the message was posted recently. if datetime.now() - prevMsgTimes[mentionedUser] > timedelta(0, 300): # Looks like it wasn't. Let's remove it from the list and forget about it. menti...
pkilambi/python-jsonpath-rw
setup.py
Python
apache-2.0
1,220
0.012295
import setuptools import io import sys import os.path import subprocess setuptools.setup( name='jsonpath-rw', version='1.4.0', description='A robust and significantly extended implementation of JSONPath for Python, with a clear AST for metaprogramming.', author='Kenneth Knowles', author_email='ken...
: 3', 'Programming L
anguage :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
sergeyf/scikit-learn
sklearn/ensemble/_voting.py
Python
bsd-3-clause
19,214
0.000364
""" Soft Voting/Majority Rule classifier and Voting regressor. This module contains: - A Soft Voting/Majority Rule classifier for classification estimators. - A Voting regressor for regression estimators. """ # Authors: Sebastian Raschka <se.raschka@gmail.com>, # Gilles Louppe <g.louppe@gmail.com>, # ...
self.named_estimators_ = Bunch() # Uses 'drop' as placeholder for dropped estimators est_iter = iter(self.estimators_) for name, est in self.estimators: current_est = est if est == "drop" else next(est_iter)
self.named_estimators_[name] = current_est if hasattr(current_est, "feature_names_in_"): self.feature_names_in_ = current_est.feature_names_in_ return self def fit_transform(self, X, y=None, **fit_params): """Return class labels or probabilities for each estimato...
Makeystreet/makeystreet
woot/apps/catalog/migrations/0029_auto__del_field_toindexstore_basemodel_ptr__add_field_toindexstore_id.py
Python
apache-2.0
26,077
0.007363
# -*- 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 'ToIndexStore.basemodel_ptr' db.delete_column(u'catalog_...
bases': ['catalog.BaseModel']}, u'basemodel_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['catalog.BaseModel']", 'unique': 'True', 'primary_key': 'True'}), 'body': ('django.db.models.fields.CharField',
[], {'max_length': '1000'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['django_facebook.FacebookCustomUser']"}) }, 'catalog.documentation': { 'Meta': {'object_name': 'Documentation', '_ormbases': ['catalog.BaseModel']}, u'basemodel_ptr':...
beanbaginc/django-evolution
django_evolution/compat/py23.py
Python
bsd-3-clause
1,420
0
"""Compatibility functions for Python 2 and 3.""" from __future__ import unicode_literals import io from django_evolution.compat import six from django_evolution.compat.picklers import DjangoCompatUnpickler from django_evolution.compat.six.moves import cPickle as pickle def pickle_dumps(obj): """Return a pickl...
ion of an object. This will always use Pickle protocol 0, which is the default on Python 2, for compatibility across Python 2 and 3. Args: obj (object): The object to dump. Returns: unicode: The Unico
de pickled representation of the object, safe for storing in the database. """ return pickle.dumps(obj, protocol=0).decode('latin1') def pickle_loads(pickled_str): """Return the unpickled data from a pickle payload. Args: pickled_str (bytes): The pickled data. Returns...
buhii/tomato
tests.py
Python
mit
3,294
0.002732
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tomato.tests """ import unittest import msgpack import time try: from PIL import Image except ImportError: import Image from tomato.swf_processor import Swf from tomato.exceptions_tomato import MovieClipDoesNotExist from tomato.utils import bits_list2string, B...
slate_x', translate[0]) m2.setattr_value('translate_y', translate[1]) m2.generate_bits() return m1.value == m2.value class TestSwfProcessor(unittest.TestCase): def setUp(self): self.swf_bitmap = Swf(open('sample/bitmap/bitmap.swf').read()) self.swf_tank = Swf(open('sample/mc/tank.s...
27182 float_num = 1.6180339 self.assertEqual(int_num, int(Bits(int_num))) self.assertEqual(signed_num, int(SB(signed_num))) self.assertAlmostEqual(float_num, float(FB(float_num)), 4) def test_bits2string(self): spam_string = "This is a spam!" self.assertEqual(spam_st...
wubr2000/googleads-python-lib
examples/dfa/v1_20/create_spotlight_activity_group.py
Python
apache-2.0
2,085
0.004796
#!/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...
writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WAR
RANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Creates a new activity group for a given spotlight configuration. To get spotlight tag configuration, run get_advertisers.py. To get activity types, r...
djoproject/pyshell
pyshell/utils/test/misc_test.py
Python
gpl-3.0
2,472
0
#!/usr/bin/env python -t # -*- coding: utf-8 -*- # Copyright (C) 2015 Jonathan Delvaux <pyshell@djoproject.net> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License...
tring concatenation import os import shutil import tempfile import pytest from pyshell.utils.exception import DefaultPyshellException from
pyshell.utils.misc import createParentDirectory def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) class TestMisc(object): def test_createParentDirectory1(self): file_path = tempfile.gettempdir() + os.sep + "plop.txt" assert os.path.exists(tempfile.gettempdi...
cevaris/pants
src/python/pants/backend/python/targets/python_requirement_library.py
Python
apache-2.0
1,293
0.006187
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.p...
ntLibrary(Target): """A set of pip requirements. :API: public """ def __init__(self, payload=None, requirements=None, **kwargs): """ :param requirements: pip requirements as `python_requirement <#python_requirement>`_\s. :type requirements: List of python_requirement calls """ payload = pa...
(requirements or []), }) super(PythonRequirementLibrary, self).__init__(payload=payload, **kwargs) self.add_labels('python') @property def requirements(self): return self.payload.requirements
gkc1000/pyscf
pyscf/scf/hf_symm.py
Python
apache-2.0
36,696
0.003706
#!/usr/bin/env python # Copyright 2014-2019 The PySCF Developers. 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 # # U...
lativistic restricted Hartree-Fock with point group symmetry. The symmetry are not handled in a separate data structure. Note that during the SCF iteration, the orbitals are grouped in terms of symmetry irreps. But the orbitals in the result are sorted based on the orbital energies. Func
tion symm.label_orb_symm can be used to detect the symmetry of the molecular orbitals. ''' import time from functools import reduce import numpy import scipy.linalg from pyscf import lib from pyscf import symm from pyscf.lib import logger from pyscf.scf import hf from pyscf.scf import rohf from pyscf.scf import chkfil...
rdo-management/heat
heat/db/sqlalchemy/migrate_repo/versions/024_event_resource_name.py
Python
apache-2.0
807
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 # ...
t sqlalchemy def upgrade(migrate_engine): meta = sqlalch
emy.MetaData() meta.bind = migrate_engine event = sqlalchemy.Table('event', meta, autoload=True) event.c.logical_resource_id.alter(name='resource_name')
Saftophobia/shunting
data/__init__.py
Python
mit
28
0.035714
__au
thor__ = 'saftophob
ia'
sciosci/nsf_data_ingestion
nsf_data_ingestion/arxiv/fetch_data_hdfs_loop.py
Python
apache-2.0
2,651
0.000754
from datetime import datetime import urllib.request import time from subprocess import call import sys import os retry_time = 45 # save_path = "" def get_raw_data(path): start = time.clock() query = "http://export.arxiv.org/oai2?verb=ListRecords&metadataPrefix=oai_dc" print("request: %s" % (query)) ...
s + 1:pos_end] print("request_resume: %s" % (resume_token)) get_resume(resume_token, path)
repeat += 1 except Exception as err: print(err) print("retry resume_token: %s" % (token)) time.sleep(30) get_resume(token) def save_to_hdfs(filename, path): print(">>>>>>>", path) file = os.path.join(path, filename) try: out = call("hdfs dfs -test -e %s" % (fil...
noplay/gns3-gui
gns3/modules/dynamips/pages/frame_relay_switch_configuration_page.py
Python
gpl-3.0
6,628
0.00166
# -*- coding: utf-8 -*- # # Copyright (C) 2014 GNS3 Technologies Inc. # # 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. ...
if not group: self.uiNameLineEdit.se
tText(settings["name"]) else: self.uiNameLineEdit.setEnabled(False) self.uiMappingTreeWidget.clear() self._mapping = {} self._node = node for source, destination in settings["mappings"].items(): item = QtGui.QTreeWidgetItem(self.uiMappingTreeWidget) ...