id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1706484 | <reponame>abhiWriteCode/Num-Eng-Machine-Translation
from bs4 import BeautifulSoup
from requests import get
import random
import asyncio
import pandas as pd
from time import time
random.seed(12345)
async def convert2text(number):
html_body = get('https://www.calculatorsoup.com/calculators/conversions/numberstowords... | StarcoderdataPython |
85877 | #
# Copyright 2022 Autodesk
#
# 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 applicable law or agreed to in writing, s... | StarcoderdataPython |
119356 | from .guitar_spec import GuitarSpec, GuitarType, Wood, Builder
class Guitar:
serial_number: str
price: float
spec: GuitarSpec
def __init__(self, serial_number: str, price: float, spec: GuitarSpec) -> None:
self.serial_number = serial_number
self.price = price
self.spec = spec
... | StarcoderdataPython |
1641938 | import logging
import os
import sys
logger = logging.getLogger(__name__)
from bert import constants, remote_webservice
logger.info(f'Starting service[{constants.SERVICE_NAME}] Daemon. Debug[{constants.DEBUG}]')
logger.info(f'Loading Service Module[{constants.SERVICE_MODULE}]')
if constants.SERVICE_MODULE is None:
ra... | StarcoderdataPython |
4800810 | <filename>codes/Baseline Model Example/scoring/matching.py
"""
Copyright 2018 Defense Innovation Unit Experimental
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.ap... | StarcoderdataPython |
1706536 | """
Identify the fewest combined steps the wires
must take to reach an intersection
"""
from part_01_solution import (
positions,
crossed_paths,
ORIGIN
)
# remove the origin from both wires
for wire in positions:
positions[wire].remove(ORIGIN)
# for each crossed path, sum the steps it took both wires ... | StarcoderdataPython |
1760376 | from _skelet_functions import *
def worst_case_strategy(guesses, answer, possibilities=None):
if len(guesses) < 1:
remaining_answers = create_list_of_combinations(COMBINATIONS, 4)
guess = remaining_answers[7]
feedback = feedback_calculate(answer, guess)
else:
remaining_answer... | StarcoderdataPython |
4812440 | import json
import time, datetime
import csv
import os
import preProcess
import dataVis
from pandas import DataFrame
from pandas import TimeGrouper
import pandas as pd
from matplotlib import pyplot
def readWholeCSV(docName):
Folder_Path = r'/Users/siqiyaoyao/git/python3/fnirs/fnirsAnalysis/dataset/'+ docName ... | StarcoderdataPython |
90230 | <gh_stars>0
"""Tabular QL agent"""
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import framework
import utils
DEBUG = False
GAMMA = 0.5 # discounted factor
TRAINING_EP = 0.5 # epsilon-greedy parameter for training
TESTING_EP = 0.05 # epsilon-greedy parameter for testing
NUM_... | StarcoderdataPython |
3289711 | <reponame>NEISSproject/tf_neiss
from trainer.trainer_base import TrainerBase
import model_fn.model_fn_nlp.model_fn_pos as models
import util.flags as flags
from input_fn.input_fn_nlp.input_fn_pos import InputFnPOS
# Model parameter
# ===============
flags.define_string('model_type', 'ModelPOS', 'Model Type to use choo... | StarcoderdataPython |
124478 | <reponame>franzihe/Python_Masterthesis<gh_stars>0
# coding: utf-8
# In[2]:
import sys
sys.path.append('/Volumes/SANDISK128/Documents/Thesis/Python/')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import colormaps as cmaps
import save_fig as SF
import datetime
from dateti... | StarcoderdataPython |
3333365 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
@Name: dump_db_pickle.py
@Desc:
@Author: <EMAIL>
@Create: 2020.05.06 14:26
-------------------------------------------------------------------------------
@Chang... | StarcoderdataPython |
1650449 | from setuptools import find_packages, setup
setup(
name="NIFR",
version="0.2.0",
author="<NAME>, <NAME>, <NAME>",
packages=find_packages(),
description="Null-sampling for Interpretable and Fair Representations",
python_requires=">=3.8",
package_data={"nifr": ["py.typed"]},
install_requi... | StarcoderdataPython |
3381138 | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
3264407 | <reponame>djbsmith/dmu_products
"""Script to generate the HELP homogenised SPIRE maps."""
from datetime import datetime
from itertools import product
import numpy as np
from astropy.io import fits
from astropy.table import Table
VERSION = "0.9"
spire_maps = Table.read("spire_maps.fits")
all_obsids = Table.read("sp... | StarcoderdataPython |
3336236 | <reponame>cuauv/software
#!/usr/bin/env python3
''' Run this script to increase laod on a system (useful for stress-testing cpu heating)
Credits to Stackoverflow for the multiprocessing code:
http://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool
'''
import multip... | StarcoderdataPython |
1760458 | from enum import Enum
# 2806
class Aplicacao(Enum):
E_HEALTH_1 = (1, 'Monitoramento de Saúde', 1.0, 0.3, 30.0, 1.15, 1.0)
E_HEALTH_2 = (2, 'Telemedicina', 25.0, 1.0, 30.0, 1.15, 0.4)
E_HEALTH_3 = (3, 'Navegação Web', 2.0, 1.0, 30.0, 1.15, 0.5)
E_LEARNING_4 = (4, 'EaD', 13.9, 1.0, 30.0, 1.15, 0.16)
... | StarcoderdataPython |
69951 | <filename>ModernArchitecturesFromScratch/basic_operations_01.py<gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: basic_operations.ipynb (unless otherwise specified).
__all__ = ['MNIST_URL', 'Path', 'set_trace', 'datasets', 'pickle', 'gzip', 'math', 'torch', 'tensor', 'random', 'pdb',
'show_doc', 'is_e... | StarcoderdataPython |
3381551 | <filename>src/mOps/core/number_generators.py
import random
rangeGenerator = lambda start=0, size=10, skip=1: (x for x in range(start, size, skip))
randomGenerator = lambda size=10, min=10, max=100: (x for x in random.sample(range(min, max), size))
def isPrime(n):
if (n <= 1 or n % 1 > 0):
return False
... | StarcoderdataPython |
4825156 | <filename>affordable_water/settings/testing.py
import os
# pylint:disable=unused-wildcard-import
from affordable_water.settings.base import * # noqa: F401
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
DEBUG_PROPAGRATE_EXCEPTIONS = True
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
'testserver'
]
SEC... | StarcoderdataPython |
1694946 | <reponame>aolney/dgm_latent_bow
"""The matching model for measuring semantic similarity
based on:
https://github.com/airalcorn2/Deep-Semantic-Similarity-Model/blob/master/deep_semantic_similarity_keras.py
and the MSR paper:
A Latent Semantic Model with Convolutional-Pooling Structure for Information
Retrieval
<NAM... | StarcoderdataPython |
148696 | <reponame>CyberZHG/keras-embed-sim
from .embeddings import *
__version__ = '0.9.0'
| StarcoderdataPython |
3370898 | #!/usr/local/CyberCP/bin/python
import socket
import sys
sys.path.append('/usr/local/CyberCP')
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import argparse
from plogical.mailUtilities import mailUtilities
class cacheClient:
cleaningPath = '/home/cyberpanel/purgeCache'
@staticmetho... | StarcoderdataPython |
7923 | <reponame>python-itb/knn-from-scratch
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 18:52:28 2018
@author: amajidsinar
"""
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
iris = datasets.load_iris()
dataset = iris.data
# only ... | StarcoderdataPython |
1757601 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/xavier_ssd/TrekBot/TrekBot2_WS/devel/.private/urg_node/include;/xavier_ssd/TrekBot/TrekBot2_WS/src/urg_node/include".split(';') if "/xavier_ssd/TrekBot/TrekBot2_WS/devel/.private/urg_node/include;/xav... | StarcoderdataPython |
3221213 | <gh_stars>0
import time
import tensorflow as tf
from model import evaluate
from model import srgan
from tensorflow.keras.applications.vgg19 import preprocess_input
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.losses import MeanAbsoluteError
from tensorflow.keras.losses import MeanSquar... | StarcoderdataPython |
184221 | N = int(input())
vals1 = [int(a) for a in input().split()]
vals2 = [int(a) for a in input().split()]
total = 0
for i in range(N):
h1, h2 = vals1[i], vals1[i + 1]
width = vals2[i]
h_dif = abs(h1 - h2)
min_h = min(h1, h2)
total += min_h * width
total += (h_dif * width) / 2
print(total) | StarcoderdataPython |
119778 | <reponame>tombiasz/django-pointer
from django.contrib.gis.db import models
class PointOfInterest(models.Model):
name = models.CharField(max_length=255)
point = models.PointField(srid=4326)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def ... | StarcoderdataPython |
3388811 | <gh_stars>1-10
from configparser import ConfigParser
from croniter import croniter
from datetime import datetime, timedelta
import datetime
import sys
import subprocess
import pandas as pd
import logging
import os
from pathlib import Path
pd.options.mode.chained_assignment = None
pd.options.display.float_format = '{:.... | StarcoderdataPython |
21106 | <gh_stars>0
import logging
import os
def initLogger() -> object:
"""
Initialize the logger.
"""
logger_level = logging.INFO
if 'APP_ENV' in os.environ:
if os.environ['APP_ENV'] == 'dev':
logger_level = logging.DEBUG
logging.basicConfig(level=logger_level,
... | StarcoderdataPython |
1779874 | <reponame>rraddi/iphas-dr2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Constants used in the IPHAS Data Release modules."""
import os
from astropy.io import fits
DEBUGMODE = False
# What is the data release version name?
VERSION = 'iphas-dr2-rc6'
# Where are the CASU pipeline-produced images and detection tables... | StarcoderdataPython |
3381501 | <filename>viz/viz_helpers.py
import csv
import numpy as np
import pandas as pd
import torch
from torchvision.utils import make_grid
from torchvision import transforms
from utils.datasets import get_background
from PIL import Image, ImageDraw, ImageFont
def reorder_img(orig_img, reorder, by_row=True, img_size=(3, 32,... | StarcoderdataPython |
3256950 | #PyJ2D - Copyright (C) 2011 <NAME> <https://gatc.ca/>
#Released under the MIT License <https://opensource.org/licenses/MIT>
from java.awt.image import BufferedImage
from pyj2d.surface import Surface
__docformat__ = 'restructuredtext'
__doc__ = 'Surface pixel manipulation'
_initialized = False
def _init():
""... | StarcoderdataPython |
1795842 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from __future__ import division
from collections import namedtuple
import math
Vector3 = namedtuple('Vector3', ['x', 'y', 'z'])
Vector2 = namedtuple('Vector2', ['x', 'y'])
def crossProduct(a, b):
""" return normalized cross product
"""
x = a.y*b.z - a.z*b.y
y... | StarcoderdataPython |
4825874 | from __future__ import annotations
from typing import Any, Optional
from datastax.linkedlists.doubly_linked_list import DoublyLinkedList
from datastax.linkedlists.private_lists import doubly_circular_llist
class DoublyCircularList(doubly_circular_llist.DoublyCircularList,
DoublyLinkedList):... | StarcoderdataPython |
3219978 | <filename>sched_slack_bot/utils/find_block_value.py
import logging
from enum import Enum
from typing import Optional, Union, List
from sched_slack_bot.utils.slack_typing_stubs import SlackState
logger = logging.getLogger(__name__)
class SlackValueContainerType(Enum):
value: str
plain_text_input = "value"
... | StarcoderdataPython |
113039 | <reponame>GabrieleMaurina/withcd
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='withcd',
version='1.0.2',
author='<NAME>',
author_email='<EMAIL>',
description='Change working directory utility compatible with with statements',
long_description=long_des... | StarcoderdataPython |
1753178 | <reponame>j-bernardi/bayesian-label-smoothing<gh_stars>1-10
GLOBAL_TYPE = 'float32'
| StarcoderdataPython |
3332609 | """
Class to retrieve some meta information about dataset based on name and subset.
"""
from dataclasses import dataclass
from typing import Optional, List
@dataclass
class DatasetInfo:
"""
Class containing meta information about dataset
"""
name: str
subset: Optional[str]
text_columns... | StarcoderdataPython |
2829 | #!/usr/bin/python
import unittest
import json
import sys
import os
import string
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir,
os.pardir))
from nysa.cbuilder import sdb_component as sdbc
from nysa.cbuilder import sdb_object_model as som
... | StarcoderdataPython |
3215675 | # Copyright 2011 OpenStack LLC.
# 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 |
1706630 | <gh_stars>0
# coding: utf-8
"""
Metacore IoT Object Storage API
Metacore Object Storage - IOT Core Services # noqa: E501
OpenAPI spec version: 1.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PreferencesDashboard... | StarcoderdataPython |
84936 | <filename>auxiliaries.py<gh_stars>10-100
"""
Contains utility functions to compute standard DML metrics such as Recall, NMI or F1.
Also some other QOL stuff that is helpful and the main Data-Logger class.
"""
"""=========================================================================================================... | StarcoderdataPython |
119513 | '''
Program: string_processor.py
Demo of method chaining in Python.
By: <NAME> -
http://jugad2.blogspot.in/p/about-vasudev-ram.html
Copyright 2016 <NAME>
'''
import copy
class StringProcessor(object):
'''
A class to process strings in various ways.
'''
def __init__(self, st):
'''Pass a string... | StarcoderdataPython |
165774 | <reponame>GuyPaulHadad/IML.HUJI<gh_stars>0
import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
import math
import plotly.grap... | StarcoderdataPython |
3365436 | import json
from notifications.models import Notification
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework import exceptions
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from authors.apps.notify... | StarcoderdataPython |
1694728 | <filename>pyaxis/pyaxis.py
"""Pcaxis Parser module parses px files into dataframes.
This module obtains a pandas DataFrame of tabular data from a PC-Axis
file or URL. Reads data and metadata from PC-Axis [1]_ into a dataframe and
dictionary, and returns a dictionary containing both structures.
Example:
from pyaxi... | StarcoderdataPython |
107856 | <reponame>haydenshively/Tezos-Prediction
from training.train_cnn_timeseries import main as train_cnn_timeseries
from training.train_lstm import main as train_lstm
from testing.test_cnn_timeseries import main as test_cnn_timeseries
from testing.test_lstm import main as test_lstm
if __name__ == '__main__':
# train_... | StarcoderdataPython |
184106 | """
Algorithm to use Obspy's metadata to pull response and other metadata. Returns an apporpiate
inventory class.
A.V. Newman Mon Jul 26 15:26:35 EDT 2021
"""
from obspy.clients.fdsn import Client as fdsnClient
from obspy import UTCDateTime
def get_respinv(network,eloc,etime,rads,chan):
fclient = fdsnClient()
... | StarcoderdataPython |
3385101 | import pytest
from Modules.device_module import *
class TestDeviceModule:
def test_device_module_no_input(self):
with pytest.raises(json.decoder.JSONDecodeError):
dm_json_check("")
def test_device_module_incomplete_input(self):
with pytest.raises(AttributeError):
json_str = '''{
"patientname": "Jack"... | StarcoderdataPython |
1724820 | <gh_stars>1-10
import gym, gym_envs
from stable_baselines.common.vec_env import DummyVecEnv, VecNormalize
from stable_baselines.common.env_checker import check_env
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import time
import argparse
def main():
parser = argparse.ArgumentP... | StarcoderdataPython |
127020 | #usando strip para eliminar espaços vazios nas bordas de uma string. Equivalente ao trim()
arquivo = open('pessoas.csv')
for linha in arquivo:
print('Nome: {}, Idade: {}'.format(*linha.strip().split(','))) #Usando * irá extrair os elementos de uma coleção de dados (lista, tuplas dicionários, sets, etc)
arquivo.... | StarcoderdataPython |
5751 | <filename>qiskit_metal/qlibrary/lumped/cap_n_interdigital.py
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source t... | StarcoderdataPython |
1629846 | version = (1, 2, 0)
version_string = '.'.join(str(x) for x in version)
| StarcoderdataPython |
3390078 | from django import forms
from .models import InstaUser,Test
class InstaForm(forms.ModelForm):
text = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter your text'}))
class Meta:
model = InstaUser
fields = ['username','password','text','image']
widgets = {
'... | StarcoderdataPython |
118368 | import re
from functools import cache
def lmap(f, it):
return list(map(f, it))
def ints(it):
return lmap(int, it)
@cache
def F(d, s):
reset_at = d - s - 1
if reset_at < 0:
return 1
return F(reset_at, 6) + F(reset_at, 8)
def solve(input):
return sum(F(256, x) for x in ints(re.find... | StarcoderdataPython |
176882 | #!/usr/bin/python3
class ComplexThing:
def __init__(self, name, data):
self.name = name
self.data = data
def __str__(self):
return self.name + ": " + str(self.data)
| StarcoderdataPython |
3372953 | import functools
import json
from amcp_pylib.core.syntax import Scanner, Parser, CommandGroup
def command_syntax(syntax_rules: str):
scanner = Scanner(syntax_rules)
parser = Parser(scanner)
result_tree = parser.parse()
command_syntax_tree = result_tree # copy.deepcopy(result_tree)
command_varia... | StarcoderdataPython |
126229 | '''
Une application minimaliste qui switche a intervalle de temps regulier entre deux pages Internet.
L'idée de l'application vient de cette discussion :
http://www.developpez.net/forums/d1255957/autres-langages/python-zope/general-python/jongler-entre-onglets-navigateur-web
'''
import sys
from PyQt4 import QtCore, Q... | StarcoderdataPython |
3261709 | <gh_stars>1-10
# Generated by Django 2.2 on 2019-10-08 06:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('utils', '0002_auto_20190824_2234'),
('meals', '0002_auto_20190824_2234'),
]
operations = [
... | StarcoderdataPython |
3381328 | <gh_stars>1-10
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
def __init__(self, gamma=2, reduction='mean'):
super().__init__()
self.gamma = gamma
self.reduction = reduction
def forward(self, logit, target):
target = target.float()
ma... | StarcoderdataPython |
73487 | <gh_stars>0
# -*- coding: utf-8 -*-
from ._common import *
encode_translation = bytes.maketrans(b'+/=', b'_~-')
decode_translation = bytes.maketrans(b'_~-', b'+/=')
def encode_tk2(s):
s = bytearray(base64.b64encode(s.encode()).translate(encode_translation))
s.reverse()
return s.decode()
def decode_tk2(... | StarcoderdataPython |
4824755 | from bot.common.threads.thread_builder import (
BaseThread,
ThreadKeys,
BaseStep,
StepKeys,
Step,
)
from bot.config import read_file
class ReportStep(BaseStep):
""""""
name = StepKeys.USER_DISPLAY_CONFIRM.value
def __init__(self, guild_id):
self.guild_id = guild_id
async... | StarcoderdataPython |
175847 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 14:10:46 2019
@author: gui
"""
import sys, pygame
import numpy as np
from pygame.locals import *
import pygame.freetype
w = 600
h = 600
scale = 100
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
score = max_score = 0
pygame.init()
screen = pygame.... | StarcoderdataPython |
181568 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright (c) 2019 the HERA Project
# Licensed under the MIT License
"""Class and algorithms to compute per Antenna metrics."""
import numpy as np
from copy import deepcopy
import os
import re
from .version import hera_qm_version_str
from . import utils, metrics_io
def get_an... | StarcoderdataPython |
1638644 | <gh_stars>0
from django.test import TestCase
from .models import Location, Category, Image
import datetime as dt
# Create your tests here.
class LocationTestClass(TestCase):
"""
Tests Location class and its functions
"""
#Set up method
def setUp(self):
self.loc = Location()
def test_i... | StarcoderdataPython |
1636004 | <gh_stars>10-100
#!/usr/bin/env python2.7
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import frontend
import os
import tempfile
import unittest
class TestFrontend(unittest.TestCase):
def test_loa... | StarcoderdataPython |
1781469 | <filename>analytics/analyzer.py
import os
from typing import Tuple, List
import numpy as np
import pandas as pd
from utils.plotting import create_chart, plot_different_metrics, plot_loss_comparison
from utils.typing import OptionAvgType, NetType
from positive_network.net_maker import get_trained_net_and_test_set as g... | StarcoderdataPython |
1633643 | <reponame>MaggieChege/New_App
import os
# You need to replace the next values with the appropriate values for your configuration
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = "postgresql://username:password@localhost/databa... | StarcoderdataPython |
1707409 | <filename>app/exam/models.py<gh_stars>0
from django.db import models
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.auth.models import User
from django.urls import reverse
from django.shortcuts import render, redirect
import datetime
from django... | StarcoderdataPython |
29170 | # -*- coding: utf-8 -*-
# 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 applicable law or agreed to in writing, softw... | StarcoderdataPython |
3347479 | <reponame>ruchirtravadi/pykaldi
from kaldi.base import math as kaldi_math
from kaldi.matrix import Vector, Matrix
from kaldi.cudamatrix import (CuMatrix, CuVector,
approx_equal_cu_matrix, same_dim_cu_matrix, cuda_available)
import unittest
import numpy as np
class TestCuMatrix(unittest.... | StarcoderdataPython |
153416 | <reponame>SenHuang19/EnergyPlus-Volttron-Toolkit<filename>dashboard/src/zone_data.py
from flask import request
from flask_restful import Resource
import os
import json
import pytz
import sqlite3
import pandas as pd
from utils import *
from eplus_tmpl import EPlusTmpl
class ZoneData(Resource):
def __init__(self)... | StarcoderdataPython |
4834899 | <reponame>zidingz/datasets<filename>tests/test_metadata_util.py
import re
import tempfile
import unittest
from dataclasses import asdict
from pathlib import Path
from datasets.utils.metadata import (
DatasetMetadata,
metadata_dict_from_readme,
tagset_validator,
validate_metadata_type,
yaml_block_fr... | StarcoderdataPython |
3360752 | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
from std_msgs.msg import Int32
from scipy.spatial import KDTree
import numpy as np
import time
import thread
import math
'''
This node will publish waypoints from the car's current position to some `... | StarcoderdataPython |
1621011 | # test2_pyganim.py - A pyganim test program.
#
# This program shows off a lot more of Pyganim features, and offers some interactivity.
#
# The animation images come from POW Studios, and are available under an Attribution-only license.
# Check them out, they're really nice.
# http://powstudios.com/
import pyga... | StarcoderdataPython |
62351 | import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*(testing.product({
'batchsize': [1, 5],
'size': [10, 20],
'dtype': [numpy.float32],
'eps': [1e-5, 1e-1],
})))
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
]
# GPU tests
... | StarcoderdataPython |
3270230 | <gh_stars>1-10
import boto3
from .client import logger, BatchSourceBase, BatchDestinationBase
class SQSClientBase():
def __init__(self, queue_name, region_name="us-east-1"):
logger.info(f"Connecting to SQS queue with name '{queue_name}' in region '{region_name}'.")
self.sqs = boto3.client("sqs", r... | StarcoderdataPython |
3339456 | """
Replay Buffer for Deep Reinforcement Learning
"""
from collections import deque
import random
import numpy as np
class ReplayBuffer:
def __init__(self, size_buffer, random_seed=None):
if random_seed:
random.seed(random_seed)
np.random.seed(random_seed)
self._size_... | StarcoderdataPython |
1663698 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 18 12:47:18 2022
A small investigation into the correlation of errors in the dD and d18O is performed
from the snow cores at EastGRIP.
@author: michaeltown
"""
import pandas as pd
import statsmodels.api as sm
import seaborn as sns
import numpy as... | StarcoderdataPython |
3314952 | import numpy as np
import dircache
from sets import Set
import time
import tables as pt
import sys
import time
import os
from optparse import OptionParser
class TimestampsModel (pt.IsDescription):
timestamp = pt.Time64Col()
#class TimestampsModel ends
class StrategyDataModel(pt.IsDescription):
... | StarcoderdataPython |
3331234 | import re
########
# PART 1
def extra_space(dimensions):
sortedDimensions = list(dimensions)
sortedDimensions.sort()
return sortedDimensions[0] * sortedDimensions[1]
def needed_paper(dimensions):
l = dimensions[0]
w = dimensions[1]
h = dimensions[2]
# 2*l*w + 2*w*h + 2*h*l
return 2*... | StarcoderdataPython |
1657614 | #!/usr/bin/env python3
import connexion
import logging
from swagger_server import encoder
def create_app():
#logging.getLogger('connexion.operation').setLevel('ERROR')
app = connexion.App(__name__, specification_dir='./swagger/')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', ... | StarcoderdataPython |
1608127 | <gh_stars>10-100
def linear_search(values, search_for):
search_at = 0
search_res = False
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34... | StarcoderdataPython |
1747467 | <filename>tests/test_job.py
from unittest.mock import patch
from digester.job import run
@patch('digester.job.get_recently_played')
@patch('digester.job.send_email')
def test_run(send_email, get_recently_played):
run()
get_recently_played.assert_called()
send_email.assert_called()
| StarcoderdataPython |
1784079 | <reponame>larsoner/genz-1<gh_stars>1-10
__version__ = '2.0.0.dev0+fa29bb7'
| StarcoderdataPython |
3291056 | import os
import pickle
import pandas as pd
from . import feature_selection
PATRIC_FILE_EXTENSION_TO_PGFAM_COL = {'.txt' : 'pgfam', '.tab' : 'pgfam_id'}
GENOME_ID = 'Genome ID'
LABEL = 'Label'
HP = 'HP'
NHP = 'NHP'
def read_merged_file(file_path):
"""
Reads genomes merged file into pd.Series object
Para... | StarcoderdataPython |
105123 | from django.core.management.base import BaseCommand, CommandError
from dashboard.models import Bin, Dataset
class Command(BaseCommand):
"""for testing only!!"""
help = 'delete all bins'
def add_arguments(self, parser):
parser.add_argument('-ds', '--dataset', type=str, help='name of dataset')... | StarcoderdataPython |
1797635 | from rest_framework import viewsets
from rest_framework.generics import ListAPIView
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from .models import Favourite, Category, Metadata
from .serializers import FavouriteSerializer, CategorySerializer, MetadataSerializer
class F... | StarcoderdataPython |
57247 | <gh_stars>0
# -*- coding:utf-8 -*-
__author__ = 'zhangzhibo'
__date__ = '202018/5/18 16:56'
| StarcoderdataPython |
1780984 | <reponame>anasf97/drug_learning
import drug_learning.two_dimensions.Input.fingerprints as fp
def sdf_to_fingerprint(input_file, fp_list, format_dict, urdkit_voc=None):
for fp_class in fp_list:
if fp_class:
if fp_class == fp.UnfoldedRDkitFP:
fingerprint = fp_class(urdkit_voc)
... | StarcoderdataPython |
3272917 |
import sys
import subprocess as sp
import networkx as nx
import os
from itertools import combinations
import glob
from matplotlib import pyplot as plt
import numpy as np
from matplotlib_venn import venn3, venn3_circles
file_list=sorted(glob.glob('/home/fast2/onimaru/DeepGMAP-dev/data/predictions/quick_benchmark/bed_c... | StarcoderdataPython |
154563 | from abc import abstractmethod, ABC
import torch
from dpm.distributions import (
Distribution, Normal, Data,
GumbelSoftmax, ConditionalModel,
Categorical
)
from dpm.distributions import MixtureModel
from dpm.train import train
from dpm.criterion import cross_entropy, ELBO
from torch.nn import Softmax, Modul... | StarcoderdataPython |
1660466 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return
... | StarcoderdataPython |
1661850 | <filename>0001 Two Sum.py
# https://leetcode.com/problems/two-sum/
# brute force
# O(n^2) time | O(1) space
# Brute Force -- O(n^2) time | O(1) space
def twoSum(array, targetSum):
for i in range(len(array) - 1):
first_num = array[i]
for j in range(i + 1, len(array)):
second_num = array[j]
if first... | StarcoderdataPython |
1788384 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from swagger_client.api.core_employees_v2_api import CoreEmployeesV2Api
from swagger_client.api.core_me_api import CoreMeApi
| StarcoderdataPython |
3258713 | # Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers. See the top-level LICENSE file for dates and other
# details. No copyright assignment is required to contribute to VisIt.
"""
file: __init__.py
author: <NAME> <<EMAIL>>
created: 3/28/2012
description:
Init for 'vi... | StarcoderdataPython |
3213451 | <reponame>jiangdou2015/blog
from django.shortcuts import render_to_response, get_object_or_404
from djpjax import pjax
from blogpost.models import Blogpost
def index(request):
return render_to_response('index.html', {
'posts': Blogpost.objects.all()[:5]
})
@pjax(pjax_template="pjax.html", additional_... | StarcoderdataPython |
78728 | <reponame>tbsschroeder/dbas
import dbas.handler.issue as ih
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import Issue, User, Language
from dbas.strings.translator import Translator
from dbas.tests.utils import construct_dummy_request, TestCaseWithConfig
class TestIssueDictByIssue(... | StarcoderdataPython |
1615664 | <filename>models/fs_networks.py
"""
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
import torch.nn as nn
class InstanceNorm(nn.Module):
def __init__(self, epsilon=1e-8):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.