id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
58929
<filename>LineMapLayer.py from math import * from kivy.graphics import Color, Line, SmoothLine, MatrixInstruction from kivy.graphics.context_instructions import Translate, Scale from kivy.clock import Clock from kivy.garden.mapview.mapview.utils import clamp from kivy.garden.mapview.mapview import MapLayer, MIN_LONGI...
StarcoderdataPython
3376197
from pathlib import Path from fhir.resources.valueset import ValueSet as _ValueSet from oops_fhir.utils import ValueSet from oops_fhir.r4.code_system.data_type import DataType from oops_fhir.r4.code_system.resource_type import ResourceType __all__ = ["FHIRDefinedType"] _resource = _ValueSet.parse_file(Path(__fi...
StarcoderdataPython
2157
<reponame>paulineollitrault/qiskit-ignis<gh_stars>100-1000 # -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # 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 tree or a...
StarcoderdataPython
3314615
<gh_stars>0 from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse , HttpResponseRedirect from blog.models import Category ,Post , Comment , Like, Tag from .forms import * from django.db.models import Q from django.contrib.auth.decorators import login_required def landpage(request):...
StarcoderdataPython
2122
from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from sesame import utils from django.core.mail import send_mail def login_page(request): if request.method == "POST": email = request.POST.get("emailId") user =...
StarcoderdataPython
3270208
import h5py import matplotlib.pyplot as plt import numpy as np import os import os.path import tensorflow as tf from keras.backend import floatx from keras.layers import Conv2D, Conv3D, Dense, Dropout from keras.layers.core import Flatten from keras.models import load_model, Sequential from keras import optimizers fr...
StarcoderdataPython
3367356
# MIT License # # Copyright (c) 2021 <NAME>. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use...
StarcoderdataPython
176421
<gh_stars>0 class CDI(): def __init__(self,v3,v2,v3SessionID,v3BaseURL,v2BaseURL,v2icSessionID): print("Created CDI Class") self._v3=v3 self._v2=v2 self._v3SessionID = v3SessionID self._v3BaseURL = v3BaseURL self._v2BaseURL = v2BaseURL self._v2icSessionID = v2...
StarcoderdataPython
1774947
<reponame>lin-tan/fairness-variance<filename>dlfairness/original_code/Balanced-Datasets-Are-Not-Enough/verb_classification/data/convert_pickle.py import os import dill import pickle import argparse import shutil def convert(old_pkl): """ Convert a Python 2 pickle to Python 3 """ # Make a name for the ...
StarcoderdataPython
72247
<filename>semvermanager/__main__.py import sys from semvermanager import main if __name__ == "__main__": main(sys.argv[1:]) # clip off the program name
StarcoderdataPython
3389878
<gh_stars>0 from ._CosmicVoidsAnalysis import CVA from ._Fitting import HSW_Fitting from ._Fitting import HSW from ._Profiles import Profiles from ._Load import Load
StarcoderdataPython
1667212
<gh_stars>1-10 import aud import bpy from bpy.props import IntProperty, FloatProperty, PointerProperty import nodeitems_utils from nodeitems_utils import NodeItem, NodeCategory bl_info = { "name": "Audio Nodes", "category": "Node", } class AudioNodeTree(bpy.types.NodeTree): bl_description = "Audio Node Trees" ...
StarcoderdataPython
147656
<filename>tests/int/test_flashloans.py<gh_stars>10-100 from deficrawler.lending import Lending def test_flashloans_aave_2_eth(): aave = Lending(protocol="Aave", chain="Ethereum", version=2) flash_loans = aave.get_data_from_date_range( '30/08/2021 00:00:01', '30/08/2021 18:01:00', "flashloans") as...
StarcoderdataPython
3329002
<reponame>ToFeWe/qpricesim<filename>qpricesim/simulations/performance.py """ Collection of functions to calculate performance measures for the agents upon convergence. """ import numpy as np from ..model_code.economic_environment import calc_reward from ..model_code.economic_environment import calc_winning_price from...
StarcoderdataPython
80506
<reponame>rupol/Hash-Tables-Lecture # substitution ciphers # or, how to transform data from one thing to another encode_table = { 'A': 'H', 'B': 'Z', 'C': 'Y', 'D': 'W', 'E': 'O', 'F': 'R', 'G': 'J', 'H': 'D', 'I': 'P', 'J': 'T', 'K': 'I', 'L': 'G', 'M': 'L', 'N':...
StarcoderdataPython
54818
<reponame>plutasnyy/tutorials<gh_stars>0 import os from os.path import abspath from pathlib import Path import pytest from click.testing import CliRunner from sst import cli from tests.path_utils import get_tests_dir STATIC_FILES = Path(get_tests_dir() + os.sep + 'static') example_input = abspath(STATIC_FILES / "tr...
StarcoderdataPython
1635349
<reponame>peskaf/ramAIn<gh_stars>0 from PySide6.QtWidgets import QFrame, QWidget from PySide6.QtGui import QIcon class View(QFrame): """ A widget for viewing method for the manual preprocessing part of the app. """ def __init__(self, parent: QWidget = None) -> None: """ The constructor...
StarcoderdataPython
163278
# https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/745/ # https://leetcode.com/problems/power-of-three/description/ # Power of Three # # Given an integer, write a function to determine if it is a power of three. # ie, 45 % 3 is 0, but 45 is not power of 3 # so it is not simply "n % 3 ...
StarcoderdataPython
61942
<reponame>jlubken/cfgenvy<filename>src/cfgenvy/__init__.py # -*- coding: utf-8 -*- """Cfg env yaml.""" from .env import Env from .parser import Parser from .yaml import ( yaml_dump, yaml_dumps, yaml_implicit_type, yaml_load, yaml_loads, yaml_type, Mapping as YamlMapping, ) __all__ = ( ...
StarcoderdataPython
16589
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from sklearn import datasets, linear_model from difflib import SequenceMatcher import seaborn as sns from statistics import mean from ast import literal_eval from scipy import stats from sklearn.linear_model import LinearRegression from s...
StarcoderdataPython
1677841
<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");...
StarcoderdataPython
1726686
# # PySNMP MIB module ZXR10-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-SMI # Produced by pysmi-0.3.4 at Mon Apr 29 21:41:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
StarcoderdataPython
3370094
<reponame>imsofi/codejam-grand-geckos<filename>grand_geckos/database/exceptions.py from sqlalchemy.exc import ArgumentError class UserAlreadyExistsError(ArgumentError): pass class AuthenticationError(ArgumentError): pass
StarcoderdataPython
107101
############################################################################### # Script for generating results from paper ############################################################################### import subprocess import matplotlib.pyplot as plt import os, sys sizes = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512,...
StarcoderdataPython
62891
import tensorflow as tf from tensorflow import keras def build_mlp( mlp_input, output_size, n_layers, size, output_activation = None): x = mlp_input for _ in range(n_layers) : x = keras.layers.Dense(units = size, activation = 'relu')(x) return keras.layers.Dense(units = output_...
StarcoderdataPython
72792
from matplotlib import pyplot as plt plt.xkcd() ages_x = [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55] py_dev_y = [20046, 17100, 20000, 24744, 30500, 37732, 41247, 45372, 48876, 53850, 57287, 63016, ...
StarcoderdataPython
1693710
# 5.2 Learning is just parameter estimation import torch import numpy as np import csv import matplotlib.pyplot as plt # data t_c = [0.5, 14.0, 15.0, 28.0, 11.0, 8.0, 3.0, -4.0, 6.0, 13.0, 21.0] t_u = [35.7, 55.9, 58.2, 81.9, 56.3, 48.9, 33.9, 21.8, 48.4, 60.4, 68.4] t_c = torch.tensor(t_c) t_u = torch.tensor(t_u) # ...
StarcoderdataPython
3316787
from django.db.models.signals import post_save from django.dispatch import receiver from .models import Question, Answer, QuestionAnswer from .utils import notify_new_question @receiver(post_save, sender=Question) def new_question_handler(sender, instance, created, **kwargs): subject = f'New question from {insta...
StarcoderdataPython
1675990
import argparse import sys import os import traceback from biokbase.CompressionBasedDistance.Client import _read_inifile, ServerError as CBDServerError from biokbase.CompressionBasedDistance.Helpers import get_config, parse_input_file, start_job desc1 = ''' NAME cbd-buildmatrixlocal -- build a distance matrix to...
StarcoderdataPython
3288232
import time,os if not os.path.exists('Token.txt'): newFile = open('Token.txt','w') newFile.close() class Func(): class tokenClass(): def __init__(self): self.userToken = "" self.userType = "" def chkAvail(self,userType): availList = ['global-admin','privileged-admin','common-admin','readonly','writeo...
StarcoderdataPython
3260155
<reponame>howardisaacson/APF-BL-DAP import argparse import os import datetime parser = argparse.ArgumentParser() parser.add_argument("-resid_out","--residuals_out_path", type=str, help= "Directory to save residuals to (ie. 'NDRR_calib').") parser.add_argument("-results_out","--results_filename", type=str, help= "Fil...
StarcoderdataPython
1627481
from lib import commandlib commandlib.execute_command("./find/find_training.sh")
StarcoderdataPython
1640842
"""Gathers output from test runs and create an XML file in JUnit format. The output files from the individual tests have been written in a directory structure like: $DIR/joblog (output from "parallel --joblog joblog") $DIR/logs/1/cpp/stdout $DIR/logs/1/cpp/stderr $DIR/logs/1/csharp/stdout $DIR/logs/1/cshar...
StarcoderdataPython
1633013
from numpy import array from pybimstab.astar import Astar grid = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0,...
StarcoderdataPython
3265689
import autolens as al import numpy as np import pytest class TestSimulatorInterferometer: def test__from_tracer__same_as_tracer_input(self): grid = al.Grid2D.uniform(shape_native=(20, 20), pixel_scales=0.05, sub_size=1) lens_galaxy = al.Galaxy( redshift=0.5, l...
StarcoderdataPython
199340
#!/usr/bin/env python3 """ itio: Interactive Twinleaf I/O License: MIT Author: <NAME> <<EMAIL>> """ import tldevicesync import argparse def main(): parser = argparse.ArgumentParser(prog='itio', description='Interactive Twinleaf I/O.') parser.add_argument("url", ...
StarcoderdataPython
1779317
"""doc""" from chain import split_chain import pandas as pd import plotly.graph_objects as go def plot_surface3d(symbol: str, S: float, chain: pd.DataFrame, data_to_plot: dict): """Plot 3d surfaces of itm/otm calls/puts. data_to_plot = { price_type: 'mid' or 'bid' or 'ask' or 'last' opt_type:...
StarcoderdataPython
4837897
<gh_stars>0 __author__ = '<NAME>' from .settings import GuildSettings from .superportal import SuperPortal
StarcoderdataPython
3370177
<reponame>Joey-Resende/Estudando-Python<filename>Python3/scripts-python3/outrosEstudos/cursoIntroDunossauro/exercicio_20.py # monte um dicionario com as seguintes chaves = lista, somatorio, tamanho, maior valor, menor valor
StarcoderdataPython
30141
<reponame>inlgmeeting/inlgmeeting.github.io<gh_stars>0 import argparse import csv import json import sklearn.manifold import torch def parse_arguments(): parser = argparse.ArgumentParser(description="MiniConf Portal Command Line") parser.add_argument("papers", default=False, help="paper file") ...
StarcoderdataPython
4808099
<reponame>VatsalP/py_chip8 """ Holds Scenes =) """ from random import randint import pygame from pygame.locals import * import main class SceneBase: def __init__(self): self.next = self def process_input(self, events, pressed_keys): self.pressed_keys = pressed_keys def update(self): ...
StarcoderdataPython
3263111
"""Git tools for Python.""" from pathlib import Path, PurePosixPath from datetime import datetime import json from copy import copy from git import Repo, InvalidGitRepositoryError # ============================ Custom exceptions ============================= class DirtyRepo(Exception): """Specific exception in...
StarcoderdataPython
67036
<filename>utils/__init__.py import typing from enum import Enum, EnumMeta class ChoiceEnumMeta(EnumMeta): def __getattribute__(cls, name: str) -> typing.Any: attr = super().__getattribute__(name) if isinstance(attr, Enum): return attr.value return attr def __iter__(cls): ...
StarcoderdataPython
4810671
<reponame>vedantc6/LCode class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ n = len(nums) num_zeros = 0 for i in range(n): if nums[i] == 0: ...
StarcoderdataPython
1902
<reponame>huchenxucs/WaveRNN import math import numpy as np import librosa from utils import hparams as hp from scipy.signal import lfilter import soundfile as sf def label_2_float(x, bits): return 2 * x / (2**bits - 1.) - 1. def float_2_label(x, bits): assert abs(x).max() <= 1.0 x = (x + 1.) * (2**bits...
StarcoderdataPython
176843
<gh_stars>1-10 from __future__ import absolute_import import logging log = logging.getLogger('reversible') def execute(action): """ Execute the given action. An action is any object with a ``forwards()`` and ``backwards()`` method. .. code-block:: python class CreateUser(object): ...
StarcoderdataPython
168733
<filename>os_android_adb_handler/test.py from os_android_adb_handler import adb_handler time.sleep(7) adb_handler.dpad_right() time.sleep(1) adb_handler.dpad_right() adb_handler.dpad_right() print("yey!")
StarcoderdataPython
103777
<filename>scripts/chlam_hpi.py import WD_Utils from wikidataintegrator import wdi_core, wdi_login import getpass username = "djow2019" password = <PASSWORD>("<PASSWORD>") count = 0 d_strain = "272561" l2_strain = "471472" sparql = WD_Utils.WDSparqlQueries() login = wdi_login.WDLogin(user=username, pwd=password) ref ...
StarcoderdataPython
3371059
import sqlite3 import os.path import sys class Sqlite: _file_db = None _conn = None def __init__(self, file_db='temp', auto_conect=True, with_file_existed=True): self.setFileDB(file_db) if with_file_existed: if self.checkFile(): print "DB file not found!" ...
StarcoderdataPython
1713105
<filename>plnn/mip_solver.py import gurobipy as grb import torch from itertools import product from torch import nn from plnn.modules import View, Flatten from torch.nn import functional as F from plnn.dual_network_linear_approximation import LooseDualNetworkApproximation from plnn.network_linear_approximation import ...
StarcoderdataPython
4817425
# Generated by Django 3.0.2 on 2020-09-06 01:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analysis', '0072_auto_20200714_2144'), ] operations = [ migrations.CreateModel( name='MarkCriticalPointTask', fields...
StarcoderdataPython
4821118
<filename>pythonizame/apps/blog/models.py from __future__ import unicode_literals import os import uuid import logging from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.core.cache import cache from ckeditor_uploader.fields import RichTextUploadingF...
StarcoderdataPython
29747
from flask import Flask, render_template, request, redirect, url_for import tensorflow as tf from keras.models import load_model from keras.backend import set_session from src.utils import image_preprocessing from src.utils import overall_class_label from src.utils import infinite_scraper # sessions and default graphs...
StarcoderdataPython
1726889
<filename>character_sheet/src/player/sense.py class Senses: def get_passive_insight(self, insight): return 10 + insight def get_passive_perception(self, perception): return 10 + perception
StarcoderdataPython
3386940
from django.http import HttpResponse from django.shortcuts import render from django.views import View from .models import Grid from apps.subjects.models import Subject # Create your views here. ''' class GridView(View): template_name = 'grids/grids.html' def get(self, request): grids = Grid.object...
StarcoderdataPython
4818635
import pathlib from setuptools import setup with open('requirements.txt') as fp: install_requires = fp.readlines() with open('README.md') as fp: readme = fp.read() about = {} version_file_path = pathlib.Path(__file__).parent / 'synthetic' / '__version__.py' exec(version_file_path.read_text('utf-8'), about...
StarcoderdataPython
1602816
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import io import unittest import pure_interface from tests.interface_module import IAnimal from unittest import mock class TestIsInstanceChecks(unittest.TestCase): def test_abc_register(self)...
StarcoderdataPython
1693998
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-03 14:14 from __future__ import unicode_literals from django.db import migrations from bluebottle.utils.utils import update_group_permissions def add_group_permissions(apps, schema_editor): group_perms = { 'Staff': { 'perms': ( ...
StarcoderdataPython
3384763
from .create_project import create_project from .download_tags import download_tags from .make_training_database import make_training_database from .train_project import train_project from .evaluate_project import evaluate_project from .grad_cam import grad_cam from .evaluate import evaluate, evaluate_image
StarcoderdataPython
1198
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Defines coordinate frames and ties them to data axes. """ from __future__ import absolute_import, division, unicode_literals, print_function import numpy as np from astropy import units as u from astropy import utils as astutil from astropy import coo...
StarcoderdataPython
33938
import os import re import shutil def svnLockFiles(files): fileStr = ' '.join(files) print('Locking files: ', fileStr) os.system('svn lock ' + fileStr) def svnUnlockFiles(files): fileStr = ' '.join(files) print('Unlocking files: ', fileStr) os.system('svn unlock ' + fileStr) ...
StarcoderdataPython
3293250
def edgeos_action(object, on=None): """ Return the appropriate EdgeOS configuration command to send with *object*. Unless *on* is specified, return "set" if *object* evaluates to ``True`` or "delete" if *object* evaluates to ``False``. When *on* is specified, if *object* evaluates to ``True``, the...
StarcoderdataPython
125202
<reponame>jqueguiner/training_results_v1.0 """NumPy implementation of losses in 3DUnet. https://github.com/mmarcinkiewicz/training/blob/Add_unet3d/image_segmentation/unet3d/model/losses.py """ from __future__ import absolute_import from __future__ import division from __future__ import REDACTED from __future__ import...
StarcoderdataPython
52615
e = 1
StarcoderdataPython
126224
<gh_stars>1-10 from .pairwise import ( # noqa pairwise_distances, pairwise_distances_argmin_min, euclidean_distances, ) from .regression import ( # noqa mean_absolute_error, mean_squared_error, r2_score, ) from .classification import ( # noqa accuracy_score, ) from .scorer import ( # no...
StarcoderdataPython
3274282
from time import sleep from random import randint computador = randint(0, 10) soma = 0 print('''Sou seu computador .... Acabei de pensar em um número entre 0 e 10. Será que você consegue adivinhar qual foi ?''') sleep(2) palpite = int(input('Qual é o seu palpite ? ')) while palpite != computador: soma = soma + 1 ...
StarcoderdataPython
9876
import dash from dash import html app = dash.Dash(__name__) app.layout = html.Div(children=[html.H1('Data Science', style = {'textAlign': 'center', 'color': '#0FD08D', 'font-size': '...
StarcoderdataPython
1696164
<gh_stars>1-10 from zerver.models import Realm from zerver.lib.cache import cache_with_key, realm_rendered_description_cache_key from zerver.lib.bugdown import convert as bugdown_convert @cache_with_key(realm_rendered_description_cache_key, timeout=3600*24*7) def get_realm_rendered_description(realm: Realm) -> str: ...
StarcoderdataPython
14477
"""Base utility functions, that manipulate basic data structures, etc.""" ################################################################################################### ################################################################################################### def flatten(lst): """Flatten a list of l...
StarcoderdataPython
67984
#coding=utf-8 import sys import os import json import jinja2 import time import Filter class Generator(object): def __new__(cls, name): if name == 'FlatView': return FlatViewGenerator() elif name == 'MemoView': return MemoViewGenerator() class BaseGenerator(object): de...
StarcoderdataPython
3385431
#This was created using the following tutorial as a reference: #https://realpython.com/how-to-make-a-discord-bot-python/#how-to-make-a-discord-bot-in-python import os import random import math import discord from discord.ext import commands from dotenv import load_dotenv from datetime import datetime load_dotenv() T...
StarcoderdataPython
1728999
<filename>plot_util.py import matplotlib.pyplot as plt def show_accuracy(history): acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validating ac...
StarcoderdataPython
178103
<reponame>LynxN1/amino_service import traceback from typing import Union from termcolor import colored from src import database, amino_async from src.utils import convert_from_txt, logger, file_logger from src.login import login from src.scripts.badass import Badass from src.scripts.bot_management import Bot...
StarcoderdataPython
1763059
<filename>Application/models.py __author__ = 'dimitris' from Application import db class Researchers(db.Model): __tablename__ = 'Researchers' phone_id = db.Column(db.String(80), nullable=False, primary_key=True) name = db.Column(db.String(80), nullable=False) surname = db.Column(db.String(80), nulla...
StarcoderdataPython
3276419
import logging from django.utils import timezone from eve_api.esi_client import EsiClient from eve_api.models import EVEPlayerAlliance, EVEPlayerCharacter, CcpIdTypeResolver from django.apps import apps from .util import is_downtime from django.core.cache import cache logger=logging.getLogger(__name__) def _get_cac...
StarcoderdataPython
1760452
<filename>pradreader/rdcarlo.py #!/usr/bin/python # -*- coding: utf-8 -*- """ rdcarlo.py: Proton radiography reades2d_cm specific to Carlo's format Created by <NAME> & <NAME> on Thu Aug 17 12:31:25 2017 To generate the reference flux map, currently just takes the average of the signal flux map. TODO: * Get a bet...
StarcoderdataPython
47407
<reponame>Firexd2/social-network from django import forms from chat.models import Message, Room class NewRoomForm(forms.ModelForm): ids_users = forms.CharField(label='', required=False, widget=forms.TextInput(attrs={'hidden': 'true'})) first_message = forms.CharField(label='Приветственное сообщение', requi...
StarcoderdataPython
170616
"""市町村コード関係の関数群.""" from collections import namedtuple Urls = namedtuple('Urls', 'hourly') def get_cityname(code): """市町村名を取得する. Arguments: code {str} -- 市町村コード Returns: str -- 市町村名 """ if code != '01101': return None return "札幌市中央区" def get_tenkijp_urls(code): ...
StarcoderdataPython
3230332
<gh_stars>10-100 import torch device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') FloatTensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor LongTensor = torch.cuda.LongTensor if torch.cuda.is_available() else torch.LongTensor
StarcoderdataPython
1720450
import os import datetime t = datetime.datetime.now().strftime("%m\/%d\/%Y") os.system(f'echo -n {t} > ./my_date.txt')
StarcoderdataPython
4840596
<gh_stars>0 from mdx_linkify import makeExtension
StarcoderdataPython
152544
<filename>tests/test_data.py import pytest import dice_ml from dice_ml.utils import helpers def test_data_initiation(public_data_object, private_data_object): assert isinstance(public_data_object, dice_ml.data_interfaces.public_data_interface.PublicData), "the given parameters should instantiate PublicData class"...
StarcoderdataPython
3308209
<filename>NAS/lib/log_utils/time_utils.py ##################################################### # Copyright (c) <NAME> [GitHub D-X-Y], 2019.01 # ##################################################### import time def time_for_file(): ISOTIMEFORMAT = "%d-%h-at-%H-%M-%S" return "{:}".format(time.strftime(ISOTIMEF...
StarcoderdataPython
177242
<filename>models/PNPNet/pnp_net.py ''' * PNP-Net: flexibly takes a tree-structure program and assemble modules for image generative modeling * It contains: -- primitive visual elements -- unit modules -- tree recursive function -- forward(), generate() -- utility functions: clean_tree...
StarcoderdataPython
118761
#!/usr/bin/env python # -*- coding:utf8 -*- # Power by viekie. 2017-05-19 15:36:33 import struct class Loader(object): def __init__(self, path, count): self.path = path self.count = count def get_file_content(self): with open(self.path, 'rb') as f: content = f.read() ...
StarcoderdataPython
3213481
<gh_stars>1-10 # Copyright 2021 The MLX Contributors # # SPDX-License-Identifier: Apache-2.0 import kfp.dsl as dsl import kfp from kfp import components import yaml dlf_op = components.load_component_from_file('component.yaml') with open("dlf_example.yaml", 'r') as stream: sample_dlf = yaml.safe_load(stream) @ds...
StarcoderdataPython
151011
<reponame>CWrath/tradekit import datetime import sqlite3 from polygon import RESTClient def ts_to_datetime(ts) -> str: return datetime.datetime.fromtimestamp(ts / 1000.0).strftime('%Y-%m-%d %H:%M') def main(from_, to, ticker, timespan): key = '<KEY>' # RESTClient can be used as a context manager to fa...
StarcoderdataPython
1717777
# Rock Paper Scissors import random # Keep track of user and comp score user = 0 comp = 0 options = ["rock", "paper", "scissors"] while True: # .lower() to make all data the same user_input = input("Rock - Paper - Scissors\nQ to Quit\n").lower() if user_input == 'q': # Stops the While Loop ...
StarcoderdataPython
1702609
<reponame>pfmoore/em-keyboard import argparse from unittest.mock import call, patch import pytest from em import cli, copier @pytest.mark.parametrize( "test_name", [ "star", ":star:", ], ) @patch("em.argparse.ArgumentParser.parse_args") @patch("em.sys.exit") @patch("builtins.print") def ...
StarcoderdataPython
3267860
import logging import luigi from sqlalchemy import func, insert, select from models.db import get_db_session from models.models import CuratedFctProduct, StageSearchResultsScraped from .build_dim import BuildDim logger = logging.getLogger(__name__) class BuildFctStatus(luigi.Target): def __init__(self, today:...
StarcoderdataPython
3215261
windows = False if windows: directory = '//nas.sala.ubc.ca/ELabs/100_personal/nm/Databases/' bca_dir = '//nas.sala.ubc.ca/ELabs/50_projects/16_PICS/07_BCA data/' else: directory = '/Volumes/Samsung_T5/Databases/' bca_dir = '/Volumes/ELabs/50_projects/16_PICS/07_BCA data/' modes = ['transit', 'bike', 'w...
StarcoderdataPython
1622086
<filename>src/plot.py # Standard library imports import csv # Third library imports import matplotlib.pyplot as plt def plot (x, xlabel, ys, ylabel, ylabels, title, output_name="plot", save_csv=False): """ It represents received data as a line plot. :param x: X axis data. :param xlabel: X axis label....
StarcoderdataPython
1760894
<gh_stars>1-10 """ Google Image Scraper """ import os import requests import shutil import imghdr import base64 import argparse from harvest_urls import HarvestURLs from multiprocessing import Pool class Sites: GOOGLE = 1 GOOGLE_FULL = 3 @staticmethod def get_text(code): ...
StarcoderdataPython
3345298
import time current_milli_time = lambda: int(round(time.time() * 1000)) lastTime = current_milli_time() def pow_mod(x, y, z): number = 1 while y: if y & 1: number = number * x % z y >>= 1 x = x * x % z return number i = 190000000 num = 0 while (num != 10483580695461...
StarcoderdataPython
3229443
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. 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 ...
StarcoderdataPython
1792680
<filename>src/elaspic2_rest_api/config.py import os from typing import Optional ROOT_PATH = os.getenv("ROOT_PATH", "") GITLAB_HOST_URL: str = os.getenv("GITLAB_HOST_URL", "https://gitlab.com") GITLAB_PROJECT_ID: int = int(os.getenv("GITLAB_PROJECT_ID", "21481523")) GITLAB_AUTH_TOKEN: Optional[str] = os.getenv("GITL...
StarcoderdataPython
3374760
''' Python MongoDB Find * In MongoDB we use the find and findOne methods to find data in a collection. * Just like the SELECT statement is used to find data in a table in a MySQL database. Find One To select data from a collection in MongoDB, we can use the find_one() method. The find_one() method returns the firs...
StarcoderdataPython
1704481
<reponame>NULLCT/LOMC # -*- coding: utf-8 -*- import math import collections import bisect import itertools import heapq import os from collections import defaultdict, deque, Counter import sys import copy import string from pprint import pprint from decimal import Decimal import re sys.setrecursionlimit(10**9) readli...
StarcoderdataPython
3230350
<gh_stars>10-100 # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup ------------------------------------------------------...
StarcoderdataPython
149904
<filename>vsts_accounts/models/vss_json_collection_wrapper.py # coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # ------------...
StarcoderdataPython