id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5167360 | from typing import List, Union, Set, Tuple
from mason.engines.scheduler.models.dags.dag_step import DagStep
from mason.engines.scheduler.models.dags.invalid_dag import InvalidDag
from mason.engines.scheduler.models.dags.invalid_dag_step import InvalidDagStep
from mason.engines.scheduler.models.dags.valid_dag import Va... | StarcoderdataPython |
4820444 | <reponame>dsfcode/algolia-analytics
from setuptools import setup
setup(
name='algolia-analytics',
description='Python interface for the Algolia Analytics REST API',
version='0.1',
packages=['algolia_analytics'],
test_suite='tests',
tests_require=[
'mock',
],
install_requires=[
... | StarcoderdataPython |
3432433 | <reponame>MacHu-GWU/pyclopedia-project
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
string, bytes, encode, decode等概念经常困惑着初学者。这里将其一一阐明。
"""
| StarcoderdataPython |
390857 | from .cli_drives import main
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter; Reason: @click.command decorator edits the function parameters, but pylint does not know this since it does not run the code.
| StarcoderdataPython |
1729026 | """Parties have official names, short names, and nicknames.
This submodule attempts to link these different types of name.
The short name is the colloquial name as used by
https://www.parliament.uk/about/mps-and-lords/members/parties/ .
Example:
- official name: Conservative and Unionist Party
- short name: C... | StarcoderdataPython |
5031337 | """ Package for Airtunnel's custom operators. """
class Colours:
""" Custom colours used for the Airtunnel operators. """
ingestion = "#aeffae"
transformation = "#ffff00"
loading = "#ffb3b1"
archival = "#85d8ff"
| StarcoderdataPython |
8163649 | #!/usr/bin/python
import json
import re
import sys
import tweepy
import mmap
import string
sys.path.append('../wowgic_dev')
from py2neo import *
#import neo4jInterface
#connect our DB
#neo4jInt = neo4jInterface.neo4jInterface()
##graph_db = neo4j.GraphDatabaseService("https://564c60239913d:D5B3YxJFXqH9Ftt... | StarcoderdataPython |
1976950 | <gh_stars>0
import argparse
parser = argparse.ArgumentParser(prog='MC DiNT',description='Monte Carlo setup for DiNT')
parser.add_argument('--temp', type=float, help='Input temperature (K)')
parser.add_argument('-A', type=str, action='append', nargs='+', help='adds a reactive species to the system')
parser.add_argument... | StarcoderdataPython |
193558 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A class for managing the Linux cgroup subsystem."""
from __future__ import print_function
import contextlib
import errno
... | StarcoderdataPython |
6549809 | <reponame>gmulz/budget-tracker-2
from .models import RecurringExpense, Transaction, Category, User
from datetime import date
def create_recurring_transactions():
print("asdf")
recurring_expenses = RecurringExpense.objects.all().values()
today = date.today().strftime("%Y-%m-%d")
for expense in recurring... | StarcoderdataPython |
1941304 | # -*- coding: utf-8 -*-
"""
run the neural walker model
@author: hongyuan
"""
import pickle
import time
import numpy
import theano
from theano import sandbox
import theano.tensor as tensor
import os
import scipy.io
from collections import defaultdict
from theano.tensor.shared_randomstreams import RandomStreams
import... | StarcoderdataPython |
6622444 | # This file is part of listparser.
# Copyright 2009-2021 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
#
import copy
from . import common
from . import dates
class OpmlMixin(common.CommonMixin):
def start_opml_opml(self, attrs):
self.harvest['version'] = 'opml'
if attrs.get('version') in ('1.0... | StarcoderdataPython |
6536851 | # __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.contrib import admin
from geocamMemo.models import MemoMessage
class MemoMessageAdmin(admin.ModelAdm... | StarcoderdataPython |
5123586 | """
ROI collection and object definitions
"""
__author__ = "jerome.colin'at'ces<EMAIL>"
__license__ = "MIT"
__version__ = "1.0.3"
import numpy as np
from scipy import stats
import sys
class Roi_collection:
"""
A collection of ROIs defined according to the coordinate file given to roistats
"""
def ... | StarcoderdataPython |
1946289 | ######################################################################
# DOWNLOAD #
######################################################################
class Download:
def __init__(self, url, extension, name, display_name, path):
self.display_nam... | StarcoderdataPython |
1815045 | <reponame>gustavoromerobenitez/python-playground
#!/usr/bin/python3
def lowestPositiveInt(A):
A.sort()
index = -1
try:
index = A.index(1)
except ValueError:
return 1
# Remove all negatives and zero if 1 is found
# if index >= 0:
A = A[index:]
length =... | StarcoderdataPython |
1809288 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module allow to access any bible verses from Dbt Api Platform
"""
__version__ = "0.1.3"
| StarcoderdataPython |
1790552 | <gh_stars>1-10
from __future__ import annotations
from prettyqt import location
from prettyqt.qt import QtLocation
from prettyqt.utils import types
class PlaceMatchRequest(QtLocation.QPlaceMatchRequest):
def __setitem__(self, index: str, val: types.Variant):
attrs = self.parameters()
attrs[index]... | StarcoderdataPython |
3577815 | <reponame>lidongYang22/Autonomous-microrobot-swarm-navigation<gh_stars>0
import torch
from PIL import Image
import math
import copy
threshold = 100
tab = []
for i in range(256):
if i < threshold:
tab.append(0)
else:
tab.append(1)
def draw_rectangular(pic, c_x, c_y, area, ratio, angle, resize_x... | StarcoderdataPython |
255877 | <reponame>fabratu/networkit
#!/usr/bin/env python3
"""
This tool iterates over all C++ files and replaces tab-based
indentation with spaces (tabwidth = 4). If used in read-only
mode it returns a negative exit code if a change is necessary.
"""
import nktooling as nkt
import re
import os, sys
nkt.setup()
numScannedFil... | StarcoderdataPython |
3443869 | <reponame>jappa/PyFR<filename>pyfr/tests/test_ele_mats.py
# -*- coding: utf-8 -*-
from io import BytesIO
import pkgutil
import numpy as np
import sympy as sy
from pyfr.bases.tensorprod import HexBasis
from pyfr.inifile import Inifile
def test_hex_gleg_ord3_csd():
# Config for a third order spectral difference ... | StarcoderdataPython |
6689835 | from app.utils import db
from sqlalchemy import exc
from datetime import datetime
from app.utils import to_camel_case, format_response_timestamp
from sqlalchemy.inspection import inspect
from app.repositories.base_repo import BaseRepo
class BaseModel(db.Model):
__abstract__ = True
id = db.Column(db.Integer(), pri... | StarcoderdataPython |
6605642 | <reponame>postmates/marshmallow
# -*- coding: utf-8 -*-
'''Field classes for formatting and validating the serialized object.
'''
# Adapted from https://github.com/twilio/flask-restful/blob/master/flask_restful/fields.py.
# See the `NOTICE <https://github.com/sloria/marshmallow/blob/master/NOTICE>`_
# file for more lic... | StarcoderdataPython |
183749 | """Test the TcEx Utils Module."""
# pylint: disable=no-self-use
class TestBool:
"""Test the TcEx Utils Module."""
def test_utils_encrypt(self, tcex):
"""Test writing a temp file to disk.
Args:
tcex (TcEx, fixture): An instantiated instance of TcEx object.
"""
key ... | StarcoderdataPython |
9786021 | '''
Function:
Some utils related with logging
Author:
Charles
WeChat public account:
Charles_pikachu
'''
import logging
from prettytable import PrettyTable
'''define the colors'''
COLORS = {
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'pink': '\033... | StarcoderdataPython |
11229855 | <reponame>sdeittrick/Wildfire_Detection_Capstone_697
import pandas as pd
import numpy as np
import altair as alt
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import sklearn
def plot_roc(name, labels, predictions, **kwargs):
"""ROC/AUC plot"""
fp, tp, _ = sklearn.metrics.roc_curve(... | StarcoderdataPython |
8020374 | '''
Created on 2022-01-24
@author: wf
'''
import unittest
from tests.basetest import BaseTest
from osprojects.osproject import OsProject, Commit, Ticket, main, GitHub, gitlog2wiki
class TestOsProject(BaseTest):
'''
test the OsProject concepts
'''
def testOsProject(self):
'''
tests i... | StarcoderdataPython |
3542869 | #
# Copyright(c) 2019 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
from ctypes import CFUNCTYPE, c_size_t, c_char_p, Structure, c_void_p
from enum import IntEnum, auto
from threading import Event
import logging
from ..utils import Size as S
class OcfErrorCode(IntEnum):
OCF_ERR_INVAL = 10000... | StarcoderdataPython |
9705645 | from django.contrib.auth.models import User
from rest_framework import serializers
from system.models import Goal, DirectReward, PointReward
class DirectRewardSerializer(serializers.ModelSerializer):
class Meta:
model = DirectReward
fields = ['id', 'name', 'description']
class PointRewardSerial... | StarcoderdataPython |
8136149 | <filename>pyramda/iterable/__init__.py
from .all_satisfy import all_satisfy
from .any_satisfy import any_satisfy
from .chain import chain
from .concat import concat
from .cons import cons
from .contains import contains
from .contains_with import contains_with
from .drop import drop
from .filter import filter
from .find... | StarcoderdataPython |
8079634 | <reponame>TakamiChie/TkSugar<filename>tksugar/widgets/notebook.py<gh_stars>1-10
import tkinter.ttk
from tksugar.widgets.generatorsupport import GeneratorSupport
class Notebook(tkinter.ttk.Notebook, GeneratorSupport):
"""
`tkinter.ttk.Notebook` with added methods to support Generator.
"""
def append_child(sel... | StarcoderdataPython |
9657670 | from django.views import generic | StarcoderdataPython |
6678782 | <reponame>udrea/iex
# Filename: market/hist.py
"""
Data provided for free by IEX (https://iextrading.com/developer/).
See https://iextrading.com/api-exhibit-a/ for more information.
"""
from iex.base import _Base, IEXAPIError
import pandas as pd
class HIST(_Base):
"""https://iextrading.com/developer/docs/#hist"""... | StarcoderdataPython |
9793285 | from django.dispatch import receiver
from django.db.models import signals
from comment.models import Comment, Flag, FlagInstance, Reaction, ReactionInstance
@receiver(signals.post_save, sender=Comment)
def add_reaction(sender, instance, created, raw, using, update_fields, **kwargs):
if created:
Reaction.... | StarcoderdataPython |
142549 | <gh_stars>0
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from product_spiders.items import Product, ProductLoader
from product_spiders.utils import extract_price2uk
from decimal import Decimal
import logging
class RefrinclimaItSpider(BaseSpider):... | StarcoderdataPython |
1824885 | <filename>src/schemathesis/specs/graphql/schemas.py
from functools import partial
from typing import Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, TypeVar, Union, cast
from urllib.parse import urlsplit
import attr
import graphql
import requests
from hypothesis import strategies as st
from hypothesis.str... | StarcoderdataPython |
5102776 | from django.conf.urls import url
from . import views
app_name = "url_inspector"
urlpatterns = [
url(r"^index$", views.IndexView.as_view(), name="index"),
url(r"^inspection/(?P<pk>\d+)", views.InspectionView.as_view(), name="inspection"),
url(r"^inspections$", views.SavedInspectionsView.as_view(), name="i... | StarcoderdataPython |
199282 | <filename>src/orders/tests/pay_signals/conftest.py
import pytest
pytestmark = [pytest.mark.django_db]
@pytest.fixture
def order(factory):
return factory.order()
| StarcoderdataPython |
4847423 | <reponame>holla2040/ad2
#!/usr/bin/env python
from ctypes import *
from dwfconstants import *
class PowerSupply(object):
def __init__(self,dwf,hdwf,channel):
self.dwf = dwf
self.hdwf = hdwf
self.channel = c_int(channel)
self._setOffset = 0.0
self._getOffset = 0.0
... | StarcoderdataPython |
4934573 | <gh_stars>1-10
from django import forms
from django.utils.translation import ugettext_lazy as _
from sentry.plugins.bases.issue import IssuePlugin
from sentry.utils import json
import sentry_github_issues
import urllib2
class GitHubIssuesOptionsForm(forms.Form):
repo = forms.CharField(label=_('Repository Name'),
... | StarcoderdataPython |
9655126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import datetime
import coloredlogs
def set_logs():
try:
logging.basicConfig(filename="./logs/"+str(datetime.date.today())+".log", level=logging.DEBUG)
logger_init = logging.getLogger(__name__)
coloredlogs.install()
retu... | StarcoderdataPython |
3486495 | from abc import ABC
from typing import cast
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses.ppo import PPO
from allenact.utils.experiment_utils import (
TrainingPipeline,
Builder,
PipelineStage,
LinearDecay,
)
from projects.gym_... | StarcoderdataPython |
1957196 | from mathutils import Euler, Vector
from torch.utils.data import DataLoader
import bpy
import math
import numpy as np
import os
import snook.data.blender as blender
import snook.data.generator as generator
import snook.data.dataset as dataset
def assert_vector_eq(a: Vector, b: Vector) -> bool:
_a, _b = np.array(... | StarcoderdataPython |
11374439 | <gh_stars>1-10
import random
from time import sleep
from operator import itemgetter
maior = menor = contador = 1
num = dict()
numero1 = random.randint(1, 6)
num['jogador 1 '] = numero1
numero2 = random.randint(1, 6)
num['jogador 2'] = numero2
numero3 = random.randint(1, 6)
num['jogador 3'] = numero3
numero4 = random.r... | StarcoderdataPython |
9625542 | import unittest
import xlrd
class TestXlsxParse(unittest.TestCase):
# loc = "./e_sockets.xlsx" #mac
loc = "server/data/e_sockets.xlsx" #pc
def test_for_correctinfo(self):
workbook = xlrd.open_workbook(self.loc)
worksheet = workbook.sheet_by_index(0)
# Test an empty inlineStr c... | StarcoderdataPython |
383905 | from setuptools import setup, find_packages
from os import path
# read the contents of your README file
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="wifi_conf",
version="0.1dev",
... | StarcoderdataPython |
9682892 | <filename>app/temperatures/urls.py
from django.urls import path
from . import views
app_name = "temperatures"
urlpatterns = [
path("", views.TemperatureListView.as_view(), name="temperature-list"),
path("add", views.TemperatureCreateView.as_view(), name="temperature-create"),
path(
"detail-<int:... | StarcoderdataPython |
3480875 | import functools
import os
from collections import OrderedDict
import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from models.arch_util import ConvBnLelu, ConvGnSilu, ExpansionBlock, ExpansionBlock2, MultiConvBlock
from models.switched_conv.switched_conv import BareConvSwitch, comput... | StarcoderdataPython |
9609552 | <filename>models.py
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channe... | StarcoderdataPython |
3358646 | import os
import time
from threading import Thread
import cpuinfo
import GPUtil
import psutil
from tensorboardX import SummaryWriter
class Monitor(Thread):
"""Monitor Class."""
def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False):
"""Initialize monitor, log_dir and gpu_id are needed."""
... | StarcoderdataPython |
25047 | <filename>{{cookiecutter.repo_slug}}/tests/unit/user/test_managers.py
import pytest
pytestmark = pytest.mark.django_db
class TestUserManagers:
def test_create_user(self, django_user_model, faker):
email = faker.email()
password = faker.password()
user = django_user_model.objects.create_u... | StarcoderdataPython |
1706397 | <reponame>pgmilenkov/100daysofcode-with-python-course
from research import BadDriversResearch
research = BadDriversResearch()
print("States sorted by died drivers:")
for state in research.sort_states_by_died_drivers()[:5]:
print("'{}' and died '{}'".format(state.state, state.drivers_fatal_collisions))
print("#" ... | StarcoderdataPython |
4880908 | <reponame>mattjshannon/swsnet
# coding: utf-8
# # Make predictions of stellar 'group' on CASSIS spectra
# Trained on SWS Atlas data.
# In[1]:
import glob
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from swsnet.dataframe_utils import read_spectrum
# In[2]:
def load_model(file_pat... | StarcoderdataPython |
9684000 | <filename>src/linear_regression/parameter_optimisations/univariate.py
"""
"""
from math import inf
from pandas import Series
from tqdm import tqdm
from src.linear_regression.cost_functions import mean_squared_error
from src.linear_regression.models import UnivariateLinearRegressionModel
def batch_gradient_descent(... | StarcoderdataPython |
5004123 | <filename>tests/fixtures/loading/relative_1.py<gh_stars>0
def relative_1(s):
return 'relative_1: ' + s
| StarcoderdataPython |
353985 | <gh_stars>1-10
#!./venv/bin/python
import logging
def setupLogging():
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) #possible levels: DEBUG, INFO, WARNING, CRITICAL
formatter = logging.Formatter('%(levelname)s [%(asctime)s]: %(message)s')
fh = logging.FileHandler('server.log')
fh.s... | StarcoderdataPython |
6484836 | import datetime
import bcrypt
import voluptuous as schema
from authd import models
USER_SCHEMA = schema.Schema({
schema.Required("email"):
schema.Email(),
schema.Required("password"):
schema.All(str, schema.Length(min=6))
})
PASSWORD = schema.Schema({
schema.Required("password"):
schema.All(... | StarcoderdataPython |
6682252 | <reponame>vincent770/ifolder
from setuptools import setup, find_packages
import sys
import os
def publish():
"""Publish to PyPi"""
print('publishing...')
os.system("rm -rf dist ifolder.egg-info build")
os.system("python3 setup.py sdist build")
os.system("twine upload dist/*")
os.system("rm -rf... | StarcoderdataPython |
6457324 | import threading
import time
from subprocess import Popen, PIPE
from typing import Optional, List
from unittest import TestCase
from tests.testing_utils import get_sam_command
RETRY_COUNT = 20
RETRY_SLEEP = 2
class TracesIntegBase(TestCase):
@staticmethod
def get_traces_command_list(
trace_id: Option... | StarcoderdataPython |
1814555 | # Copyright (c) Facebook, Inc. and its affiliates.
from .instantiate import instantiate
from .lazy import LazyCall, LazyConfig
__all__ = [
"LazyCall",
"LazyConfig",
"instantiate",
]
assert __all__ == sorted(__all__)
| StarcoderdataPython |
6472148 | #
# Copyright (C) 2015-2018 Pico Technology Ltd. See LICENSE file for terms.
#
"""
This is a Python module defining the functions from the ps2000.h C header file
for PicoScope 2000 Series oscilloscopes using the ps2000 driver API functions.
"""
from ctypes import *
from picosdk.library import Library
from picosdk.erro... | StarcoderdataPython |
5089083 | <gh_stars>1-10
"""
Test suite for tstables
"""
import os
import tempfile
import numpy as np
import numpy.ma as ma
import numpy.ma.mrecords as mr
from numpy.ma import MaskedArray, masked_array, masked
import scikits.timeseries as ts
from scikits.timeseries import TimeSeries
from numpy.testing import *
from numpy.ma.... | StarcoderdataPython |
5197937 | import psycopg2
import pdb
class PostgresClient(object):
"""Python PostgresClient Client Implementation for testrunner"""
def __init__(self):
self.connection = self.connect("dbname='test' user='root' password='password'")
def connect(self, connstr):
connection = None
try:
... | StarcoderdataPython |
1771092 | # -*- coding: utf-8 -*-
# 털과 날개가 있는지 없는지에 따라 포유류인지 조류인지 분류하는 신경망 모델
import tensorflow as tf
import numpy as np
# [털, 날개]
x_data = np.array([[0,0], [1,0], [1,1], [0,0], [0,0], [0,1]])
# [기타, 포유류, 조류]
# 다음과 같은 형식을 one-hot 형식의 데이터라고 한다
# 한종류에만 해당하는 것을 의미하는듯...
y_data = np.array([
[1,0,0], # 기타
... | StarcoderdataPython |
3252482 | <reponame>gyulkkajo/linux-util<gh_stars>0
import os.path
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
class Procstat():
PROCSTATPATH = '/proc/%d/stat'
STATLIST = (
'pid',
'comm',
'state',
'ppid',
'pgrp',
'session',
'tty_nr',
'tpgid',
'flags',
'minflt',
'cminflt',
... | StarcoderdataPython |
6627751 | from fastapi import APIRouter,status,Depends
from blog import schemas,database
from sqlalchemy.orm.session import Session
from blog.repository import user
# If you are building an application or a web API
# FastAPI provides a convenience tool to structure your application while keeping all the flexibility.
"""
├── a... | StarcoderdataPython |
8087576 | <reponame>andrew-kulikov/intro-to-cv-ud810<gh_stars>1-10
import numpy as np
import random
from load_file import *
from least_squares_proj_matrix import *
from svd_proj_matrix import *
from check_point import *
def main():
points_2d = load_file('input/pts2d-norm-pic_a.txt')
points_3d = load_file('input/pts3d-n... | StarcoderdataPython |
1995988 | <filename>python/seq2seq_attn/model.py
import torch, sys
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
sys.path.append('..')
from utils import *
class EncoderRNN(nn.Module):
"""
Encoder RNN (GRU/LSTM)
"""
# TODO: set up for attention... | StarcoderdataPython |
3451219 | <reponame>kyleburton/inline-plz
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from inlineplz.interfaces.github import GitHubInterface
INTERFACES = {"github": GitHubInterface}
| StarcoderdataPython |
1657174 | from apiclient.discovery import build
import json
from csv import writer
vidID = 'lj8TV9q59P4'
def build_service(filename):
with open(filename) as f:
key = f.readline()
print(key)
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
return build(YOUTUBE_API_SERVICE_NAME,YOUTUB... | StarcoderdataPython |
11272085 | import pytest
import psycopg2
import uuid
from copy import deepcopy
from itertools import islice
from kafka import (
KafkaClient,
SimpleProducer,
)
from kazoo.client import KazooClient
from kafka import KafkaClient
from tests.pgshovel.fixtures import (
cluster,
create_temporary_database
)
from tests.pg... | StarcoderdataPython |
12807490 | <filename>src/programy/parser/template/nodes/log.py
"""
Copyright (c) 2016-17 <NAME> http://www.keithsterling.com
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 wit... | StarcoderdataPython |
1742451 | import requests
import json
import boto3
from decimal import Decimal
import time
import datetime
from boto3.dynamodb.conditions import Key
params = {
'api_key': 'REGISTER ON AIRLABS.CO TO RETRIEVE YOUR API KEY', #REPLACE WITH YOUR API KEY
'dep_iata': 'LAS',
'_fields': 'dep_iata,arr_iata,airline_iata,flight_numbe... | StarcoderdataPython |
3444642 | # -*- coding: utf-8 -*-
# AtCoder Beginner Contest
def main():
n, m = list(map(int, input().split()))
short = (n % 12) * 30 + m / 2
long = 6 * m
diff = abs(short - long)
print(min(diff, 360 - diff))
if __name__ == '__main__':
main()
| StarcoderdataPython |
12809160 | <gh_stars>1-10
#!/usr/bin/env python3
import numpy as np
from numpy import inf
from numpy import nan
from scipy.optimize import fmin
from scipy.stats import beta
from scipy.special import beta as B
from scipy.special import comb
import sys
#import matplotlib.pyplot as plt
def betaNLL(params,*args):
a,b = params
... | StarcoderdataPython |
4819775 | <filename>scripts/resnet_birds_cars/eval_model_birds.py
# Load in pre-trained model weights and evaluate its goodness (ECE, MCE, error) also saves logits.
import keras
import pickle
from keras.models import Model
from keras.optimizers import SGD
from sklearn.model_selection import train_test_split
from load_data_bird... | StarcoderdataPython |
1624400 | <reponame>netarachelhershko/crawler
from request_getter_mocks import get_request_getter_mock
from sitemap_fetcher import SitemapFetcher
from mock import MagicMock
def get_sitemap_fetcher_mock(request_limit):
fetcher = SitemapFetcher(request_limit=request_limit)
fetcher._try_fetch_sitemaps = MagicMock(return_v... | StarcoderdataPython |
315442 | #!/usr/bin/python
# @Author <NAME> (helno)
#
# This script throttles a fan based on CPU temperature.
#
# It expects a fan that's externally powered, and uses GPIO pin 11 for control.
import RPi.GPIO as GPIO
import time
import os
# Return CPU temperature as float
def getCPUtemp():
cTemp = os.popen('vcgencmd measure_t... | StarcoderdataPython |
6404807 | <filename>bemongo.py
#!/usr/bin/env python3
import os, sys
sysArgList, command, doc, collection = sys.argv, "", "", ""
try:
command = sysArgList[1].lower()
if command == "add":
try:
doc = sysArgList[2]
print("WARNING: Please make sure your json value quotes are escaped: {test:\\\"escape me\\\"}")
try:
... | StarcoderdataPython |
5117893 | <reponame>nikitakit/sabertooth<filename>layers.py
# Copyright 2020 The Sabertooth 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
#... | StarcoderdataPython |
8153608 | <gh_stars>1-10
import glob
import json
import logging
import os
import random
import sys
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset, ConcatDataset
from tqdm import tqdm
from transformers import (
WE... | StarcoderdataPython |
5079351 | import struct
from dso_tools.opcodes import OPCODES
SUPPORTED_DSO_VERSIONS = (43,)
U32_BYTES = 4
FLOAT_BYTES = 8
class DSO:
version = SUPPORTED_DSO_VERSIONS[0]
global_strings = []
function_strings = []
global_floats = []
function_floats = []
code = []
line_break_count = 0
string_refe... | StarcoderdataPython |
4867455 | <gh_stars>0
from dataclasses import dataclass
from veho.vector import margin_mapper, margin_mutate
from xbrief.margin.utils import marginal
from xbrief.margin.vector_margin.sizing import sizing
@dataclass
class VectorMargin:
vec: list
head: int
tail: int
@staticmethod
def build(vec: list, head:... | StarcoderdataPython |
4933291 | print('='*8,'Soma dos Pares','='*8)
s = 0
cont = 0
for n in range(1, 7):
n = int(input('Digite o {} valor inteiro: '.format(n)))
if n % 2 == 0:
s = s + n
cont = cont + 1
print('A somatoria dos {} valores {}PARES{} dados foi de {}.'.format(cont,'\033[36m','\033[m',s))
| StarcoderdataPython |
3590038 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
import pyt... | StarcoderdataPython |
122097 | <filename>netforce_mfg/netforce_mfg/models/barcode_ops.py
# Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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... | StarcoderdataPython |
4904370 | <filename>CreeDictionary/shared/__init__.py
"""
shared (expensive) instances
"""
from typing import Dict, Iterable, Set, Tuple
from hfstol import HFSTOL
from utils import paradigm_filler as pf
from utils import shared_res_dir
class FilteredHFSTOL:
"""
Acts like HFSTOL but removes analyses with +Err/Frag.
... | StarcoderdataPython |
55970 | <filename>fcn.py
import numpy as np
import random
import pandas as pd
def remove_outlier(feature, name, data):
q1 = np.percentile(feature, 25)
q3 = np.percentile(feature, 75)
iqr = q3-q1
cut_off = iqr*1.5
lower_limit = q1-cut_off
upper_limit = q3+cut_off
data = data.drop(data[(data[name] > ... | StarcoderdataPython |
8136906 | <gh_stars>100-1000
from netCDF4 import Dataset
import math
import numpy as np
import matplotlib.pyplot as plt
gridSize = 640
#gridTypes = ["quad","hex"]
gridTypes = ["quad"]
operatorMethods = ["wachspress","pwl","weak"]
#subcycleNumbers = [120,240,480,960,1920,3840,7680,15360,30720]
subcycleNumbers = [120,240,480,960,... | StarcoderdataPython |
381828 | import beanstalkc
import logging
import os
import sys
from jack.registry import ManagerRegistry, DelegateRegistry
from jack.util import ServerResult, default_host, default_port # noqa F401
log = logging.getLogger(__name__)
stop = False
DEFAULT_TTR = beanstalkc.DEFAULT_TTR
class DelayedCall(object):
__slots__ = ... | StarcoderdataPython |
1988721 | from typing import TypedDict
class IAppConfig(TypedDict):
flaskSecret:str
flaskPort:str
rawOutagesCreationServiceUrl: str
rawPairAnglesCreationServiceUrl:str | StarcoderdataPython |
1778260 | <gh_stars>0
from pathlib import Path
from typing import Callable, Dict, List
input_file: Path = Path(__file__).parent.joinpath("input.txt")
def get_allowed_numbers(rules):
allowed_numbers = {}
for rule in rules:
name, rest = rule.split(": ")
allowed_numbers[name] = []
ranges = rest.sp... | StarcoderdataPython |
1832578 | """Methods for number-rounding."""
import collections
import numpy
from gewittergefahr.gg_utils import error_checking
def round_to_nearest(input_value, rounding_base):
"""Rounds numbers to nearest x, where x is a positive real number.
:param input_value: Either numpy array of real numbers or scalar real
... | StarcoderdataPython |
5014989 | from setuptools import setup, find_packages
setup(
name = "mmal",
description = "Meteorological Middleware Application Layer",
url = "https://github.com/hodgesds/mmal-python",
version = "0.0.3",
author = "<NAME>",
author_email = "<EMAIL>",
... | StarcoderdataPython |
5138787 | <reponame>afg984/happpycoding
from django import forms
from django.contrib import messages
from django.contrib.auth import login as login_user, logout as logout_user
from django.contrib.auth.models import User
from django.shortcuts import render, redirect, get_object_or_404 as go404
from problem.models import Code, Hin... | StarcoderdataPython |
6639191 | <reponame>Amourspirit/ooo_uno_tmpl
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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-... | StarcoderdataPython |
3406118 | <filename>src/tfr_utilities/scripts/pwm_calibrate.py
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
from tfr_msgs.msg import PwmCommand
def talker():
pub = rospy.Publisher('/motor_output', PwmCommand, queue_size=10)
rospy.init_node('talker', anonymous=True)
... | StarcoderdataPython |
8048430 | <reponame>RichardoLuo/ColossalAI<filename>colossalai/gemini/gemini_context.py
from enum import EnumMeta
class GeminiMemoryManager(object):
def __init__(self, states_cls: EnumMeta):
super().__init__()
self.states_cls = states_cls
self._cnter = 0 # the counter of instances
... | StarcoderdataPython |
1794130 | <filename>ichnaea/scripts/datamap.py
#!/usr/bin/env python3
"""
Generate datamap image tiles and upload them to Amazon S3.
The process is:
1. Export data from datamap tables to CSV.
The data is exported as pairs of latitude and longitude,
converted into 0 to 6 pairs randomly around that point.
2. Convert the da... | StarcoderdataPython |
11380873 | <gh_stars>0
# (C) Crown Copyright, Met Office. All rights reserved.
#
# This file is part of ocean_error_covs and is released under the BSD 3-Clause license.
# See LICENSE in the root of the repository for full licensing details.
#######################################################################
import numpy as np... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.