id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
165412 | <reponame>shawnduong/manimations<filename>2021-10-Python-SEA-ENGRSL-Workshops/Workshop_1-Hello-Python/code/s06a_s1.py
if condition:
...
else:
...
| StarcoderdataPython |
140057 | import binascii
from unittest import TestCase
from aioquic.buffer import Buffer, encode_uint_var
from aioquic.h3.connection import (
H3_ALPN,
ErrorCode,
FrameType,
FrameUnexpected,
H3Connection,
MessageError,
Setting,
SettingsError,
StreamType,
encode_frame,
encode_settings,... | StarcoderdataPython |
195716 | """tests for the 'wget' command."""
import os
import tempfile
from stash.tests.stashtest import StashTestCase, requires_network
class WgetTests(StashTestCase):
"""tests for the 'wget' command."""
cwd = tempfile.gettempdir()
download_target = "https://github.com/ywangd/stash/archive/master.zip"
invali... | StarcoderdataPython |
34031 | import sys
import os
import random
klasorAdi = os.path.dirname(sys.argv[0])
dosyaIsmi = klasorAdi + "/test.txt"
soruSayisi = 40
ogrenciSayisi = 60
d = {}
dogruSayisi = {}
yalisSayisi = {}
bosSayisi = {}
puan = {}
def sinavHazirla():
for j in range(1, soruSayisi + 1):
r1 = random.randint(1, 5)
d[0, j] = chr(... | StarcoderdataPython |
3375269 | <filename>sodp/views/migrations/0003_auto_20210728_2106.py<gh_stars>0
# Generated by Django 3.1.12 on 2021-07-28 21:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('views', '0002_stats'),
]
operations = [
migrations.AddIndex(
... | StarcoderdataPython |
1614759 | from threading import Thread
from queue import Queue
from whatsapp_controller import *
from packet_scapy_sniff import packet_sniff
from timer import timer_func
# from win10toast import ToastNotifier
if __name__ == "__main__":
# sleep(60)
# notifier = ToastNotifier()
q_packet_detector = Queue(maxsize=1)
... | StarcoderdataPython |
132577 | from .calibration import circle_point_analysis, generate_description, robot_world_calibration
from .create import (read_instrument_description_file, read_detector_description, read_jaw_description,
read_instrument_description)
from .instrument import Instrument
from .robotics import Sequence, Link,... | StarcoderdataPython |
79881 | <filename>dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/dc_20000110.py
#Example from <NAME> <<EMAIL>> to <NAME> <<EMAIL>> on 10 Jan 2000
from Xml.Xslt import test_harness
sheet_1 = """<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
>
<xsl:output method="xml" indent="ye... | StarcoderdataPython |
3392074 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-13 17:04
from __future__ import unicode_literals
import autoslug.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrat... | StarcoderdataPython |
4811373 | <gh_stars>0
from django.http import Http404
class AuthenticateLoginViewMixin(object):
def dispatch(self, request, *args, **kwargs):
self.authenticate()
return super().dispatch(request, *args, **kwargs)
def authenticate(self):
if not self.request.user.is_authenticated():
raise Http404 # for now returning 4... | StarcoderdataPython |
3363429 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | StarcoderdataPython |
3216479 | <filename>Shell.py
#
# MiddleWorks Shell
# Version 1.0
#
# Licensed under the MIT license
#
# Created by matthewgallant on 11/3/16
#
# (c) 2016 <NAME>
#
import sys
from Tkinter import Tk, Label, Button
print("\nMiddleWorks Shell\nAn interactive shell for MiddleWorks\nVersion 1.0\nLicensed under the MIT license\n(c) 2... | StarcoderdataPython |
1630153 | import time
import terminalio
import displayio
import adafruit_imageload
from adafruit_display_text import label
from adafruit_bitmap_font import bitmap_font
from adafruit_magtag.magtag import MagTag
# --| USER CONFIG |--------------------------
STATION_ID = (
"9447130" # tide location, find yours here: https://t... | StarcoderdataPython |
175891 | from .main import BasicBuild
from .csv_export import export_csvs
import zipfile
import os
import pandas as pd
from pathlib import Path
from datetime import datetime
from importlib import resources
from reportlab.platypus import (
SimpleDocTemplate,
ListFlowable,
Paragraph,
Spacer,
Image,
PageBre... | StarcoderdataPython |
1669866 | import asyncio
import enum
import json
import logging
import random
import time
from asyncio.events import AbstractEventLoop
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from json.decoder import JSONDecodeError
from mmap import ACCESS_WRITE, mmap
from pathlib import Path
from typing i... | StarcoderdataPython |
44397 | #!/usr/bin/env python
"""Utility and General purpose functions."""
import inspect
import warnings
import os
import re
import shatter.constants as cts
__author__ = '<NAME>'
def read_file(absolute_path):
"""
:param absolute_path: string path.
:return: list with lines of the file.
"""
return [line... | StarcoderdataPython |
3305496 | # -*- coding: utf-8 -*-
"""Test the TcEx Metrics Module."""
import os
import sys
from tcex import TcEx
from tcex import Benchmark, Debug, FailOnInput, FailOnOutput, IterateOnArg, OnException, OnSuccess
from ..conftest import _config_data
# pylint: disable=W0201
class TestDecorators:
"""Test the TcEx Decorators.""... | StarcoderdataPython |
92159 | <reponame>Maria-28/LRn-6<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Объявите функцию, которая возвращает переданную ей строку в нижнем регистре (с
# малыми буквами). Определите декоратор для этой функции, который имеет один параметр
# tag , определяющий строку с названием тега (начальное значение п... | StarcoderdataPython |
3361929 | #!/usr/bin/env python
'''
example of a module
'''
import pandas as pd
import numpy as np
TEST = pd.DataFrame(np.ones(10))
COLORS = ('Blue', 'Orange', 'Red', 'Green', 'Violet', 'Cyan')
def increment(number):
"""Increases a given number by 1"""
return number + 1 | StarcoderdataPython |
1634562 | from django.apps import AppConfig
class ColumAppConfig(AppConfig):
name = 'colum_app'
| StarcoderdataPython |
1684044 | # -*- coding: utf-8 -*-
import torch.nn.functional as F
from ...utils.nn import get_rnn_hidden_state
from ..attention import HierarchicalAttention, UniformAttention, get_attention
from .. import Fusion
from . import ConditionalDecoder
class ConditionalMMDecoder(ConditionalDecoder):
"""A conditional multimodal de... | StarcoderdataPython |
107065 | from ..core.tooling.htstrings import HeadTailString
class WalletURL(HeadTailString):
__head__ = "https://edge.qiwi.com/"
class urls:
me = WalletURL("person-profile/v1/profile/current")
identification = WalletURL("identification/v1/persons/{}/identification")
history = WalletURL("payment-history/v2/p... | StarcoderdataPython |
3263171 | <reponame>jorisvandenbossche/scipy-lecture-notes<gh_stars>1-10
"""
"""
from skimage import data, exposure
import matplotlib.pyplot as plt
camera = data.camera()
camera_equalized = exposure.equalize(camera)
plt.figure(figsize=(7, 3))
plt.subplot(121)
plt.imshow(camera, cmap='gray', interpolation='nearest')
plt.a... | StarcoderdataPython |
1718313 | # -*- coding: utf-8 -*-
# Octowire Framework
# Copyright (c) ImmunIT - <NAME> / <NAME>
# License: Apache 2.0
# <NAME> / Eresse <<EMAIL>>
# <NAME> / Ghecko <<EMAIL>>
import asyncio
import pkgutil
import selectors
import sys
from importlib import import_module
from pathlib import Path
from prompt_toolkit.shortcuts im... | StarcoderdataPython |
3305628 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
44992 | # Databricks notebook source
# MAGIC %md
# MAGIC **Description** This notebook runs the model analysis pipeline for CCU004-2
# MAGIC
# MAGIC **Project(s)** CCU004-2 - A nationwide deep learning pipeline to predict stroke and COVID-19 death in atrial fibrillation
# MAGIC
# MAGIC **Author(s)** <NAME>
# MAGIC
# MAGI... | StarcoderdataPython |
1772292 | import numpy
StrippedDown = {
'galaxyID' : (0, int),
'x': (1, float),
'y' : (2, float),
'z' : (3, float),
'mag_bc' : (4, float),
'mag_bB' : (5, float),
}
MSdata = {
'galaxyID' : (0, int),
'lastProg' : (1, int),
'descedantID' : (2, int),
'haloID' : (3, int),
'subHaloID' : (4... | StarcoderdataPython |
1795337 | <filename>teste.py
res = input()
if(res == "61"):
print ('Brasilia')
elif(res == "71"):
print ('Salvador')
elif (res == "11"):
print ('Sao Paulo')
elif (res == "21"):
print ('Rio de Janeiro')
elif (res == "32"):
print ('Juiz de Fora')
elif (res == "19"):
print ('Campinas')
elif (res == "27"):
... | StarcoderdataPython |
3377346 | import os
import torch
import util.util as util
class BaseModel:
def name(self):
return self.__class__.__name__.lower()
def initialize(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.Tensor = torch.cuda.FloatTensor if self.gpu_ids... | StarcoderdataPython |
1601103 | # Copyright (c) <NAME>
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
import espress... | StarcoderdataPython |
90779 | """
This is used for dynamic object completion.
Jedi tries to guess the types with a backtracking approach.
"""
def func(a):
#? int() str()
return a
#? int()
func(1)
func
int(1) + (int(2))+ func('')
# Again the same function, but with another call.
def func(a):
#? float()
return a
func(1.0)
# Agai... | StarcoderdataPython |
88237 | """
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates... | StarcoderdataPython |
1681476 | """
Helpers for merging dictionary representations
of :class:`relaton.models.bibdata.BibliographicItem` instances.
"""
from typing import Any
from deepmerge import Merger, STRATEGY_END
from common.util import as_list
def deduplicate_and_coerce_to_list(
config, path,
base: Any, nxt: Any):
"""
... | StarcoderdataPython |
37961 | from flask import Flask
from wdb.ext import WdbMiddleware
class Wdb(object):
def __init__(self, app=None):
self.app = app
if app:
self.init_app(self.app)
def init_app(self, app):
if app.config.get('WDB_ENABLED', app.debug):
start_disabled = app.config.get('WD... | StarcoderdataPython |
3392473 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2018 Zuse Institute Berlin, www.zib.de
Permissions are granted as stated in the license file you have obtained
with this software. If you find the library useful for your purpose,
please refer to README.md for how to cite IPET.
@author: <NAME>
"""
from ... | StarcoderdataPython |
3373127 | study_whenDownloaded = """{
\"patientName\": \"Case1\",
\"patientId\": \"Case1\",
\"internalId\": \"a294f5\",
\"studyDate\": \"20080408\",
\"modality\": \"BREAST IMAGING TOMOSYNTHESIS\",
\"studyDescription\": \"BREAST IMAGING TOMOSYNTHESIS\",
\"numImages\": 1,
\"studyId\": \"dec7949e-a99... | StarcoderdataPython |
1761525 | from networkx import MultiDiGraph
from ..steps import Step, AbstractDynamicStep, NON_RECURSIVE_ABSTRACT_STEPS
def do_sanity_check(graph: MultiDiGraph, step: Step) -> None:
"""Perform sanity checks defined in step ``sanity_checks`` methods
on given step, and recursively on all substeps and child steps in given... | StarcoderdataPython |
190537 | import sys
import subprocess
from datetime import date
args = sys.argv
if len(args) < 3:
print(f"usage: {args[0]} <log_file> <go_file> <opt:semantic_version>")
exit(-1)
log_file = args[1]
go_file = args[2]
semantic_version = None
build_date = date.today().isoformat()
go_version = ' '.join(str(subprocess.... | StarcoderdataPython |
1653415 | import unittest
import bot
class Testbot(unittest.TestCase):
def test_getATweet(self):
tweet = bot.getSingleStatus(1328477170788945924)
self.assertEqual(tweet, '@botimd #genre5 action')
if __name__ == '__main__':
unittest.main() | StarcoderdataPython |
3244382 | """Tests for the Attribute class."""
from stransi.attribute import Attribute
def test_whether_attribute_is_on_or_off():
"""Test whether the Attribute class is working correctly."""
assert Attribute.NORMAL.is_on()
assert Attribute.BOLD.is_on()
assert Attribute.DIM.is_on()
assert Attribute.ITALIC.... | StarcoderdataPython |
1606907 | import logging
from datetime import datetime
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.core.serializers import serialize
from django.db.models import Count
from django.http import HttpResponseRedirect
from django.urls import path, reverse
from django.util... | StarcoderdataPython |
131796 | from pych.extern import Extern
#
# Mapping the Python function "hello_world" to the function "hello_world"
# from the library "libexamples.so".
#
@Extern(lib="libexamples.so", ename="hello_world")
def hello_world():
return None
#
# Mapping the Python function "add_ints" to the function "add_ints"
# from the libra... | StarcoderdataPython |
1635145 | <reponame>fredhallgren/nystrompca
# Copyright 2021 <NAME>
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | StarcoderdataPython |
1663514 | import cx_Oracle
try:
import configparser
except ImportError:
import ConfigParser as configparser
import logging
import threading
import time
import sys
from dbsource import DBSource
def open(configuration_file):
'''Create an user admin DB connection using settings from a configuration file.'''
config = config... | StarcoderdataPython |
3374466 | import tensorflow.compat.v1 as tf
import tensorflow_addons as tfa
import numpy as np
import gym
import logging
import copy
from tensorflow.compat.v1 import layers
class Policy(object):
def reset(self, **kwargs):
pass
def act(self, observation):
# should return act, info
raise NotImpl... | StarcoderdataPython |
3342676 | #!/usr/bin/env python
""" Problem 22 daily-coding-problem.com """
from typing import List
def reconstruct(words: List[str], s: str) -> List[str]:
check = s
for w in words:
check = check.replace(w, "")
s = s.replace(w, " "+w+" ")
if check:
return None
return [i f... | StarcoderdataPython |
3397384 | from benchmark import Benchmark, benchmark
import astropy.units as u
import pytest
@benchmark(
{
"log.final.secondary.HZLimRecVenus": {"value": 9.828450e10, "unit": u.m},
"log.final.secondary.HZLimEarlyMars": {"value": 2.673083e11, "unit": u.m},
"log.final.secondary.HZLimRunaway": {"value"... | StarcoderdataPython |
1694861 | <reponame>jhauberg/comply<filename>comply/rules/standard/including_source_file.py
# coding=utf-8
import re
from comply.rules.rule import *
from comply.rules.patterns import INCLUDE_PATTERN
class IncludingSourceFile(Rule):
""" Don't include source files (.c) in other source files.
This is advisable to avoid... | StarcoderdataPython |
1789836 | #!/usr/bin/python3
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | StarcoderdataPython |
64187 | <gh_stars>1-10
from django.core.management.base import BaseCommand
from django.conf import settings
from angular_scaffold.management.commands.helpers._generate_view import generate_view
class Command(BaseCommand):
args = '<view_name view_name ...>'
help = 'Creates a new view, adds the styles, and imports it'... | StarcoderdataPython |
70169 | <filename>src/062.py
from collections import defaultdict
from itertools import count
def ans():
groups = defaultdict(list)
for num in count():
num_cubed = num ** 3
key = tuple(sorted(str(num_cubed)))
groups[key].append(num_cubed)
if len(groups[key]) == 5:
return gro... | StarcoderdataPython |
1692818 | #-------------------------------------------------------------------------------
# elftools example: dwarf_location_lists.py
#
# Examine DIE entries which have location list values, and decode these
# location lists.
#
# <NAME> (<EMAIL>)
# This code is in the public domain
#---------------------------------------------... | StarcoderdataPython |
1655819 | from flask import Flask
from flask_restful import Api
import logging as logger
from api.Root import Root
from api.RootApi import RootApi
from api.Spend import Spend, SpendById, SpendByWhopaid
from api.Devs import Devs
logger.basicConfig(level="DEBUG")
myApp = Flask(__name__)
restServer = Api(myApp)
restServer.add_... | StarcoderdataPython |
143742 | # -*- coding: utf-8 -*-
'''
:file: use_verify.py
:author: -Farmer
:url: https://blog.farmer233.top
:date: 2022/01/14 21:33:06
'''
from school_sdk.client import UserClient
from school_sdk import SchoolClient
# 实例化学校
# 并根据验证码类型指定captcha_type为kap或者cap
# 使用Kaptcha(与旧版系统类似的验证码)
Gdust = SchoolClient("172.16... | StarcoderdataPython |
1640610 | class Pessoa:
olhos = 2
def __init__(self, *filhos, nome = None, idade = 19):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá, meu nome é {self.nome}'
@staticmethod
def metodo_estatico():
return 42
@cl... | StarcoderdataPython |
1766967 | <gh_stars>10-100
def binarySearch(my_array, target):
left = 0
right = len(my_array) - 1
result = helper(my_array, target, left, right)
return result
def helper(my_array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
middle_element = my_array[mid... | StarcoderdataPython |
63674 | # ----------------------------------------------------------------------
# ConfDB hints system syntax
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# N... | StarcoderdataPython |
3277314 |
import yaml
class Hyperparameter:
''' hyperparameter manager '''
def __init__(self, config_file: str):
''' Hyperparameter
Args:
config_file (str): the config file.
'''
# Audio
self.sample_rate = 22050
self.hop_length = 256
self.win_l... | StarcoderdataPython |
136754 | <filename>tests/test_color.py
import sys
import unittest
from unimport.color import RED, RESET, TERMINAL_SUPPORT_COLOR, paint
class TestColor(unittest.TestCase):
maxDiff = None
def setUp(self):
self.content = "test content"
@unittest.skipUnless(sys.platform == "win32", "requires Windows32")
... | StarcoderdataPython |
3322544 | <filename>src/connections/_hazelcast.py<gh_stars>0
from .__interface import IConnection
class Hazelcast(IConnection):
pass
| StarcoderdataPython |
3375741 | <filename>core/pretrain.py<gh_stars>1-10
"""Train classifier for source dataset."""
import torch.nn as nn
import torch.optim as optim
from utils.utils import save_model
from core.test import eval
def train_src(model, params, data_loader, device):
"""Train classifier for source domain."""
###################... | StarcoderdataPython |
1755182 | <reponame>danmarshall/piling.js
import os
import sys
from keras_tqdm import TQDMCallback, TQDMNotebookCallback
from tqdm import tqdm, tqdm_notebook
# Stupid Keras things is a smart way to always print. See:
# https://github.com/keras-team/keras/issues/1406
stderr = sys.stderr
sys.stderr = open(os.devnull, "w")
from k... | StarcoderdataPython |
3246019 | <gh_stars>0
import pytest
from choo.models import Model
from choo.types import Coordinates, LineType
class TestCoordinates:
def test_distance(self):
assert round(Coordinates(51.451379, 7.013569).distance_to(Coordinates(51.454726, 6.979494)), 3) == 2390.268
with pytest.raises(TypeError):
... | StarcoderdataPython |
1714707 | <filename>securedpi_profile/views.py<gh_stars>1-10
from django.shortcuts import render
from django.views.generic import UpdateView
from securedpi_profile.models import SecuredpiProfile
from django.urls import reverse
class EditProfileView(UpdateView):
"""Define edit profile class."""
model = SecuredpiProfile
... | StarcoderdataPython |
90408 | from boa_test.tests.boa_test import BoaTest
from boa.compiler import Compiler
from neo.Prompt.Commands.BuildNRun import TestBuild
class TestContract(BoaTest):
def test_binops(self):
output = Compiler.instance().load('%s/boa_test/example/BinopTest.py' % TestContract.dirname).default
out = output.... | StarcoderdataPython |
1709876 | # -*- coding: utf-8 -*-
import platform
import time
from datetime import datetime, timezone
import requests_mock
from chaoshumio.probes import search_query
def test_search_query_probe(humio_url: str):
with requests_mock.mock() as m:
m.post(
"{}/api/v1/repositories/sandbox/query".format(humio... | StarcoderdataPython |
155124 | <filename>tessa/orbiturary/pictures/parse_text.py
import sys
import os
sys.path.append("../../text_parser")
import text_parser
li = [i for i in os.walk(os.getcwd())]
root = li[0]
for fi in root[2]:
if fi[len(fi)-10:] == "output.txt":
text_parser.tojsonfile(fi[:len(fi)-10]+"parsed", text_parser.get_orbit... | StarcoderdataPython |
1698322 | # Generated by Django 2.1.4 on 2018-12-28 07:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('example', '0005_auto_20180922_1508'),
]
operations = [
migrations.CreateModel(
name='AuthorBioM... | StarcoderdataPython |
3365910 | <reponame>dkfellows/sphinx4bug
from foo.bar import Grill
class FooBarExample:
def make_grill(self, grill):
"""
:rtype: Grill
"""
return Grill()
| StarcoderdataPython |
146320 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | StarcoderdataPython |
146553 | # MIT License
# Copyright (c) 2020 <NAME> (Alias: Alanthiel)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | StarcoderdataPython |
32511 | <gh_stars>0
import json
import requests
import requests.utils
# Fixes some issues with TLS
import os
os.environ['REQUESTS_CA_BUNDLE'] = 'ca.pem';
# --- Debug Purposes Only, Server Config Is Hard Coded ---
#
#
# print "Debug ... " + deployed.ResultUri;
# response = requests.get('https://webhook.site/062e2ea7-5a36-4... | StarcoderdataPython |
3213321 | #!/usr/bin/env python3
# The bell slapper script.
# Adapted from: https://gist.github.com/meub/c3833921a3a45a3ec392d9962313b68e
from time import sleep
# Try importing the GPIO library.
try:
import RPi.GPIO as GPIO
except ModuleNotFoundError:
print("RPi module not found. Ignoring bell slaps.\n")
# Slap the ... | StarcoderdataPython |
3327587 | <filename>main.py
tabuleiro = [' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' '
]
def coordenada_esta_no_limite(c, texto):
while (c < 0) or (c > 2):
c = int(input('Digite o valor da '+ str(texto) + ': ' ))
return c
def entrada_do_usuario(): # Esta função representa a en... | StarcoderdataPython |
1356 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cms_pages', '0014_homepage_news_count'),
]
operations = [
migrations.AlterField(
model_name='ne... | StarcoderdataPython |
1788060 | <reponame>aether-space/trompet<filename>trompet/service.py
# encoding: utf-8
try:
import json
except ImportError:
import simplejson as json
import random
import re
import signal
import sys
from twisted import plugin
from twisted.application import internet, service
from twisted.python import usage
from twiste... | StarcoderdataPython |
14917 | <gh_stars>0
matches = True
if mat<caret> | StarcoderdataPython |
3279640 | import collections
class Solution:
def groupAnagrams(self, strs):
ans = collections.defaultdict(list)
for s in strs:
a = [0] * 26
for c in s:
a[ord(c) - ord('a')] += 1
ans[tuple(a)].append(s)
return list(ans.values())
| StarcoderdataPython |
3323467 | import scipy as sc
import numpy as np
class PCA:
def __init__(self, *, n_components: int):
self.n_components = n_components
def fit(self, x: np.ndarray):
cov = np.cov(x.transpose())
eig_values, eig_vectors = sc.linalg.eigh(cov)
order = np.argsort(eig_values)[::-1]
eig_... | StarcoderdataPython |
1712046 | <gh_stars>1-10
"""
A catch-all file that imports the whole framework.
:file: __init__.py
:date: 27/08/2015
:authors:
- <NAME> <<EMAIL>>
"""
# Core classes.
from .base import *
from .struct import *
# Serializers
from .scalars import *
from .enum import *
# Misc.
from .validators import *
| StarcoderdataPython |
4833841 | <reponame>aktechthoughts/m3d-api
import py
class HQLHelper(object):
class Tags(object):
CONFIG = "config"
VIEW = "view"
PUSHDOWN = "pushdown"
@staticmethod
def get_hql_file_path(
config_subdir,
destination_system,
destination_database,
... | StarcoderdataPython |
3373174 | from __future__ import print_function
import logging
logger = logging.getLogger(__file__)
logging.basicConfig(
format="[%(asctime)s - %(filename)s:line %(lineno)s] %(message)s",
datefmt='%d %b %H:%M:%S')
logger.setLevel(logging.INFO)
import os
import sys
import numpy as np
from keras.utils import generic_util... | StarcoderdataPython |
54164 | <filename>Python/UberX.py
from car import Car
class UberX(Car):
brand=str
model=str
def __init__(self, license, driver,brand,model):
super().__init__(license, driver)
self.brand=brand
self.model=model | StarcoderdataPython |
3363791 | """MPC interface for circuit_sat and compressed_pivot modules.
Circuit_sat implementation of https://eprint.iacr.org/2020/152
``Compressed Sigma-Protocol Theory and Practical Application
to Plug & Play Secure Algorithmics''
"""
import mpyc.mpctools as mpctools
from mpyc.runtime import mpc, logging
from mpy... | StarcoderdataPython |
117077 | <reponame>genomehubs/genomehubs
#!/usr/bin/env python3
"""
Index a file, directory or repository.
Usage:
genomehubs index [--hub-name STRING] [--hub-path PATH] [--hub-version PATH]
[--config-file PATH...] [--config-save PATH]
[--es-host URL...] [--assembly-dir PATH]
... | StarcoderdataPython |
1763508 | import numpy as np
import cv2
from config import Config
import tensorflow as tf
from PIL import Image
words_dict = {}
n_2_w = {}
CHARS =set()
with open(Config.dict_file_path, "r", encoding="utf8") as dict_file:
for index, line in enumerate(dict_file.readlines()):
line = line.strip()
if not line == "... | StarcoderdataPython |
1639494 | # Date: 01/28/2019
# Author: Mohamed | StarcoderdataPython |
1739753 | import os
import sys
import shlex
import signal
import threading
import itertools
import subprocess
from .utils import *
if sys.version_info >= (3, 0):
import queue as Queue
lfDEVNULL = subprocess.DEVNULL
else:
import Queue
lfDEVNULL = open(os.devnull)
class AsyncExecutor(object):
"""
A class... | StarcoderdataPython |
1791589 | """
Problem:
PageRank is an algorithm used by Google to rank the importance of different websites.
While there have been changes over the years, the central idea is to assign each site
a score based on the importance of other pages that link to that page.
More mathematically, suppose there are N sites, and each site ... | StarcoderdataPython |
1796560 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from create_database import Base
import os
class Database:
def __init__(self):
os.environ.get('DB_HOST')
engine = create_engine(f"mysql+pymysql://{os.environ.get('DB_USERNAME')}:{os.environ.get('DB_PASS')}@{os.environ.ge... | StarcoderdataPython |
25069 | # -*- coding: utf-8 -*-
# @Time : 5/31/2018 9:20 PM
# @Author : sunyonghai
# @File : test.py
# @Software: ZJ_AI
from multiprocessing import Pool, Lock, Value
import os
tests_count = 80
lock = Lock()
counter = Value('i', 0) # int type,相当于java里面的原子变量
def run(fn):
global tests_count, lock, counter
wi... | StarcoderdataPython |
111254 | """
Base class of site movers
:author: <NAME>
"""
import hashlib
import os
import time
from subprocess import Popen, PIPE, STDOUT
from pUtil import tolog #
from PilotErrors import PilotErrors, PilotException
class BaseSiteMover(object):
"""
File movers move files between a storage element (of different... | StarcoderdataPython |
1727313 | import os
import pickle
import time
from functools import partial
from typing import List, Optional, Dict, Tuple, Any, Callable
import jax
import jax.numpy as jnp
import numpy as np
import wandb
from jax import jit, value_and_grad
from jax.experimental.optimizers import adam, sgd
from jax.tree_util import tree_leaves
... | StarcoderdataPython |
184584 | <reponame>fgl-foundation/MovieDB
from . import watchlistitems
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from MyWatchList.views.list.userstatus import UserStat
from MyWatchList.models import Wa... | StarcoderdataPython |
3255708 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# 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
#
# Unl... | StarcoderdataPython |
174114 | # main code for the ground station, mounted to the launchpad. All data must be received from the rocket over radio and transmitted to the analysis tool over a network socket
#from C:/Users/CalSu/Documents/.ACTUAL_DOCS/YAR/yar-software/workspaces/ground-station import server
from server import server
HOST = '192.168.0... | StarcoderdataPython |
1639281 | <reponame>OrlandoSoto/owning-a-home<filename>test/jmeter-bootstrap/bin/JMeterInstaller.py
import os, sys, hashlib, urllib2, tempfile, zipfile, distutils.core
class JMeterInstaller(object):
def __init__(self):
self.jmeter_version = "2.11"
self.jmeter_dir = "apache-jmeter-%s/" % self.jmeter_version... | StarcoderdataPython |
1640282 | <reponame>khuranalab/DeepMILO<gh_stars>1-10
from sklearn.metrics import roc_auc_score, average_precision_score
import keras
import numpy as np
class ROC_Callback(keras.callbacks.Callback):
def __init__(self, val_generator, fout=None):
self.val_generator = val_generator
self.fout = fout
def ... | StarcoderdataPython |
1755355 | <reponame>jameszhan/notes-ml
# -*- coding: utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
figure = plt.figure()
ax = Axes3D(figure)
x = np.linspace(-6 * np.pi, 6 * np.pi, 1000)
y = np.sin(x)
z = np.cos(x)
ax.plot(x, y, z, 'r--')
ax.set_xlabel('X Axis')
ax.set_y... | StarcoderdataPython |
1678475 | <filename>test/test_python_groups.py
import unittest
from app.python_groups import process_python_group_by_location, get_location_based_python_groups
class TestPythonGroups(unittest.TestCase):
@classmethod
def setUpClass(self):
self.__colombia_code__ = "CO" # Colombia
self.__latam_country_co... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.