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
tanchao/chaos.trade
__init__.py
Python
bsd-2-clause
1,215
0
import sys import os cur_path = os.getcwd() sys.path.append(cur_path) start_env = ''' 1. mysqld should be start by sys 2. ngnix should be start by sys 3. need manually start uwsgi: . uwsgi_chaos.sh note socket 127.0.0.1:9527 is takend by it ''' init_env = ''' 1. install git: sudo yum ...
thon and pip were installed by aws default): sudo pup install Flask 4. create project:
ERROR: type should be string, got " https://github.com/tanchao/chaos.trade\n 5. install mysql:\n sudo yum install mysql mysql-server mysql-libs mysql-devel\n sudo service mysqld start\n sudo chkconfig --level 35 mysqld on\n chkconfig --list | grep mysql\n http://jingyan.baidu.com/article/acf728fd10c3d6f8e510a3ef.html\n http://www.360doc.com/content/15/0516/11/14900341_470864335.shtml\n http://www.cnblogs.com/bjzhanghao/archive/2011/07/24/2115350.html\n 6. install web server\n yum install nginx\n sudo service nginx start\n sudo yum install gcc\n sudo CC=gcc pip install uwsgi\n'''\n"
carmelom/sisview-bec-tn
sisview.py
Python
gpl-3.0
10,034
0.005382
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright (C) 2016 Carmelo Mordini # # 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 la...
v) self.treeView.doubleClicked.connect(self.goToFolder) self.colormapComboBox.currentIndexChanged.connect(lambda: self.replot(self.currentSis)) self.fftComboBox.currentIndexChanged.connect(self.set_fft_flag) self.vminDoubleSpinBox.valueChanged.connect(lambda: self.replot(self.cur...
ock_to_area(self.actionTop.text())) self.actionRight.triggered.connect(lambda: self.dock_to_area(self.actionRight.text())) self.actionDetatch_All.triggered.connect(self.dock_detatch_all) self.actionToggle0 = self.dockWidget0.toggleViewAction() self.actionToggle1 = self.dockWidget1.toggle...
darrellsilver/norc
core/models/extras.py
Python
bsd-3-clause
417
0.014388
from django.db.models import Model, CharField class Revision(Model): """Represents a code revision
.""" class Meta: app_label = 'core' db_table = 'norc_revision' info = CharField(max_length=64, unique=True) @staticmethod def create(info): return Revision.objects.create(in
fo=info) def __str__(self): return "[Revision %s]" % self.info
RayRuizhiLiao/ITK_4D
Modules/Filtering/ImageFeature/test/itkGradientVectorFlowImageFilterTest.py
Python
apache-2.0
2,887
0.000693
#========================================================================== # # Copyright Insight Software Consortium # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file exc
ept in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the Li
cense is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #==========================================================================*/ import...
timedata-org/expressy
expressy/__init__.py
Python
mit
99
0
from . import express
ion, units p
arse = expression.Maker() parse_with_units = units.inject(parse)
Iconik/eve-suite
src/model/static/planet/schematic_type_map.py
Python
gpl-3.0
914
0.00547
''' Created on Mar 20, 2011 @author: frederikns ''' from model.flyweight import Flyweight from collections import namedtuple from model.static.database import database from model.dynamic.inventory.item import Item class SchematicTypeMap(Flyweight): def __init__(self,schematic_id): #prevents reinitializing...
w["typeID"], row["quantity"]), is_input=(ro
w["isInput"]))) cursor.close()
dmonroy/python-etcd
src/etcd/client.py
Python
mit
27,306
0.001099
""" .. module:: python-etcd :synopsis: A python etcd client. .. moduleauthor:: Jose Plana <[email protected]> """ import logging try: # Python 3 from http.client import HTTPException except ImportError: # Python 2 from httplib import HTTPException import socket import urllib3 import urllib3.util im...
allow_reconnect (bool): allow the client to reconnect to another etcd server in the cluster in the case the default one does not respond. use_proxies (bool): we are using a list of proxies to which we connect, ...
want to connect to the original etcd cluster. expected_cluster_id (str): If a string, recorded as the expected UUID of the cluster (rather than learning it from the first request), reads wil...
WaterSheltieDragon/Wango-the-Robot
faceup.py
Python
gpl-3.0
368
0.038043
import time import maestro # servo 0 is left/right # servo 1 is up/down try: servo = maestro.Controller() servo.setRange(1,4000,8000) # about 5 clicks per full motion # 1040 for left
/right + is left, - is rig
ht. # 800 for up/down + is up, - is down. x = servo.getPosition(1) + 800 servo.setAccel(1,6) servo.setTarget(1,x) finally: servo.close
mengzhuo/my-leetcode-solution
valid-anagram.py
Python
mit
180
0
class Solution(object):
def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ return sorted(s)
== sorted(t)
sirinath/root
main/python/rootbrowse.py
Python
lgpl-2.1
711
0.002813
#!/usr/bin/env python # ROOT command line tools: rootbrowse # Author: Julien Ripoche # Mail: julien.ripoche@u-ps
ud.fr # Date: 20/08/15 """Command line to open a ROOT file on a TBrowser""" import cmdLineUtils import sys # Help strings COMMAND_HELP = "Open a ROOT file in a TBrowser" EPILOG = """Examples: - rootbrowse Open a TBrowser - rootbrowse file.root Open the ROOT file 'file.root' in a TBrowser """ def execute(): ...
getArgs(parser) # Process rootBrowse return cmdLineUtils.rootBrowse(args.FILE) sys.exit(execute())
axiom-data-science/paegan
paegan/utils/asamath.py
Python
gpl-3.0
1,568
0.00574
from math import sqrt, atan2, degrees, radians class AsaMath(object): @classmethod def speed_direction_from_u_v(cls, **kwargs): if "u" and "v" in kwargs: speed = cls.__speed_from_u_v(kwargs.get('u'), kwargs.get('v')) direction = cls.__direction_from_u_v(kwargs.get('u'), kwargs....
sqrt((u*u) + (v*v)) @classmethod def __direction_from_u_v(cls, u, v, **kwargs): rads = atan2(v, u) if 'output' in kwargs: if kwargs.pop('output') == 'radians': return rads # if 'output' was not specified as 'radians', we return degrees return cls.nor...
classmethod def math_angle_to_azimuth(cls, **kwargs): return cls.normalize_angle(angle=(360 - kwargs.get("angle")) + 90) @classmethod def normalize_angle(cls, **kwargs): return kwargs.get('angle') % 360 @classmethod def is_number(cls, num): try: float(num) # for...
ajackal/honey-hornet
honeyhornet/viewchecker.py
Python
gpl-3.0
5,097
0.002747
import os import argparse from logger import HoneyHornetLogger from threading import BoundedSemaphore import threading import logging from datetime import date, datetime from termcolor import colored import http.client import re import time class ViewChecker(HoneyHornetLogger): def __init__(self, config=None): ...
sage)s', level=logging.DEBUG) def determine_camera_model(self, vulnerable_host, https=False, retry=False): """ simple banner grab with http.client """ ports = [] self.CONNECTION_LOCK.acquire() service = "DETERMINE-CAMERA-MODEL" if retry is False: ...
lnerable_host.ip ports_to_check = set(vulnerable_host.ports) except vulnerable_host.DoesNotExist: host = str(vulnerable_host) ports_to_check = set(ports.split(',').strip()) elif retry is True: host = vulnerable_host if self.verbose:...
brainysmurf/xattr3
xattr/tool.py
Python
mit
6,510
0.003533
#!/usr/bin/env python3 ## # Copyright (c) 2007 Apple Inc. # # This is the MIT license. This software may also be distributed under the # same terms as Python (the PSF license). # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "...
= Fa
lse write = False delete = False compress = lambda x: x decompress = compress status = 0 for opt, arg in optargs: if opt in ("-h", "--help"): usage() elif opt == "-l": long_format = True elif opt == "-p": read = Tru...
openstack/swift
test/unit/common/middleware/crypto/test_encryption.py
Python
apache-2.0
31,916
0
# Copyright (c) 2015-2016 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
= None @classmethod def setUpClass(cls): cls._test_context = setup_servers() cls.proxy_app = cls._test_context["test_servers"][0] @classmethod def tearDownClass(cls): if cls._test_context is not None: teardown_servers(cls._test_context) cls._test_context...
g = md5hex(self.plaintext) self._setup_crypto_app() def _setup_crypto_app(self, disable_encryption=False, root_secret_id=None): # Set up a pipeline of crypto middleware ending in the proxy app so # that tests can make requests to either the proxy server directly or # via the crypto ...
Centre-Alt-Rendiment-Esportiu/att
src/python/test/test_classes/PingPongAppMock.py
Python
gpl-3.0
376
0.00266
from test.classes.PingPongApp import PingPongApp from test.test_classes.BallTrackerMock import BallTrackerMock class PingPongAppMock(PingPongApp): d
ef __init__(self, args): super(PingPongAppMock, self).__init__(args) self.ball_tracker = BallTrackerMock() def run(self): super(PingPongAppMock, self).run() self.ball_tracker.end
_test()
Matvey-Kuk/cspark-python
examples/1_room_mentions_counter.py
Python
mit
1,702
0.00235
########################################## # Check examples/0_simple_echo.py before # ########################################## from cspark.Updater import Updater from cspark.EventTypeRouter import EventTypeRouter from cspark.UpdateHandler import UpdateHandler from cspark.SQLiteContextEngine import SQLiteContextEngin...
ted from UpdateHandler and PeeweeContextStorage. UpdateHandler gives you "self.send_response" to send answers. PeeweeContextStorage gives you "self.context" which is a dictionary. You can save your data there for future. It's stateful container, which stores your data in Peewee ORM (SQLite by default)...
ntext.room: self.context.room['counter'] = 1 else: self.context.room['counter'] += 1 self.send_response( MessageResponse("Room counter: " + str(self.context.room['counter'])) ) class Router(EventTypeRouter): """ Router should decide which message sh...
scanlime/flipsyfat
flipsyfat/cores/sd_emulator/core.py
Python
mit
4,333
0.001846
from flipsyfat.cores.sd_emulator.linklayer import SDLinkLayer from migen import * from misoc.interconnect.csr import * from misoc.interconnect.csr_eventmanager import * from misoc.interconnect import wishbone class SDEmulator(Module, AutoCSR): """Core for emulating SD card memory a block at a time, with re...
.cd_local = ClockDomain() self.comb += self.cd_local.clk.eq(ClockSignal()) self.comb += self.cd_local.rst.eq(ResetSignal() | self._reset.storage) # Current data operation self._read_act = CSRStatus() s
elf._read_addr = CSRStatus(32) self._read_byteaddr = CSRStatus(32) self._read_num = CSRStatus(32) self._read_stop = CSRStatus() self._write_act = CSRStatus() self._write_addr = CSRStatus(32) self._write_byteaddr = CSRStatus(32) self._write_num = CSRStatus(32) ...
PastebinArchiveReader/PAR
PAR.py
Python
gpl-2.0
1,869
0.00428
""" Python Archive Reader 1.0 https://github.com/PastebinArchiveReader/PAR """ import requests from bs4 import BeautifulSoup import urllib import argparse import time # add parsing functionality to provide files parser = argparse.ArgumentParser(description="Script to download pastebin.com archives", ...
ed files", metavar="/home/anon/scripts/") args = parser.parse_args() url = "http://pastebin.com/archive/" + args.language while 1: source = requests.get(url) soup = BeautifulSoup(source.text) for link in soup.find_all('a'): if len(link.get('href')) == 9: if link.g...
om Pastebin.com. Pointless. ID = link.get('href') paste = link.get('href').replace('/', '') paste = "http://www.pastebin.com/raw.php?i=" + paste print("[?] {}".format(paste)) downloaded_file = args.path + "/" + ID + args.extension ...
psederberg/pynamite
docs/examples/wish.py
Python
gpl-3.0
1,653
0.009679
# # My wish for Pynamite # from __future__ import with_statement from pynamite import * from pynamite.actor import TextBox def scene1():
# define some actors x = TextBox("Pynamite") y = TextBox("Rocks!!!") # tell the first actor to enter enter(x) # wait for a keypress to continue pause() # fade out one actor while other comes in # # You can use with blocks
# with parallel(): # fadeout(1.0,x) # fadein(1.0,y) # Or the functional notation set_var(y, "opacity", 0.0) enter(y) def together(): fadeout(4.0,x) with serial(): linear(y, "opacity", end_val=.5, duration=1.0) linear(y, "opacity", end_val=.0, d...
TamiaLab/carnetdumaker
apps/snippets/apps.py
Python
agpl-3.0
323
0
""" Application file for the code snippets app. """ from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class SnippetsConf
ig(AppConfig): """ Application configuration class for the code snippets app. """ name = 'apps.snippets' verbose_name = _('Code snippets')
Extremus-io/djwebsockets
djwebsockets/mixins/__init__.py
Python
mit
358
0
class BaseWSMixin(object): @classmethod def on_connect(cls
, socket, path): pass @classmethod def on_message(cls, socket, message): pass @classmethod def on_close(cls, socket): pass class MixinFa
il(Exception): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) pass
googleapis/python-analytics-data
google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py
Python
apache-2.0
19,474
0.002003
# -*- 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...
oogle.api_core.exceptions.DuplicateCredentialA
rgs: If both ``credentials`` and ``credentials_file`` are passed. """ self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is depre...
quizlet/grpc
src/python/grpcio/grpc/_auth.py
Python
apache-2.0
2,543
0
# Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
=1) # Hack to determine if these are JWT creds and we need to pass # additional_claims when getting a token self._is_jwt = 'additional_claims' in inspect.getargspec( credentials.get_access_token).args def __call__(self, context, callback): # MetadataPlugins cannot block...
additional_claims={'aud': context.service_url}) else: future = self._pool.submit(self._credentials.get_access_token) future.add_done_callback(_create_get_token_callback(callback)) def __del__(self): self._pool.shutdown(wait=False) class AccessTokenCallCredentials(...
code4bones/Triton
examples/crackme_hash_collision.py
Python
lgpl-3.0
5,246
0.006672
from triton import * import smt2lib # # This example breaks a simple hash routine. # # Check the ./samples/crackmes/crackme_hash.c file. This file builds # a 'hash' and checks the checksum 0xad6d. # # The needed password is 'elite'. Example: # $ ./samples/crackmes/crackme_hash elite # Win # # This Triton code will ...
r_4': "0x62, 'b'"} # {'SymVar_1': "0x7a, 'z'", 'SymVar_0': "0x6f, 'o'", 'SymVar_3': "0x62, 'b'", 'SymVar_2': "0x62, 'b'", 'SymVar_4': "0x6a, 'j'"}
# {'SymVar_1': "0x7a, 'z'", 'SymVar_0': "0x6e, 'n'", 'SymVar_3': "0x62, 'b'", 'SymVar_2': "0x63, 'c'", 'SymVar_4': "0x6a, 'j'"} # {'SymVar_1': "0x78, 'x'", 'SymVar_0': "0x6e, 'n'", 'SymVar_3': "0x62, 'b'", 'SymVar_2': "0x63, 'c'", 'SymVar_4': "0x68, 'h'"} # {'SymVar_1': "0x78, 'x'", 'SymVar_0': "0x6e, 'n'", 'SymVar_3':...
nop33/indico-plugins
piwik/indico_piwik/queries/utils.py
Python
gpl-3.0
1,914
0.001045
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
rver responded with an error: %s', data['message']) return {} return data except Exception: current_plugin.logger.exception('Unable to load JSON from sourc
e %s', rawjson) return default def reduce_json(data): """Reduce a JSON object""" return reduce(lambda x, y: int(x) + int(y), data.values()) def stringify_seconds(seconds=0): """ Takes time as a value of seconds and deduces the delta in human-readable HHh MMm SSs format. """ secon...
Janzert/halite_ranking
rating_stats.py
Python
mit
8,861
0.003611
#!/usr/bin/env python3 import argparse import json import math import sys from collections import defaultdict import trueskill import matplotlib.pyplot as plot import utility def phi(x): """Cumulative distribution function for the standard normal distribution Taken from python math module documentation""" ...
rueskill ratings. Formula found at https://github.com/sublee/trueskill/issues/1#issuecomment-244699989""" if not env: env = trueskill.global_env() epsilon = trueskill.calc_draw_margin(env.draw_probability, 2) denom = math.sqrt(a.sigma**2 + b.
sigma**2 + (2 * env.beta**2)) return phi((a.mu - b.mu - epsilon) / denom) def wl_winp(a, b): ciq = math.sqrt(a.sigma**2 + b.sigma**2 + (2 * (25/6)**2)) return 1 / (1 + math.exp((b.mu - a.mu) / ciq)) def pl_winp(a, b): """Win probability of player a over b given their PL ratings.""" return a / (a +...
lancepants/notes
lern/fibonacci.py
Python
gpl-3.0
857
0.015169
#!/usr/bin/python3 ''' The fibonacci series is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, 13, 21 etc. It's a common example used when learning recursion. Its inefficiency also leads to an alternate, iterative, "dynam...
ib(n-1) + fib(n-2) # Instead of recursion, iterate by populating a table using the previous two # values in said table. def fibdp(n): fibresult =
{} # populate our first two values, aka "base cases" fibresult[0] = 1 fibresult[1] = 1 for i in range(2,n): fibresult[i] = fibresult[i-1] + fibresult[i-2] return fibresult.values() # See which of these takes longer for i in range(1,40): print(fib(i)) fibdp(40)
rohitranjan1991/home-assistant
tests/components/zwave/test_light.py
Python
mit
16,201
0.000864
"""Test Z-Wave lights.""" from unittest.mock import MagicMock, patch import pytest from homeassistant.components import zwave from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_RGB_COLOR, ATTR_RGBW_COLOR, ATTR_TRANSITION, COLOR_MODE_BRIGHTNESS, COLOR_MODE_C...
LOR_MODE_COLOR_TEMP, COLOR_MODE_RGB} def test_get_device_detects_rgbw_light(mock_openzwave): """Test get_device returns a color light.""" node = MockNode(command_classes=[const.COMMAND_CLASS_SWITCH_COLOR]) value = MockVa
lue(data=0, node=node) color = MockValue(data="#0000000000", node=node) color_channels = MockValue(data=0x1D, node=node) values = MockLightValues(primary=value, color=color, color_channels=color_channels) device = light.get_device(node=node, values=values, node_config={}) device.value_added() a...
jonaustin/advisoryscan
django/tests/regressiontests/fixtures_regress/models.py
Python
mit
854
0.008197
from django.db import models class Animal(models.Model): name = models.CharField(maxlength=150) latin_name = models.CharField(maxlength=150) def __str__(self):
return self.common_name class Plant(models.Model): name = models.CharField(maxlength=150) class Meta: # For testing
when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" __test__ = {'API_TESTS':""" >>> from django.core import management # Load a fixture that uses PK=1 >>> management.load_data(['sequence'], verbosity=0) # Create a new animal. Without a sequence reset, this ne...
edgedb/edgedb
edb/schema/links.py
Python
apache-2.0
21,887
0
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http...
f'cannot implicitly resolve the ' f'`on target delete` action for ' f'{tgt_repr!r}: it is defined as {current} in ' f'{cf_repr!r} and as {theirs} in {other_repr!r}; ' f'to resolve, declare `on target delete` '...
repr!r}' ) return current else: return ours class Link( sources.Source, pointers.Pointer, s_abc.Link, qlkind=qltypes.SchemaObjectClass.LINK, data_safe=False, ): on_target_delete = so.SchemaField( LinkTargetDeleteAction, default=LinkTarge...
BFriedland/RPi-HAUS
haus_site/api/serializers.py
Python
lgpl-3.0
3,890
0.001799
from django.contrib.auth.models import User, Group from rest_framework import serializers from haus.models import Device, Atom, Data, CurrentData class AtomSerializer(serializers.ModelSerializer): class Meta: model = Atom def restore_object(self, attrs, instance=None): print("attrs == "...
Meta: model = Device def get_atoms(self, obj): return {atom.atom_name: atom.pk for atom in obj.atoms.all()} # Requires importing the models (so you can creat
e a new entry in the DB) def restore_object(self, attrs, instance=None): print("attrs == " + str(attrs)) print str(instance) if instance: self.was_created = False instance.device_name = attrs.get('device_name', instance.device_name) instance.user = att...
glogiotatidis/mozillians-new
vendor-local/lib/python/south/creator/changes.py
Python
bsd-3-clause
24,279
0.004078
""" Contains things to detect changes - either using options passed in on the commandline, or by using autodetection, etc. """ from __future__ import print_function from django.db import models from django.contrib.contenttypes.generic import GenericRelation from django.utils.datastructures import SortedDict from sou...
)) elif change_name == "Ad
dUnique": parts.append("add_unique_%s_%s" % ( params['model']._meta.object_name.lower(), "_".join([x.name for x in params['fields']]), )) elif change_name == "DeleteUnique": parts.append("del_unique_%s_%s" % ( ...
playpauseandstop/setman
testproject-django/testapp/forms.py
Python
bsd-3-clause
783
0.002554
from django import forms from django.utils.translation import ugettext_lazy as _ __all__ = ('SandboxForm', ) class SandboxForm(forms.Form): """ Simple form form "Sandbox" page. """ FORBIDDEN_SETTINGS = ( 'DATABASES', 'ODESK_PRIVATE_KEY', 'ODESK_PUBLIC_KEY', 'SECRET_KEY' ) name = for...
ame'), required=True, help_text=_('Enter name of available setting, press Enter - get ' \ 'setting value.'), widget=forms.TextInput(attrs={'size': 50})) def clean_name(self): name = self.cleaned_data['name'] if name in self.FORBIDDEN_SETTINGS: raise ...
)) return name
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/zeitgeist/datamodel.py
Python
gpl-3.0
49
0.020408
../../../
../share/pyshared/zeitgeist/datamodel.p
y
jarble/EngScript
libraries/factors.py
Python
mit
136
0.022059
def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(
1, int(n**0.5) + 1) if n % i == 0)))
lowitty/selenium
com/ericsson/xn/x/fm/TestCases/case_ltehss_fm.py
Python
mit
891
0.013468
''' Created on Mar 1, 2016 @author: eyyylll ''' import os from com.ericsson.xn.x.fm.FmCommons.GuiDataFunc import check_alarm_data_accuracy from com.ericsson.xn.commons.caseutils import pre_test_case, post_test_case root_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__))).split('com' + os.sep...
rver
_info_cfg = root_dir + "x" + os.sep + "pm" + os.sep + "execute_conf.cfg" ne_info_cfg = root_dir + "x" + os.sep + "pm" + os.sep + "nes" + os.sep + "ltehss.cfg" alarm_mapping_cfg = root_dir + "x" + os.sep + "fm" + os.sep + "gui_mapping" + os.sep + "hss.cfg" def check_ltehss_alarm_accuracy(): pre_test_case("ch...
scigghia/l10n-italy
l10n_it_ricevute_bancarie/__openerp__.py
Python
agpl-3.0
2,231
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: [email protected] # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
ndation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it w
ill 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...
jayvdb/flake8-putty
tests/__init__.py
Python
mit
44
0
# -*- coding: utf-8 -*- ""
"Test package."""
nathanbjenx/cairis
cairis/gui/RolesDialog.py
Python
apache-2.0
2,882
0.028799
# 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...
nless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import wx from cairis.core.armid import * from cairis.core.Role import Role from RoleDialog import RoleDialog from DialogClassParameters import DialogClas...
roadmapper/ansible
lib/ansible/modules/cloud/vmware/vmware_export_ovf.py
Python
gpl-3.0
15,634
0.00339
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # Copyright: (c) 2018, Diane Wang <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSI...
) self.mf_file = '' self.ovf_dir = '' # set read device content chunk size to 2 MB self.chunk_size = 2 * 2 ** 20 # set lease progress update interval to 15 seconds self.lease_interval = 15 self.facts = {'device_files': []} self.download_timeout = None ...
try: os.makedirs(self.ovf_dir) except OSError as err: self.module.fail_json(msg='Exception caught when create folder %s, with error %s' % (self.ovf_dir, to_text(err))) self.mf_file = os.path.join(self.ovf_dir, vm_obj.name +...
itkvideo/ITK
Wrapping/WrapITK/Languages/Python/Tests/SmoothingRecursiveGaussianImageFilter.py
Python
apache-2.0
1,074
0.011173
#========================================================================== # # Copyright Insight Software Consort
ium # # 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.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, #...
NeuroRoboticTech/Jetduino
Software/Python/grove_sound_sensor.py
Python
mit
2,624
0.003049
#!/usr/bin/env python # # Jetduino Example for using the Grove Sound Sensor and the Grove LED # # The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino # # Modules: # http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor # ht...
OF MERCHAN
TABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR...
allisnone/pytrade
position_history_update.py
Python
gpl-2.0
22,677
0.016749
# -*- coding:utf-8 -*- # !/usr/bin/env python #import easytrader import easyhistory import pdSql_common as pds from pdSql import StockSQL import sys import datetime from pytrade_api import * from multiprocessing import Pool import os, time import file_config as fc import code stock_sql_obj=StockSQL(s...
th('1') or code.startswith('5'): funds.append(code) pds.update_codes_from_YH(funds,realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=True) elif update_type == 'position': #更新仓位 #stock_sql.update_sql_position(users={'36005':{'broker':'yh','json':'yh...
stock_sql.update_sql_position(users={'account':'38736','broker':'yh','json':'yh1.json'}) hold_df,hold_stocks,available_sells = stock_sql.get_hold_stocks(accounts = ['36005', '38736']) print('hold_stocks=',hold_stocks) print(hold_df) elif update_type == 'stock': #从新浪 qq...
Pr0Ger/SGSB
plugins/Cogs.py
Python
mit
526
0.001901
import os from lib.base_plugin import BasePlugin from lib.paths import SteamCloudPath, SteamGamesPath class CogsPlugin(BasePlugin): Name = "Cogs" support_os = ["Windows"] def backup(self, _): _.add_folder('Data', os.path.join(SteamCloudPath, '26500'), 'remote') def restore(self, _):
_.restore_folder('Data', os.path.join(
SteamCloudPath, '26500'), 'remote') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'cogs')): return True return False
pennersr/django-allauth
allauth/account/models.py
Python
mit
5,643
0.000709
import datetime from django.core import signing from django.db import models, transaction from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .. import app_settings as allauth_app_settings from . import app_settings, signals from .adapter import get_adapter from .managers imp...
ld(verbose_name=_("verified"), default=False) primary = models.BooleanField(verbose_n
ame=_("primary"), default=False) objects = EmailAddressManager() class Meta: verbose_name = _("email address") verbose_name_plural = _("email addresses") if not app_settings.UNIQUE_EMAIL: unique_together = [("user", "email")] def __str__(self): return self.emai...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/DataHandlers/Mcl_Cmd_NetBios_DataHandler.py
Python
unlicense
13,809
0.001521
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: Mcl_Cmd_NetBios_DataHandler.py def DataHandlerMain(namespace, InputFilename, OutputFilename): import mcl.imports import mcl.data.Input ...
SCLOSED: return 'The session was closed' if error == RESULT_NRC_CMDCAN: return 'The command was canceled' if error == RESULT_NRC_DUPNAME: return 'A duplicate name existed in the local name table' if error == RESULT_NRC_NAMTFUL: return 'The name ta
ble was full' if error == RESULT_NRC_ACTSES: return 'The command finished; the name has active sessions and is no longer registered' if error == RESULT_NRC_LOCTFUL: return 'The local session table was full' if error == RESULT_NRC_REMTFUL: return 'The remote se...
pigmej/uwsgi_no_pp
plugins/pypy/pypy_setup.py
Python
gpl-2.0
29,660
0.002293
import sys import os sys.path.insert(0, '.') sys.path.extend(os.environ.get('PYTHONPATH', '').split(os.pathsep)) import imp import traceback __name__ = '__main__' mainmodule = type(sys)('__main__') sys.modules['__main__'] = mainmodule import cffi # this is a list holding object we do not want to be freed (like call...
_hook_request)(struct wsgi_request *); void (*uwsgi_pypy_post_fork_hook)(void); ''' # here we load CFLAGS and uwsgi.h from the binary defines0 = ''' char *uwsgi_get_cflags(); char *uwsgi_get_dot_h(); ''' ffi.cdef(defines0) lib0 = ffi.verify(defines0) # this is ugly, we should find a better approach # basically it bu...
wsgi_cflags: if cflag.startswith('-D'): line = cflag[2:] if '=' in line: (key, value) = line.split('=', 1) uwsgi_cdef.append('#define %s ...' % key) uwsgi_defines.append('#define %s %s' % (key, value.replace('\\"', '"').replace('""', '"'))) else: ...
daicang/Euler
p47.py
Python
mit
702
0.002849
# Problem 47 # First number of first 4 consecutive numbers to have 4 distictive prime factors each import ite
rtools from prime import prime class Solve(object): def __init__(self): pass def solve(self): def satisfy(x): """ Test if x has four distinctive prime factors """ return len(prime.prime_factor(x)) == 4 prev_satisfy_counter = 0 ...
rtools.count(start=600): if satisfy(i): prev_satisfy_counter += 1 if prev_satisfy_counter == 4: return i - 3 else: prev_satisfy_counter = 0 s = Solve() print s.solve()
ssssam/nightbus
nightbus/tasks.py
Python
apache-2.0
12,497
0.00056
# Copyright 2017 Codethink Ltd. # # 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 writin...
value(pair[1]) for pair in combo} this_parameter_reprs = [param_repr(pair[1]) for pair in combo] this_name = '.'.join([task_base_name] + this_parameter_reprs) tasks.append(Task(entry, name=this_name, defaults=defaults,
parameters=this_parameters)) else: tasks = [Task(entry, defaults=defaults)] return tasks def names(self): return [task.name for task in self] class TaskResult(): '''Results of executing a one task on one host.''' def __init__(self, name, host, duration=Non...
yosshy/nova
nova/api/openstack/compute/server_usage.py
Python
apache-2.0
2,859
0
# Copyright 2013 OpenStack Foundation # # 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...
nsions.os_compute_soft_authorizer(ALIAS) resp_topic = "OS-SRV-USG" class ServerUsageController(wsgi.Controller): def __init__(self, *args, **kwargs):
super(ServerUsageController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _extend_server(self, server, instance): for k in ['launched_at', 'terminated_at']: key = "%s:%s" % (resp_topic, k) # NOTE(danms): Historically, this timestamp has been generated...
DavidMcDonald1993/ghsom
parameter_tests.py
Python
gpl-2.0
6,711
0.013709
# coding: utf-8 # In[12]: import os from shutil import copyfile import subprocess from save_embedded_graph27 import main_binary as embed_main from spearmint_ghsom import main as ghsom_main import numpy as np import pickle from time import time def save_obj(obj, name): with open(name + '.pkl', 'wb...
ithm: {}'.format(running_time) running_times[r-1] = running_time #save save_obj(nmi_scores, 'nmi_scores') save_obj(running_times, 'running_times') print 'saved nmi score for network {}: {}'.format(gml_filename, nmi_score) ...
nning times to file' np.savetxt('nmi_scores.csv',nmi_scores,delimiter=',') np.savetxt('running_times.csv',running_times,delimiter=',') print print 'DONE' print 'OVERALL NMI SCORES' print overall_nmi_scores # In[9]: for i in range(len(num_communities)): for j in range(l...
andree1320z/deport-upao-web
deport_upao/core/forms.py
Python
mit
224
0
from django import forms class ContactForm(forms.Form): n
ame = forms.CharField(label='Nombre', max_length=100) file = forms.ImageField(label='Imagen
') message = forms.CharField(label='Mensaje', max_length=100)
ThomasSweijen/yadesolute2
py/utils.py
Python
gpl-2.0
47,303
0.043089
# encoding: utf-8 # # utility functions for yade # # 2008-2009 © Václav Šmilauer <[email protected]> """Heap of functions that don't (yet) fit anywhere else. Devs: please DO NOT ADD more functions here, it is getting too crowded! """ import math,random,doctest,geom,numpy from yade import * from yade.wrapper import * ...
ynamic=%s is deprecated, use fixed=%s instead'%(str(dynamic),str(not dynamic)),category=DeprecationWarning,stacklevel=2) fixed=not dynamic b.state.blockedDOFs=('xyzXYZ' if fixed else '') def sphere(center,radius,dynamic=None,fixed=False,w
ire=False,color=None,highlight=False,material=-1,mask=1): """Create sphere with given parameters; mass and inertia computed automatically. Last assigned material is used by default (*material* = -1), and utils.defaultMaterial() will be used if no material is defined at all. :param Vector3 center: center :param fl...
loktacar/wallpapermaker
plugins/simple_resize/simple_resize.py
Python
mit
734
0.004087
import logging import pygame from .. import Collage class SimpleResize(Collage): """ Example class for collage plugins - Takes a single image and res
izes it """ name = 'sim
ple resize' def __init__(self, config): super(SimpleResize, self).__init__(config) def generate(self, size): wallpapers = self._get_wallpapers() logging.debug('Generating...') collage = pygame.Surface(size) wp_offset, wp = self._resize_wallpaper(wallpapers[0], size) ...
Ultimaker/Cura
cmake/mod_bundled_packages_json.py
Python
lgpl-3.0
2,593
0.015812
#!/usr/bin/env python3 # # This script removes the given package entries in the bundled_packages JSON files. This is used by the PluginInstall # CMake module. # import argparse import collections import json import os import sys def find_json_files(work_dir: str) -> list: """Finds all JSON files in the given dir...
raise IOError(msg) def main() -> None: parser = argparse.ArgumentParser("mod_bundled_packages_json") parser.add_argument("-d", "--dir", dest = "work_dir", help = "The directory to l
ook for bundled packages JSON files, recursively.") parser.add_argument("entries", metavar = "ENTRIES", type = str, nargs = "+") args = parser.parse_args() json_file_list = find_json_files(args.work_dir) for json_file_path in json_file_list: remove_entries_from_json_file(json_file_path, args.e...
cescudero/ptavi-p2
calcplusplus.py
Python
gpl-2.0
1,398
0.001432
#!/usr/bin/python3 # -*- coding: utf-8 -*-ç import sys import calcoo import calcoohija import csv if __name__ == "__main__": calc = calcoohija.CalculadoraHija() with open(sys.argv[1]) as fichero: reader = csv.reader(fichero) for operandos in reader: operacion = operandos[0] ...
ero)) print (resultado) elif operacion == "divide": resultado = calc.division(int(operandos[1]),
int(operandos[2])) for numero in operandos[3:]: resultado = calc.division(int(resultado), int(numero)) print (resultado)
dmangot/devops-certifyme
gendocert.py
Python
mit
2,175
0.005057
#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def get_brooklyn_integer(): ''' Ask Brooklyn Integers for a single i
nteger. Returns a tuple with number and integer permalink. From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Ty
pe': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data ...
allenai/allennlp
tests/modules/seq2seq_encoders/pytorch_seq2seq_wrapper_test.py
Python
apache-2.0
8,239
0.002913
import numpy from numpy.testing import assert_almost_equal import pytest import torch from torch.nn import LSTM, GRU from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.modules....
sequence_lengths = [4, 6, 7] states = [] for batch_size, sequence_length in zip(batch_sizes, sequence_lengths): tensor = torch.rand([batch_size, sequence_length, 3]) mas
k = torch.ones(batch_size, sequence_length).bool() mask.data[0, 3:] = 0 encoder_output = encoder(tensor, mask) states.append(encoder._states) # Check that the output is masked properly. assert_almost_equal(encoder_output[0, 3:, :].data.numpy(), numpy.zeros((4, 14))) ...
ShengRang/c4f
leetcode/rotate-list.py
Python
gpl-3.0
617
0.027553
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object):
def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ xs = [] p = head while p: xs.
append(p.val) p = p.next if not xs: return None k = k % len(xs) xs = xs[-k:] + xs[:-k] p = None while xs: np = ListNode(xs.pop()) np.next = p p = np return p
dracos/django
django/shortcuts.py
Python
bsd-3-clause
5,580
0.001613
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ import warnings from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from dj...
return queryset.get(*args, **kwargs) except AttributeError: klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, " "or QuerySet, not '%s'." % klass__name ) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) def get_list_or_404(klass, *args, **kwargs): ...
faizan-barmawer/openstack_ironic
ironic/drivers/modules/drac/client.py
Python
apache-2.0
4,315
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...
Filter Dialects, see (Section 2.3.1): # http://en.community.dell.com/techcenter/extras/m/white_papers/20439105.aspx _FILTER_DIALECT_MAP = {'cql': 'http://schemas.dmtf.org/wbem/cql/1/dsp0202.pdf', 'wql': 'http://schemas.microsoft.com/wbem/wsman/1/WQL'} class Client(object): def __init__(se...
ac_username, drac_password): pywsman_client = pywsman.Client(drac_host, drac_port, drac_path, drac_protocol, drac_username, drac_password) # TODO(ifarkas): Add support for CACerts pywsman.wsman_transport_set_verify_p...
avian2/unidecode
unidecode/x077.py
Python
gpl-2.0
4,673
0.054783
data = ( 'Ming ', # 0x00 'Sheng ', # 0x01 'Shi ', # 0x02 'Yun ', # 0x03 'Mian ', # 0x04 'Pan ', # 0x05 'Fang ', # 0x06 'Miao ', # 0x07 'Dan ', # 0x08 'Mei ', # 0x09 'Mao ', # 0x0a 'Kan ', # 0x0b 'Xian ', # 0x0c 'Ou ', # 0x0d 'Shi ', # 0x0e 'Yang ', # 0x0f 'Zheng ', # 0...
', # 0x8e 'Qiong ', # 0x8f 'Mao ', # 0x90 'Ming ', # 0x91 'Man ', # 0x92 'Shui ', # 0x93 'Ze ', # 0x94 'Zhang ', # 0x95 'Yi ', # 0x96 'Diao ', # 0x97 'Ou ', # 0x98 'Mo ', # 0x99 'Shun ', # 0x9a 'Co
ng ', # 0x9b 'Lou ', # 0x9c 'Chi ', # 0x9d 'Man ', # 0x9e 'Piao ', # 0x9f 'Cheng ', # 0xa0 'Ji ', # 0xa1 'Meng ', # 0xa2 None, # 0xa3 'Run ', # 0xa4 'Pie ', # 0xa5 'Xi ', # 0xa6 'Qiao ', # 0xa7 'Pu ', # 0xa8 'Zhu ', # 0xa9 'Deng ', # 0xaa 'Shen ', # 0xab 'Shun ', # ...
Elchi3/kuma
kuma/scrape/fixture.py
Python
mpl-2.0
10,807
0.000833
"""Load test fixtures from a specification.""" import logging from django.apps import apps from django.contrib.auth.hashers import make_password logger = logging.getLogger("kuma.scraper") class FixtureLoader(object): """Load fixtures into the current database.""" # Needed information about the supported ...
logger.debug( "%s %s requires %s %s", model_i
d, item["key"], relation["resource"], key, ) pending += 1 else: self.instances[model_id][item["key"]] = instance loaded ...
ChristianAnthony46/PomegranateCMYK
Channel.py
Python
gpl-3.0
314
0.006369
from PIL import Image class Channel: def __init__(self, channelLabel, size): self.channelLabel = channelLabel self.channel = Image.new("CMYK", (size[0], size[1]), "black") self.pixelMap = self.c
hannel.load() def save(self, filen
ame): self.channel.save(filename)
TomAugspurger/pandas
pandas/tests/test_join.py
Python
bsd-3-clause
9,296
0
import numpy as np import pytest from pandas._libs import join as _join from pandas import Categorical, DataFrame, Index, merge import pandas._testing as tm class TestIndexer: @pytest.mark.parametrize( "dtype", ["int32", "int64", "float32", "float64", "object"] ) def test_outer_join_indexer(self...
assert_numpy_array_equal(ares, np.array([0], dtype=np.int64)) tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.int64)) def test_left_join_indexer2(): idx = Index([1, 1, 2, 5]) idx
2 = Index([1, 2, 5, 7, 9]) res, lidx, ridx = _join.left_join_indexer(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) tm.assert_almost_equal(res, exp_res) exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.int64) tm.assert_almost_equal(lidx, exp_lidx) exp_ridx = ...
rwightman/pytorch-image-models
timm/models/convmixer.py
Python
apache-2.0
3,631
0.004682
import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.registry import register_model from .helpers import build_model_with_cfg def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, ...
d/timm-v1.0/convmixer_1024_20_ks9_p14.pth.tar') } class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x): return self.fn(x) + x class ConvMixer(nn.Module):
def __init__(self, dim, depth, kernel_size=9, patch_size=7, in_chans=3, num_classes=1000, activation=nn.GELU, **kwargs): super().__init__() self.num_classes = num_classes self.num_features = dim self.head = nn.Linear(dim, num_classes) if num_classes > 0 else nn.Identity() self...
rdo-infra/ci-config
ci-scripts/infra-setup/roles/rrcockpit/files/telegraf_py3/vexxhost.py
Python
apache-2.0
5,854
0
#!/usr/bin/env python import argparse import datetime import json import os import re import subprocess import time # This file is running on toolbox periodically FILE_PATH = 'influxdb_stats_vexx' SECRETS = "/etc/vexxhostrc" re_ex = re.compile(r"^export ([^\s=]+)=(\S+)") def _run_cmd(cmd): env = os.environ.copy...
uxdb_data def write_influxdb_file(webdir, influxdb_data): with open(os.path.join(webdir, FILE_PATH), "w") as f: f.write(influxdb_data)
def main(): parser = argparse.ArgumentParser( description="Retrieve cloud statistics") parser.add_argument( '--webdir', default="/var/www/html/", help="(default: %(default)s)") args = parser.parse_args() servers = run_server_check() quotes = run_quote_check() stacks = run_st...
anupam-mitra/PySpikeSort
spikesort/cluster/__init__.py
Python
gpl-3.0
2,703
0.007769
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ${FILENAME} # # Copyright 2015 Anupam Mitra <[email protected]> # # 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...
out even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import numpy as np import sklear...
amadeusproject/amadeuslms
banco_questoes/serializers.py
Python
gpl-2.0
5,241
0.009593
""" Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela ...
recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENSE", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA. """ import os import zipfile import time from django.db.models import Q from django.conf import settings from django.core.files import File from django.shortcuts import get_object_or_404 from rest_framework import serializers from subjects.serializers import TagSerializer from su...
y-sira/atcoder
abc002/a.py
Python
mit
51
0
x, y = map(int, inpu
t().split()) print(ma
x(x, y))
qtumproject/qtum
contrib/linearize/linearize-data.py
Python
mit
13,632
0.003301
#!/usr/bin/env python3 # # linearize-data.py: Construct a linear, no-fork version of the chain. # # Copyright (c) 2013-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import struct import re impo...
self.outF.write(rawblock) self.outsz = self.outsz + len(inh
dr) + len(blk_hdr) + len(rawblock) self.blkCountOut = self.blkCountOut + 1 if blkTS > self.highTS: self.highTS = blkTS if (self.blkCountOut % 1000) == 0: print('%i blocks scanned, %i blocks written (of %i, %.1f%% complete)' % (self.blkCountIn, self.b...
skewerr/deskbot
modules/commands/tell.py
Python
bsd-3-clause
4,602
0.026728
import re from .. import irc, var, ini from ..tools import is_identified # Require identification with NickServ to send messages. def ident (f): def check (user, channel, word): if is_identified(user): f(user, channel, word) else: irc.msg(channel, "{}: Identify with NickServ first.".format(user)) return c...
ir[0], pair[1]) for pair in var.data["messages"][target]] ini.add_to_ini("Messages", target, "\n".join(message_list), "messages.ini") irc.msg(channel, "{}: Message stored.".format(user)) # Send a user stored
messages. def send_messages (user): # Be case insensitive, please. for nick in var.data["messages"]: if user.lower() == nick.lower(): user = nick # There's no use going on if the user isn't in the messages database. if user not in var.data["messages"]: return if len(var.data["messages"][user]) > 4: # S...
ywangd/stash
bin/gh.py
Python
mit
6,911
0.011431
# coding: utf-8 ''' Usage: gh <command> [<args>...] gh <command> (-h|--help) supported commands are: gh fork <repo> forks user/repo gh create <repo> creates a new repo gh pull <repo> <base> <head> create a pull request gh list_keys list user keys gh create_key <title> [<public_key_path>] add a key to gi...
= ':'.join([headowner, headbranch]) pullreq = baserepo.create_pull(**kwargs) print('Created pull %s' % pullreq.html_url) print('Commits:') print([(x.sha, x.commit.message) for x in pullreq.get_commits()]) print('Changed Files:') print([x.filename for x in pullreq.get_fi...
@command def gh_list_keys(args): '''Usage: gh list_keys [options] Options: -h, --help This message List keys ''' g, u = setup_gh() for key in u.get_keys(): print('{}:\n {}\n'.format(key.title, key.key)) @command def gh_create_key(args): '''Usage: gh create_key <title> [<publi...
ksetyadi/Sahana-Eden
controllers/org.py
Python
mit
9,210
0.008686
# -*- coding: utf-8 -*- """ Organisation Registry - Controllers @author: Fran Boon @author: Michael Howden """ prefix = request.controller resourcename = request.function if prefix not in deployment_settings.modules: session.error = T("Module disabled!") redirect(URL(r=request, c="default", f="inde...
they will - uncomment this and comment the next one #if r.method in ("create", "update"): if r.method == "create": # person_id mandatory for a staff! table.person_id.requires = IS_ONE_OF_EMPTY
(db, "pr_person.id") table.organisation_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "org_organisation.id")) table.office_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "org_office.id")) return True response.s3.prep = prep return s3_rest_controller(prefix, resourcename) #=======...
avatartwo/avatar2
avatar2/targets/jlink_target.py
Python
apache-2.0
1,183
0.003381
import sys from avatar2.targets import Target, TargetStates from avatar2.protocols.jlink import JLinkProtocol from avatar2.watchmen import watch if sys.version_info < (3, 0): from Queue import PriorityQueue else: from queue import PriorityQueue class JLinkTarget(Target
): def __init__(self, avatar, serial, device, **kwargs): """ Create a JLink target instance :param avatar: The avatar instance :param serial: The JLink's serial number :param device: The Device string to use (e.g., ARM7, see JlinkExe for the list) :param kwargs: ...
) self.avatar = avatar self.serial = serial self.device = device @watch("TargetInit") def init(self): jlink = JLinkProtocol(serial=self.serial, device=self.device, avatar=self.avatar, origin=self) self.protocols.set_all(jlink) if jlink.jlink.halted(): ...
MaxMorgenstern/EmeraldAI
EmeraldAI/Pipelines/ResponseProcessing/__init__.py
Python
apache-2.0
30
0
__al
l__ = ["ProcessRe
sponse"]
pouyaAB/ros_teleoperate
CPR_mover/setup.py
Python
mit
391
0.002558
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup # fetch values from package.xml setup_args = generate_distutils_setup( pa
ckages=['cpr_mover_controller'], package_dir={'': 'scripts'}, requires=['std_msgs', 'rospy', 'geomet
ry_msgs', 'sensor_msgs'] ) setup(**setup_args)
MostlyOpen/odoo_addons
myo_event/models/annotation.py
Python
agpl-3.0
1,400
0
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public L
icense 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 im
plied 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/>. # #################################...
Auzzy/pyinq
examples/suite_class_tests.py
Python
isc
407
0.066339
from pyinq.tags import * @testClass(suite="suite1") class Class1(object): @test def test1
(): assert True @test def test2(): assert True @testClass(suite="suite2") class Class2(object): @test(suite="suite1") def test3(): assert True @test(suite="suite2") def test4(): assert True @testClass class Class3(object): @test def test5(): assert True @test def test6(): assert True
TalentedComponent/SDC
click_and_crop.py
Python
gpl-3.0
1,905
0.032021
# import the necessary packages import argparse import cv2 # initialize the list of reference points and boolean indicating # whether croppi
ng is being performed or not refPt = [] cropping =
False def click_and_crop(event, x, y, flags, param): # grab references to the global variables global refPt, cropping # if the left mouse button was clicked, record the starting # (x, y) coordinates and indicate that cropping is being # performed if event == cv2.EVENT_LBUTTONDOWN: refPt = [(x, y)] croppi...
tuomasjjrasanen/t2jrbot
lib/plugins/command.py
Python
gpl-3.0
4,817
0.001246
# -*- coding: utf-8 -*- # Command plugin for t2jrbot. # Copyright © 2014 Tuomas Räsänen <[email protected]> # # 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 Licen...
del self.__command_handlers[command] except KeyError: raise Error("command '%s' is not registered" % command) del self.__command_descriptions[command] def __irc_privmsg(self
, prefix, this_command, params): nick, sep, host = prefix.partition("!") target, text = params if target == self.__bot.nick: # User-private messages are not supported and are silently # ignored. return channel = target # Ignore all leading ...
andrewyoung1991/abjad
abjad/tools/scoretools/__init__.py
Python
gpl-3.0
278
0.014388
# -*-
encoding: utf-8 -*- '''Dependencies: The ``scoretools`` package should not import ``instrumenttools`` at top level. ''' fr
om abjad.tools import systemtools systemtools.ImportManager.import_structured_package( __path__[0], globals(), ) _documentation_section = 'core'
yfilali/graphql-pynamodb
examples/flask_pynamodb/app.py
Python
mit
552
0.001812
from database import init_db from flask import Flask from flask_graphql import GraphQLView from schema import schema app = Flask(__name__) app.debug = True
default_query = ''' { allEmployees { edges { node { id, name, department { id, name }
, role { id, name } } } } }'''.strip() app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True)) if __name__ == '__main__': init_db() app.run()
alexpilotti/python-glanceclient
glanceclient/common/progressbar.py
Python
apache-2.0
3,171
0
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
ce a progress bar whenever data is consumed from the iterator. :note: Use only with iterator that yield strings. """ def __iter__(self): return self def next(self): try: data = six.next(self._wrapped) # NOTE(mouad): Assuming that data is a string b/c otherw...
# len function will not make any sense. self._display_progress_bar(len(data)) return data except StopIteration: if self._show_progress: # Break to a new line from the progress bar for incoming # output. sys.stdout.write('\n')...
jailuthra/onetimepad
onetimepad.py
Python
mit
2,562
0.005855
#!/usr/bin/env python3 # Copyright (C) 2013-2014 Jai Luthra <[email protected]> # See LICENSE file for more details '''En
crypt or Decrypt data using One-Time Pad''' import binascii, argparse, itertools def main(): parser = argparse.ArgumentParser( description='Encrypt or Decrypt data using One-Time Pad') parser.add_argument('-d', '--decrypt', action='store_true', help='Decrypt data (default is to encrypt...
args.filename # Decrypt Mode if args.decrypt: if fname == None: cipher = input('Cipher: ') key = input('Key: ') print('Message:', decrypt(cipher, key)) else: # Read from a file with open(fname, 'r') as cryptfile: key = input('Key: ...
RDFLib/rdflib
rdflib/graph.py
Python
bsd-3-clause
84,117
0.001034
from typing import ( IO, Any, BinaryIO, Iterable, Optional, TextIO, Union, Type, cast, overload, Generator, Tuple, ) import logging from warnings import warn import random from rdflib.namespace import Namespace, RDF from rdflib import plugin, exceptions, query, namespace ...
dflib.graph.Graph'>)> >>> g1.add((stmt1, RDF.subject, ... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS <Graph identifier=... (<class 'r...
<Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS <Graph identifier=... (<class 'rdflib.graph.Graph'>)> >>> g2.add((stmt2, RDF.subject, ... URIRef('http://rdflib.net/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS <Graph ...
danpoland/pyramid-restful-framework
pyramid_restful/pagination/utilities.py
Python
bsd-2-clause
964
0
from pyramid.compat import urlparse def replace_query_param(url, key, val): """ Given a URL and a key/val pair, set or replace an item in the query parameters of the URL, and return the new URL. """ (scheme, netloc, path, query, fragment) = urlparse.urlsplit(url) query_dict = urlparse.parse_q...
ir, remove an item in the query parameters of the URL, and return the new URL. """ (scheme, netloc, path, que
ry, fragment) = urlparse.urlsplit(url) query_dict = urlparse.parse_qs(query) query_dict.pop(key, None) query = urlparse.urlencode(sorted(list(query_dict.items())), doseq=True) return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
itucsdb1611/itucsdb1611
templates_operations/personal/default.py
Python
gpl-3.0
8,587
0.005008
from flask import render_template from flask import url_for from flask import redirect from flask import request from datetime import datetime from flask_login import current_user, login_required from classes.operations.person_operations import person_operations from classes.operations.project_operations import project...
followed_person_operations from classes.operations.personComment_operations import personComment_operations from classes.look_up_tables import * from classes.person import Person from classes.operations.followed_project_operations import followed_project_operations from classes.followed_project import FollowedProject f...
cation_operations from classes.operations.skill_operations import skill_operations from classes.operations.Experience_operations import experience_operations from classes.operations.information_operations import information_operations from classes.operations.language_operations import language_operations from classes.o...
Mitali-Sodhi/CodeLingo
Dataset/python/test_utils_sitemap.py
Python
mit
5,404
0.003331
import unittest from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots class SitemapTest(unittest.TestCase): def test_sitemap(self): s = Sitemap("""<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.google.com/schemas/sitemap/0.84"> <url> <loc>http://www.example.com/</loc>...
def test_sitemap_strip(self): """Assert we can deal with trailing spaces inside <loc> tags - we've seen those """
s = Sitemap("""<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.google.com/schemas/sitemap/0.84"> <url> <loc> http://www.example.com/</loc> <lastmod>2009-08-16</lastmod> <changefreq>daily</changefreq> <priority>1</priority> </url> <url> <loc> http://www.example.com/2</l...
kumar303/rockit
vendor-local/boto/cloudformation/template.py
Python
bsd-3-clause
1,318
0.002276
from boto.resultset import ResultSet class Template: def __init__(self, connection=None): self.connection = connection self.description = None self.template_parameters = None def startElement(self, name, attrs, connection): if name == "Parameters": self.template_par...
self.description = value else: setattr(self, name, value) class TemplateParameter: def __init__(self, parent): self.parent = parent self.default_value = None self.descriptio
n = None self.no_echo = None self.parameter_key = None def startElement(self, name, attrs, connection): return None def endElement(self, name, value, connection): if name == "DefaultValue": self.default_value = value elif name == "Description": s...
jirikuncar/invenio-demosite
invenio_demosite/base/recordext/functions/get_creation_date.py
Python
gpl-2.0
1,041
0.012488
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) a...
ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. de...
aram recid: @return: Creation date """ from invenio.modules.records.models import Record as Bibrec return Bibrec.query.get(recid).creation_date
michogar/FullDiskAlert
setup.py
Python
gpl-3.0
399
0.002506
__a
uthor__ = 'michogarcia' from setuptools import setup, find_packages version = '0.1' setup(name='FullDiskAlert', version=version, author="Micho Garcia", author_email="[email protected]", license="LICENSE.txt", description="Sends mail when disk is above threshold", packages=fi...
)
insomnia-lab/libreant
webant/agherant_standalone.py
Python
agpl-3.0
591
0
from flask import Flask, request from flask_bootstrap import Bootstrap from flask_babel import Babel import agherant from webserver_utils import gevent_run def create_app(conf): app = Flask(__name__) app.config.update(conf) Bootstrap(app) babel = Babel(app) app.register_blueprint(agherant.agheran...
p = create_app(conf) gevent_run(
app) if __name__ == '__main__': main()
nazrulworld/mailbox
application/validators.py
Python
mit
565
0.00354
# _*_
coding: utf-8 _*_ __author__ = 'nis
lam <[email protected]>' import re from wtforms.validators import ValidationError class EmailProviders(object): def __init__(self, message=None): if message is None: message = u'We are only accept Gmail or Yahoo or AOL or Outlook' self.message = message self.pattern = r...
tyarkoni/pliers
pliers/extractors/audio.py
Python
bsd-3-clause
23,156
0.002202
''' Extractors that operate on AudioStim inputs. ''' from abc import ABCMeta from os import path import sys import logging import numpy as np from scipy import fft import pandas as pd from pliers.stimuli.audio import AudioStim from pliers.stimuli.text import ComplexTextStim from pliers.extractors.base import Extract...
ctor(Extractor): ''' Base Audio Extractor class; all subclasses can only be applied to audio. ''' _inpu
t_type = AudioStim class STFTAudioExtractor(AudioExtractor): ''' Short-time Fourier Transform extractor. Args: frame_size (float): The width of the frame/window to apply an FFT to, in seconds. hop_size (float): The step size to increment the window by on each iteratio...
lgrech/MapperPy
mapperpy/attributes_util.py
Python
bsd-3-clause
1,031
0.00194
import inspect def get_attributes(obj): if isinstance(obj, dict): return obj.keys(
) attributes = inspect.getmembers(obj, lambda a: not(inspect.isroutine(a
))) return [attr[0] for attr in attributes if not(attr[0].startswith('__') and attr[0].endswith('__'))] class AttributesCache(object): def __init__(self, get_attributes_func=get_attributes): self.__cached_class = None self.__cached_class_attrs = None self.__get_attributes_func = get_a...
daniel-yavorovich/django-redmine-auth-backend
setup.py
Python
apache-2.0
382
0
from distutils.core import setup setup( name='django-redmine-auth-backend', version='0.1', packa
ges=['redmine_auth'], url='https://github.com/daniel-yavorovich/django-redmine-auth-backend', license='Apac
he V2 License', author='daniel', author_email='[email protected]', description='A Django authentication backend for use with the Redmine' )
frrmack/CallofCthulhu
cardheap.py
Python
mit
6,455
0.010225
from card import Card from util import * from layout import * import pygame class CardHeap(list): # A pile of cards def __init__(self): list.__init__(self) #-- Actions def add(self, card): self.append(card) card.position = self def remove(self, card): ...
(x,y,w,h) return self.rect def draw(self): self.screen = self.player.game.screen x,y,w,h = self.get_rect() x = x + w - DISCARDHEIGHT if len(self) > 1: step = (w-DI
SCARDHEIGHT)//(len(self)-1) step = min(step, DISCARDSTEP) else: step = DISCARDSTEP if self.player.position == "Player 1": for i in range(len(self)): pos = (x - step*i, y) self[i].image.draw(pos) elif self.player.position == "Pla...
Tefx/turnip
storage/auth/baidu_auth.py
Python
gpl-2.0
1,525
0.03541
import httplib import urllib import json client_id = "UkDnoQzEWYdVMkvbtQeNfP0B" client_secret = "LoooyWceGKIrxNyG0niwiwjCYLB8X0xw" parameters_code = {"client_id": client_id, "response_type": "device_code", "scope": "netdisk"} parameters_token = {"grant_type": "device_token", "code": ...
"] conn = httplib.HTTPSConnection("openapi.baidu.com") conn.request("GET", "/oauth/2.0/token?%s" % urllib.urlencode(parameters_token)) response = conn.getresponse() return json.loads(response.read()) def auth(): code = get_code() if "error" in code: print "Get User Code failed: [%s] %s" % (code["error"], code[...
description"]) return print "Your User Code is: %s" % code["user_code"] print "Please open %s to finish the authorization" % code["verification_url"] raw_input("And press any key to continue...") token = get_token(code) if "error" in token: print "Get Access Token failed: [%s] %s" % (token["error"], token["err...
foursquare/pants
tests/python/pants_test/backend/jvm/tasks/false.py
Python
apache-2.0
330
0.006061
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licen
sed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import sys #This works just like /bin/false, but Windows users might not have that sys.ex
it(1)