id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
28871 | <filename>tdcsm/cli.py
#! /usr/bin/env python
"tdcsm command-line interface"
import argparse
from pathlib import Path
from typing import Any, Sequence, Callable, List, Optional
from logging import getLogger
from .tdgui import coa as tdgui
from .tdcoa import tdcoa
from .model import load_filesets, load_srcsys, dump_sr... | StarcoderdataPython |
169759 | import logging
import json
from functools import wraps, update_wrapper, partialmethod
import tornado.web
import tornado.httpclient
from tornado.platform.asyncio import to_asyncio_future
from rest_tools.client import RestClient
from rest_tools.server import Auth, RestHandlerSetup, authenticated, catch_error
from rest_... | StarcoderdataPython |
149922 | <gh_stars>0
import argparse
from sklearn import preprocessing
import numpy as np
import pandas as pd
# args
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="CSV file")
args = parser.parse_args()
# data
df = pd.read_csv(args.filename)
print(df)
print()
# numpy array
ar = np.array(df, dtype=np... | StarcoderdataPython |
1680115 | import requests
from bs4 import BeautifulSoup
url = 'http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture'
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html, "html.parser")
print(soup.get_text())
| StarcoderdataPython |
1711843 | <filename>tools/addons/TK_OpenGex_LDJAM.py<gh_stars>0
# =============================================================
#
# Open Game Engine Exchange
# http://opengex.org/
#
# Export plugin for Blender
# by <NAME>
#
# Version 2.0
#
# Copyright 2017, Terathon Software LLC
#
# This software is licens... | StarcoderdataPython |
3383114 | import csv
import torch
import random
"""
load synth / real data as:
[
{
"questionId": tensor([ 0, 1, 2.,..]) # id 1~n, torch.LongTensor
"correct": tensor([ 0, 1, 0.,..]) # correct 1, incorrect 0, torch.LongTensor
"n_answers": 4 # seq_len, int
},
{
"questionId": tensor([... | StarcoderdataPython |
197343 | <reponame>devind-team/graphene-django-filter
"""Queries execution tests."""
from datetime import datetime
from typing import List
from django.test import TestCase
from django.utils.timezone import make_aware
from graphql.execution import ExecutionResult
from graphql_relay import from_global_id
from .data_generation ... | StarcoderdataPython |
3259429 | from src.game_screens.screen import Screen
from src.misc.game_enums import Game_mode, Difficulty
from pygame.locals import QUIT, KEYUP, MOUSEBUTTONUP
from src.ui.button import Button
class Game_Mode_Screen(Screen):
def __init__(self, pygame, res, surface, game_manager):
Screen.__init__(self, pygame, res, ... | StarcoderdataPython |
160823 | <filename>Day06_2021.py<gh_stars>0
# PART ONE
import os
scriptsPath = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptsPath)
print("\nCurrent working directory: " + str(os.getcwd()) + "\n")
rawFile = open("input.txt")
contents = rawFile.read()
items = contents.split(",")
state = []
for i in items:
... | StarcoderdataPython |
1761863 | # Leetcode 103. Binary Tree Zigzag Level Order Traversal
#
# Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Difficulty: Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = l... | StarcoderdataPython |
1673213 | # stdlib
from itertools import chain
import argparse
import os
# 3P
import torch
import torch.nn as nn
from torch import save
from torch.cuda import FloatTensor
from torch.autograd import Variable
# Project
from utils.utils import CHECKPOINT_DIR
from utils.utils import lambda_scheduler, init_weights_normal
from utils.d... | StarcoderdataPython |
149685 | import sys
from charts.GanttChart import GanttChart
REDDIT_CSV_ROUTE = "../../output/reddit/reddit.csv"
REDDIT_CSV_OUTLIERS_ROUTE = "../../output/reddit/reddit_filtered.csv"
REDDIT_CSV_LIVEVARS_ROUTE = "../../output/reddit/reddit.csv"
SOF_CSV_ROUTE = "../../output/stackoverflow/stackoverflow.csv"
SOF_CSV_OUTLIERS_ROUT... | StarcoderdataPython |
4807758 | <gh_stars>1-10
import os
import re
import urllib.parse
import urllib.request
def download_files(first_url, output_dir):
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
url_head, url_tail = os.path.split(first_url)
first_index = re.findall(r'[0-9]+', url_tail)[-1]
index_c... | StarcoderdataPython |
126031 | """ This module contains auxiliary functions to plot some information on the
RESTUD economy.
"""
# standard library
import matplotlib.pylab as plt
import numpy as np
import shutil
import shlex
import os
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import FuncFormatter
from matplotlib import cm
# Ev... | StarcoderdataPython |
190735 | from client_lib.servercall import remote_call
_isInitialized = False
_productList = None
_productNameList = []
_productNumberList = []
def _prodSugInit():
global _isInitialized
global _productList
global _productNameList
global _productNumberList
_productList = remote_call('/product/all')
# Build product name... | StarcoderdataPython |
1776244 | <reponame>RyosukeDTomita/gcmDataUse<filename>modules/fontjp.py
#########################################################################
# Name: fontjp.py
#
# Return japanese font path.
# if you do not have source-han-code-jp, you can download [here](https://github.com/adobe-fonts/source-han-code-jp/archive/2.000R.zip)... | StarcoderdataPython |
163048 | <filename>Agents/train.py
import logging, os, time, multiprocessing, sys, signal
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
import gym
import pybullet, pybullet_envs, pybullet_data
import numpy as np
import pandas as pd
from stable_baselines.sac.policies impor... | StarcoderdataPython |
4831038 | import time
import platform
import getpass
import os
#import os.path.join as join
# function:
# genaration(arg)
# writeFrame(writefile) *with path
# writeEntity(writefile, entityname) *must be used adjacent to writeframe
# addports(writefile, arg)
def writeFrame(writefile):
'''
Write title and libaraies.
''... | StarcoderdataPython |
177891 | <reponame>ehultee/stoch-SMB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Load process-model SMB in a given catchment and regress a mass balance gradient
Created on Thu Aug 5 14:14:05 2021
Edit Sept 2: compute 30-year mean of anomaly
@author: lizz
"""
from shapely.geometry import MultiPoint
from shapely.ops im... | StarcoderdataPython |
25131 | #!/usr/bin/env python
#
# // SPDX-License-Identifier: BSD-3-CLAUSE
#
# (C) Copyright 2018, Xilinx, Inc.
#
import tensorflow as tf
import numpy as np
from xfdnn_compiler_tensorflow import TFFrontend
#from xfdnn.tools.compile.frontends.frontend_caffe import CaffeFrontend
from tensorflow.python.platform import gfile
impo... | StarcoderdataPython |
3239073 | from shortest import Database, ConnectingFlights, console
if __name__ == '__main__':
db = Database('localhost', 27017, "connecting_flight")
cf = ConnectingFlights(db)
console.menu(db, cf)
console.clear()
| StarcoderdataPython |
1600168 | import argparse
from os import path
DATA_DIR = path.join(path.dirname(path.dirname(__file__)), "data")
MODEL_DIR = path.join(DATA_DIR, "models")
def get_argparser():
parser = argparse.ArgumentParser('EDU segmentation toolkit 1.0')
parser.add_argument('--prepare', action='store_true',
... | StarcoderdataPython |
177965 | <reponame>jof2jc/custom1<gh_stars>0
from __future__ import unicode_literals
import frappe
from frappe import _, scrub
from frappe.utils import nowdate, nowtime, now_datetime, flt, cstr, formatdate, get_datetime, add_days, getdate, get_time
from frappe.utils.dateutils import parse_date
from frappe.model.naming import m... | StarcoderdataPython |
1770995 | import tensorflow as tf
import tree
def initialize_tf_variables(session, only_uninitialized=True):
variables = tf.compat.v1.global_variables() + tf.compat.v1.local_variables()
def is_initialized(variable):
try:
session.run(variable)
return True
except tf.errors.FailedP... | StarcoderdataPython |
92459 | <reponame>albertdow/zinv-analysis<gh_stars>0
import numpy as np
import pandas as pd
import operator
from cachetools import cachedmethod
from cachetools.keys import hashkey
from functools import partial
from utils.NumbaFuncs import get_bin_indices, weight_numba
def evaluate_pu(var, corrs):
@cachedmethod(operator.... | StarcoderdataPython |
3267442 | <reponame>jobscry/soc-analyst<filename>analyst/__main__.py
"""
Example Application
Usage:
analyst [options]
Options:
-h --help Show this screen.
"""
import sys
import aumbry
from docopt import docopt
from gunicorn.app.base import BaseApplication
from gunicorn.workers.sync import SyncWorker
fr... | StarcoderdataPython |
4804678 | <filename>Exercicios/ex086 - Matriz em Python.py
matriz = [[],[],[]]
for l in range (3):
for c in range (3):
matriz[l].append(int(input(f'Digite o valor para [{l}][{c}]: ')))
for v in range(3):
for p in range(3):
print(f'[{matriz[v][p]:^5}]', end=' ')
print('') | StarcoderdataPython |
1661804 | KUBEFLOW_JOB_GROUP = "kubeflow.org"
TF_JOB_KIND = "TFJob"
TF_JOB_PLURAL = "tfjobs"
TF_JOB_VERSION = "v1beta1"
TF_SPEC = 'tfReplicaSpecs'
PYTORCH_JOB_KIND = "PyTorchJob"
PYTORCH_JOB_PLURAL = "pytorchjobs"
PYTORCH_JOB_VERSION = "v1beta1"
PYTORCH_SPEC = 'pytorchReplicaSpecs'
MPI_JOB_KIND = "MPIJob"
MPI_JOB_PLURAL = "mp... | StarcoderdataPython |
1779955 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
train the multimodal network
"""
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
import numpy as np
import glob
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.transforms as transform... | StarcoderdataPython |
3284696 | <filename>src/python/T0/WMBS/Oracle/RunConfig/ReleasePromptReco.py
"""
_ReleasePromptReco_
Oracle implementation of ReleasePromptReco
Release PromptReco for given run and primary dataset.
"""
from WMCore.Database.DBFormatter import DBFormatter
class ReleasePromptReco(DBFormatter):
def execute(self, binds, conn =... | StarcoderdataPython |
3249041 | <reponame>francium/microurl
import json
import sys
import time
from Crypto.Hash import SHA256
import MySQLdb as sqldb
class DB_Interface:
def __init__(self):
try:
config = parse_config()
self.user = config['user']
self.passwd = config['password']
self.host ... | StarcoderdataPython |
4814479 | <filename>08-Analog-Joystick-Color-Wheel-Test/spidev_mock.py
# Created by comments in spidev_module.c, in the py-spidev package
# available here -> https://github.com/doceme/py-spidev
def SpiDev():
return SpiDevMock()
class SpiDevMock:
def __init__(self):
print("New instance of class created: {}".fo... | StarcoderdataPython |
30708 | """
Script to generate a custom list of stopwords that extend upon existing lists.
"""
import json
import spacy
from urllib.request import urlopen
from itertools import chain
def combine(*lists):
"Combine an arbitrary number of lists into a single list"
return list(chain(*lists))
def get_spacy_lemmas():
... | StarcoderdataPython |
157572 | import os
from os import system
import sys
import time
def has_root():
return os.geteuid() == 0
if not has_root():
print("[-] Please run as Root... Quitting!!")
sys.exit(1)
else:
print("[+] Running as Root")
print("[+] Installing Dependencies....")
time.sleep(2)
system("apt-get update")
system("apt... | StarcoderdataPython |
1714102 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def CustomizationVirtualMachineName(vim, *args, **kwargs):
'''Specifies that VirtualCente... | StarcoderdataPython |
3547 | from controller.invoker import (
invoker_cmd_branch_checkout,
invoker_cmd_branch_commit,
invoker_cmd_branch_create,
invoker_cmd_branch_delete,
invoker_cmd_branch_list,
invoker_cmd_evaluate,
invoker_cmd_filter,
invoker_cmd_gpu_info,
invoker_cmd_inference,
invoker_cmd_init,
inv... | StarcoderdataPython |
84277 | def test():
print('\nNON-NESTED BLOCK COMMENT EXAMPLE:')
sample = ''' /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function s... | StarcoderdataPython |
130322 | <filename>tests/system/test_platform.py
import pygemstones.system.platform as p
# -----------------------------------------------------------------------------
def test_windows():
ret = p.is_windows()
assert isinstance(ret, bool)
# ----------------------------------------------------------------------------... | StarcoderdataPython |
3372276 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ddtools.seqContext import list_combinations
from ddtools.utilities import *
def _groupByLastBase(indict):
#######
# params:tokeep defined by user
# length of ... | StarcoderdataPython |
3276662 | from hashlib import sha256
digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def decode_base58(bc, length):
n = 0
for char in bc:
n = n * 58 + digits58.index(char)
return n.to_bytes(length, 'big')
def is_bitcoin_address_valid(address):
try:
bcbytes = decode_bas... | StarcoderdataPython |
1698024 | from importlib.resources import path
import random
import sqlite3
from typing import Any, Dict, List, Optional
from hyperborea3.valid_data import VALID_ALIGMENTS_SHORT, VALID_SQL_TABLES
with path("hyperborea3", "hyperborea.sqlite3") as p:
DBPATH = p
URI = f"file:{str(DBPATH)}?mode=ro"
con = sqlite3.connect(URI, c... | StarcoderdataPython |
3290938 | import pytest
from tasks.consts import MissionStatus, TaskStatus
from tasks.models import (
Task, Item, Annotation,
Mission)
from tasks.controllers.annotation_controller import AnnotationController
from tasks.tests.conftest import add_annotation
@pytest.mark.django_db
def test_task_progress(task_with_items, ... | StarcoderdataPython |
3256253 | #coding=utf-8
#Test orm extension support
import time, sys
sys.path.insert(0, '../uliweb/lib')
from uliweb.core import dispatch
from uliweb.orm import *
import uliweb.orm as orm
orm.__auto_create__ = True
orm.__nullable__ = True
orm.__server_default__ = False
def _get_model(sender, model_name, model_inst, model_info,... | StarcoderdataPython |
1600160 | <reponame>Manu87DS/Computer_vision_basic_study_Images_Filters
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 5 11:43:28 2021
@author: <NAME>
"""
import numpy as np
import cv2
import pandas as pd
from skimage.filters import roberts, sobel, scharr, prewitt
from scipy import ndimage as nd
img = cv2.imread('... | StarcoderdataPython |
3392324 | <gh_stars>1-10
from .layer import Layer
import numpy as np
class ReLU(Layer):
def __init__(self, node, params=None):
if params is None:
params = {}
params['number_of_inputs'] = 1
super(ReLU, self).__init__(node, params=params)
def computeSize(self):
super(ReLU, self).computeSize()
return tuple(self... | StarcoderdataPython |
3287921 | # Copyright 2017 <NAME>. All rights reserved.
from Nodes3DAPI.Manifest import AssetAPI
from Nodes3DAPI.Manifest import FnAttribute, FnGeolibServices
from Nodes3DAPI.Manifest import NodegraphAPI
from Nodes3DAPI.TimingUtils import GetModifiedFrameTime
from Nodes3DAPI.TimingUtils import GetTimingParameterHints
from Nodes... | StarcoderdataPython |
3374249 | <filename>useradm/rbaccount.py
#-----------------------------------------------------------------------------#
# MODULE DESCRIPTION #
#-----------------------------------------------------------------------------#
"""RedBrick Account Module; contains RBAccount c... | StarcoderdataPython |
14370 | <reponame>ChouHsuan-Cheng/Learning_Python_Base<gh_stars>0
from direct.showbase.ShowBase import ShowBase
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Load the environment model.
self.environ = self.loader.loadModel("models/environment")
# Reparent the model ... | StarcoderdataPython |
160943 | # builtin
import asyncio
# third party
from aioconsole import ainput
# custom
from utils import cfg, MCP
from selection import copysel
from commands import parse
mc = MCP()
async def cmdloop() -> None:
try: parse(mc, cfg["autoexec"], fatal=True)
except Exception as e:
print(f"Error in autoexe... | StarcoderdataPython |
1720751 | """The decora component."""
| StarcoderdataPython |
10213 | import os
from shutil import rmtree
from tempfile import mkdtemp
from unittest import TestCase
from enjoliver import generator
class GenerateGroupTestCase(TestCase):
api_uri = None
test_matchbox_path = None
test_resources_path = None
tests_path = None
@classmethod
def setUpClass(cls):
... | StarcoderdataPython |
86195 | # def flatten(current, result=[]):
# if isinstance(current, dict):
# for key in current:
# flatten(current[key], result)
# else:
# result.append(current)
# return result
import ndmg
def test_flatten():
current = {'name':'liming', 'age':'20'}
value = ndmg.utils.bids_ut... | StarcoderdataPython |
3273499 | <filename>earlier-2020/python_mod_tutorials/mlutiprocess/tsubprocess.py
import subprocess
import time
# obj = subprocess.Popen(['python' ,'tsleep.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj = subprocess.Popen(['python' ,'tsleep.py'])
# out,err = obj.communicate()
# print(out)
# obj... | StarcoderdataPython |
184689 | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import pathlib
import shutil
import subprocess
SCRIPT_DIR = pathlib.Path(__file__).parent.resolve()
DEFAULT_OPS_CONFIG_RELATIVE_PATH = "tools/ci_build/github/android/mobile_package.requ... | StarcoderdataPython |
1742236 | #!/usr/bin/env python3.8
# @generated by pegen from ./Tools/peg_generator/pegen/metagrammar.gram
import ast
import sys
import tokenize
from typing import Any, Optional
from pegen.parser import memoize, memoize_left_rec, logger, Parser
from ast import literal_eval
from pegen.grammar import (
Alt,
... | StarcoderdataPython |
3351707 | <reponame>oskaralfons/coinapi-sdk
# coding: utf-8
"""
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> ... | StarcoderdataPython |
50035 | # Generated by Django 3.0.5 on 2020-04-19 18:06
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('basta', '0004_session_sl... | StarcoderdataPython |
64117 | # Copyright 2018 NOKIA
#
# 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 wri... | StarcoderdataPython |
3298665 | import matplotlib, os, errno
# IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg:
#print matplotlib.get_backend()
if not('DISPLAY' in os.environ):
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=N... | StarcoderdataPython |
3256307 | import os
import sys
import traceback
def fasta2dict(fasta_file, samtools, picard):
try:
print " - genome.dict"
os.system("java -jar " + picard + "/CreateSequenceDictionary.jar R=" + fasta_file + " O=" + fasta_file.replace(".fa", ".dict") + " &>/dev/null")
print " - genome.fa.fai"
... | StarcoderdataPython |
3327844 | import formats.event as evdat
from formats.filesystem import NintendoDSRom
import unittest
import os
class TestEventData(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
rom_path = os.path.dirname(__file__)
cls.rom = NintendoDSRom.fromFile(rom_path + "/../../test_rom.nds")
de... | StarcoderdataPython |
1763636 | <reponame>vetalpaprotsky/python-project-lvl1<gh_stars>1-10
from brain_games import engine
from brain_games.games import even
def main():
engine.play(even)
if __name__ == '__main__':
main()
| StarcoderdataPython |
3263634 | <filename>fn_api_void/fn_api_void/util/selftest.py
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# -*- coding: utf-8 -*-
"""
Function implementation test.
Usage: resilient-circuits selftest -l fn_api_void
"""
import logging
LOG = logging.getLogger(__name__)
from resilient_lib import RequestsCommon, vali... | StarcoderdataPython |
3358893 | <gh_stars>100-1000
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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/license... | StarcoderdataPython |
1702441 | """
The :mod:`skmultiflow.metrics` module includes performance metrics.
"""
from .measure_collection import ClassificationMeasurements
from .measure_collection import RegressionMeasurements
from .measure_collection import MultiTargetClassificationMeasurements
from .measure_collection import MultiTargetRegressionMeasur... | StarcoderdataPython |
180500 | <gh_stars>1-10
from calculate_time import cal_time
def split(li, left, right):
tmp = li[left]
i, j = left, right
while i < j:
while li[j] >= tmp and i < j:
j -= 1
li[i] = li[j]
while li[i] <= tmp and i < j:
i += 1
li[j] = li[i]
li[i] = tmp
re... | StarcoderdataPython |
37879 | <reponame>stefanos90/Utilities<filename>utilities/send_custom_mail.py
# In order to use this function you have to create a Django project
from django.conf import settings
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMultiAlterna... | StarcoderdataPython |
173386 | <filename>workerInfra/domain/__init__.py
from .dbApiInterface import DbApiTableInterface
# from .dbApiTableInterface import DbApiTableInterface
from .cacheInterface import CacheInterface
from .outputInterface import OutputInterface
from .outputFormatterInterface import OutputFormatterInterface
from .loggerInterface imp... | StarcoderdataPython |
3206350 | import connexion
from fdp import config
def create_app(host, port, graph_endpoint=None):
config.init_fairgraph(host, port, graph_endpoint)
app = connexion.FlaskApp(__name__, specification_dir='openapi/', debug=True)
options = {"swagger_ui": True}
app.add_api('openapi.yaml',
options=options... | StarcoderdataPython |
3358763 | <reponame>millingermarkus/pypsa-eur
# SPDX-FileCopyrightText: : 2020 @JanFrederickUnnewehr, The PyPSA-Eur Authors
#
# SPDX-License-Identifier: MIT
"""
This rule downloads the load data from `Open Power System Data Time series <https://data.open-power-system-data.org/time_series/>`_. For all countries in the network, ... | StarcoderdataPython |
4816090 | <gh_stars>0
#!/usr/bin/env python2
#
# Copyright 2017 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.
#
# pylint: disable=cros-logging-import
# This is the script to run specified benchmark with different toolchain
# se... | StarcoderdataPython |
172643 | import os
import click
import boto3
import json
from airmail.cli import pass_context
from airmail.services.ecs_service import ECSService
@click.group(short_help='Create/modify ECS services')
@pass_context
def cli(ctx):
if ctx.dry_run:
ctx.warn_log("Running in dry run mode! Commands will not execute against... | StarcoderdataPython |
7054 | from django.test import TestCase
from django.utils import timezone
from accounts.models import CustomUser, CustomUserManager
class UserCreateTestCase(TestCase):
def test_create_user_correctly(self):
"Creating users correctly"
new_user = CustomUser.objects.create(
email="<EMAIL>",
... | StarcoderdataPython |
3290466 | import logging
import socket
import threading
log = logging.getLogger(__name__)
class ELM327Proxy(threading.Thread):
TERMINATOR = b"\r"
PROMPT = b"\r>"
def __init__(self):
super(ELM327Proxy, self).__init__()
self.name = "elm327_proxy_{:}".format(id(self))
#self.daemon = True
... | StarcoderdataPython |
3355069 | # Copyright 2008-2018 pydicom authors. See LICENSE file for details.
# -*- coding: utf-8 -*-
"""unittest tests for pydicom.filereader module"""
import gzip
from io import BytesIO
import os
import shutil
import sys
import tempfile
import unittest
import pytest
import pydicom.config
from pydicom.dataset import Dataset... | StarcoderdataPython |
122457 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = [
"transformer",
"message",
"SimpleDataDialog",
"DataEntry",
"execdir",
]
import gui
import message
import misc
transformer = gui.transformer
SimpleDataDialog = gui.SimpleDataDialog
DataEntry = gui.DataEntry
execdir... | StarcoderdataPython |
1694422 | <reponame>euirim/pulse
from django.contrib import admin
from .models import Keyphrase
# Register your models here.
@admin.register(Keyphrase)
class KeyphraseAdmin(admin.ModelAdmin):
date_hierarchy = 'time_created'
search_fields = ('name',)
list_display = ('name', 'time_created', 'active', 'display')
... | StarcoderdataPython |
3290248 | from base.views.api.api_gene import lookup_gene, gene_variants
from collections import OrderedDict
from flask import render_template, Blueprint, redirect, url_for
from base.constants import BIOTYPES, TABLE_COLORS
#
# Gene View
#
gene_bp = Blueprint('gene',
__name__,
template_fol... | StarcoderdataPython |
60735 | import numpy as np
import os
import sklearn.metrics
from scipy.optimize import curve_fit
def slice_lat(ds):
return ds.sel(lat=slice(-25, 25))
def ensure_dir(file_path):
"""Check if a directory exists and create it if needed"""
if not os.path.exists(file_path):
os.makedirs(file_path)
def days_p... | StarcoderdataPython |
3388181 | <reponame>vishalbelsare/pydmrs<filename>pydmrs/graphlang/graphlang.py
from pydmrs.components import Pred, RealPred, GPred, Sortinfo, EventSortinfo, InstanceSortinfo
from pydmrs.core import Link, Node, ListDmrs
from pydmrs.mapping.mapping import AnchorNode, OptionalNode, SubgraphNode
default_sortinfo_classes = dict(
... | StarcoderdataPython |
38519 | # -*- coding: utf-8 -*-
import datetime
from django.db.models import Count, Q
from django.utils import timezone
from trojsten.events.models import EventParticipant
from trojsten.people.constants import SCHOOL_YEAR_END_MONTH
from trojsten.results.constants import COEFFICIENT_COLUMN_KEY
from trojsten.results.generator... | StarcoderdataPython |
1608843 | # Modified from https://github.com/TDeVries/cub2011_dataset/blob/master/cub2011.py
import os
import pandas as pd
from torchvision.datasets.folder import default_loader
from .utils import download_url
from torch.utils.data import Dataset
import shutil
class CUB200(Dataset):
base_folder = 'images'
url = 'http:/... | StarcoderdataPython |
1626226 | from .alluvial import *
from .overall_coverage import *
from .bar_line import *
from .value_add_bar import *
| StarcoderdataPython |
163123 | <filename>nxt/nxt_python/sensor_tests/color_sensor_test.py
#!/usr/bin/env python
import roslib; roslib.load_manifest("nxt_python")
import rospy
import time
import nxt.locator
from nxt.sensor import *
def test_sensors(b):
rospy.init_node('test_sensor')
cs = ColorSensor(b, PORT_1)
print "This is... | StarcoderdataPython |
1769205 | <gh_stars>1-10
import datetime
import click
from aspen.config.config import Config
from aspen.database.connection import (
get_db_uri,
init_db,
session_scope,
SqlAlchemyInterface,
)
from aspen.database.models import (
GisaidDumpWorkflow,
ProcessedGisaidDump,
RawGisaidDump,
WorkflowStat... | StarcoderdataPython |
3227409 | # Generated by Django 2.0.8 on 2019-09-25 21:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20190413_1520'),
]
operations = [
migrations.AddField(
model_name='endworker',
name='experience',... | StarcoderdataPython |
1675352 | <gh_stars>0
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); y... | StarcoderdataPython |
3212242 | import os
import subprocess
__version__ = '1.0.0.dev0'
try:
__revision__ = subprocess.check_output([
'git', 'describe', '--tags', '--always', '--dirty'
], cwd=os.path.dirname(__file__)).strip().decode()
except subprocess.CalledProcessError:
__revision__ = 'unknown'
| StarcoderdataPython |
6072 | ################################################################################
# Copyright (c) 2015-2018 Skymind, Inc.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless... | StarcoderdataPython |
170452 | <gh_stars>0
"""Decorators for authorization that raise an error when the user is not authorizated."""
| StarcoderdataPython |
45076 | <reponame>abagusetty/Uintah<gh_stars>1-10
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import math
import tempfile
import numpy as np
import subprocess as sub_proc
#Plotting stuff below
from matplotlib import rc
import matplotlib.pyplot as plt
from matplotlib import ticker
SHOW_ON_MAKE = False
#Usefu... | StarcoderdataPython |
1706076 | <reponame>nileshmahale03/Python
#id function
x = 10
print(id(x)) #140607028914768
y = 20
print(id(y)) #140607028915088
z = y
print(id(z)) #140607028915088
#is operator gives you a Boolean value
print(y is z)
print(x is z) | StarcoderdataPython |
97795 | <reponame>scottwedge/OpenStack-Stein
# 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 agr... | StarcoderdataPython |
1702953 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 17 01:04:26 2021
@author: <NAME>
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris()
data = iris.data[:,:2]
iris2 = pd.read_csv("data/iris.data").to_numpy()
data = iris2[:, ... | StarcoderdataPython |
3359985 | <filename>typeidea_MTV/typeidea/comment/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-09 11:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
d... | StarcoderdataPython |
1695791 | """Support for AirTouch 3 sensors."""
import logging
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ICON,
CONF_NAME,
CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT,
TEMP_CELSIUS
)
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_INSIDE_TEMPERATURE,
SENSOR_TYPE... | StarcoderdataPython |
1791144 | # -*- coding:utf-8 -*-
"""
-------------------------------------------------------------------------------
Project Name : ESEP
File Name : base.py
Start Date : 2022-03-25 07:45
... | StarcoderdataPython |
3214221 | # coding=UTF-8
"""
.. contents::
Welcome to **Cognate**, a package designed with making it easy to create
component services. **Cognate** strives to ease the burden of configuration
management and logging configuration, by providing the infrastructure.
**Cognate** fosters component service architectures by making the... | StarcoderdataPython |
3273251 | <filename>viscous/calc/calc_utilities.py<gh_stars>0
import numpy as np
from scipy import integrate
def integral(y,x,axis=0):
y[np.isnan(y)] = 0
return integrate.simps(y,x,axis=axis)
def average(y,x,axis=0):
""" Iterates over all axes except 'axis' and averages by slice. Excludes non-finite values"""
i... | StarcoderdataPython |
1633282 | wordList = open('./Lyrics.txt', 'r').readlines()
newWord = []
for word in wordList:
if word.lower().endswith('\n'):
newWord.append(str(word)[:-2])
else:
newWord.append(str(word))
f = open('./NewLyrics.txt', 'w+')
joinedStr = ' '.join(newWord)
f.write(joinedStr.lower().replace('!', '').replace('(... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.