id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
4820598 | <gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class Service(pulumi.CustomResource):
"""
This resource creates and rolls out ... | StarcoderdataPython |
131926 | import os
import struct
import numpy as np
import torch
import torch.utils.data
from functools import lru_cache
def read_longs(f, n):
a = np.empty(n, dtype=np.int64)
f.readinto(a)
return a
def write_longs(f, a):
f.write(np.array(a, dtype=np.int64))
dtypes = {
1: np.uint8,
2: np.int8,
3... | StarcoderdataPython |
1776907 | <filename>lms_aadi_postgres/Address/address_modules/create_address.py<gh_stars>0
import psycopg2
conn = psycopg2.connect(database="lms", user="postgres", password="<PASSWORD>", host="127.0.0.1", port="12345")
cur = conn.cursor()
class CreateAddress:
def create_address(self, user_id, house_number, street, city, di... | StarcoderdataPython |
1605990 | # -*- coding: utf-8 -*-
"""
Created on 2021/4/23 13:20
---------
@summary: 生成配置文件
---------
@author: mkdir700
@email: <EMAIL>
"""
import os
import shutil
class CreateSetting:
def create(self):
if os.path.exists("setting.py"):
confirm = input("配置文件已存在 是否覆盖 (y/n). ")
if confirm !=... | StarcoderdataPython |
3343718 | <filename>model_layers.py
import tensorflow as tf
def individual_conv_layers(layer_input, num_sensors, mode):
conv1 = tf.layers.conv2d(layer_input, filters=64, kernel_size=[1, 6*3], strides=[1, 6], padding="valid")
conv1 = tf.layers.batch_normalization(conv1, training=(mode == tf.estimator.ModeKeys.TRAIN))
... | StarcoderdataPython |
1719155 | <filename>Scripts/plot_U700_SeasonalCycle_MeanPeriod_FDR.py
"""
Plot U700 seasonal cycle from PAMIP data over 300 ensemble members
and then adjusts statistics for FDR test
Notes
-----
Author : <NAME>
Date : 8 July 2019
"""
### Import modules
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolki... | StarcoderdataPython |
3237024 | <gh_stars>0
import argparse
import boto
import boto.glacier.layer2
import datetime
import json
import os
import sqlite3
import sys
SQLITE_DB = 'glacier_archive.sqlite3'
ACCESS_KEY = ''
SECRET_KEY = ''
ACCOUNT_ID = ''
#SNS_TOPIC = 'arn:aws:glacier:us-east-1:203237044369:vaults/'
def check_jobs_status(vault=None, **kwa... | StarcoderdataPython |
3343879 | <filename>setup.py
from setuptools import setup
from setuptools import find_packages
from setuptools import Extension
from datetime import date
import os
import sys
from glob import glob
import tensorflow as tf
from absl import logging
logging.set_verbosity(logging.INFO)
TF_INCLUDE, TF_CFLAG = tf.sysconfig.get_compi... | StarcoderdataPython |
4800267 | <reponame>General-ITer/Flask-Introduction
from flask import Blueprint, request, flash, render_template
from .models import *
blue = Blueprint('blue', __name__)
def init_blue(app):
app.register_blueprint(blue)
@blue.route('/register/', methods=['GET', 'POST'])
def register():
if request.method =... | StarcoderdataPython |
4841369 | <gh_stars>1-10
import os
import sys
import unittest
import torch
import torch.distributions as ds
from torchgan.losses import *
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
class TestLosses(unittest.TestCase):
def match_losses(
self,
l_g,
l_d,
dx,
dgz... | StarcoderdataPython |
3255903 | <gh_stars>1-10
def bubblesort(A):
for i in range (len (A)):
for k in range (len (A)-1,i,-1):
if (A[k]< A[k-1]):
swap (A,k,k-1)
def swap (A,x,y):
A[x], A[y] = A[y], A[x]
count = int(input("Enter entries for sorting"))
sort_list = []
for i in range(count):
sor... | StarcoderdataPython |
3238724 | import time
maior = 0
opcao = 11
n1 = int(input("Informe um número: "))
n2 = int(input("Informe outro número: "))
while opcao not in [12345]:
print('''Opções disponíveis:
(1) Somar
(2) Multiplicar
(3) Maior
(4) Novos números
(5) Sair''')
opcao = ... | StarcoderdataPython |
3327538 | <filename>report_kahip_cut.py
import os, sys, json
import numpy as np
from collections import defaultdict
dataset = sys.argv[1]
### Paths
# Location of raw dataset (HDF5 format)
dataset_folder = "./datasets"
# Output folder
output_folder = "workflow_output"
dataset_output_folder = os.path.join(output_folder, dataset)... | StarcoderdataPython |
166985 | # encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
from QLayout import QLayout
class QFormLayout(QLayout):
# no doc
def addItem(self, *args, **kwargs): # r... | StarcoderdataPython |
3350024 | <reponame>xlcteam/py-soccersim<filename>soccersim/soccersim.py<gh_stars>0
import pygame
from pygame.locals import *
import sys
import imp
import os
import Box2D
from Box2D.b2 import *
from env import Env
from robot import Robot
from objects import BoxProp
from ball import Ball
if __name__ == "__main__":
WIDTH = ... | StarcoderdataPython |
121099 | <filename>tests/stdlib/test_datetime_timedelta.py
from ..utils import TranspileTestCase
class TestTimeDelta(TranspileTestCase):
def test_constructor(self):
self.assertCodeExecution("""
from datetime import timedelta
print(timedelta(1).days)
print(timedelta(seconds = 2)... | StarcoderdataPython |
55980 | <filename>aplpy/tests/setup_package.py
def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*/*.hdr', 'baseline_images/*.png']}
| StarcoderdataPython |
8234 | # Exercise 4.11
# Author: <NAME>
import sys
g = 9.81 # acceleration due to gravity
try:
# initial velocity (convert to m/s)
v0 = (1000. / 3600) * float(sys.argv[1])
mu = float(sys.argv[2]) # coefficient of friction
except IndexError:
print 'Both v0 (in km/s) and mu must be supplied on the command li... | StarcoderdataPython |
3281792 | from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parse... | StarcoderdataPython |
134180 | import time
import uuid
from threading import Timer
from ..data.device import Device
from ..testing.event_dispatcher import DEVICES, DEVICE_ADDED_EVENT, DEVICE_REMOVED_EVENT
from ..utils.user_agent_parser import parse_user_agent
from ..utils.serializer import serialize_device
from ..data.exceptions.not_found_exceptio... | StarcoderdataPython |
107312 | from __future__ import print_function
import sys
import string
import re
import shutil
import os
from os.path import join, exists, abspath
from shutil import copytree, ignore_patterns
import ConfigParser
import scrapy
from scrapy.command import ScrapyCommand
from scrapy.utils.template import render_templatefile, strin... | StarcoderdataPython |
149112 | <gh_stars>0
import tweepy
from keys import consumer_key, consumer_secret, access_token, access_secret
from scrape import auth, api, get_tweets
from create import markov, dict_maker
auth.set_access_token(access_token, access_secret)
#Dictionaries for specific accounts are created here
playstation = dict_maker("PlaySt... | StarcoderdataPython |
3217404 | import torch
from torch.utils.data import Dataset
import numpy as np
import dgl
from dgl.data.utils import download, extract_archive, get_download_dir
from .mol_tree_nx import DGLMolTree
from .mol_tree import Vocab
from .mpn import mol2dgl_single as mol2dgl_enc
from .jtmpn import mol2dgl_single as mol2dgl_dec
from .j... | StarcoderdataPython |
3290975 | """Constants for use in test suites."""
TEST_DIRECTORY = {
'antimicrobial_susceptibility': {'unknown': 'value'},
'plant_pathogen': {'unknown': 'value'},
'optimal_temperature': {'unknown': 'value'},
'optimal_ph': {'unknown': 'value'},
'animal_pathogen': {'unknown': 'value'},
'microbiome_location... | StarcoderdataPython |
89279 | <reponame>furti/open_landscape
"""Register Addon in Blender"""
bl_info = {
"name": "Open Landscape",
"description": "Create Landscapes from OpenStreetMap data",
"author": "<NAME>",
"version": (0, 1),
"blender": (2, 78, 0),
"location": "View3D > Tool Shelf > Open Landscape",
"category": "Add... | StarcoderdataPython |
53843 | <filename>utils.py
import sys
import configparser
import subprocess
def kill_child_processes(process):
if sys.platform.startswith('win'):
# p.kill() doesn't seem to kill the child processes on Windows
subprocess.run(['TASKKILL', '/F', '/T', '/PID', str(process.pid)], stdout=subprocess.DEVNULL)
... | StarcoderdataPython |
95925 | <reponame>ZackFreedman/Somatic<gh_stars>100-1000
import logging
import os
import time
from typing import List
import numpy as np
import uuid
import pickle
import bisect
standard_gesture_length = 50 # Length of (yaw, pitch) coordinates per gesture to be fed into ML algorithm
_log_level = logging.DEBUG
class Gesture... | StarcoderdataPython |
56099 | # bottomup-fib.py
# book p.215
import sys
from collections import deque
input = sys.stdin.readline
d = [0] * 100
d[1] = 1
d[2] = 1
n = 99
for i in range(3, n+1):
d[i] = d[i-1] + d[i-2]
print(d[n]) | StarcoderdataPython |
24883 | import boto3
def handler(event, _):
boto3.client('codebuild').start_build(
projectName=event['Records'][0]['customData'])
| StarcoderdataPython |
1703644 | <reponame>ScalABLE40/buildbot-ros
from buildbot.config import BuilderConfig
from buildbot.process.factory import BuildFactory
from buildbot.process.properties import Interpolate
from buildbot.steps.source.git import Git
from buildbot.steps.shell import ShellCommand, SetPropertyFromCommand
from buildbot.steps.transfer i... | StarcoderdataPython |
68586 | <filename>solutions/solution329.py
from itertools import product, chain
class GraphNode(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.out_edges = set()
self.in_edge_number = 0
self.longest_path_length = 1
class Graph(object):
def __init__(self, m, n):
... | StarcoderdataPython |
1689477 | <filename>userbot/modules/fakeload.py<gh_stars>1-10
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# made by @DneZyeK
# Port to UserBot by @MoveAngel
import asyncio
... | StarcoderdataPython |
101801 | from tensorflow.keras.layers import (
Convolution2D,
MaxPooling2D,
UpSampling2D,
BatchNormalization,
Concatenate,
LeakyReLU,
ReLU,
Activation,
Add
)
from tensorflow.keras.regularizers import l2
from tensorflow.keras import activations
from semantic_segmentation.convolutional_neural_... | StarcoderdataPython |
1768295 | def containsAny(str, set):
"""Check whether 'str' contains ANY of the chars in 'set'"""
return 1 in [c in str for c in set]
def containsAll(str, set):
"""Check whether 'str' contains ALL of the chars in 'set'"""
return 0 not in [c in str for c in set]
if __name__ == "__main__":
# unit tests, must ... | StarcoderdataPython |
1618087 | from typing import Literal, TypeVar
from pydantic import BaseModel
from alicebot.event import Event
T_MiraiEvent = TypeVar('T_MiraiEvent', bound='MiraiEvent')
Permission = Literal['OWNER', 'ADMINISTRATOR', 'MEMBER']
class Subject(BaseModel):
id: int
kind: Literal['Friend', 'Group']
class FriendInfo(Base... | StarcoderdataPython |
3331081 | <filename>globus_cli/commands/endpoint/delete.py<gh_stars>0
from globus_cli.parsing import command, endpoint_id_arg
from globus_cli.safeio import FORMAT_TEXT_RAW, formatted_print
from globus_cli.services.transfer import get_client
@command(
"delete",
short_help="Delete an endpoint",
adoc_examples="""[sour... | StarcoderdataPython |
1617490 | <gh_stars>0
from typing import Dict, Any, Union
import sys
from pathlib import Path
from .. import PycrittyError
from .command import Command
from ..io import log, yio
from ..resources import config_file, saves_dir
from ..resources.resource import ConfigFile
from rich import print, pretty, inspect
from rich.console imp... | StarcoderdataPython |
1721717 | #!/usr/bin/env python2
#
# In this file test glue layer between Fortran 95 code and module generated by f2py from numpy.
# Here and bellow `native solution` means solution that was obtained with native fortran code
# and in opposite `glue solution` means native solution transmitted through glue layer.
#
# (c) <... | StarcoderdataPython |
1687209 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# from django.contrib.auth.models import Resouce
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django import forms
from spcc... | StarcoderdataPython |
3249978 | import cv2
import os
import glob
import numpy as np
import sys
import os
from applications.keyhandler.keyhandlerdev import KeyHandler
class ObjectTrackingKeyHandler(KeyHandler):
def __init__(self):
super().__init__()
# super().setKeyHandler('q', self.processQ) # should be exited by operato-ec... | StarcoderdataPython |
198781 | <reponame>mmcdermo/RedLeader<gh_stars>0
import os.path
import os
import time
import tarfile
import random
from zipfile import ZipFile
import redleader.util as util
import botocore
class ElasticBeanstalkManager(object):
def __init__(self, context):
self._context = context
def upload_package(self, bucke... | StarcoderdataPython |
1782318 | import datetime
import uuid
import pytest
pytest.register_assert_rewrite("python_proto.tests.helpers")
from hypothesis import given
from hypothesis import strategies as st
from python_proto.common import Duration, Timestamp, Uuid
from python_proto.tests.helpers import check_encode_decode_invariant
from python_proto.... | StarcoderdataPython |
3396958 | """
733. Flood Fill
Easy
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the... | StarcoderdataPython |
1607216 | <reponame>Null-0000/vcrnb
import torch
from torch import nn, Tensor
from torch.nn import functional as F
from allennlp.data.vocabulary import Vocabulary
from allennlp.models import Model
from allennlp.modules import Seq2SeqEncoder, InputVariationalDropout, TimeDistributed
from allennlp.nn import InitializerApplicator
f... | StarcoderdataPython |
1635374 | <reponame>Mog333/CMPUT551_ML_Project
def g():
counter = 200
for use_POStagging in range (0, 2):
for use_temporalComp in range (0, 2):
for use_counterFact in range (0, 2):
for use_sentiment in range (0, 2):
for pre_drop_stop_words in range (0, 2):
for pre_automated_gramma_corector in rang... | StarcoderdataPython |
1777352 | <filename>src/tat_pytools/common.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import os, sys, logging, json
from cdumay_rest_client.client import RESTClient
class TatManager(object):
def __init__(self, config="~/.tatcli/config.json"):
self.root = os.curdir
... | StarcoderdataPython |
72983 | <reponame>ucbrise/waldo
### <NAME> - 2014
### Contains utility functions related to
### dealing with property files
############################################
import json
import os
import subprocess
from pprint import pprint
def writePropFile(propertyFile, properties):
with open(propertyFile, 'w') as fp:
... | StarcoderdataPython |
3305988 | # -*- coding:utf-8 -*-
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
from tornado.web import url, RequestHandler
import json
tornado.options.define("port", type=int, default=9999, help="端口号")
"""
{
"form_filename1":[<tornado.httputil.HTTPFile>, <tornado.httputil.HTTPFile>... | StarcoderdataPython |
3425 | <filename>examples/todo_advanced/main.py
import fastarg
import commands.todo as todo
import commands.user as user
app = fastarg.Fastarg(description="productivity app", prog="todo")
@app.command()
def hello_world(name: str):
"""hello world"""
print("hello " + name)
app.add_fastarg(todo.app, name="todo")
app.a... | StarcoderdataPython |
1647346 | from unittest import TestCase
from similarityPy.algorithms.find_nearest import FindNearest
from similarityPy.measure.boolean_data.matching_dissimilarity import MatchingDissimilarity
from tests import test_logger
__author__ = 'cenk'
class FindNearestTest(TestCase):
def setUp(self):
pass
def test_ma... | StarcoderdataPython |
3378232 | <reponame>lsst-sqre/qa-dashboard
from bokeh.models import Span, Label
def add_span_annotation(plot, value, text, color):
""" Add span annotation, used for metric specification
thresholds.
"""
span = Span(location=value, dimension='width',
line_color=color, line_dash='dotted',
... | StarcoderdataPython |
1704220 | import os, os.path
def read(path):
'''Reads file located at path'''
with open(path) as f:
return f.read()
def safe_write(path, content):
'''Writes content to a temporary file in path's directory,
then atomically renames temporary file to path'''
import tempfile, contextlib
... | StarcoderdataPython |
1622006 | # Generated by Django 2.2.7 on 2019-11-30 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('neighbourhood', '0005_neighbourhood_image'),
]
operations = [
migrations.AddField(
model_name='business',
name='imag... | StarcoderdataPython |
1705092 | import unittest
from test_utils.mocks import PageMock, SiteMock
from . import GenericEntryProcessorTester
class TestEnglishWiktionaryEntryprocessor(
GenericEntryProcessorTester,
unittest.TestCase):
def setUp(self):
self.setup_for_language('en', ['eau', 'air', 'газета', 'geloof'])
def... | StarcoderdataPython |
1753251 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import six
import validators
from girder import events, logprint, logger
from girder.api import access
from girder.api.describe import Description, describeRoute, autoDescribeRoute
from girder.api.rest import \
boundHandler, loadmodel, RestException
from girder.consta... | StarcoderdataPython |
1769119 | import argparse
import json
import logging
import logging.config
import os
import os.path as op
from textwrap import dedent
import pandas as pd
from elaspic import CACHE_DIR, DATA_DIR, conf, elaspic_predictor
logger = logging.getLogger(__name__)
LOGGING_LEVELS = {
None: "ERROR",
0: "ERROR",
1: "WARNING"... | StarcoderdataPython |
123184 | <filename>src/utils/typing.py
from functools import wraps
from telegram import ChatAction
def send_typing_action(func):
"""Sends typing action while processing func command."""
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(
chat_id=upda... | StarcoderdataPython |
36966 | #!/usr/bin/env python3
# Monte Carlo Simulation: Dice Game
# Based on Investopedia: Creating a Monte Carlo Simulation
# investopedia.com/articles/investing/093015/create-monte-carlo-simulation-using-excel.asp\
# Here's how the dice game rolls:
# The player throws three dice that have 6 sides 3 times.
# If the tota... | StarcoderdataPython |
74880 | '''
Test mixed layer, projections and operators.
'''
from paddle.trainer_config_helpers import *
settings(
batch_size=1000,
learning_rate=1e-4
)
din = data_layer(name='test', size=100)
din = embedding_layer(input=din, size=256)
with mixed_layer(size=100) as m1:
m1 += full_matrix_projection(input=din)
w... | StarcoderdataPython |
49904 | <filename>tests/utils/test_beta.py
import numpy as np
from pytest import mark
from beyond.utils.beta import beta, beta_limit
from beyond.env.jpl import get_body
def test_beta(iss_tle):
orbit = iss_tle.orbit()
beta_ = beta(orbit)
beta_lim = beta_limit(orbit)
assert np.isclose(beta_, -0.018861895899... | StarcoderdataPython |
3360651 | <reponame>StuartMacKay/ebird-api
import unittest
from ebird.api.validation import clean_categories
class CleanCategoryTests(unittest.TestCase):
"""Tests for the clean_category validation function."""
def test_codes_are_lower_case(self):
self.assertEqual(["species"], clean_categories("Species"))
... | StarcoderdataPython |
3318010 | <reponame>prouhard/yahoo-finance-api<filename>pyhoo/models/chart.py
from __future__ import annotations
import enum
from dataclasses import dataclass, field
from typing import List, Optional
from pyhoo.models.abc import BaseModel, OptionalFieldsModel
from pyhoo.types.chart import (
ChartMetaDictBase,
CurrentTr... | StarcoderdataPython |
1761057 | <reponame>dstoup/kwiver
"""
ckwg +31
Copyright 2016 by Kitware, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this lis... | StarcoderdataPython |
3210438 | # -*- coding: utf-8 -*-
#imports for package namespace
from .analyze import *
from .fedframe import (FEDFrame,
align,
can_concat,
concat,
load,
split,)
from .lightcycle import set_lightcycle | StarcoderdataPython |
1775126 | import json
import pickle as pk
import numpy as np
from ensemble_boxes import *
# tempDict = next(item for item in out if item['image_id'] == 1 and item['score']>confidence)
numVal = 548
numTrain = 191961
confidence = 0.001
with open('results.json', 'r') as f:
out = json.load(f)
# boxesYOLO = pk.... | StarcoderdataPython |
4677 | import os
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('braumeister/braumeister.py').read(),
re.M
).group(1)
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="braumeister",
packages=["braumeiste... | StarcoderdataPython |
94 | <filename>setup.py
from setuptools import setup
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, <NAME>"
__version__ = "1.4.0"
with open("README.md", "r") as f:
long_description = f.read()
setup(
name="pyngrok",
version=__version__,
packages=["pyngrok"],
python_requires=">=2.7, !=3.0.*, !=3... | StarcoderdataPython |
3254549 | #STEP 1: Initialization
FPS = 15
data["quit"] = False
data["screen"] = "menu"
#STEP 2: Loading assets
data["assets"] = {
"general": holo_gui.load_image(join(APP_PATH["assets"] , "images/icons/general-" + SETTINGS["theme"] + ".png"), (SETTINGS["height"] // 5,SETTINGS["height"] // 5)),
"display": holo_gu... | StarcoderdataPython |
4840997 | from opytimizer.optimizers.swarm import FPA
# One should declare a hyperparameters object based
# on the desired algorithm that will be used
params = {
'beta': 1.5,
'eta': 0.2,
'p': 0.8
}
# Creates a FPA optimizer
o = FPA(params=params)
| StarcoderdataPython |
1738875 | from alkali.peekorator import Peekorator
from .storage import Storage
from .file import FileStorage, FileAlreadyLocked
from .json import JSONStorage
from .csv import CSVStorage
from .multi import MultiStorage
| StarcoderdataPython |
1782753 | <gh_stars>0
import pytest
from inflection import humanize
from argsloader.base import ParseError
from argsloader.units import proc, keep, ufunc, add, mul
@pytest.mark.unittest
class TestUnitsFunc:
def test_proc(self):
# FunctionType, LambdaType
u = proc(lambda x: x.upper())
assert u('abc'... | StarcoderdataPython |
16415 | #!/usr/bin/env python3
"""
example.py
Example of using pypahdb to decompose an astronomical PAH spectrum.
"""
import pkg_resources
from pypahdb.decomposer import Decomposer
from pypahdb.observation import Observation
if __name__ == '__main__':
# The sample data (IPAC table).
file_path = 'resources/sample_... | StarcoderdataPython |
11583 | <filename>examples_ltnw/binary_classifier.py
# -*- coding: utf-8 -*-
import logging; logging.basicConfig(level=logging.INFO)
import numpy as np
import matplotlib.pyplot as plt
import logictensornetworks_wrapper as ltnw
nr_samples=500
data=np.random.uniform([0,0],[1.,1.],(nr_samples,2)).astype(np.float32)
data_A=dat... | StarcoderdataPython |
1768441 | import logging
import copy
from spaceone.core.service import *
from spaceone.core import utils
from spaceone.statistics.error import *
from spaceone.statistics.manager.resource_manager import ResourceManager
from spaceone.statistics.manager.schedule_manager import ScheduleManager
_LOGGER = logging.getLogger(__name__... | StarcoderdataPython |
109691 | from pygments.style import Style
from hiss.themes.tomorrow import Tomorrow
def test_wow_what_a_stupid_test():
assert isinstance(Tomorrow(), Style)
| StarcoderdataPython |
3241247 | # coding=utf-8
import os
TRAINING_FILE = '../../input/train_folds.csv'
MODELS = '../models/'
DIR = os.path.dirname(os.path.abspath(__file__))
def input_data(file_name='train_data.csv', train_path=None, project=None):
"""
:param file_name: input CSV file name with all semesters.
:return: full pah
""... | StarcoderdataPython |
1746327 | import os
import time
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from matplotlib import patches as patches
from matplotlib.ticker import FormatStrFormatter
# from tensorflow.keras.utils import multi_gpu_model
# import data loader
from data import load
# import computational graphs... | StarcoderdataPython |
1611833 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | StarcoderdataPython |
134623 | from Crypto.Util.number import *
import requests
import json
import codecs
import base64
def rsapq(p:int , q:int , e:int , ct:int) -> int:
p = int(p)
q = int(q)
e = int(e)
ct = int(ct)
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return ... | StarcoderdataPython |
199248 | #!/usr/bin/env python
"""
_LoadBulkFilesByID_
Oracle implementation of DBSBufferFiles.LoadBulkFilesByID
"""
from WMComponent.DBS3Buffer.MySQL.DBSBufferFiles.LoadBulkFilesByID import LoadBulkFilesByID as MySQLLoadBulkFilesByID
class LoadBulkFilesByID(MySQLLoadBulkFilesByID):
"""
Same as MySQL
"""
pas... | StarcoderdataPython |
1732106 | import sys
from pathlib import Path
project_dir = Path(__file__).resolve().parents[2]
helper_folder = str(project_dir.parent / 'Utils')
sys.path.insert(0, helper_folder)
# print(helper_folder)
import notifications as n
from dotenv import find_dotenv, load_dotenv
import os
import pandas as pd
import logging
logger = lo... | StarcoderdataPython |
77131 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import numpy as np
import matplotlib.pyplot as plt
#####################################################
### Helper data structures ##########################
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Polygon:
... | StarcoderdataPython |
106721 | from data.vispapers import read_all, DATA_FOLDER
import json
import gzip
def preprocess():
with gzip.open(DATA_FOLDER / 'vispapers.jsonl.gz', 'wt', encoding='utf-8') as file:
for document in read_all():
file.write(json.dumps(document)+'\n')
if __name__ == '__main__':
preprocess() | StarcoderdataPython |
3326300 | name = "download_gitignore_pkg" | StarcoderdataPython |
3265918 | #!/usr/bin/python
from __future__ import print_function
import sys
bedname = sys.argv[1]
size = 0
with open(bedname) as bedfile:
for line in bedfile:
data = line.rstrip().split("\t")
chrom,start,end=data[0],int(data[1]),int(data[2])
size += (end-start+1)
print(size)
| StarcoderdataPython |
3283041 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from numpy import pi
from numpy import array
from numpy.random import random
from numpy.random import randint
from numpy import linspace
from numpy import arange
from numpy import column_stack
from numpy import cos
from numpy import sin
BG = [1,1,1,1]
FRONT = [0,0,0,0.01]
... | StarcoderdataPython |
1722677 | from src.app.auth.model import UserModel
from src.common.exceptions import ExceptionHandler
class PostAuthService(object):
""" Amazon Cognito invokes this trigger to initiate the custom authentication flow. """
def __init__(self, event):
"""
:param self.event: dict
:return: dict
... | StarcoderdataPython |
1755800 | #! /usr/bin/env python
# standard library imports
import argparse
import textwrap
import sys # NOQA importing sys so I can mock sys.argv in tests
from pandashells.lib import module_checker_lib, arg_lib
module_checker_lib.check_for_modules(['pandas'])
from pandashells.lib import io_lib
import pandas as pd
import n... | StarcoderdataPython |
1745440 | <filename>IORN_install/install/iorn/modules/__init__.py
from .ORConv import ORConv2d
from .ORConv import ORBatchNorm2d
__all__ = ['ORConv2d','ORBatchNorm2d'] | StarcoderdataPython |
3206303 | <reponame>python-spain/socios.es.python.org<filename>pythonspain/partners/helpers.py<gh_stars>0
from typing import TYPE_CHECKING
from pythonspain.core.helpers import basic_exporter
if TYPE_CHECKING:
from io import StringIO
from pythonspain.partners.managers import PartnerQuerySet
def export_partners(querys... | StarcoderdataPython |
113714 | # coding=utf-8
from werobot.reply import create_reply
from .. import client
from openerp.http import request
def main(robot):
@robot.subscribe
def subscribe(message):
from .. import client
entry = client.wxenv(request.env)
serviceid = message.target
openid = message.source
... | StarcoderdataPython |
3243600 | from unittest import TestCase
import aiohttp
from aiohttp import ClientConnectionError
from aioresponses import aioresponses, CallbackResult
from flask_jwt_extended import create_access_token
from dimensigon.domain.entities import Server, Scope, Locker, State, Route, Catalog
from dimensigon.domain.entities.bootstrap ... | StarcoderdataPython |
1644707 | import math
from tqdm import tqdm
tqdm.monitor_interval = 0
class Arena():
"""
An Arena class where any 2 agents can be pit against each other.
"""
def __init__(self, player1, player2, game, display=None):
"""
Input:
player 1,2: two functions that takes board as input, r... | StarcoderdataPython |
184427 | """
Choice functions.
We focus upon the cumulative normal distribution as the choice function, but you
could impliment your own, eg Logistic, SoftMax, etc.
"""
from scipy.stats import norm
import numpy as np
def StandardCumulativeNormalChoiceFunc(decision_variable, θ, θ_fixed):
"""Cumulative normal choice func... | StarcoderdataPython |
72819 | # -*- coding: UTF-8 -*-
from app.controller.base_controller import BaseController
from app.validator.journal_entry_validator import JournalEntryValidator
from app.service.journal_entry_service import JournalEntryService
from app.entity.journal_entry_entity import JournalEntryEntity
'''
Journal Entry Controller Contro... | StarcoderdataPython |
3316873 | <reponame>ridicolos/featuretools<gh_stars>100-1000
import inspect
import logging
import pkg_resources
from .api import * # noqa: F403
# Load in a list of primitives registered by other libraries into Featuretools.
#
# Example entry_points definition for a library using this entry point:
#
# entry_points={
# ... | StarcoderdataPython |
45625 | <reponame>kemsakurai/django-sql-reporter
from django.core.management.base import BaseCommand
from django.db import connections
from django_sql_reporter.models import SQLResultReport
from django.core.mail import send_mail
from pathlib import Path
import glob
import yaml
import sys
from tests.testapp.settings import BAS... | StarcoderdataPython |
72741 | import subprocess
import os
import argparse
import time
from operator import add
DATA_LOC='/home/boubin/Images/'
CUBE_LOC='/home/boubin/SoftwarePilot/DistributedRL/Data/'
def consoleLog(string):
print("#################################################")
print("##############DRL Controller:")
print(string)
print("... | StarcoderdataPython |
15375 | <reponame>ayasyrev/model_constructor<gh_stars>1-10
from functools import partial
from .activations import Mish
from .net import Net
__all__ = ['mxresnet_parameters', 'mxresnet34', 'mxresnet50']
mxresnet_parameters = {'stem_sizes': [3, 32, 64, 64], 'act_fn': Mish()}
mxresnet34 = partial(Net, name='MXResnet32', expa... | StarcoderdataPython |
101032 | import numpy as np
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.ml.feature import IDF, Tokenizer, CountVectorizer
def isin(element, test_elements, assume_unique=False, invert=False):
"""
Impliments the numpy function isin() for legacy versions of
the library
"""
ele... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.