id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3331917 | import unittest
import mock
from mock import MagicMock,patch
import os.path
import logging
import sys,os
from MockData import User_Details_list
import sys
import sys, os
sys.path.append(os.path.abspath(os.path.join('..','Models/')))
import MyUser
sys.path.append(os.path.abspath(os.path.join('..', 'extensions/')))
impo... | StarcoderdataPython |
160523 | import logging
import os
import docker
from background_task import background
from nifi_web.models import ImageMirrorJob
logger = logging.getLogger(__name__)
@background(schedule=0, remove_existing_tasks=True)
def perform_mirror_ops_bg():
perform_mirror_ops()
def perform_mirror_ops():
logger.info('perform... | StarcoderdataPython |
12005 | <filename>xarray/backends/npy_io.py
import numpy as np
import xarray as xr
import pandas as pd
import sys
import json
import os
import datetime
from xarray.core.utils import (
decode_numpy_dict_values,
either_dict_or_kwargs,
ensure_us_time_resolution,
)
from numpy.compat import (
asbytes, asstr, asun... | StarcoderdataPython |
3339381 | <reponame>ferhatelmas/algo
class PeekingIterator:
def __init__(self, iterator):
self.i = iterator
self.v = None
def peek(self):
if self.v:
return self.v
self.v = self.i.next()
return self.v
def next(self):
if self.v is None:
return se... | StarcoderdataPython |
1681812 | <reponame>ranking-agent/aragorn-ranker
"""Neo4j lookup utilities."""
import httpx
import logging
from abc import ABC, abstractmethod
from urllib.parse import urlparse
from neo4j import GraphDatabase, basic_auth
logger = logging.getLogger(__name__)
class Neo4jDatabase():
"""Neo4j database.
This is a thin wr... | StarcoderdataPython |
1673989 | <reponame>tws0002/anima
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2018, <NAME>
#
# This module is part of anima-tools and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
import logging
import os
from collections import namedtuple
import anima
from anima import logger
from ani... | StarcoderdataPython |
1677808 | # -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon En... | StarcoderdataPython |
3211416 | import pytest
import time
import random
from endpoints.stores import ReadStoreError
from services import service_factories
from tools import tools
from endpoints.tests.emulators import (
DSMR_Emulator,
Fronius_Emulator
)
from services.strategies.basic import Log_Strategy
from services.events import Periodic... | StarcoderdataPython |
3235987 | import numpy as np
from multiagent.coreRace import World, Agent, Landmark
from multiagent.scenario import BaseScenario
backWardPunishment = 5
class Scenario(BaseScenario):
def __init__(self):
super(Scenario, self).__init__()
self.agentsToLandMarks = {}
self.numberOfAgents=6
self.a... | StarcoderdataPython |
74399 | import numpy as np
import unittest
from chainer import testing
from chainercv.experimental.links.model.pspnet import convolution_crop
class TestConvolutionCrop(unittest.TestCase):
def test_convolution_crop(self):
size = (8, 6)
stride = (8, 6)
n_channel = 3
img = np.random.uniform... | StarcoderdataPython |
1604370 | <reponame>latte-horse/jaehyun
#!/usr/bin/python
#analyza.py
from gensim.models import Word2Vec
from modules import util
from modules import morpheus
from modules import tfidf
import pandas
#------------------------------------------------------------------------------
# word2vec
#----------------------------------... | StarcoderdataPython |
3236127 | <gh_stars>0
from gym.envs.registration import register
MAX_STEPS = 1000
register(
id='DeepRacerRacetrack-v0',
entry_point='markov.environments.deepracer_racetrack_env:DeepRacerRacetrackEnv',
max_episode_steps=MAX_STEPS,
reward_threshold=200
)
register(
id='DeepRacerRacetrackCustomActionSpaceEnv-v... | StarcoderdataPython |
1651554 | <filename>ex3/database.py<gh_stars>0
db = []
def db_add(value):
pass
def db_remove_first():
pass
def db_remove_last():
pass
def db_find(value):
return False
def db_add_multiple(value_list):
pass
def db_export_to_file(file_name):
pass
def db_import_from_file(file_name):
pass
| StarcoderdataPython |
18080 | <reponame>Raniac/NEURO-LEARN<gh_stars>1-10
""" Tests for the import manager. """
from traits.util.api import import_symbol
from traits.testing.unittest_tools import unittest
class TestImportSymbol(unittest.TestCase):
""" Tests for the import manager. """
def test_import_dotted_symbol(self):
""" imp... | StarcoderdataPython |
1754805 | from prune import prune
from rest_framework.response import Response
from .get_field_keys import get_field_keys
from .subpaths import subpaths
class FileNameMixin:
def get_filename(self, request, response):
try:
return request.path_info.replace("/", "_").strip("_")
except:
... | StarcoderdataPython |
3346371 | <reponame>MattiasDC/mercs
import numpy as np
def get_i_o(data, desc_ids, targ_ids, filter_nan=True):
if filter_nan:
i_o = data[:, desc_ids+targ_ids]
mask = ~np.any(np.isnan(i_o), axis=1)
i_o_filtered = i_o[mask]
# This works because we ordered the columns very specifically.
... | StarcoderdataPython |
1760904 | <filename>scripts/import-ig-mt4.py
#!/usr/bin/python3
import sys
import subprocess
import pathlib
MODE = "ohlc"
BROKER = "ig.com"
BASE_PATH = "/mnt/storage/Data/market/ig.com/MT4"
MARKETS = {
"CS.D.AUDNZD.MINI.IP": "AUDNZD",
"CS.D.AUDUSD.MINI.IP": "AUDUSD",
"CS.D.EURCAD.MINI.IP": "EURCAD",
"CS.D.EURCH... | StarcoderdataPython |
181189 | import os
from dotenv import load_dotenv
load_dotenv()
DISCORD_SNEAKER_WEBHOOK = os.getenv("DISCORD_SNEAKER_WEBHOOK")
DISCORD_KONG_WEBHOOK = os.getenv("DISCORD_KONG_WEBHOOK")
TWEEPY_API_KEY = os.getenv("TWEEPY_API_KEY")
TWEEPY_API_SECRET = os.getenv("TWEEPY_API_SECRET")
TWEEPY_ACCESS_TOKEN = os.getenv("TWEEPY_ACCESS... | StarcoderdataPython |
1691288 | <reponame>prashantbhutani90/EVM-for-CCF<gh_stars>10-100
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os
import web3
from utils import *
import e2e_args
import infra.ccf
import provider
from loguru import logger as LOG
class ERC20Contract:
def _... | StarcoderdataPython |
1798182 | <gh_stars>100-1000
import os
import synapse.common as s_common
import synapse.lib.lmdbslab as s_lmdbslab
import synapse.lib.slaboffs as s_slaboffs
import synapse.tests.utils as s_t_utils
class SlabOffsTest(s_t_utils.SynTest):
async def test_lmdbslab_base(self):
with self.getTestDir() as dirn:
... | StarcoderdataPython |
4815633 | from django.views.generic import TemplateView
class QgisMapView(TemplateView):
template_name = 'qgisapp/qgis_map.html'
| StarcoderdataPython |
1633304 | <reponame>toebes/onshape-clients<filename>python/onshape_client/client.py<gh_stars>10-100
import os
import warnings
import webbrowser
from enum import Enum
from pathlib import Path
from types import SimpleNamespace
from oauthlib.oauth2 import (
UnauthorizedClientError,
UnsupportedGrantTypeError,
MissingTok... | StarcoderdataPython |
46294 | # Generated by Django 3.0.4 on 2020-03-18 15:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('imdb', '0003_remove_cast_is_debut_movie'),
]
operations = [
migrations.AlterField(
model_name='... | StarcoderdataPython |
1699965 | <reponame>Instagram/Fix
# 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.
from typing import List, Union
import libcst as cst
from libcst.metadata import (
Assignment,
QualifiedName,
... | StarcoderdataPython |
3262838 | from stevedore import enabled
from stevedore.tests import utils
class TestEnabled(utils.TestCase):
def test_enabled(self):
def check_enabled(ep):
return ep.name == 't2'
em = enabled.EnabledExtensionManager(
'stevedore.test.extension',
check_enabled,
... | StarcoderdataPython |
1755494 | <reponame>meghasin/RTX
#!/usr/bin/env python3
'''Filters the RTX "KG2" second-generation knowledge graph, simplifying predicates and removing redundant edges.
Usage: filter_kg.py <predicate-remap.yaml> <kg-input.json> <kg-output.json>
'''
__author__ = '<NAME>'
__copyright__ = 'Oregon State University'
__credits__ ... | StarcoderdataPython |
11438 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
from collections import defaultdict
class Solution(object):
def verticalOrder(self, ... | StarcoderdataPython |
3308423 | <filename>Ejemplo1.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 4 2019
@author: Nahuel
"""
# la variable veces especifica cada cuantas muestras se quiere hacer el promedio
def MediaMovil(vector, veces):
prom = [];
k = 0;
iteraciones = len(vector) - veces + 1;
for i in range(iteraciones... | StarcoderdataPython |
3277632 | from flask_restful import Resource, reqparse
from models.product import ProductModel
class Products(Resource):
def get(self):
# SELECT * FROM products
return {'products:': [product.json() for product in ProductModel.query.all()]}
class Product(Resource):
attribute = reqparse.RequestParser()
... | StarcoderdataPython |
1630312 | <reponame>hajime9652/observations
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def cloud_seeding(path):
"""Cloud Seedi... | StarcoderdataPython |
39298 | <gh_stars>0
from enum import Enum
class BrokerAddressFamily(str, Enum):
any = 'any'
v4 = 'v4'
v6 = 'v6'
class SecurityProtocol(str, Enum):
plaintext = 'plaintext'
ssl = 'ssl'
sasl_plaintext = 'sasl_plaintext'
sasl_ssl = 'sasl_ssl'
class SslEndpointIdentificationAlgorithm(str, Enum):
... | StarcoderdataPython |
3238789 | <reponame>njw1204/BOJ-AC
T=input()
for i in range(97,123):print(T.find(chr(i)),end=' ') | StarcoderdataPython |
1620029 | from random import randint
from time import sleep
computador = randint(0,5)
print("Pensarei em um número entre 0 e 5...")
print('-=-' * 16)
jogador = int(input("Em que número pensei? "))
print("PROCESSANDO...")
sleep(3)
if jogador == computador:
print("Parabéns! Você ganhou :)")
else:
print("GANHEI!!!! Pensei n... | StarcoderdataPython |
1611071 | <filename>prepare_dataset.py
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import unicodedata
import re
import numpy as np
import os
import io
import time
def unicode_to_ascii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c... | StarcoderdataPython |
1714563 | #-*- encoding:UTF-8 -*-
from tools.CrawlerBase import *
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def extract(page):
if page is None:
return (None,None,None)
linkpattern = re.compile(u'<div class=\'article\'><h2><a href=\'(.*?)\' class=\'tj\' target=\'_blank\... | StarcoderdataPython |
1652836 | <gh_stars>0
##
#
# File: CvsAdminTests.py
# Author: <NAME>
# Date: 11-April-2011
# Version: 0.001
#
# Update:
# 12-April-2011 jdw - revision checkout test cases.
# 29-Nov -2012 jdw - refactor CvsAdmin and CvsSandBoxAdmin classes
# 2-Dec -2012 jdw - add commit tests
# 28-Jan -2013 jdw - revise tests for chang... | StarcoderdataPython |
198099 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.system('./retrieve_pdb_chain.py')
os.system('./map_pos.py')
os.system('./TMalign.py')
os.system('./CalSA.py')
os.system('./coord.py') | StarcoderdataPython |
45615 | <reponame>chiragkhandhar/ODAS
from django.http import HttpResponse
from django.shortcuts import render
def index0(request):
return render(request,'home/homepage.html')
| StarcoderdataPython |
1667263 | # coding: utf-8
"""
AquaPi Swagger API
REST API for the AquaPi
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import swagger_client
from swagger_client.rest import Ap... | StarcoderdataPython |
1692084 | """
To find the single number in a list.
Counts number of times each element is present in the list
prints all the elements which are present only once
"""
# function takes input list and converts to a dictionary, key being the element and value is the count
def single_number(input_list):
my_dict = {}
for element ... | StarcoderdataPython |
153790 | #!/usr/bin/env python3
""" Run the gear: set up for and call command-line code """
import json
import os
import subprocess as sp
import sys
import shutil
import psutil
import glob
import flywheel
from utils import args
from utils.bids.download_bids import *
from utils.bids.validate_bids import *
from utils.fly.custom... | StarcoderdataPython |
66161 | import os
from django import template
from django.conf import settings
from django.template import Template, Context
from django.utils.safestring import mark_safe
from django.utils.text import normalize_newlines
from wagtailmenus.models import FlatMenu
from xr_pages import services
from xr_pages.svg_icons import svg_... | StarcoderdataPython |
88098 | <gh_stars>0
__all__ = ["encoder", "mldecoder", "rltrain", "crf"]
| StarcoderdataPython |
3369102 | from flask import Flask, request, abort
import telebot
app = Flask(__name__)
app.config.from_object('{}.config'.format(__name__))
bot = telebot.TeleBot(app.config['TELEGRAM_BOT_TOKEN'], threaded=False)
from . import handlers # noqa
# Why do this? See https://core.telegram.org/bots/api#setwebhook
webhook_url_path =... | StarcoderdataPython |
1670132 | """
Measure several resonators per LO frequency and record SweepStreamArrays.
"""
import time
import numpy as np
from kid_readout.roach import hardware_tools, analog
from kid_readout.measurement import acquire, basic
from kid_readout.equipment import hardware
logger = acquire.get_script_logger(__file__)
# Parameter... | StarcoderdataPython |
1638525 | <reponame>psFournier/deep-rl
import numpy as np
from segmentTree import SumSegmentTree, MinSegmentTree
# added by <NAME> --------------------------------
import pickle
import matplotlib.pyplot as plt
# end of added by <NAME> --------------------------------
#TODO : same buffer for goals and for expe
class RingBuffe... | StarcoderdataPython |
1628892 | <reponame>tiennguyen1510/Android-Pentest-Suite
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
import subprocess
import utils.report_handle as report_handle
import utils.common as common
from report.models import ReportQark, ReportDc, ReportSniffgit, ReportA... | StarcoderdataPython |
3153 | '''
multi-threading (python3 version)
https://docs.python.org/3/library/threading.html
'''
from time import clock
import threading
THREADS=2
lock = threading.Lock()
A = 0
B = 0
C = 0
def test_globals():
global A, B, C
for i in range(1024*1024):
lock.acquire()
A += 1
B += 2
C = A + B
lock.release()
def... | StarcoderdataPython |
184232 | import os
import sys
import re
import json
import cgi
import threading
import datetime
import time
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import urlparse
class AMQPBridgeServer(HTTPServer):
def __init__(self, config, requestHandler):
HTTPServer.__init__(... | StarcoderdataPython |
3214284 | import argparse
import getpass
from termcolor import colored
import github
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--username", required=True, help="Github username")
return parser.parse_args()
def main():
args = parse_args()
password = getpass.getpass("Enter G... | StarcoderdataPython |
3389362 | # -*- coding: utf-8 -*-
import base64, json, random
from illiad_app import settings_app
from django.test import Client, TestCase
from illiad_app.lib.cloud_article_request import ILLiadParamBuilder, Mapper
class ILLiadParamBuilder_Test( TestCase ):
""" Tests parsing of notes in openurl.
Notes-tests corres... | StarcoderdataPython |
3277601 | <reponame>CPSSD/LUCAS
from pymongo import MongoClient
from credentials import username, password
import statistics
import re
from collections import Counter
client = MongoClient('172.16.31.10',
username=username,
password=password,
authSource='admin')
datase... | StarcoderdataPython |
188129 | <filename>leaderboards.py
"""
This module reads a CSV file from Sentiment140
(http://help.sentiment140.com/for-students/)
to create various leaderboards in Redis.
"""
import argparse
import enum
import logging
import pandas as pd
import redis
# Turn on logging with level of info
logging.basicConfig(format="%(asctime)... | StarcoderdataPython |
3367668 | <filename>py/p8.py
# -*- coding: utf-8 -*-
"""P8.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Q_zoAx67N6JCTX6r-Ctlbz1EesyAkHOd
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
... | StarcoderdataPython |
3338879 | <reponame>jigneshoo7/AlgoBook
'''
Jump search is searching algorithm for sorted arrays.It skips some elements by taking fixed steps defined by the block size
instead of travesing through all the elements.
'''
import math #for sqrt
def jumpsearch(arr,ele): #function to perform jump search
n = ... | StarcoderdataPython |
3267167 | <gh_stars>0
from django.forms.widgets import Select
from django.utils.translation import ugettext_lazy as _
from mapentity.filters import PolygonFilter, PythonPolygonFilter, YearFilter, YearBetweenFilter
from geotrek.core.models import Topology
from geotrek.common.filters import StructureRelatedFilterSet
from .model... | StarcoderdataPython |
93395 | import sys
import re
import os
import fnmatch
from os import walk as py_walk
def walk(top, callback, args):
for root, dirs, files in py_walk(top):
callback(args, root, files)
def find_data_files(srcdir, destdir, *wildcards, **kw):
"""
get a list of all files under the srcdir matching wildcards,
... | StarcoderdataPython |
3201982 | ##################################################################
# This script crop faces from a folder contains many human figures
##################################################################
import sys
import dlib
import cv2
import os
import argparse
import largest_face_detector
import copy
Images_Folder = ... | StarcoderdataPython |
3376518 | <reponame>banteg/brownie<filename>brownie/network/web3.py
#!/usr/bin/python3
from pathlib import Path
from web3 import (
HTTPProvider,
IPCProvider,
WebsocketProvider,
Web3 as _Web3
)
from brownie._singleton import _Singleton
class Web3(_Web3, metaclass=_Singleton):
'''Singleton version of web3.... | StarcoderdataPython |
29447 | <reponame>rch/levelpy<filename>levelpy/async/__init__.py
#
# levelpy/async/__init__.py
#
import asyncio
| StarcoderdataPython |
3283919 | <filename>refdata/cli/store.py
# This file is part of the Reference Data Repository (refdata).
#
# Copyright (C) 2021 New York University.
#
# refdata is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Commands that interact with the l... | StarcoderdataPython |
3399061 | <filename>tracking.py<gh_stars>1-10
import numpy as np
import cv2
from skimage.measure import ransac
from helpers import add_ones, poseRt, fundamentalToRt, normalize, EssentialMatrixTransform, myjet
img1 = cv2.imread('/home/lukas/Videos/2021-05-14_08-08-09_camera_1/125.jpg')
img2 = cv2.imread('/home/lukas/Videos/2021... | StarcoderdataPython |
3294930 | import torch
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader
import os
from glob import glob
class RealBlur(Dataset):
def __init__(self, root, transform=None, loader=default_loader):
self.root = root
self.transform = transform
self.loader = loade... | StarcoderdataPython |
1689024 | <reponame>gangchill/nip-convnet
# ----------------------------------------------------
# train and test a convolutional neural network
# ----------------------------------------------------
from tensorflow.python.framework import dtypes
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import... | StarcoderdataPython |
156815 | <reponame>cming091/SearchEngineService<gh_stars>1-10
# -*- coding: utf-8 -*-
import json
import sys
import time
import re
import hashlib
from .utils import make_md5
from .log import LogHandler
log = LogHandler(__name__)
def filter_tags(htmlstr):
# 先过滤CDATA
re_cdata = re.compile('//<!\[CDATA\[[^>]*//\]\]>', ... | StarcoderdataPython |
1695546 | <reponame>Kadantte/twist.moe
import signal
import sys
import requests
import cfscrape
from tqdm import tqdm
scraper = cfscrape.create_scraper()
# to prevent ctrl+c traceback
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko... | StarcoderdataPython |
3251320 | <reponame>Gentostage/prizivnik75
# Generated by Django 2.1.7 on 2019-03-31 03:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0006_auto_20190329_1646'),
]
operations = [
migrations.CreateModel(
name='reviews',
... | StarcoderdataPython |
4820213 | import torch.nn as nn
import torch
def make_optimizer(arg, model):
params = []
bn_param_set = set()
for name, module in model.named_modules():
if isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
bn_param_set.add(name+".weight")
bn_param_set.add(name+".b... | StarcoderdataPython |
1787339 | <reponame>gixita/pulsarnews<filename>app/main/routes.py
from datetime import datetime
from flask import (
flash,
redirect,
render_template,
request,
url_for,
current_app,
jsonify,
)
from flask_jwt import JWT
import json
from flask_login import current_user, login_required
from app import d... | StarcoderdataPython |
1686630 |
# todo 8. Palíndromo. Um palíndromo é uma seqüência de caracteres cuja leitura é idêntica se feita da direita para esquerda ou vice−versa. Por exemplo: OSSO e OVO são palíndromos. Em textos mais complexos os espaços e pontuação são ignorados. A frase SUBI NO ONIBUS é o exemplo de uma frase palíndroma onde os espaços f... | StarcoderdataPython |
3208571 | from django.urls import include, path
from .api import RegisterAPI, LoginAPI, UserAPI
from knox import views as knox_views
from .views import *
urlpatterns = [
path('api/auth', include('knox.urls')),
path('api/auth/register', RegisterAPI.as_view()),
path('api/auth/login', LoginAPI.as_view()),
path('api/auth/user',... | StarcoderdataPython |
163773 | #!/usr/bin/env python
'''General interface for SDL to read and write data sources.
For files, use `SDL_RWFromFile`. Other Python file-type objects can be
used with `SDL_RWFromObject`. If another library provides a constant void
pointer to a contiguous region of memory, `SDL_RWFromMem` and
`SDL_RWFromConstMem` can b... | StarcoderdataPython |
126005 | <filename>language/logic/_illogical.py<gh_stars>0
"""
*Illogical*
Illogical, logically-speaking.
"""
from abc import ABCMeta
__all__ = ["Illogical"]
class Illogical:
__metaclass__ = ABCMeta
| StarcoderdataPython |
30173 | <filename>ex038.py
print('Analisador de números')
print('=-=' * 15)
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
if n1 > n2:
print('O número {} é maior que o número {}'.format(n1, n2))
elif n2 > n1:
print('O número {} é maior que o número {}'.format(n2, n1))
else:
... | StarcoderdataPython |
3352515 | <reponame>UltronAI/Neural-SLAM<filename>utils/optimization.py<gh_stars>100-1000
import inspect
import re
from torch import optim
def get_optimizer(parameters, s):
"""
Parse optimizer parameters.
Input should be of the form:
- "sgd,lr=0.01"
- "adagrad,lr=0.1,lr_decay=0.05"
"""
if "... | StarcoderdataPython |
3225265 | #!/usr/bin/env python
import os, sys, argparse, errno, yaml, time, datetime
import rospy, rospkg
import numpy as np
from road_following.msg import Inference
from road_following.cfg import PID_ControlConfig
from road_following.srv import save_action, save_actionResponse
from rosky_msgs.msg import Twist2DStamped
from dy... | StarcoderdataPython |
3073 | from pyLMS7002M import *
print("Searching for QSpark...")
try:
QSpark = QSpark()
except:
print("QSpark not found")
exit(1)
print("\QSpark info:")
QSpark.printInfo() # print the QSpark board info
# QSpark.LMS7002_Reset() # reset the LMS7002M
lms700... | StarcoderdataPython |
1653544 | #!/usr/bin/env python3
# Copyright (c) 2019 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
This script polls git for new commits, build electrscash and publishes it.
'''
from datetime import d... | StarcoderdataPython |
21991 | <filename>home/pi/_testing/logging-test.py<gh_stars>10-100
#!/usr/bin/env python
import logging
import logging.handlers
import os
# Logging to file
dir_path = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(filename=dir_path + "/test.log", format='%(asctime)s - %(message)s', level=logging.INFO, filemo... | StarcoderdataPython |
88961 | <reponame>maximedaniel/ESTIA-TechnoWebValidator
import os
import zipfile
import shutil
import sys
import time
import json
import urllib.parse
import subprocess
import xlrd
from colorama import init, Fore, Back, Style
init()
# fill this array with specific student names or let it blank to take all students
students =... | StarcoderdataPython |
1617936 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2013 eBay Inc.
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http... | StarcoderdataPython |
190510 | import inspect
import re
import typing as tp
from dataclasses import MISSING
import flax.struct
import jax
import jax.numpy as jnp
import numpy as np
from flax.struct import dataclass
EPSILON = 1e-7
A = tp.TypeVar("A")
IndexLike = tp.Union[str, int, tp.Sequence[tp.Union[str, int]]]
PathLike = tp.Tuple[IndexLike, ..... | StarcoderdataPython |
4806620 | <reponame>erewok/tokamak<filename>examples/tokamak_app.py
import json
from typing import Iterable, Optional, Tuple
from hypercorn.config import Config
from hypercorn.trio import serve
import trio
from tokamak.web import AsgiRouter, Request, Response, Route, Tokamak
async def bg_task(arg1=None):
for n in range(1... | StarcoderdataPython |
3398561 | '''
데이터 분포 살펴보기
1. 기술 통계 - 데이터의 분포의 특징을 대표하는 값
데이터의 숫자 (count)
평균 (mean, average)
분산 (variance)
표준 편차 (standard deviation)
최댓값 (maximum)
최솟값 (minimum)
중앙값 (median)
사분위수 (quartile)
2. 히스토그램 - 히스토그램은 자료 값이 가질 수 있는 범위를 몇 개의 구간으로 나누고
각 구간에 해당하는 값의 숫자 혹은 상대적 빈도를 계산하는 방법이다.
3. 커널 밀도 - 커... | StarcoderdataPython |
3368787 | #%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
# ms-python.python added
import os
try:
os.chdir(os.path.join(os.getcwd(), "example"))
print(os.getcwd())
except:
pass
#%% [markdown]
# Initialisation... | StarcoderdataPython |
1723176 | from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template, render_to_string
def send_templated_mail(subject, from_email, recipients, context,
template_text, template_html=None, **kwargs):
"""Enviá un email usando EmailMultiAlternatives con template... | StarcoderdataPython |
4812753 | from . import datamodification
from . import datatransform
from .adversarial_learning import AdversarialLearning
from .adversary import Adversary
from .binary_greedy import BinaryGreedy
from .coordinate_greedy import CoordinateGreedy
# from .cost_sensitive import CostSensitive - AdversaryAware depends on this
from .fe... | StarcoderdataPython |
126785 | from core.models import Node
from core.services.DisplayDataService import DisplayDataService
import math
from pkg_resources import resource_string
class DetailedGraphVisualization(DisplayDataService):
def __init__(self):
self.links = []
self.found = []
self.row_chars = 30
self.grap... | StarcoderdataPython |
3391500 | import numpy as np
import cv2
import random
import pandas as pd
class Quiz:
"""
Class for quiz data
Attributes:
questions: a dictionary contains all questions (id: string)
answers: a dictionary contains all the user answers (id: list of answers)
scores: a dictionary contains the acr... | StarcoderdataPython |
36430 | <filename>lattly_tests/converter_tests.py
__author__ = 'yanikafarrugia'
import unittest
import lattly_service.converter
class ConverterTests(unittest.TestCase):
def test_degrees_to_radians(self):
rad = lattly_service.converter.Converter.degrees_to_radians(120)
self.assertEqual(rad, 2.0943951023931953)
self.as... | StarcoderdataPython |
1710713 | <reponame>ressourceplanning/StochasticMRP
import pandas as pd
from Tool import Tool
import openpyxl as opxl
import cPickle as pickle
from GraveInstanceReader import GraveInstanceReader
from TemplemeierInstanceReader import TemplemeierInstanceReader
from Constants import Constants
class MRPInstance:
FileName = ".... | StarcoderdataPython |
3306132 | from re import M
import cv2
import discord
import random
client = discord.Client()
a = False
f = 0
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
msg = message.content.startswith
def check(message):
return me... | StarcoderdataPython |
4828871 | import cx_Oracle
import datetime as dt
from typing import Optional, Union
from src.repos.codes.getNextCodeForInsertion import getNextCodeForInsertion
def insertGenericCode(appDbConnStr: str, code_issue_time: Optional[dt.datetime],
code_str: str, other_ldc_codes: str,
code_d... | StarcoderdataPython |
3219517 | <gh_stars>1-10
#!/usr/bin/python
# based on joint_state_publisher by <NAME>!!
import roslib; # roslib.load_manifest('tf_camera_gui')
import rospy
import wx
import tf
from math import pi
from threading import Thread
RANGE = 10000
class TfPublisher():
def __init__(self):
self.parent_frame = rospy.get_para... | StarcoderdataPython |
1618133 | <gh_stars>0
'''Module to learn a steerable basis'''
import os
import sys
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.nn import Parameter
from torch.nn import functional as F
from scipy.special import binom
... | StarcoderdataPython |
121817 | from typing import Dict, Callable
from kallisticore.lib.action import Action
from kallisticore.lib.credential import Credential
from kallisticore.lib.expectation import Expectation
class PrometheusAction(Action):
def __init__(self, module_func: Callable, arguments: Dict,
expectations: [Expectati... | StarcoderdataPython |
1673951 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2013-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the Licen... | StarcoderdataPython |
1799783 | <filename>freecad/lumberjack/cutlist.py<gh_stars>1-10
from importlib import reload as _reload
import FreeCADGui as Gui
import FreeCAD as App
from os import path
from . import utils
def reload():
from freecad import lumberjack as this
_reload(this)
def main():
list = CutList(Gui.Selection.getSelection()... | StarcoderdataPython |
1797122 | <filename>mainapp/consumers.py
from channels.generic.websocket import JsonWebsocketConsumer
from asgiref.sync import async_to_sync
from .models import Topic, ChatMessage
from django.contrib.auth.models import User
from django.utils.html import escape
from django.core import serializers
import markdown
import bleach
imp... | StarcoderdataPython |
185759 | <gh_stars>1-10
from functools import reduce
from typing import List
from abc import ABC, abstractmethod
import logging
import pandas as pd
import warnings
"""
This module implements the BaseOperator object.
Operators are applied to inputs using the __call__ python API, which wraps
the `transform` methods implement... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.