id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
107507 | import urllib.request
from bs4 import BeautifulSoup
from django.core.exceptions import ObjectDoesNotExist
import re
from standard.models import *
from projects.models import *
dwc_url = 'http://rs.tdwg.org/dwc/terms/'
simple_dwc_url ='http://rs.tdwg.org/dwc/terms/simple/'
def get_dwc_html(url=dwc_url):
opener = ... | StarcoderdataPython |
135679 | import time
debug = False
def error_fx(text):
'''The default error handling, print the text to the console.
replace with your own function if you want, have it print to your
wx application or whatever.'''
sys.stderr.write(text)
def output_fx(text):
'''The default output handling, print text to... | StarcoderdataPython |
1696387 | """
Grab bag of tests implemented for the various CASA routines. This
isn't a systematic unit test, but if you write something useful put it
here. This collection for be for tests that can be run with only the
pipeline itself in place. There are other test files in the scripts/
directory.
"""
#region Imports and defin... | StarcoderdataPython |
153496 | __version__ = "0.1.0"
__version_info__ = (0, 1, 0)
import loggerpy
logger_level = loggerpy.Level.DEBUG
def get_version():
return __version__
DATA_FIELD = [
"id",
"CAP",
"city",
"provincia",
"provincia_iso",
"regione",
"stato",
"stato_iso",
"latitude",
"longitude",
"... | StarcoderdataPython |
101552 | <reponame>ValeriaRibeiroDev/CursoEmVideo-Scripts-Python<gh_stars>0
dia=input ('Qual é o dia que você nasceu?')
mês=input ('Qual é o mês que você nasceu?')
ano=input ('Qual é o ano que você nasceu?')
| StarcoderdataPython |
1656022 | array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]
for i in range(len(array)):
min_index = i
for j in range(i+1, len(array)):
if array[min_index] > array[j]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
print(array)
# swap example ##########################
array = [3, 5... | StarcoderdataPython |
3200125 | import pycom
import time
import config
class LED:
SUCCESS = 0x00ff00
ERROR = 0xff0000
TRANSMIT = 0x0000ff
PROCESSING = 0xffff00
def set(self, color, timeout = None):
if not config.LEDS:
return
pycom.rgbled(color)
if timeout is not None:
time.sleep(... | StarcoderdataPython |
179800 | """
Node for Panda3d that renders a floor.
@author <NAME>
"""
from os import path
from pathlib import Path
from panda3d.core import GeomVertexFormat, Geom, GeomVertexData, GeomVertexWriter, GeomTriangles, GeomNode, \
TextureAttrib, RenderState, SamplerState
from direct.showbase.Loader import Loader
class FloorNo... | StarcoderdataPython |
3216764 | #!/usr/bin/env python3
"""
** Allows you to format the text color. **
------------------------------------------
Specifically allows you to choose from a reduced list,
the highlighting color and the text color.
"""
import colorama
from context_printer.memory import get_lifo
colorama.init() # for windows
def _st... | StarcoderdataPython |
79686 | def make_subject(sector: str, year: str, q: str):
return f'[업종: {sector}] {year}년도 {q}분기'
def make_strong_tag(value: str):
return f'<strong>{value}</strong>'
def make_p_tag(value: str):
return f'<p>{value}</p>'
def make_img_tag(name: str, src: str):
return f'<img src="{src}" alt="{name}">'
def m... | StarcoderdataPython |
1701059 | <filename>ttracker/model/thread_logger/deck.py
from ttracker.model.items.deck import DeckList
class CreateDeckV3:
def __init__(self, payload):
self.deck = DeckList(payload)
class GetDeckListsV3:
def __init__(self, payload):
self.deck_lists = self.get_deck_lists(payload)
def get_deck_lis... | StarcoderdataPython |
1633683 | <filename>sphinxpapyrus/docxbuilder/nodes/description.py
# -*- coding: utf-8 -*-
"""
Translate docutils node description formatting.
each description start will processed with visit() and finished with depart()
"""
from docutils.nodes import Node
from sphinxpapyrus.docxbuilder.translator import DocxTranslator
node_na... | StarcoderdataPython |
12863 | from .common import *
HEADER = r'''\usepackage{tikz}
\definecolor{purple}{cmyk}{0.55,1,0,0.15}
\definecolor{darkblue}{cmyk}{1,0.58,0,0.21}
\usepackage[colorlinks,
linkcolor=black,
urlcolor=darkblue,
citecolor=purple]{hyperref}
\urlstyle{same}
\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{L... | StarcoderdataPython |
1616788 | #!/usr/bin/env python3
from collections import defaultdict
MAX_N = 10 ** 6 + 1
def main():
n, a = ints()
colors = list(ints())
# Count of each color
counts = [0] * MAX_N
# Map from count -> {Set of colors with this count...}
index = defaultdict(set)
index[0] = set(colors)
for c i... | StarcoderdataPython |
5888 | from mushroom_rl.utils.plots import PlotItemBuffer, DataBuffer
from mushroom_rl.utils.plots.plot_item_buffer import PlotItemBufferLimited
class RewardPerStep(PlotItemBuffer):
"""
Class that represents a plot for the reward at every step.
"""
def __init__(self, plot_buffer):
"""
Constr... | StarcoderdataPython |
1767006 | # Generated by Django 3.0.5 on 2020-10-28 10:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('configs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='sysconfigs',
name='web_desc',
... | StarcoderdataPython |
1707710 | """
File: show_results.py
Author: <NAME>
TFG
"""
import argparse
import os
import keras
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
from keras.models import load_model
from keras.preprocessing.ima... | StarcoderdataPython |
93896 | """TDD support for a function cleaning cluttered HTML code.
"""
import re
import unittest
CLUTTERED = ''' <P CLASS="western"><A NAME="ScID:17"></A><A NAME="ScID:120"></A><!-- Climb up rope to safety. Back in ship for hyperspace. --><FONT COLOR="#000000"><SPAN STYLE="text-decoration: none"><FONT FACE="m... | StarcoderdataPython |
3283861 | import requests
from itertools import chain
from bs4 import BeautifulSoup, Tag
BASE_URL = 'https://mvnrepository.com/artifact/{group}/{artifact}/{number}'
class MvnRepository:
def __init__(self, http_compression=True):
self._session = requests.Session()
if not http_compression:
self... | StarcoderdataPython |
3314369 | <reponame>Conchsk/mlapt
HDFS_HOST = '127.0.0.1'
HDFS_PORT = 9870
HDFS_USER = 'conch'
| StarcoderdataPython |
1652967 | <filename>ds/backpropogation.py
import numpy as np
x = 5.0
y = 7.0
lmb = 0.1
w1 = 1.0
w2 = -1.0
w3 = 2.0
u = np.tanh(w1*x)
z = np.tanh(w2*u)
yhat = w3*z
dL_yhat = 2 * (yhat - y)
dL_w3 = 2 * (yhat - y) * z
w3 = w3 - lmb * dL_w3
| StarcoderdataPython |
3322349 | from flask_login import UserMixin, AnonymousUserMixin
from flask_bcrypt import generate_password_hash
from datetime import datetime
from services.web_application.web_app.myapp import database
'''
# How to add roles to a user?
# CODE:
role = Role.query.filter_by(name='MyRole').first()
user = User.query.filter_by(userna... | StarcoderdataPython |
1785967 | #!/usr/bin/env python3
# coding:utf-8
from setuptools import setup
setup(name='easy_util',
version='0.0.dev1',
description='Easy util provide memory usage, flush animation during calculation and so on.',
author='Mogu',
author_email='<EMAIL>',
url='https://github.com/Moguf/easy_util',
... | StarcoderdataPython |
3363645 | import pytest
from collections import defaultdict
from coffea import processor
from functools import partial
import numpy as np
def test_accumulators():
a = processor.value_accumulator(float)
a += 3.
assert a.value == 3.
assert a.identity().value == 0.
a = processor.value_accumulator(partial(np.a... | StarcoderdataPython |
4811783 | import numpy as np
def log_gaussian(x, mean, sigma):
"""
Evaluate the log of a normal law
Parameters
----------
x: float or array-like
Value at which the log gaussian is evaluated
mean: float
Central value of the normal distribution
sigma: float
Width of the norma... | StarcoderdataPython |
3204381 | <reponame>Kamil732/DK-team<filename>backend/project/accounts/api/pagination.py
from rest_framework import pagination
from rest_framework.response import Response
class CustomerImagesPagination(pagination.PageNumberPagination):
page_size = 20
def get_paginated_response(self, data):
return Response({
... | StarcoderdataPython |
4824881 | <filename>kronos/settings.py
import os
import sys
from django.conf import settings
PROJECT_PATH = os.getcwd()
PROJECT_MODULE = sys.modules['.'.join(settings.SETTINGS_MODULE.split('.')[:-1])]
| StarcoderdataPython |
1718229 | <reponame>Sheetal0601/InterviewBit
# Numbers of length N and value less than K
# https://www.interviewbit.com/problems/numbers-of-length-n-and-value-less-than-k/
#
# Given a set of digits (A) in sorted order, find how many numbers of length B are possible
# whose value is less than number C.
#
# NOTE: All numbers c... | StarcoderdataPython |
70365 | <filename>lhotse/recipes/timit.py
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corporation (Author: <NAME>)
# Apache 2.0
import glob
import logging
import zipfile
from collections import defaultdict
from concurrent.futures.thread import ThreadPoolExecutor
from pathlib import Path
from typing import Dict, Optional, ... | StarcoderdataPython |
3360486 | from flask import Flask
from flask_bcrypt import Bcrypt
from flask_graphql import GraphQLView
import config
from gql import schema
app = Flask(__name__)
bcrypt = Bcrypt(app)
app.debug = config.DEBUG
app.config["SQLALCHEMY_DATABASE_URI"] = config.DB_URI
app.config[
"SQLALCHEMY_TRACK_MODIFICATIONS"] = config.SQLAL... | StarcoderdataPython |
3394857 | <reponame>Kaufi-Jonas/VaRA-Tool-Suite<filename>varats/varats/tables/code_centrality_table.py
"""Module for code centrality tables."""
import logging
import typing as tp
from pathlib import Path
import pandas as pd
from tabulate import tabulate
from varats.data.reports.blame_interaction_graph import (
create_blame... | StarcoderdataPython |
100074 | from pykeepass import PyKeePass
kp4_pass = "<PASSWORD>"
kp4 = PyKeePass("keepass_v4_test.kdbx", password=kp4_pass)
kp3_pass = "<PASSWORD>"
kp3 = PyKeePass("keepass_v4_test.kdbx", password=kp3_pass)
kp = kp4
divider = "#" * 50
print("list all groups:")
print(kp.groups)
print(divider)
print("for each group, list all... | StarcoderdataPython |
1777742 | import unittest
from iterable_collections import collect
class TestPop(unittest.TestCase):
def test_list(self):
c = collect(list(range(10)))
self.assertEqual(c.pop(), list.pop(list(list(range(10)))))
self.assertEqual(c.len(), 9)
c.pop()
self.assertEqual(c.len(), 8)
d... | StarcoderdataPython |
3274249 | <gh_stars>0
from .travis_logs import TravisLogsStorage
| StarcoderdataPython |
3215104 | <filename>tests/components/deconz/test_light.py
"""deCONZ light platform tests."""
from unittest.mock import Mock, patch
from homeassistant import config_entries
from homeassistant.components import deconz
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_co... | StarcoderdataPython |
1629860 | from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import F, Q
from django.shortcuts import redirect, render
from django.vi... | StarcoderdataPython |
1797906 | '''
Created on 08/20/2014
@<NAME>
'''
import argparse
import glob
import os
import sys
import time
import stat
from subprocess import Popen
from subprocess import call
import shlex
import shutil
from pprint import pprint
import re
def main():
parser = argparse.ArgumentParser(prog='dmp_run_pipeline_in_batch.py', de... | StarcoderdataPython |
3212572 | <filename>galois_field/exceptions.py
#!/usr/bin/python3
class FFOperationException(Exception):
"""
Finite Field Element Operation Exception
"""
def __init__(self, op="", msg=""):
self.operator = op
self.message = msg
class PrimeFieldNoFitException(Exception):
"""
No fitting ... | StarcoderdataPython |
1709084 | from setuptools import setup
setup(
name='journal-cli', # This is the name of your PyPI-package.
version='0.3', # Update the version number for new release
scripts=['journal'] # The name of your scipt, and also the command you'll be using for calling it
) | StarcoderdataPython |
3349041 | import unittest
import time
from collections.abc import Iterable
import numpy as np
import openmdao.api as om
from openmdao.utils.mpi import MPI
from openmdao.utils.array_utils import evenly_distrib_idxs, take_nth
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
try:
from parameterized i... | StarcoderdataPython |
3291078 | <reponame>droctothorpe/robin
import os
from flask_migrate import Migrate, upgrade
from app import create_app, db
from app.models import Channel
app = create_app(os.getenv("FLASK_CONFIG") or "default")
migrate = Migrate(app, db)
@app.shell_context_processor
def make_shell_context():
return dict(db=db, Channel=C... | StarcoderdataPython |
14152 | <gh_stars>1-10
# Generated by Django 2.1.4 on 2018-12-21 21:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fi... | StarcoderdataPython |
1717423 | lev=[]
with open('map.txt') as f:
for line in f:
tmp=[]
for letter in line:
if letter != '\n':
tmp.append(letter.replace('.', '0'))
lev.append(tmp)
ly=len(lev)
lx=len(lev[0])
for i in lev:
print(i)
fx=0
fy=0
for line in lev:
try:
fx = line.index('x... | StarcoderdataPython |
16600 | <filename>lite/tests/unittest_py/pass/test_conv_elementwise_fuser_pass.py
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | StarcoderdataPython |
131833 | <gh_stars>1-10
###############################################################################
# Caleydo - Visualization for Molecular Biology - http://caleydo.org
# Copyright (c) The Caleydo Team. All rights reserved.
# Licensed under the new BSD license, available at http://caleydo.org/license
#######################... | StarcoderdataPython |
164306 | #!/usr/bin/env python
import sys
import time
import obd
import json
import os
if len(sys.argv) == 1:
connection = obd.OBD()
else:
connection = obd.OBD(sys.argv[1])
os.system('clear')
while True:
print 'Car Information: '
print 'Speed : ' + \
str(connection.query(obd.commands.SPEED).value.to("... | StarcoderdataPython |
1617554 | <filename>samtranslator/model/preferences/deployment_preference_collection.py<gh_stars>0
from .deployment_preference import DeploymentPreference
from samtranslator.model.codedeploy import CodeDeployApplication
from samtranslator.model.codedeploy import CodeDeployDeploymentGroup
from samtranslator.model.iam import IAMRo... | StarcoderdataPython |
1788933 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
file : LISTA_base.py
author: xhchrn
email : <EMAIL>
date : 2019-02-18
A base class for all LISTA networks.
"""
import numpy as np
import numpy.linalg as la
import tensorflow as tf
import sys, os
import time
import utils.train
class LISTA_base ... | StarcoderdataPython |
1732730 | <filename>Solutions/mailroom/mailroom_fp/test_mailroom.py<gh_stars>0
# test-mailroom.py
import pytest
from random import randint, SystemRandom
from string import ascii_letters as letters
# from mailroom_mfr import (
from mailroom_parallel import (
load_donordb,
add_donation,
tally_report,
)
@pytest.fixt... | StarcoderdataPython |
3325408 | <filename>backend/board/serializer.py
from rest_framework import serializers
from .models import Post, Comment,Category
from users.models import User
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model=Category
fields = ('name','post_num')
class CommentSerializer(serializers.M... | StarcoderdataPython |
3251045 | # -*- coding: utf-8 -*-
#
# Copyright 2017-2018 AVSystem <<EMAIL>>
#
# 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 ap... | StarcoderdataPython |
1614629 | <filename>test.py
import i3
import unittest
import platform
py3 = platform.python_version_tuple() > ('3',)
class ParseTest(unittest.TestCase):
def setUp(self):
self.msg_types = ['get_tree', 4, '4']
self.event_types = ['output', 1, '1']
def test_msg_parse(self):
msg_types = []
... | StarcoderdataPython |
1700033 | """https://github.com/lw/BluRay/wiki/MPLS"""
__all__ = ['MoviePlaylist']
from abc import ABC, abstractmethod
from io import BufferedReader
from pprint import pformat
from struct import unpack
from typing import Any, Dict, Tuple
class MplsObject(ABC):
"""Abstract MPLS object interface"""
mpls: BufferedReade... | StarcoderdataPython |
25448 | """TuneBlade API Client."""
import logging
import asyncio
import socket
from typing import Optional
import aiohttp
import async_timeout
TIMEOUT = 10
_LOGGER: logging.Logger = logging.getLogger(__package__)
HEADERS = {"Content-type": "application/json; charset=UTF-8"}
class TuneBladeApiClient:
def __init__(
... | StarcoderdataPython |
3201536 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 13:17:52 2020
@author: <NAME>, Finnish Meteorological Institute
@licence: MIT licence Copyright
"""
import matplotlib
import numpy
import os
import pathlib
import seaborn
from Data import Data
from FileSystem import FileSystem
from PlotTweak imp... | StarcoderdataPython |
3337751 | import pandas as pd
import numpy as np
import xgboost as xgb
from collections import Counter
import random
from sklearn.metrics import accuracy_score, confusion_matrix
# from xgboost.sklearn import XGBClassifier
from sklearn.model_selection import train_test_split
# from sklearn import cross_validation, metrics
from sk... | StarcoderdataPython |
170109 | <gh_stars>1-10
from comet_ml import OfflineExperiment # needed at top for Comet plugin
from collections import defaultdict, OrderedDict
import torch
import torch.nn as nn
import tqdm
import time
from sklearn.metrics import f1_score, precision_score, recall_score
import torch.nn.functional as F
from utils import *
impor... | StarcoderdataPython |
87576 | <reponame>rkulyn/telegram-pig-latin-bot
from functools import lru_cache
from .constants import VOWELS
from .decorators import check_if_word_capitalized
from .rules import vowel_rule, h_rule, consonant_rule
@lru_cache(maxsize=50)
@check_if_word_capitalized
def translate(word):
"""
Translation strategy selecti... | StarcoderdataPython |
1639822 | <reponame>sermonis/three-globe-flight-line
import os
command = "python -m SimpleHTTPServer 8000"
os.system(command)
| StarcoderdataPython |
1610325 | from pathlib import Path
import moonleap.resource.props as P
from moonleap import extend, rule
from moonleap.verbs import has
from titan.react_pkg.reactapp import ReactApp
from .props import get_context
@rule("react-app", has, "routes:module")
def react_app_has_routes_module(react_app, routes_module):
routes_mo... | StarcoderdataPython |
1711723 | <gh_stars>0
from collections import defaultdict, OrderedDict, namedtuple
from decimal import Decimal
from operator import itemgetter
from billy import db
KEYS = 'versions actions documents votes sponsors'.split()
class SaneReprList(list):
def __repr__(self):
return '<SaneReprList: %d elements>' % len(s... | StarcoderdataPython |
1745611 | import numpy as np
import pandas as pd
import pytest
from featuretools.primitives import CityblockDistance, GeoMidpoint, IsInGeoBox
def test_cityblock():
primitive_instance = CityblockDistance()
latlong_1 = pd.Series([(i, i) for i in range(3)])
latlong_2 = pd.Series([(i, i) for i in range(3, 6)])
pri... | StarcoderdataPython |
164289 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## mds.py
##
## Created on: Dec 3, 2017
## Author: <NAME>
## E-mail: <EMAIL>
##
# print function as in Python3
#==============================================================================
from __future__ import print_function
from minds.check import Consiste... | StarcoderdataPython |
1792031 | from ifem import test_solve_system
test_solve_system()
from applications import test_uniform_bar
test_uniform_bar()
| StarcoderdataPython |
195113 | """A basic example of using the SQLAlchemy Sharding API.
Sharding refers to horizontally scaling data across multiple
databases.
The basic components of a "sharded" mapping are:
* multiple databases, each assigned a 'shard id'
* a function which can return a single shard id, given an instance
to be saved; this is c... | StarcoderdataPython |
1783390 | from django.urls import path, include
from rest_framework import routers
from .viewsets import NewsReadOnlyModelViewSet, NewsRetrieveModelViewSet
router = routers.SimpleRouter()
router.register('news', NewsReadOnlyModelViewSet)
router.register('retrieve', NewsRetrieveModelViewSet)
urlpatterns = [
path('', inclu... | StarcoderdataPython |
3359863 | import tensorflow as tf
import numpy as np
############################################################################################################
# Convolution layer Methods
def __conv2d_p(name, x, w=None, num_filters=16, kernel_size=(3, 3), padding='SAME', stride=(1, 1),
initializer=tf.contrib.l... | StarcoderdataPython |
127300 | import claripy
from ..errors import SimMemoryError
def obj_bit_size(o):
if type(o) is bytes:
return len(o) * 8
return o.size()
class SimMemoryObject(object):
"""
A MemoryObjectRef instance is a reference to a byte or several bytes in
a specific object in SimSymbolicMemory. It is only use... | StarcoderdataPython |
1645664 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `rmdawn` package."""
import pytest
from click.testing import CliRunner
from cli import rmdawn_cli
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
def test_content(respo... | StarcoderdataPython |
3366890 | """
module docs go here
"""
| StarcoderdataPython |
3355450 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: <NAME> <<EMAIL>>
#
# 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
#
#... | StarcoderdataPython |
3278172 | <filename>Python3/0747-Largest-Number-At-Least-Twice-of-Others/soln.py
class Solution:
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# find the largest and second
first, second, idx = float('-inf'), float('-inf'), 0
for i, num in enu... | StarcoderdataPython |
184388 | <reponame>ExpressAI/eaas_client<filename>setup.py
from setuptools import setup, find_packages
import codecs
import eaas
import eaas.client
setup(
name="eaas",
version=eaas.__version__,
description="Evaluation as a Service for Natural Language Processing",
long_description=codecs.open("README.md", encoding="u... | StarcoderdataPython |
130218 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ast
import contextlib
import fnmatch
import json
import os
import pipes
import re
import shlex
import shutil
import stat
import subprocess
import sys
... | StarcoderdataPython |
1613772 | <reponame>hbasria/bitresource
from bitutils.objects import Exchange
from registry import Registry
class ResourceRegistry(Registry):
def get_object_name(self, data):
if hasattr(data, 'name'):
exchange_code = getattr(data, 'name')
exchange_registry.register(Exchange(code=exchange_co... | StarcoderdataPython |
3231733 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Example for commanding robot with position control using moveit planner
"""
from pyrobot import Robot
from pyrobot.utils.util import Movei... | StarcoderdataPython |
1741841 | <reponame>SirLegolot/hide.me
#Steganography for hiding text inside images
from PIL import Image
import imghdr
import math
import ast
import random
# the structure of the for loops for the encoding functions was inspired by:
# https://hackernoon.com/simple-image-steganography-in-python-18c7b534854f
# particu... | StarcoderdataPython |
3256984 | #!/usr/bin/env python
import os, sys, time
if len(sys.argv) < 2:
print "usage: %s directory..." % sys.argv[0]
sys.exit(1)
def get_date(file_name):
i = file_name.rfind('-')
if i == -1:
return ""
t = int(file_name[i+1:])
return time.ctime(t)
for dir in sys.argv[1:]:
print dir
f... | StarcoderdataPython |
3270332 | # 青岛啤酒活动,联通每天领3次共90M流量
# https://www.52pojie.cn/thread-950775-1-1.html
import requests as r
import time
def f1(num):
data1 = {
'phoneVal': num,
'type': '21'
}
# 获取验证码
print(r.post('https://m.10010.com/god/AirCheckMessage/sendCaptcha', data=data1).text)
# 领取流量
print(r.get('http... | StarcoderdataPython |
1738600 | from .CompDesc import CompDesc
from .functionToolbox import *
| StarcoderdataPython |
151094 | import gtimer as gt
from rlkit.core import logger
from ROLL.online_LSTM_replay_buffer import OnlineLSTMRelabelingBuffer
import rlkit.torch.vae.vae_schedules as vae_schedules
import ROLL.LSTM_schedule as lstm_schedules
from rlkit.torch.torch_rl_algorithm import (
TorchBatchRLAlgorithm,
)
import rlkit.torch.pytorch_u... | StarcoderdataPython |
3391041 | <reponame>czchen/debian-pgcli
from __future__ import print_function
import sys
import logging
from collections import namedtuple
from .tabulate import tabulate
TableInfo = namedtuple("TableInfo", ['checks', 'relkind', 'hasindex',
'hasrules', 'hastriggers', 'hasoids', 'tablespace', 'reloptions', 'reloftype',
'relpersis... | StarcoderdataPython |
4813898 | import glob
import logging
import urllib.request
from discord.ext import commands
from discord import Embed, Color
from config import config
from log import DiscordHandler
description = """
Solving your image needs
"""
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
log.info(urllib.request.url... | StarcoderdataPython |
4832404 | ################################################################################
# Copyright 2016-2021 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in t... | StarcoderdataPython |
3367621 | <filename>testing/test_all.py
#!/usr/bin/env python
#
# Launch all testing scripts.
#
# Author: <NAME>, <NAME>
# Last Modif: 2014-06-11
import os
import getopt
import sys
from numpy import loadtxt
import commands
# get path of the toolbox
status, path_sct = commands.getstatusoutput('echo $SCT_DIR')
# append path that... | StarcoderdataPython |
3374490 | <reponame>andreportela/qas_intrusion_detection<filename>qas_experimental_evaluation_project/ransomware.py<gh_stars>0
from os import listdir, remove
from os.path import isfile, join
from random import seed, randint
import time
seed(1)
folder = "medical_records/"
first_file_index = 0
seconds_to_sleep = 1
def start():
... | StarcoderdataPython |
1782047 | '''
Base driver class
'''
import pandas as pd
import requests
import json
from copy import deepcopy
import pyperclip
import math
import re
import inspect
import yaml
import itertools
from datetime import datetime
import warnings
import functools
from textwrap import dedent
from datapungi_fed import generalSettings ... | StarcoderdataPython |
170873 | ## pip install librosa
#
import time
import matplotlib.pyplot as plt
import librosa
import librosa.display
# wav 采样率转换
def convert_wav(file, rate=16000):
signal, sr = librosa.load(file, sr=None)
new_signal = librosa.resample(signal, sr, rate) #
out_path = file.split('.wav')[0] + "_new.wav"
librosa.out... | StarcoderdataPython |
1730346 | from Core.IFactory import IFactory
from Regs.Block_C import RC120
class RC120Factory(IFactory):
def create_block_object(self, line):
self.rc120 = _rc120 = RC120()
_rc120.reg_list = line
return _rc120
| StarcoderdataPython |
17996 | <gh_stars>1-10
#zadanie 1
i=1
j=1
k=1
ciag=[1,1]
while len(ciag)<50:
k=i+j
j=i
i=k
ciag.append(k)
print(ciag)
#zadanie 2
wpisane=str(input("Proszę wpisać dowolne słowa po przecinku "))
zmienne=wpisane.split(",")
def funkcja(*args):
'''Funkcja sprawdza długość słów i usuw... | StarcoderdataPython |
1743918 | from gym_TD.utils import logger
import time
def PPO_train_single(ppo, state, action, next_state, reward, done, info, writer, title, config):
if (action != info['RealAction']).any():
reward -= 0.3
ppo.record_single(state, action, reward, done)
if ppo.len_trajectory % config.horizon == 0:
ppo... | StarcoderdataPython |
3240024 |
# author: https://blog.furas.pl
# date: 2020.07.16
# link: https://stackoverflow.com/questions/62921395/pandas-include-key-to-json-file/
import requests
import pandas as pd
import json
url = 'http://www.fundamentus.com.br/resultado.php'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit... | StarcoderdataPython |
3220702 | <reponame>corycrean/moveit2
import os
import yaml
from launch import LaunchDescription
from launch.actions import ExecuteProcess
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import xacro
def load_file(package_name, file_path):
package_path = get_package_s... | StarcoderdataPython |
1649649 | <filename>utils/logConf.py
import logging
format="%(asctime)s [%(filename)s:%(lineno)d] %(levelname)-8s %(message)s"
logging.basicConfig(level=logging.DEBUG, format=format) | StarcoderdataPython |
1641187 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from rdflib import Graph, Namespace, Literal
from os.path import abspath, dirname, join
hierarchy_path = join(dirname(abspath(__file__)),
'../resources/activity_hierarchy.rdf')
def save_hierar... | StarcoderdataPython |
22930 | from pytracetable.core import tracetable
__all__ = [
'tracetable',
]
| StarcoderdataPython |
1750825 | import os.path
import re
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as f:
version_content = [line for line in f.readlines() if re.search(r'([\d.]+)',line)]
if len(version_content) != 1:
raise RuntimeError('Invalid format of VERSION file.')
__version__ = version_content[0]
| StarcoderdataPython |
1798842 | <reponame>82ndAirborneDiv/BMGAP
#!/usr/bin/env python3.4
### Phylogeny Building Tool v1
### Import Modules ###
import sys
from Bio import SeqIO
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
... | StarcoderdataPython |
171835 | <reponame>mdaal/rap
import numpy as np
import copy
import sys
def circle_fit(loop):
S21 = loop.z
Freq = loop.freq
LargeCircle = 10
def pythag(m,n):
'''compute pythagorean distance
sqrt(m*m + n*n)'''
return np.sqrt(np.square(m) + np.square(n))
def eigen2x2(a,b,c):
... | StarcoderdataPython |
3346075 | # -*- coding: utf-8 -*-
"""Top-level package for Visualate."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.