repo_name stringlengths 7 94 | repo_path stringlengths 4 237 | repo_head_hexsha stringlengths 40 40 | content stringlengths 10 680k | apis stringlengths 2 680k |
|---|---|---|---|---|
mark-nicholson/python-editline | examples/elCmd.py | c23f1071c4b832a92f66e2f49142e5c5f00e500d | """A generic class to build line-oriented command interpreters.
Interpreters constructed with this class obey the following conventions:
1. End of file on input is processed as the command 'EOF'.
2. A command is parsed out of each line by collecting the prefix composed
of characters in the identchars member.
3. A ... | [((7848, 7859), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (7856, 7859), False, 'import string, sys\n'), ((14928, 14946), 'sys.modules.keys', 'sys.modules.keys', ([], {}), '()\n', (14944, 14946), False, 'import string, sys\n'), ((4270, 4331), 'editline.editline', 'editline.editline', (['"""CMD"""', 'self.stdin', '... |
Shanu85/FCS_Project | ecommerce-website/orders/admin.py | def3437d58b4d2ff00e26c0a5ca769af66eccfad | from django.contrib import admin
from .models import Order, receiverInfo
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
date_hierarchy = 'created_at'
list_display = ('user', 'code', 'total_price', 'shipping_status', 'created_at')
list_display_links = ('user',)
list_editable = ('shipping_s... | [((77, 98), 'django.contrib.admin.register', 'admin.register', (['Order'], {}), '(Order)\n', (91, 98), False, 'from django.contrib import admin\n'), ((715, 743), 'django.contrib.admin.register', 'admin.register', (['receiverInfo'], {}), '(receiverInfo)\n', (729, 743), False, 'from django.contrib import admin\n')] |
jeremyCtown/data-structures-and-algorithms | data_structures/linked_lists/ll-kth-from-end/ll_kth.py | d4ba8741f858fb5298f8ce560240373fb7742e20 | from node import Node
class LinkedList:
"""
initializes LL
"""
def __init__(self, iter=[]):
self.head = None
self._size = 0
for item in reversed(iter):
self.insert(item)
def __repr__(self):
"""
assumes head will have a val and we will need this... | [((688, 708), 'node.Node', 'Node', (['val', 'self.head'], {}), '(val, self.head)\n', (692, 708), False, 'from node import Node\n'), ((846, 861), 'node.Node', 'Node', (['val', 'None'], {}), '(val, None)\n', (850, 861), False, 'from node import Node\n'), ((1312, 1325), 'node.Node', 'Node', (['new_val'], {}), '(new_val)\n... |
ckamtsikis/cmssw | MuonAnalysis/MomentumScaleCalibration/test/LikelihoodPdfDBReader_cfg.py | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | import FWCore.ParameterSet.Config as cms
process = cms.Process("LIKELIHOODPDFDBREADER")
# process.load("MuonAnalysis.MomentumScaleCalibration.local_CSA08_Y_cff")
process.source = cms.Source("EmptySource",
numberEventsInRun = cms.untracked.uint32(1),
firstRun = cms.untracked.uint32(1)
)
process.load("Configur... | [((52, 88), 'FWCore.ParameterSet.Config.Process', 'cms.Process', (['"""LIKELIHOODPDFDBREADER"""'], {}), "('LIKELIHOODPDFDBREADER')\n", (63, 88), True, 'import FWCore.ParameterSet.Config as cms\n'), ((1452, 1491), 'FWCore.ParameterSet.Config.EDAnalyzer', 'cms.EDAnalyzer', (['"""LikelihoodPdfDBReader"""'], {}), "('Likeli... |
vinid/fast_fine_tuna | fast_fine_tuna/fast_fine_tuna.py | 2d128f58df0407448cdb2e179972573afa7ac636 | from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
from sklearn.model_selection import StratifiedKFold
import numpy as np
import torch
from fast_fine_tuna.dataset import MainDatasetDouble, MainDataset
from transformers import AdamW
from torch.utils.data import DataLoader
i... | [((955, 1005), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['self.tokenizer_name'], {}), '(self.tokenizer_name)\n', (984, 1005), False, 'from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer, AutoConfig\n'), ((1022, 1037), 'numpy.array', 'np.array', ([... |
gauravyeole/KVstoreDB | Message/Message.py | 1c7c83b158e95daec998fba62a89fa1211a05089 | # Message class Implementation
# @author: Gaurav Yeole <gauravyeole@gmail.com>
class Message:
class Request:
def __init__(self, action="", data=None):
self.action = action
self.data = data
class Rsponse:
def __init__(self):
self.status = False
se... | [] |
gsnedders/presto-testo | wpt/websockets/websock_handlers/open_delay_wsh.py | a0acfbef13a3f8cae67cc7145216d31b67aa8eb4 | #!/usr/bin/python
from mod_pywebsocket import msgutil
import time
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
time.sleep(3)
msgutil.send_message(request, "line")
| [((177, 190), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (187, 190), False, 'import time\n'), ((192, 229), 'mod_pywebsocket.msgutil.send_message', 'msgutil.send_message', (['request', '"""line"""'], {}), "(request, 'line')\n", (212, 229), False, 'from mod_pywebsocket import msgutil\n')] |
augusto-herrmann/airflow | airflow/providers/microsoft/psrp/operators/psrp.py | 7ee4295dd3f7dba4fcd763286c7823bb1707fe99 | #
# 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... | [((2123, 2145), 'airflow.providers.microsoft.psrp.hooks.psrp.PSRPHook', 'PSRPHook', (['self.conn_id'], {}), '(self.conn_id)\n', (2131, 2145), False, 'from airflow.providers.microsoft.psrp.hooks.psrp import PSRPHook\n'), ((2344, 2378), 'airflow.exceptions.AirflowException', 'AirflowException', (['"""Process failed"""'],... |
mithro/chromium-infra | appengine/monorail/services/api_pb2_v1_helpers.py | d27ac0b230bedae4bc968515b02927cf9e17c2b7 | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Convert Monorail PB objects to API PB objects"""
import datetime
import logging
import time
... | [((1946, 2055), 'proto.api_pb2_v1.Status', 'api_pb2_v1.Status', ([], {'status': 'status.status', 'meansOpen': 'status.means_open', 'description': 'status.status_docstring'}), '(status=status.status, meansOpen=status.means_open,\n description=status.status_docstring)\n', (1963, 2055), False, 'from proto import api_pb... |
mhmgad/ExCut | excut/feedback/rulebased_deduction/deduction_engine_extended.py | 09e943a23207381de3c3a9e6f70015882b8ec4af | """
This module contains the rule-based inference (rulebased_deduction engine)
"""
import itertools
from collections import defaultdict
from itertools import chain
from excut.explanations_mining.descriptions import dump_explanations_to_file
from excut.explanations_mining.descriptions_new import Description2, Atom, loa... | [((9790, 9877), 'excut.clustering.target_entities.load_from_file', 'tes.load_from_file', (['"""/scratch/GW/pool0/gadelrab/ExDEC/data/yago/yago_art_3_4k.tsv"""'], {}), "(\n '/scratch/GW/pool0/gadelrab/ExDEC/data/yago/yago_art_3_4k.tsv')\n", (9808, 9877), True, 'from excut.clustering import target_entities as tes\n'),... |
urasakikeisuke/rigidmask | dataloader/viperlist_train.py | 4bb781102218dfd11efa767e2d0ba987d9949fd1 | import torch.utils.data as data
from PIL import Image
import os
import os.path
import numpy as np
import pdb
import glob
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extensi... | [((406, 449), 'glob.glob', 'glob.glob', (["(filepath + left_fold + '/0*.jpg')"], {}), "(filepath + left_fold + '/0*.jpg')\n", (415, 449), False, 'import glob\n'), ((739, 755), 'glob.glob', 'glob.glob', (['flowp'], {}), '(flowp)\n', (748, 755), False, 'import glob\n')] |
jsosa/floodcomparison | floodcomparison/__init__.py | c6662ae9142b4e89c6c05f93adaba49c5d8e4314 | from floodcomparison.core import floodcomparison
| [] |
crim-ca/weaver | weaver/wps_restapi/quotation/quotes.py | 107fec5e19f20b77061b9405a764da911d2db8a2 | import logging
import random
from datetime import timedelta
from typing import TYPE_CHECKING
from duration import to_iso8601
from pyramid.httpexceptions import HTTPBadRequest, HTTPCreated, HTTPNotFound, HTTPOk
from weaver import sort
from weaver.config import WEAVER_CONFIGURATION_ADES, WEAVER_CONFIGURATION_EMS, get_w... | [((1050, 1077), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1067, 1077), False, 'import logging\n'), ((1938, 2040), 'weaver.exceptions.log_unhandled_exceptions', 'log_unhandled_exceptions', ([], {'logger': 'LOGGER', 'message': 'sd.InternalServerErrorResponseSchema.description'}), '(lo... |
agustinhenze/mibs.snmplabs.com | pysnmp/CISCO-VSI-CONTROLLER-MIB.py | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | #
# PySNMP MIB module CISCO-VSI-CONTROLLER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VSI-CONTROLLER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | [] |
AartGoossens/streamlit-activity-viewer | strava.py | b43f157d8bee596908c4f2222be9bb0d8bd9b9e8 | import base64
import os
import arrow
import httpx
import streamlit as st
import sweat
from bokeh.models.widgets import Div
APP_URL = os.environ["APP_URL"]
STRAVA_CLIENT_ID = os.environ["STRAVA_CLIENT_ID"]
STRAVA_CLIENT_SECRET = os.environ["STRAVA_CLIENT_SECRET"]
STRAVA_AUTHORIZATION_URL = "https://www.strava.com/oau... | [((466, 494), 'streamlit.cache', 'st.cache', ([], {'show_spinner': '(False)'}), '(show_spinner=False)\n', (474, 494), True, 'import streamlit as st\n'), ((2582, 2636), 'streamlit.cache', 'st.cache', ([], {'show_spinner': '(False)', 'suppress_st_warning': '(True)'}), '(show_spinner=False, suppress_st_warning=True)\n', (... |
reap3r/nmfta-bouncer | appliance/src/ufw_interface.py | a178244dbf0b8a165aabc02a5d1ba05006f9ec22 | #!/usr/bin/env python
#shamelessy stolen from: https://gitlab.com/dhj/easyufw
# A thin wrapper over the thin wrapper that is ufw
# Usage:
# import easyufw as ufw
# ufw.disable() # disable firewall
# ufw.enable() # enable firewall
# ufw.allow() # default allow -- allow all
# ufw.allow... | [((1023, 1048), 'gettext.install', 'gettext.install', (['progName'], {}), '(progName)\n', (1038, 1048), False, 'import gettext\n')] |
etri-city-traffic-brain/traffic-simulator | test/libsalt/test_vehicle.py | 6d5061febeaef484388b2b5aee14d9894099d98a | import libsalt
def test(salt_scenario):
libsalt.start(salt_scenario)
libsalt.setCurrentStep(25200)
step = libsalt.getCurrentStep()
while step <= 36000:
if (step % 100 == 0):
print("Simulation Step: ", step)
test_funcs()
libsalt.simulationStep()
step = li... | [((46, 74), 'libsalt.start', 'libsalt.start', (['salt_scenario'], {}), '(salt_scenario)\n', (59, 74), False, 'import libsalt\n'), ((79, 108), 'libsalt.setCurrentStep', 'libsalt.setCurrentStep', (['(25200)'], {}), '(25200)\n', (101, 108), False, 'import libsalt\n'), ((120, 144), 'libsalt.getCurrentStep', 'libsalt.getCur... |
davidtahim/Glyphs-Scripts | Masters/Copy Layer to Layer.py | 5ed28805b5fe03c63d904ad2f79117844c22aa44 | #MenuTitle: Copy Layer to Layer
# -*- coding: utf-8 -*-
__doc__="""
Copies one master to another master in selected glyphs.
"""
import GlyphsApp
import vanilla
import math
def getComponentScaleX_scaleY_rotation( self ):
a = self.transform[0]
b = self.transform[1]
c = self.transform[2]
d = self.transform[3]
... | [] |
bjacobs1/vunit | vunit/test/unit/test_tokenizer.py | a7f7717a172855ea7852296bb768370d50cfc992 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com
"""
Test of the general tokenizer
"""
from unit... | [((2497, 2559), 'vunit.test.mock_2or3.mock.patch', 'mock.patch', (['"""vunit.parsing.tokenizer.read_file"""'], {'autospec': '(True)'}), "('vunit.parsing.tokenizer.read_file', autospec=True)\n", (2507, 2559), False, 'from vunit.test.mock_2or3 import mock\n'), ((1640, 1663), 'vunit.parsing.tokenizer.describe_location', '... |
tbersez/Allmine | modules/star_se_SP.py | 092fb1f5abcb4fd4e40b4a25386f05ecb2dea55b | # STAR aligner single end mode, second pass
#
# This module runs the second pass of the STAR aligner 2 path
# strategy. The goal is to align reads taking in account splice
# junction found in the fist pass..
#
# Inputs:
# - sample_trim.fastq.gz
# - splicing junction files (.tab)
#
# Output:
# ... | [] |
runzezhang/MOOCs | Udemy/REST-Django-VueJS/C3-practice/03-demo/job_board/jobs/models.py | 8df8c7adc5af3d7b085be01ae9b6963fe33acd68 | from django.db import models
class JobOffer(models.Model):
company_name = models.CharField(max_length=50)
company_email = models.EmailField()
job_title = models.CharField(max_length=60)
job_description = models.TextField()
salary = models.PositiveIntegerField()
city = models.CharField(max_leng... | [((80, 111), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (96, 111), False, 'from django.db import models\n'), ((132, 151), 'django.db.models.EmailField', 'models.EmailField', ([], {}), '()\n', (149, 151), False, 'from django.db import models\n'), ((168, 199), 'dj... |
barbaramootian/Memes-app | memeapp/views.py | 4ffa2da997758ee4f35dc21e755e3db242b8654f | from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import messages
from .forms import PictureUploadForm,CommentForm
from .models import Image,Profile,Likes,Comments
from django.contrib.auth.decorators import login_required
from django.contrib .auth import authen... | [((1915, 1948), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""login"""'}), "(login_url='login')\n", (1929, 1948), False, 'from django.contrib.auth.decorators import login_required\n'), ((2314, 2347), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'lo... |
spraakbanken/sparv-pipeline | sparv/modules/hist/diapivot.py | 7293d42c577afdaf01ce8a936743f8b83d6eb962 | """Create diapivot annotation."""
import logging
import pickle
import xml.etree.ElementTree as etree
import sparv.util as util
from sparv import Annotation, Model, ModelOutput, Output, annotator, modelbuilder
log = logging.getLogger(__name__)
PART_DELIM1 = "^1"
# @annotator("Diapivot annotation", language=["swe-1... | [((218, 245), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (235, 245), False, 'import logging\n'), ((363, 450), 'sparv.Output', 'Output', (['"""<token>:hist.diapivot"""'], {'description': '"""SALDO IDs corresponding to lemgrams"""'}), "('<token>:hist.diapivot', description=\n 'SALDO ... |
xinyang178/xbot | src/xbot/util/path.py | dad1fc67062dc6fd21802899fd68f7eb91c96569 | import os
def get_root_path():
current_path = os.path.abspath(os.path.dirname(__file__))
root_path = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(current_path)))
)
return os.path.join(root_path, "xbot")
def get_config_path():
config_path = os.path.abspath(os.path.join... | [((217, 248), 'os.path.join', 'os.path.join', (['root_path', '"""xbot"""'], {}), "(root_path, 'xbot')\n", (229, 248), False, 'import os\n'), ((68, 93), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (83, 93), False, 'import os\n'), ((321, 346), 'os.path.dirname', 'os.path.dirname', (['__file_... |
HackSoftware/hackconf.bg | home/website/wagtail_hooks.py | ab3cc9fcdccf8991098553e0374103e3a241ce50 | from django.utils.html import format_html
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_js')
def enable_source():
return format_html(
"""
<script>
registerHalloPlugin('hallohtml');
</script>
"""
)
| [((83, 117), 'wagtail.wagtailcore.hooks.register', 'hooks.register', (['"""insert_editor_js"""'], {}), "('insert_editor_js')\n", (97, 117), False, 'from wagtail.wagtailcore import hooks\n'), ((150, 269), 'django.utils.html.format_html', 'format_html', (['"""\n <script>\n registerHalloPlugin(\'hallohtm... |
msgis/ngsi-timeseries-api | src/reporter/tests/test_api.py | 5cc7a8beab748cecfd5fba61740f3730361d4e31 | from conftest import QL_URL
import requests
def test_api():
api_url = "{}/".format(QL_URL)
r = requests.get('{}'.format(api_url))
assert r.status_code == 200, r.text
assert r.json() == {
"notify_url": "/v2/notify",
"subscriptions_url": "/v2/subscriptions",
"entities_... | [] |
dyung/llvm-zorg | zorg/buildbot/conditions/FileConditions.py | 42cd139968388b14323975647faf322c99945986 | from buildbot.process.remotecommand import RemoteCommand
from buildbot.interfaces import WorkerTooOldError
import stat
class FileExists(object):
"""I check a file existence on the worker. I return True if the file
with the given name exists, False if the file does not exist or that is
a directory.
Us... | [((623, 669), 'buildbot.process.remotecommand.RemoteCommand', 'RemoteCommand', (['"""stat"""', "{'file': self.filename}"], {}), "('stat', {'file': self.filename})\n", (636, 669), False, 'from buildbot.process.remotecommand import RemoteCommand\n'), ((1688, 1734), 'buildbot.process.remotecommand.RemoteCommand', 'RemoteC... |
refaev/combat_gym | gym_combat/gym_combat/envs/main.py | f02fcf98e95a1dda29cdddd4ae271de3e18ea3bf | from matplotlib import style
from tqdm import tqdm
style.use("ggplot")
from gym_combat.envs.Arena.CState import State
from gym_combat.envs.Arena.Entity import Entity
from gym_combat.envs.Arena.Environment import Environment, Episode
from gym_combat.envs.Common.constants import *
from gym_combat.envs.Qtable import Qtab... | [((52, 71), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (61, 71), False, 'from matplotlib import style\n'), ((1611, 1651), 'matplotlib.pyplot.matshow', 'plt.matshow', (['observation_for_blue_s0.img'], {}), '(observation_for_blue_s0.img)\n', (1622, 1651), True, 'import matplotlib.pyplot ... |
ramongonze/libqif | libqif/core/hyper.py | 57be74a2342a303da5415a3d787855b8115e58f8 | """Hyper-distributions."""
from libqif.core.secrets import Secrets
from libqif.core.channel import Channel
from numpy import array, arange, zeros
from numpy import delete as npdelete
class Hyper:
def __init__(self, channel):
"""Hyper-distribution. To create an instance of this class it is
class i... | [((2486, 2518), 'numpy.arange', 'arange', (['self.channel.num_outputs'], {}), '(self.channel.num_outputs)\n', (2492, 2518), False, 'from numpy import array, arange, zeros\n'), ((2742, 2774), 'numpy.arange', 'arange', (['self.channel.num_outputs'], {}), '(self.channel.num_outputs)\n', (2748, 2774), False, 'from numpy im... |
gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_system_virtual_wan_link.py | 0fb18850afe0d8609693ba4b23f29c7cda17d97f | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, 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 Lic... | [((52332, 52394), 'ansible.module_utils.basic.AnsibleModule', 'AnsibleModule', ([], {'argument_spec': 'fields', 'supports_check_mode': '(False)'}), '(argument_spec=fields, supports_check_mode=False)\n', (52345, 52394), False, 'from ansible.module_utils.basic import AnsibleModule\n'), ((53234, 53246), 'fortiosapi.FortiO... |
victorlujan/Dise-odeSoftwarePatrones | src/Puerta.py | b9845cc1c4abdc44867c90b9e9784246e57f16b3 | from ElementoMapa import ElementoMapa
class Puerta (ElementoMapa):
def __init__(self):
self.abierta= True
self.lado2=None
self.lado1=None
def get_abierta(self):
return self.abierta
def print_cosas(self):
print("hola")
def set_abierta(self, value):
self.ab... | [] |
Teenahshe/ponggame | pong.py | 5e4032753894ce1e1ebeb51841676aac24aa22df | """
# Step 1 - Create the App
# Step 2 - Create the Game
# Step 3 - Build the Game
# Step 4 - Run the App
"""
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import C... | [((397, 415), 'kivy.properties.NumericProperty', 'NumericProperty', (['(0)'], {}), '(0)\n', (412, 415), False, 'from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty\n'), ((607, 625), 'kivy.properties.NumericProperty', 'NumericProperty', (['(0)'], {}), '(0)\n', (622, 625), False, 'from kivy... |
cyclone923/blocks-world | get_block_data/relation.py | 808127e6b4fde2a9cb499cf6934db7ff73e2f534 | class SceneRelation:
def __init__(self):
self.on_ground = set()
self.on_block = {}
self.clear = set()
def print_relation(self):
print(self.on_ground)
print(self.on_block)
print(self.clear) | [] |
EricZLou/BridgeRLAgent | bridge_RL_agent_v16.py | 78329eec5fcf320d2850f44dc33b138919fba82d | """
CS 238 Final Project: Bridge RL Agent
Eric Lou & Kimberly Tran
"""
import copy
import datetime
import numpy as np
import random
from collections import namedtuple
"""'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
REPRESENTATIONS OF BRIDGE
Representing a "Card" as an integer:
Cards 0 -> 12 are Club... | [((1427, 1497), 'collections.namedtuple', 'namedtuple', (['"""State"""', "['opening_suit', 'cards_played', 'partners_card']"], {}), "('State', ['opening_suit', 'cards_played', 'partners_card'])\n", (1437, 1497), False, 'from collections import namedtuple\n'), ((6414, 6434), 'random.shuffle', 'random.shuffle', (['deck']... |
chbonkie/hacs | tests/hacsbase/test_hacsbase_data.py | 81db513a0d3d1af1acf25da7b706ae62d8fdb6fa | """Data Test Suite."""
from aiogithubapi.objects import repository
import pytest
import os
from homeassistant.core import HomeAssistant
from custom_components.hacs.hacsbase.data import HacsData
from custom_components.hacs.helpers.classes.repository import HacsRepository
from custom_components.hacs.hacsbase.configuratio... | [((532, 542), 'custom_components.hacs.hacsbase.data.HacsData', 'HacsData', ([], {}), '()\n', (540, 542), False, 'from custom_components.hacs.hacsbase.data import HacsData\n'), ((554, 564), 'custom_components.hacs.share.get_hacs', 'get_hacs', ([], {}), '()\n', (562, 564), False, 'from custom_components.hacs.share import... |
marc-gav/PhiFlow | phi/math/backend/_backend.py | b6186fd1503d040997b52d49aa18cd875267c27e | from collections import namedtuple
from contextlib import contextmanager
from threading import Barrier
from typing import List, Callable
import numpy
from ._dtype import DType, combine_types
SolveResult = namedtuple('SolveResult', [
'method', 'x', 'residual', 'iterations', 'function_evaluations', 'converged', '... | [((209, 341), 'collections.namedtuple', 'namedtuple', (['"""SolveResult"""', "['method', 'x', 'residual', 'iterations', 'function_evaluations',\n 'converged', 'diverged', 'message']"], {}), "('SolveResult', ['method', 'x', 'residual', 'iterations',\n 'function_evaluations', 'converged', 'diverged', 'message'])\n"... |
dtrodrigues/bpython | bpython/curtsiesfrontend/parse.py | 143e4e55d8f5227149528a5880a32a516a40f14d | import re
from curtsies.formatstring import fmtstr, FmtStr
from curtsies.termformatconstants import (
FG_COLORS,
BG_COLORS,
colors as CURTSIES_COLORS,
)
from functools import partial
from ..lazyre import LazyReCompile
COLORS = CURTSIES_COLORS + ("default",)
CNAMES = dict(zip("krgybmcwd", COLORS))
# hack... | [((2247, 2274), 'curtsies.formatstring.fmtstr', 'fmtstr', (["d['string']"], {}), "(d['string'], **atts)\n", (2253, 2274), False, 'from curtsies.formatstring import fmtstr, FmtStr\n'), ((1558, 1566), 'curtsies.formatstring.FmtStr', 'FmtStr', ([], {}), '()\n', (1564, 1566), False, 'from curtsies.formatstring import fmtst... |
pressler-vsc/sarpy | sarpy/io/general/nitf_elements/tres/unclass/BANDSA.py | fa6c951c42b9a7d9df2edfa53c771494cb0246fb | # -*- coding: utf-8 -*-
from ..tre_elements import TREExtension, TREElement
__classification__ = "UNCLASSIFIED"
__author__ = "Thomas McCullough"
class BAND(TREElement):
def __init__(self, value):
super(BAND, self).__init__()
self.add_field('BANDPEAK', 's', 5, value)
self.add_field('BANDL... | [] |
husmen/ktrain | ktrain/graph/learner.py | 4147b0bd146deb513c6f94505908294a5163efac | from ..imports import *
from .. import utils as U
from ..core import GenLearner
class NodeClassLearner(GenLearner):
"""
```
Main class used to tune and train Keras models for node classification
Main parameters are:
model (Model): A compiled instance of keras.engine.training.Model
train_dat... | [] |
Thanksyy/Vega-Zero | VegaZero2VegaLite.py | dd25cb145faec047b01ca54c69ba96c56adb99f4 | __author__ = "Yuyu Luo"
import json
import pandas
class VegaZero2VegaLite(object):
def __init__(self):
pass
def parse_vegaZero(self, vega_zero):
self.parsed_vegaZero = {
'mark': '',
'data': '',
'encoding': {
'x': '',
'y': {
... | [] |
kmzbrnoI/ac-python | utils/dancer.py | 383802734e17d2a00c0b86083cf923517db02acd | """Library for executing user-defined dance."""
import logging
from typing import Any, Dict, Optional, Callable
import datetime
import ac
import ac.blocks
from ac import ACs, AC
JC = Dict[str, Any]
class DanceStartException(Exception):
pass
class Step:
"""Base class for all specific dance steps."""
... | [((6074, 6101), 'ac.blocks.on_block_change', 'ac.blocks.on_block_change', ([], {}), '()\n', (6099, 6101), False, 'import ac\n'), ((6164, 6176), 'ac.ACs.values', 'ACs.values', ([], {}), '()\n', (6174, 6176), False, 'from ac import ACs, AC\n'), ((4503, 4535), 'ac.AC.__init__', 'AC.__init__', (['self', 'id_', 'password'],... |
zachwylde00/praw | praw/models/reddit/mixins/reportable.py | ad1d73e6a4a33397bbd983bdfde1a4f99ce5607d | """Provide the ReportableMixin class."""
from ....const import API_PATH
class ReportableMixin:
"""Interface for RedditBase classes that can be reported."""
def report(self, reason):
"""Report this object to the moderators of its subreddit.
:param reason: The reason for reporting.
Ra... | [] |
TrustworthyDL/LeBA | defense/jpeg_compress.py | 3289c1330585f438dc5b931951cbb682c5513053 | def _jpeg_compression(im):
assert torch.is_tensor(im)
im = ToPILImage()(im)
savepath = BytesIO()
im.save(savepath, 'JPEG', quality=75)
im = Image.open(savepath)
im = ToTensor()(im)
return im | [] |
LaudateCorpus1/mellon | mellon/factories/filesystem/file.py | a7a9f6d8abf1dd03b63a94ddb4439c6cc6c2e272 | import collections
import os.path
from zope import component
from zope import interface
from zope.component.factory import Factory
from sparc.configuration import container
import mellon
@interface.implementer(mellon.IByteMellonFile)
class MellonByteFileFromFilePathAndConfig(object):
def __init__(self, file_p... | [((189, 234), 'zope.interface.implementer', 'interface.implementer', (['mellon.IByteMellonFile'], {}), '(mellon.IByteMellonFile)\n', (210, 234), False, 'from zope import interface\n'), ((777, 821), 'zope.component.factory.Factory', 'Factory', (['MellonByteFileFromFilePathAndConfig'], {}), '(MellonByteFileFromFilePathAn... |
CogSciUOS/DeepLearningToolbox | dltb/thirdparty/datasource/__init__.py | bf07578b9486d8c48e25df357bc4b9963b513b46 | """Predefined Datasources.
"""
# toolbox imports
from ...datasource import Datasource
Datasource.register_instance('imagenet-val', __name__ + '.imagenet',
'ImageNet', section='val') # section='train'
Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats',
... | [] |
babinyurii/RECAN | tests/test_results.py | b49326b47bae22316c3776fee2f398e09a98ba96 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 15:58:44 2019
@author: babin
"""
posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215]
dist_whole_align_ref = {'AB048704.1_genotype_C_':
[0.88,
0.938,
0.914,
0.886,
0.89,
0.908,
0.938,
0.948,
0.948,
0.886,
0.8... | [] |
SimonSuster/lxmls-toolkit | lxmls/readers/simple_data_set.py | 6a57884f8b7c98da816a60eb88593e0a1585d434 | import numpy as np
# This class generates a 2D dataset with two classes, "positive" and "negative".
# Each class follows a Gaussian distribution.
class SimpleDataSet():
''' A simple two dimentional dataset for visualization purposes. The date set contains points from two gaussians with mean u_i and std_i'''
d... | [] |
kangtastic/cryptopals | set1/c06_attack_repeating_key_xor.py | 7014a08b836b3f9ebfdc889123ccf67406738dac | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Break repeating-key XOR
#
# It is officially on, now.
#
# This challenge isn't conceptually hard, but it involves actual
# error-prone coding. The other challenges in this set are there to bring
# you up to speed. This one is there to qualify you. If you can do t... | [((3574, 3608), 'itertools.zip_longest', 'zip_longest', (['bs1', 'bs2'], {'fillvalue': '(0)'}), '(bs1, bs2, fillvalue=0)\n', (3585, 3608), False, 'from itertools import zip_longest\n'), ((3740, 3778), 'util.loader.loader', 'loader', (['"""6.txt"""', '"""base64"""'], {'split': '(False)'}), "('6.txt', 'base64', split=Fal... |
kopf-yhs/ncscos | c2nl/models/transformer.py | 8248aaad32d4d19c01d070bf0dfba7aab849ba1d | import torch
import torch.nn as nn
import torch.nn.functional as f
from prettytable import PrettyTable
from c2nl.modules.char_embedding import CharEmbedding
from c2nl.modules.embeddings import Embeddings
from c2nl.modules.highway import Highway
from c2nl.encoders.transformer import TransformerEncoder
from c2nl.decoder... | [((3482, 3510), 'torch.nn.Dropout', 'nn.Dropout', (['args.dropout_emb'], {}), '(args.dropout_emb)\n', (3492, 3510), True, 'import torch.nn as nn\n'), ((6238, 6484), 'c2nl.encoders.transformer.TransformerEncoder', 'TransformerEncoder', ([], {'num_layers': 'args.nlayers', 'd_model': 'input_size', 'heads': 'args.num_head'... |
cjellick/python-agent | cattle/plugins/docker/delegate.py | 6991369e309d050a43cba770df6e8ddd758f671d | import logging
from cattle import Config
from cattle.utils import reply, popen
from .compute import DockerCompute
from cattle.agent.handler import BaseHandler
from cattle.progress import Progress
from cattle.type_manager import get_type, MARSHALLER
from . import docker_client
import subprocess
import os
import time
... | [((326, 353), 'logging.getLogger', 'logging.getLogger', (['"""docker"""'], {}), "('docker')\n", (343, 353), False, 'import logging\n'), ((652, 672), 'cattle.type_manager.get_type', 'get_type', (['MARSHALLER'], {}), '(MARSHALLER)\n', (660, 672), False, 'from cattle.type_manager import get_type, MARSHALLER\n'), ((1075, 1... |
ehickox2012/bitraider | bitraider/strategy.py | dcc695b93dc1c22415780e3f5ff9f7ee29d6988c | import sys
import pytz
#import xml.utils.iso8601
import time
import numpy
from datetime import date, datetime, timedelta
from matplotlib import pyplot as plt
from exchange import cb_exchange as cb_exchange
from exchange import CoinbaseExchangeAuth
from abc import ABCMeta, abstractmethod
class strategy(object):
"""... | [((5274, 5296), 'numpy.array', 'numpy.array', (['fltprices'], {}), '(fltprices)\n', (5285, 5296), False, 'import numpy\n'), ((5327, 5350), 'numpy.array', 'numpy.array', (['fltvolumes'], {}), '(fltvolumes)\n', (5338, 5350), False, 'import numpy\n'), ((5374, 5436), 'numpy.average', 'numpy.average', (['np_discrete_prices'... |
PacktPublishing/Python-Deep-Learning-for-Beginners- | neural-networks.py | 90f110158cbf0ce02fd4d5d09e3b2034428d9992 | import numpy as np
# Perceptron
def predict_perceptron(inputs, weights):
if np.dot(inputs, weights) > 0:
return 1
else:
return 0
def predict_perceptron_proper(inputs, weights):
def step_function(input):
return 1 if input > 0 else 0
def linear_model(inputs, weights):
r... | [((81, 104), 'numpy.dot', 'np.dot', (['inputs', 'weights'], {}), '(inputs, weights)\n', (87, 104), True, 'import numpy as np\n'), ((326, 349), 'numpy.dot', 'np.dot', (['inputs', 'weights'], {}), '(inputs, weights)\n', (332, 349), True, 'import numpy as np\n'), ((570, 593), 'numpy.dot', 'np.dot', (['inputs', 'weights'],... |
andreasjansson/OroJaR | biggan_discovery/orojar_discover.py | ebb8c0333bbd33c063b6dd4a21a0559eb86d13e9 | """
Learns a matrix of Z-Space directions using a pre-trained BigGAN Generator.
Modified from train.py in the PyTorch BigGAN repo.
"""
import os
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim
import utils
import train_fns
from sync_batchnorm import patch_replication_callback
from torch.u... | [((1355, 1369), 'direction_utils.load_G', 'load_G', (['config'], {}), '(config)\n', (1361, 1369), False, 'from direction_utils import visualize_directions, load_G, get_direction_padding_fn, init_wandb, download_G\n'), ((1585, 1610), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (1608, 1610), F... |
Alva789ro/Regional-Comprehensive-Economic-Partnership-RCEP-Economic-Default-Risk-Analysis | file_importer0.py | 454583f47883edae17391f101b10b38b68c9834f | import xlsxwriter
import pandas as pd
import numpy as np
import mysql.connector
australia=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Australia')
brunei=pd.read_excel(r'\Users\jesica\Desktop\RCEP_economic_analysis.xlsx', sheet_name='Brunei')
cambodia=pd.read_excel(r'\Users\jesica\De... | [((91, 189), 'pandas.read_excel', 'pd.read_excel', (['"""\\\\Users\\\\jesica\\\\Desktop\\\\RCEP_economic_analysis.xlsx"""'], {'sheet_name': '"""Australia"""'}), "('\\\\Users\\\\jesica\\\\Desktop\\\\RCEP_economic_analysis.xlsx',\n sheet_name='Australia')\n", (104, 189), True, 'import pandas as pd\n'), ((190, 285), 'p... |
VIOOH/nile | packer/resources/bootstrap_node.py | 893802387b3891ea02aae05f39ff4aa051354f18 | #!/usr/bin/env python3
import os
import re
import glob
import boto3
import requests
import subprocess
from time import sleep
AWS_REGION = os.environ['AWS_REGION']
DEPLOY_UUID = os.environ['DEPLOY_UUID']
SERVICE_NAME = os.environ['SERVICE_NAME']
MOUNT_POINT = "/var/lib/" + SERVICE_NAME... | [((444, 465), 'boto3.resource', 'boto3.resource', (['"""ec2"""'], {}), "('ec2')\n", (458, 465), False, 'import boto3\n'), ((782, 801), 'boto3.client', 'boto3.client', (['"""ec2"""'], {}), "('ec2')\n", (794, 801), False, 'import boto3\n'), ((814, 835), 'boto3.resource', 'boto3.resource', (['"""ec2"""'], {}), "('ec2')\n"... |
otoriocyber/Chronos | parsers/srum_parser.py | d70e22afed723c0ad4b7e449bd253e15351bada6 | import csv
import datetime
import random
import os
from parsers.parser_base import ParserBase
FILE_TIME_EPOCH = datetime.datetime(1601, 1, 1)
FILE_TIME_MICROSECOND = 10
def filetime_to_epoch_datetime(file_time):
if isinstance(file_time, int):
microseconds_since_file_time_epoch = file_time / FILE_TIME_MIC... | [((113, 142), 'datetime.datetime', 'datetime.datetime', (['(1601)', '(1)', '(1)'], {}), '(1601, 1, 1)\n', (130, 142), False, 'import datetime\n'), ((452, 519), 'datetime.timedelta', 'datetime.timedelta', ([], {'microseconds': 'microseconds_since_file_time_epoch'}), '(microseconds=microseconds_since_file_time_epoch)\n',... |
Yoann-Vie/esgi-hearthstone | tests/csrf_tests/test_context_processor.py | 115d03426c7e8e80d89883b78ac72114c29bed12 | from django.http import HttpRequest
from django.middleware.csrf import _compare_salted_tokens as equivalent_tokens
from django.template.context_processors import csrf
from django.test import SimpleTestCase
class TestContextProcessor(SimpleTestCase):
def test_force_token_to_string(self):
request ... | [((322, 335), 'django.http.HttpRequest', 'HttpRequest', ([], {}), '()\n', (333, 335), False, 'from django.http import HttpRequest\n'), ((492, 505), 'django.template.context_processors.csrf', 'csrf', (['request'], {}), '(request)\n', (496, 505), False, 'from django.template.context_processors import csrf\n')] |
marza-animation-planet/das | python/das/types.py | 1c7460dfdd5f138d8317c72900e90b23c0c28c7b | import sys
import das
import traceback
class ReservedNameError(Exception):
def __init__(self, name):
super(ReservedNameError, self).__init__("'%s' is a reserved name" % name)
class VersionError(Exception):
def __init__(self, msg=None, current_version=None, required_version=None):
fullmsg = "ersion... | [] |
AliabbasMerchant/fileTrackAndBackup | track.py | 8cdf97be58c69061e1f60c08f89b524d91f8c17d | #! /usr/bin/python3
from help import *
import time
# short-forms are used, so as to reduce the .json file size
# t : type - d or f
# d : directory
# f : file
# ts : timestamp
# dirs : The dictionary containing info about directory contents
# time : edit time of the file/folder
# s : size of the file/folder
# p : full ... | [((3659, 3670), 'time.time', 'time.time', ([], {}), '()\n', (3668, 3670), False, 'import time\n'), ((4352, 4363), 'time.time', 'time.time', ([], {}), '()\n', (4361, 4363), False, 'import time\n')] |
Kvarnefalk/llvm-project | clang/tools/scan-build-py/libscanbuild/analyze.py | 8b5f5798aaa24074609d151ea906d114cf5337c2 | # -*- coding: utf-8 -*-
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
""" This module implements the 'scan-build' command API.
To run the static analyzer against a bui... | [((1660, 1687), 'libscanbuild.arguments.parse_args_for_scan_build', 'parse_args_for_scan_build', ([], {}), '()\n', (1685, 1687), False, 'from libscanbuild.arguments import parse_args_for_scan_build, parse_args_for_analyze_build\n'), ((2874, 2904), 'libscanbuild.arguments.parse_args_for_analyze_build', 'parse_args_for_a... |
PIRXrav/pyhack | tableborder.py | af5c86fb721053d8a3e819ab772c8144a23b86bf | #!/usr/bin/env python3
# pylint: disable=C0103
# pylint: disable=R0902
# pylint: disable=R0903
# pylint: disable=R0913
"""
Définie la classe TableBorder
"""
class TableBorder:
"""
Facillite l'usage de l'UNICODE
"""
def __init__(self,
top_left, top_split, top_right,
mi... | [] |
tkf2019/Vue-Django-SAST-Search | app/urls.py | 385af9819c608ce2d0845ed3e786777ff52b52b3 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register/', views.register),
url(r'^login/', views.login),
url(r'logout/', views.logout),
url(r'search/', views.search)
]
| [((75, 108), 'django.conf.urls.url', 'url', (['"""^register/"""', 'views.register'], {}), "('^register/', views.register)\n", (78, 108), False, 'from django.conf.urls import url\n'), ((115, 142), 'django.conf.urls.url', 'url', (['"""^login/"""', 'views.login'], {}), "('^login/', views.login)\n", (118, 142), False, 'fro... |
Ziqqo/hasl-platform | custom_components/hasl/sensor.py | 27386314bf58626538d59c38d89249b07ed9256a | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Simple service for SL (Storstockholms Lokaltrafik)."""
import datetime
import json
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from ho... | [((990, 1017), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1007, 1017), False, 'import logging\n'), ((1743, 1764), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(10)'}), '(minutes=10)\n', (1752, 1764), False, 'from datetime import timedelta\n'), ((2124, 2150), 'voluptuous.Optio... |
ishivvers/astro | simbad_tools.py | ff3f3b9f8ef4013157c277bbb5bf82ac1bd3287d | """
A quick library to deal with searching simbad for info
about a SN and parsing the results.
Author: Isaac Shivvers, ishivvers@berkeley.edu, 2014
example SIMBAD uri query:
http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=sn%201998S
"""
import re
from urllib2 import urlopen
def get_SN_info( nam... | [((973, 1004), 're.search', 're.search', (['regex_coords', 'result'], {}), '(regex_coords, result)\n', (982, 1004), False, 'import re\n'), ((1020, 1053), 're.search', 're.search', (['regex_redshift', 'result'], {}), '(regex_redshift, result)\n', (1029, 1053), False, 'import re\n'), ((1070, 1099), 're.search', 're.searc... |
StanfordASL/soft-robot-control | robots/environments.py | 29ade9b7b952e25e639b42767a4f09c87a0e824a | import os
from math import cos
from math import sin
import Sofa.Core
from splib.numerics import Quat, Vec3
from sofacontrol import measurement_models
path = os.path.dirname(os.path.abspath(__file__))
class TemplateEnvironment:
def __init__(self, name='Template', rayleighMass=0.1, rayleighStiffness=0.1, dt=0.01... | [((176, 201), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (191, 201), False, 'import os\n'), ((3298, 3339), 'splib.numerics.Vec3', 'Vec3', (['(0.0)', '(length2 - length1)', 'lengthTrunk'], {}), '(0.0, length2 - length1, lengthTrunk)\n', (3302, 3339), False, 'from splib.numerics import Quat... |
SimonPreissner/get-shifty | default.py | aff49220932921c77e419a34ca472b51e0b26b72 | """
This file contains meta information and default configurations of the project
"""
RSC_YEARS = [1660, 1670, 1680, 1690,
1700, 1710, 1720, 1730, 1740, 1750, 1760, 1770, 1780, 1790,
1800, 1810, 1820, 1830, 1840, 1850, 1860, 1870, 1880, 1890,
1900, 1910, 1920]
# cf. Chapter 4.... | [] |
SimonTopp/Graph-WaveNet | generate_training_data_drb.py | ef63a80cc397744667a5d27f7c410c10e3e03a4c | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import numpy as np
import os
import pandas as pd
import util
import os.path
import pandas as pd
import numpy as np
import yaml
import xa... | [((4982, 5002), 'numpy.asarray', 'np.asarray', (['combined'], {}), '(combined)\n', (4992, 5002), True, 'import numpy as np\n'), ((5631, 5657), 'xarray.merge', 'xr.merge', (['obs'], {'join': '"""left"""'}), "(obs, join='left')\n", (5639, 5657), True, 'import xarray as xr\n'), ((6138, 6190), 'numpy.reshape', 'np.reshape'... |
CodedLadiesInnovateTech/python-challenges | Phase-1/Python Basic 1/Day-3.py | 22ce26c68fea6c7c243ada831e47c52e27a62127 | <<<<<<< HEAD
"""
1. Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).
Sample function : abs()
Expected Result :
abs(number) -> number
Return the absolute value of the argument.
Tools: help function
2. Write a Python program to p... | [] |
gmgunter/pyre | tests/python/metaclass_inheritance.py | e9ff3f8c04661f8b2cd2ba0caded08b6fe8054e2 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2021 all rights reserved
#
#
"""
When a metaclass understands the extra keywords that can be passed during class declaration,
it has to override all these to accommodate the change in signature
"""
class meta(type):
... | [] |
idsdlab/basicai_sp21 | cs101/module8/8-1/chroma1.py | af9acba34c0417fed830de1b61753c50fd303169 |
from cs1media import *
import math
def dist(c1, c2):
r1, g1, b1 = c1
r2, g2, b2 = c2
return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2)
def chroma(img, key, threshold):
w, h = img.size()
for y in range(h):
for x in range(w):
p = img.get(x, y)
if dist(p, key) < threshold:
img.set... | [((100, 159), 'math.sqrt', 'math.sqrt', (['((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)'], {}), '((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)\n', (109, 159), False, 'import math\n')] |
RuthAngus/wfirst_stars | wfirst_stars/mklc.py | 60989fc56488ac915082e76c3088c6133909985b | import numpy as np
import scipy
import scipy.io
import pylab
import numpy
import glob
import pyfits
def mklc(t, nspot=200, incl=(scipy.pi)*5./12., amp=1., tau=30.5, p=10.0):
diffrot = 0.
''' This is a simplified version of the class-based routines in
spot_model.py. It generates a light curves for dark, p... | [((1870, 1892), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(time)\n', (1886, 1892), False, 'import scipy\n'), ((1906, 1928), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(time)\n', (1922, 1928), False, 'import scipy\n'), ((1943, 1965), 'scipy.zeros_like', 'scipy.zeros_like', (['time'], {}), '(... |
pelavarre/pybashish | bin/sort.py | 03f74356fb0a2a0ef7106f09c059fd9b375ce89a | #!/usr/bin/env python3
"""
usage: sort.py [-h]
sort lines
options:
-h, --help show this help message and exit
quirks:
sorts tabs as different than spaces
sorts some spaces ending a line as different than none ending a line
examples:
Oh no! No examples disclosed!! 💥 💔 💥
"""
# FIXME: doc -k$N,$N and -n a... | [((516, 535), 'argdoc.parse_args', 'argdoc.parse_args', ([], {}), '()\n', (533, 535), False, 'import argdoc\n'), ((650, 703), 'sys.stderr.write', 'sys.stderr.write', (['"""sort.py: error: not implemented\n"""'], {}), "('sort.py: error: not implemented\\n')\n", (666, 703), False, 'import sys\n'), ((708, 719), 'sys.exit'... |
davandev/davanserver | davan/http/service/telldus/tdtool.py | 0be914268c8e34d4092251508bae213cff3ef621 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt, httplib, urllib, json, os
import oauth.oauth as oauth
import datetime
from configobj import ConfigObj
import logging
global logger
logger = logging.getLogger(os.path.basename(__file__))
import davan.util.application_logger as log_manager
#insert your ... | [((420, 443), 'davan.config.config_creator.create', 'config_creator.create', ([], {}), '()\n', (441, 443), True, 'import davan.config.config_creator as config_creator\n'), ((227, 253), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (243, 253), False, 'import sys, getopt, httplib, urllib, js... |
rajreet/ichnaea | ichnaea/data/export.py | 7bd2eaa9568f9004e566b802623299625c29f5ae | from collections import defaultdict
import json
import re
import time
from urllib.parse import urlparse
import uuid
import boto3
import boto3.exceptions
import botocore.exceptions
import markus
import redis.exceptions
import requests
import requests.exceptions
from sqlalchemy import select
import sqlalchemy.exc
from ... | [((698, 733), 're.compile', 're.compile', (['"""\\\\s"""'], {'flags': 're.UNICODE'}), "('\\\\s', flags=re.UNICODE)\n", (708, 733), False, 'import re\n'), ((745, 765), 'markus.get_metrics', 'markus.get_metrics', ([], {}), '()\n', (763, 765), False, 'import markus\n'), ((1442, 1459), 'collections.defaultdict', 'defaultdi... |
x-y-z/HugeCTR | test/inference_correctness/dcn_multi_hot.py | 17bf942215df60827ece9dc015af5191ef9219b7 | import hugectr
from mpi4py import MPI
solver = hugectr.CreateSolver(model_name = "dcn",
max_eval_batches = 1,
batchsize_eval = 16384,
batchsize = 16384,
lr = 0.001,
vvgpu... | [((47, 306), 'hugectr.CreateSolver', 'hugectr.CreateSolver', ([], {'model_name': '"""dcn"""', 'max_eval_batches': '(1)', 'batchsize_eval': '(16384)', 'batchsize': '(16384)', 'lr': '(0.001)', 'vvgpu': '[[0]]', 'repeat_dataset': '(True)', 'use_mixed_precision': '(False)', 'scaler': '(1.0)', 'use_cuda_graph': '(True)', 'm... |
RobotLocomotion/drake-python3.7 | bindings/pydrake/systems/perception.py | ae397a4c6985262d23e9675b9bf3927c08d027f5 | import numpy as np
from pydrake.common.value import AbstractValue
from pydrake.math import RigidTransform
from pydrake.perception import BaseField, Fields, PointCloud
from pydrake.systems.framework import LeafSystem
def _TransformPoints(points_Ci, X_CiSi):
# Make homogeneous copy of points.
points_h_Ci = np.... | [((1049, 1071), 'numpy.isnan', 'np.isnan', (['scene_points'], {}), '(scene_points)\n', (1057, 1071), True, 'import numpy as np\n'), ((2467, 2492), 'pydrake.systems.framework.LeafSystem.__init__', 'LeafSystem.__init__', (['self'], {}), '(self)\n', (2486, 2492), False, 'from pydrake.systems.framework import LeafSystem\n'... |
mit-ll/CATAN | experiments/db_test.py | 7cc6f7e8af459c0f6bcf325f0754db1ba5b591ac | #!/usr/bin/env python
"""
@author Hongyi Hu
© 2015 Massachusetts Institute of Technology
"""
import argparse
import random
import catan.db
from catan.data import NodeMessage
# test data
STATUS_LIST = ['ok', 'injured', 'deceased']
# nodes
def gen_nodes(n, db, start_lat, stop_lat, start_long, stop_long):
assert... | [] |
Hellofafar/Leetcode | Medium/200.py | 7a459e9742958e63be8886874904e5ab2489411a | # ------------------------------
# 200. Number of Islands
#
# Description:
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrou... | [] |
SamuelePilleri/plaso | tests/formatters/fseventsd.py | f5687f12a89c7309797ccc285da78e855c120579 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the fseventsd record event formatter."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import fseventsd
from tests.formatters import test_lib
class FseventsdFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the... | [((959, 974), 'unittest.main', 'unittest.main', ([], {}), '()\n', (972, 974), False, 'import unittest\n'), ((449, 484), 'plaso.formatters.fseventsd.FSEventsdEventFormatter', 'fseventsd.FSEventsdEventFormatter', ([], {}), '()\n', (482, 484), False, 'from plaso.formatters import fseventsd\n'), ((657, 692), 'plaso.formatt... |
Farzin-Negahbani/PathoNet | train.py | b467a255fb356e64129b7942261e972ae15a2d2b | from keras.callbacks import ModelCheckpoint,Callback,LearningRateScheduler,TensorBoard
from keras.models import load_model
import random
import numpy as np
from scipy import misc
import gc
from keras.optimizers import Adam
from imageio import imread
from datetime import datetime
import os
import json
import models
from... | [((434, 466), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""train"""'], {}), "('train')\n", (457, 466), False, 'import argparse\n'), ((639, 647), 'config.Config', 'Config', ([], {}), '()\n', (645, 647), False, 'from config import Config\n'), ((815, 860), 'os.makedirs', 'os.makedirs', (["(conf.logPath + '/... |
mingxiaoh/chainer-v3 | tests/chainer_tests/functions_tests/array_tests/test_flatten.py | 815ff00f5eaf7944d6e8a75662ff64a2fe046a4d | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 4), ()],
'dtype': [numpy.float16, numpy.float32, numpy.flo... | [((1406, 1444), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (1424, 1444), False, 'from chainer import testing\n'), ((678, 702), 'chainer.Variable', 'chainer.Variable', (['x_data'], {}), '(x_data)\n', (694, 702), False, 'import chainer\n'), ((715, 735), '... |
snoop2head/exercise_curation_django | categories/migrations/0001_initial.py | ba35bd32d8bc203d318cb8b6e0a1722f3aa26eda | # Generated by Django 3.0.3 on 2020-03-24 09:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('exercises', '0018_photo_file'),
]
operations = [
migrations.CreateModel(
na... | [((379, 472), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (395, 472), False, 'from django.db import migrations, models\... |
neurips2020submission11699/metarl | src/metarl/envs/dm_control/dm_control_env.py | ae4825d21478fa1fd0aa6b116941ea40caa152a5 | from dm_control import suite
from dm_control.rl.control import flatten_observation
from dm_env import StepType
import gym
import numpy as np
from metarl.envs import Step
from metarl.envs.dm_control.dm_control_viewer import DmControlViewer
class DmControlEnv(gym.Env):
"""
Binding for `dm_control <https://arxi... | [((2499, 2575), 'gym.spaces.Box', 'gym.spaces.Box', ([], {'low': '(-np.inf)', 'high': 'np.inf', 'shape': '[flat_dim]', 'dtype': 'np.float32'}), '(low=-np.inf, high=np.inf, shape=[flat_dim], dtype=np.float32)\n', (2513, 2575), False, 'import gym\n'), ((588, 622), 'dm_control.suite.load', 'suite.load', (['domain_name', '... |
vatervonacht/dagster | python_modules/lakehouse/lakehouse/snowflake_table.py | 595d78c883ef20618052ac1575fe46cde51fd541 | from dagster import check
from .house import Lakehouse
from .table import create_lakehouse_table_def
class SnowflakeLakehouse(Lakehouse):
def __init__(self):
pass
def hydrate(self, _context, _table_type, _table_metadata, table_handle, _dest_metadata):
return None
def materialize(self, c... | [((562, 596), 'dagster.check.opt_dict_param', 'check.opt_dict_param', (['tags', '"""tags"""'], {}), "(tags, 'tags')\n", (582, 596), False, 'from dagster import check\n'), ((705, 774), 'dagster.check.opt_set_param', 'check.opt_set_param', (['required_resource_keys', '"""required_resource_keys"""'], {}), "(required_resou... |
tokejepsen/pype | pype/plugins/maya/publish/validate_look_no_default_shaders.py | 8f2b2b631cc5d3ad93eeb5ad3bc6110d32466ed3 | from maya import cmds
import pyblish.api
import pype.api
import pype.maya.action
class ValidateLookNoDefaultShaders(pyblish.api.InstancePlugin):
"""Validate if any node has a connection to a default shader.
This checks whether the look has any members of:
- lambert1
- initialShadingGroup
- initi... | [((1433, 1481), 'maya.cmds.listConnections', 'cmds.listConnections', (['node'], {'type': '"""shadingEngine"""'}), "(node, type='shadingEngine')\n", (1453, 1481), False, 'from maya import cmds\n')] |
Johne-DuChene/data_science_learning_app | data_science_app/app.py | 40bafce85a27155766950806b5b32a2d1f6753c4 | from flask import Flask
# initialize the app
app = Flask(__name__)
# execute iris function at /iris route
@app.route("/iris")
def iris():
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
clf = LogisticRegression(
rando... | [((52, 67), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (57, 67), False, 'from flask import Flask\n'), ((250, 276), 'sklearn.datasets.load_iris', 'load_iris', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (259, 276), False, 'from sklearn.datasets import load_iris\n'), ((287, 365), 'sklearn.line... |
VarunSrivastava19/VBDiarization | vbdiar/scoring/normalization.py | 2a460b4fc11b3a5ff73d0534cadb182be1a9d882 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Brno University of Technology FIT
# Author: Jan Profant <jan.profant@phonexia.com>
# All Rights Reserved
import os
import logging
import pickle
import multiprocessing
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from vb... | [((510, 537), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (527, 537), False, 'import logging\n'), ((1330, 1358), 'multiprocessing.Pool', 'multiprocessing.Pool', (['n_jobs'], {}), '(n_jobs)\n', (1350, 1358), False, 'import multiprocessing\n'), ((3582, 3645), 'vbdiar.embeddings.embedding... |
mattsmart/biomodels | agent_based_models/abm_allelopathy/plot_data.py | 237f87489553fa1ebf5c676fab563166dd0c39e9 | import matplotlib.pyplot as plt
import os
def data_plotter(lattice_dict, datafile_dir, plot_dir):
# total spaces on grid implies grid size
total_cells = lattice_dict['E'][0] + lattice_dict['D_a'][0] + lattice_dict['D_b'][0] + lattice_dict['B'][0]
n = int(total_cells**0.5)
plt.figure(1)
plt.plot... | [((293, 306), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (303, 306), True, 'import matplotlib.pyplot as plt\n'), ((312, 391), 'matplotlib.pyplot.plot', 'plt.plot', (["lattice_dict['time']", "lattice_dict['E']"], {'label': '"""Empty lattice points"""'}), "(lattice_dict['time'], lattice_dict['E'], ... |
JonathanGailliez/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_10_01/models/virtual_wan_security_providers.py | f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | [] |
flowgunso/jsonresume-theme-stackoverflow | jsonresume_theme_stackoverflow/filters.py | 5fcadcf41a93478a09e95d79fd62d8ac3402b33b | import datetime
import re
from .exceptions import ObjectIsNotADate
def format_date(value, format="%d %M %Y"):
regex = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", value)
if regex is not None:
date = datetime.date(
int(regex.group("year")),
int(regex.group("mont... | [((125, 194), 're.match', 're.match', (['"""(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2})"""', 'value'], {}), "('(?P<year>\\\\d{4})-(?P<month>\\\\d{2})-(?P<day>\\\\d{2})', value)\n", (133, 194), False, 'import re\n')] |
wwwbbb8510/ippso | ipec/data/core.py | fa20d23cd8edba5908e65a0ab0ab990d7ce3d5d5 | import numpy as np
import os
import logging
from sklearn.model_selection import train_test_split
DATASET_ROOT_FOLDER = os.path.abspath('datasets')
class DataLoader:
train = None
validation = None
test = None
mode = None
partial_dataset = None
@staticmethod
def load(train_path=None, valid... | [((120, 147), 'os.path.abspath', 'os.path.abspath', (['"""datasets"""'], {}), "('datasets')\n", (135, 147), False, 'import os\n'), ((3261, 3277), 'numpy.loadtxt', 'np.loadtxt', (['path'], {}), '(path)\n', (3271, 3277), True, 'import numpy as np\n'), ((3810, 3877), 'numpy.reshape', 'np.reshape', (['images', '[images.sha... |
lucasf5/Python | FOR/Analisador-completo/main.py | c5649121e2af42922e2d9c19cec98322e132bdab | # Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.
mediaidade = ''
nomelista = []
idadelista = []
sexolista = []
homens = []
mulherescommenosde20 =... | [] |
EnriqueL8/qiskit-terra | test/python/quantum_info/operators/test_operator.py | 08b801f1f8598c4e44680b4a75c232ed92db0262 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | [((1065, 1092), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1082, 1092), False, 'import logging\n'), ((1208, 1217), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (1214, 1217), True, 'import numpy as np\n'), ((1227, 1253), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, ... |
jack-skerrett-bluefruit/Python-ScreenPlay | pages/feature_modal.py | 045486bdf441fa3a7a6cde59e7b7e12a7d53fbed | from selenium.webdriver.common.by import By
class feature_modal:
title_textbox = (By.ID, "feature-name")
description_textbox = (By.ID, "description")
save_button = (By.XPATH, "/html/body/app/div[3]/div[2]/div/div/div/button[1]")
| [] |
CrookedY/AirPollutionBot | liststations.py | ce79037d6dddd1f297fce04a694b49f8b9a1bfad | from urllib2 import Request, urlopen, URLError
import json
request = Request('https://uk-air.defra.gov.uk/sos-ukair/api/v1/stations/')
try:
response = urlopen(request)
data = response.read()
except URLError, e:
print 'error:', e
stations= json.loads (data)
#extract out station 2
stations2 = stations [7]
prope... | [] |
kmiller96/PyFinancials | pyfinancials/engine.py | 73a89b0fd3a3d501b8f8c770f73473e9a2d18fdf | def hello_world():
"""Tests the import."""
return "Hello world!"
| [] |
mertyildiran/echo | core/migrations/0002_auto_20180702_1913.py | 805db64e3fa9d31fd3c24390fac2e9bf7c91ad57 | # Generated by Django 2.0.6 on 2018-07-02 19:13
import core.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='echo',
old_name='own... | [((240, 316), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""echo"""', 'old_name': '"""owner"""', 'new_name': '"""user"""'}), "(model_name='echo', old_name='owner', new_name='user')\n", (262, 316), False, 'from django.db import migrations, models\n'), ((471, 525), 'django.db.model... |
ajdavis/aiohttp | tests/test_helpers.py | d5138978f3e82aa82a2f003b00d38112c58a40c1 | import pytest
from unittest import mock
from aiohttp import helpers
import datetime
def test_parse_mimetype_1():
assert helpers.parse_mimetype('') == ('', '', '', {})
def test_parse_mimetype_2():
assert helpers.parse_mimetype('*') == ('*', '*', '', {})
def test_parse_mimetype_3():
assert (helpers.pars... | [((3124, 3162), 'unittest.mock.patch', 'mock.patch', (['"""aiohttp.helpers.datetime"""'], {}), "('aiohttp.helpers.datetime')\n", (3134, 3162), False, 'from unittest import mock\n'), ((3164, 3187), 'unittest.mock.patch', 'mock.patch', (['"""os.getpid"""'], {}), "('os.getpid')\n", (3174, 3187), False, 'from unittest impo... |
truls/faas-profiler | GenConfigs.py | d54ca0d9926f38c693f616ba4d08414aea823f51 | from os.path import join
FAAS_ROOT="/lhome/trulsas/faas-profiler"
WORKLOAD_SPECS=join(FAAS_ROOT, "specs", "workloads")
#FAAS_ROOT="/home/truls/uni/phd/faas-profiler"
WSK_PATH = "wsk"
OPENWHISK_PATH = "/lhome/trulsas/openwhisk"
#: Location of output data
DATA_DIR = join(FAAS_ROOT, "..", "profiler_results")
SYSTEM_CPU... | [((82, 119), 'os.path.join', 'join', (['FAAS_ROOT', '"""specs"""', '"""workloads"""'], {}), "(FAAS_ROOT, 'specs', 'workloads')\n", (86, 119), False, 'from os.path import join\n'), ((267, 308), 'os.path.join', 'join', (['FAAS_ROOT', '""".."""', '"""profiler_results"""'], {}), "(FAAS_ROOT, '..', 'profiler_results')\n", (... |
LuisPereda/Learning_Python | Chapter09/calc.py | e89e69346c5584be10d991010f39b59329793ba5 |
def sum1(a,b):
try:
c = a+b
return c
except :
print "Error in sum1 function"
def divide(a,b):
try:
c = a/b
return c
except :
print "Error in divide function"
print divide(10,0)
print sum1(10,0) | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.