id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
209792 | <gh_stars>0
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
def generateTrees(mini: int, maxi: int) -> List[Optional[int]]:
if mini > maxi:
return [None]
ans = []
for i in range(mini, maxi + 1):
for left in generateTrees(mini, ... | StarcoderdataPython |
8112542 | #!/usr/bin/env python3
from __future__ import print_function
import os
import platform
import time
import matplotlib
matplotlib.use('TkAgg') # to get rid of runtime error
import matplotlib.pyplot as plt
import numpy as np
# Check if the code runs on Mac (which almost all modern ones have AMD GPUs)
if platform.sys... | StarcoderdataPython |
361525 | <reponame>parallelwindfarms/byteparsing
from byteparsing.trampoline import Call, Trampoline, Parser
from byteparsing.parsers import item, choice, char
from byteparsing.cursor import Cursor
import pytest
class A(Trampoline):
pass
def test_trampoline():
a = A()
with pytest.raises(NotImplementedError):
... | StarcoderdataPython |
5128428 | from django.conf import settings
from dcu.active_memory import upload_rotate
import datetime
import os.path
import subprocess
import logging
logger = logging.getLogger(__name__)
class BackupFailed(Exception):
pass
def backup_media():
'''
make a backup of media files
'''
timestamp = datetime.d... | StarcoderdataPython |
9681308 | <gh_stars>1-10
from typing import Any, Callable, Generator, Optional, TypeVar
import azure
from azure.data.tables import TableClient, TableServiceClient
from azure.identity import DefaultAzureCredential
ModelType = TypeVar("ModelType")
def table_client() -> TableServiceClient:
"""connect to the table service.""... | StarcoderdataPython |
1681712 | <filename>dmpipe/dm_plotting.py
#!/usr/bin/env python
#
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Top level scripts to make castro plot and limits plots in mass / sigmav space
"""
import os
from os.path import splitext
import numpy as np
from astropy.table import Table
from fermipy.utils ... | StarcoderdataPython |
1859249 | print("Cal count bc you're fat")
gfat = float(input("Grams of Fat: "))
gprotein = float(input("Grams of Protein: "))
gcarbohydrate = float(input("Grams of Carbohydrates: "))
# Calorie calc
ONEG_FAT = 9
ONEG_PROTEIN = 4
ONEG_CARBOHYD = 4
fatCal = gfat * ONEG_FAT
print ("Grams of Fat: " +str(fatCal))
proteinCal = ... | StarcoderdataPython |
9662303 | #
# encoding: utf-8
import datetime
from unittest import TestCase
from mock import MagicMock
from tornadoalf.token import Token, TokenHTTPError
from tornado.httpclient import HTTPResponse
class TestToken(TestCase):
def test_should_have_an_access_token(self):
token = Token(access_token='access_token')
... | StarcoderdataPython |
9757560 | #!/usr/bin/python
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
class DummyAsyncResult(object):
""" A non-asynchronous dummy implementation of the AsyncResult object """
def __init__(self, func):
self.result = func()
def get(self):
return self.result
p... | StarcoderdataPython |
40019 | <filename>export/parts.py
from .attributes import AttributeExport
from .attributes import MimicExport
from .attributes import JointExport
from .attributes import JointOrientationExport
from .attributes import GazeExport
import os
class BodyPartsExport:
ExportClass = AttributeExport
def __init_... | StarcoderdataPython |
5173968 | <filename>house_code/tutorials_altered/modules/file_writing.py<gh_stars>1-10
from .data_functions import DataFunctions as DataFunctions
class SensorDataFileWriting:
@staticmethod
def write_sensor_data_header_to_file(file,
header=("Index,Time,Difference,Hz,AveHz,"
... | StarcoderdataPython |
9722979 | <filename>models.py
from flask_login import UserMixin
from json import load
from typing import Dict, Optional
from werkzeug.security import generate_password_hash, \
check_password_hash
class User(UserMixin):
def __init__(self, id: str, username: str, email: str, password: str):
self.id = id
... | StarcoderdataPython |
8128500 | <gh_stars>0
from flask import Flask
from .simple import simple_bp
from .signed import signed_bp
app = Flask(__name__)
app.register_blueprint(simple_bp)
app.register_blueprint(signed_bp)
| StarcoderdataPython |
308680 | '''
====================================================================
Copyright (c) 2003-2006 <NAME>. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
======================================================... | StarcoderdataPython |
1683993 | <reponame>Baidaly/datacamp-samples
'''
The election results DataFrame has a column labeled 'margin' which expresses the number of extra votes the winner received over the losing candidate. This number is given as a percentage of the total votes cast. It is reasonable to assume that in counties where this margin was les... | StarcoderdataPython |
5026822 | <filename>migrations/versions/2b5117cc3df6_.py<gh_stars>1-10
"""empty message
Revision ID: <KEY>
Revises: None
Create Date: 2014-02-25 17:44:17.487690
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import p... | StarcoderdataPython |
4809554 | from collections import defaultdict
from django.core.management.base import BaseCommand
from corehq.apps.userreports.models import (
DataSourceConfiguration,
StaticDataSourceConfiguration,
)
from corehq.apps.userreports.util import (
LEGACY_UCR_TABLE_PREFIX,
UCR_TABLE_PREFIX,
get_table_name,
)
fro... | StarcoderdataPython |
6582697 | <filename>Desafios/064 desafio.py
'''
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999,
que é a condição de parada. No final, mostre quantos números
foram digitados e qual foi a soma entre eles
(desconsiderando o flog condição de parada)
'''
... | StarcoderdataPython |
3580974 | """ RNN (Recurent Neural Network) on fashion MNIST - 88,3% over 50 epochs """
# import libraries
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import tensorflow
import numpy as np
from tensorflow.keras.layers import Dense, Activation, Input, SimpleRNN
fr... | StarcoderdataPython |
3224097 | <gh_stars>1-10
#! /usr/bin/env python
import begin
@begin.start(auto_convert=True)
def add(a=0.0, b=0.0):
""" Add two numbers """
print(a + b)
| StarcoderdataPython |
1660959 | from collections import defaultdict
from .abstract_pop_splitter import AbstractPOPSplitter
from ...graph_utils import path_to_edge_list
from math import floor
class BaselineSplitter(AbstractPOPSplitter):
def __init__(self, num_subproblems):
super().__init__(num_subproblems)
def split(self, problem):
... | StarcoderdataPython |
1638322 | <filename>onlinevars/views.py<gh_stars>0
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseBadRequest
import json
from .models import Variable
# Create your views here.
@csrf_exempt
def api_v1(re... | StarcoderdataPython |
252717 | <gh_stars>0
#A library of code to examine properties of bulk water and near solutes
#
#Should eventually be able to handle local densities and fluctuations,
#solute-water and water-water energies, 3-body angles, hydrogen bonds,
#energy densities, and all of this as a function of space. Additionally,
#should also be abl... | StarcoderdataPython |
252552 | import copy
import json
import sys
import uuid
from io import BufferedIOBase, TextIOBase
from ipaddress import (
ip_network,
ip_address,
IPv4Address,
IPv4Network,
IPv6Address,
IPv6Network
)
from jsonschema import Draft7Validator, ValidationError
from typing import (
Any,
Union
)
def p... | StarcoderdataPython |
9738495 | # import library socket karena menggunakan IPC socket
import socket as sc
# definisikan IP untuk binding
HOST = "192.168.1.15"
# definisikan port untuk binding
PORT = 4044
# definisikan ukuran buffer untuk menerima pesan
buffer_size = 1024
# buat socket (bertipe UDP atau TCP?)
s = sc.socket(sc.AF_INET, sc.SOCK_STRE... | StarcoderdataPython |
6586178 | import matplotlib.pyplot as plt
import numpy as np
def raw_plot(data):
"""
Args:
data: Numpy 2-D array. Row 0 contains episode lengths/timesteps and row 1 contains episodic returns
Returns:
"""
plt.plot(np.cumsum(data[0]), data[1])
plt.xlabel('Steps')
h = plt.ylabel("Return", lab... | StarcoderdataPython |
9600955 | <gh_stars>1-10
from threading import current_thread
from django.conf import settings
from django.contrib.auth.models import User
from ralph.account.models import Region
_requests = {}
def get_actual_regions():
thread_name = current_thread().name
if thread_name not in _requests:
return Region.objec... | StarcoderdataPython |
1865082 | <reponame>jyooru/wigle-csv
from datetime import datetime
import pytest
from wigle_csv.reader import read
from . import data_path
@pytest.mark.parametrize(
["number", "ignore_preheader"],
[[x, bool(y)] for x in range(1, 5) for y in range(2)],
)
def test_preheader(number: int, ignore_preheader: bool) -> None... | StarcoderdataPython |
3596505 | import asyncio
import aiohttp
import json
import ssl
import pyrebase
from firebasedata import LiveData
from .rcs_livesession import RCSLiveSession
DEFAULT_BASE_URL = "https://api.rcsnail.com/v1/"
FIREBASE_CONFIG = {
"apiKey": "<KEY>",
"authDomain": "rcsnail-api.firebaseapp.com",
"databaseURL": "https://r... | StarcoderdataPython |
1723295 | import datetime
from functools import wraps
from flask import Flask, request, jsonify, Response, make_response
from flask_pymongo import PyMongo
# hash password and check password
from werkzeug.security import generate_password_hash, check_password_hash
# jwt tokens
import jwt
# turn data mongo legible in json form... | StarcoderdataPython |
1833299 | <reponame>sjev/wimm
from pathlib import Path
import os
import yaml
import wimm.structure as structure
__version__ = "DEV.0.0.9"
DATE_FMT = "%Y-%m-%d"
def get_path():
""" get path of database directory """
val = os.getenv('WIMM_PATH')
if not val:
return None
return Path(val)
def get_sett... | StarcoderdataPython |
6667176 | load("@rules_foreign_cc//foreign_cc:defs.bzl", "cmake")
package(default_visibility = ["//visibility:public"])
licenses(["notice"]) # MIT
exports_files(["LICENSE"])
filegroup(
name = "all_srcs",
srcs = glob(["**"]),
)
cmake(
name = "faiss_c",
generate_args = [
"-G Ninja",
"-DFAISS_E... | StarcoderdataPython |
8148816 | import snoop
@snoop.snoop()
def f(_one, _two, _three, _four):
_five = None
_six = None
_seven = None
_five, _six, _seven = 5, 6, 7
def main():
f(1, 2, 3, 4)
| StarcoderdataPython |
241930 | default_app_config = 'tutors.apps.TutorsConfig'
| StarcoderdataPython |
3448410 | <reponame>bricerisingalgorand/mule
import platform
def get_os_type():
return platform.system().lower()
def get_cpu_arch_type():
arch = platform.machine()
if arch == "x86_64":
return "amd64"
elif arch == "armv6l":
return "arm"
elif arch == "armv7l":
return "arm"
elif arc... | StarcoderdataPython |
8083177 | <gh_stars>1-10
# Python Logical Operators: And, Or, Not:
# What is a Boolean?
isRaining = False
isSunny = True
# Logical Operators -> Special Operators for Booleans
# AND
# true and true --> true
# false and true --> false
# true and false --> false
# false and false --> false
if isRaining and isSunny:
print("Ra... | StarcoderdataPython |
6450887 | <filename>autonetkit/collection/process.py
import autonetkit.log as log
def build_reverse_mappings_from_nidb(nidb):
"""Builds IP reverse mappings from NIDB"""
rev_map = {
"subnets": {},
"loopbacks": {},
"infra_interfaces": {},
}
for node in nidb:
if node.bro... | StarcoderdataPython |
6651199 | <reponame>TAKHEXI/ALUMNI
# Generated by Django 3.2.5 on 2021-07-19 15:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Activity',
... | StarcoderdataPython |
3284776 | ###############################################
# <NAME> - PG Applied AI - Programming
# Unit tests, for the minimum edit distance
###############################################
import unittest # unit testing ftw
from excercise import Excercise # importing the actual code
class TestMethods(un... | StarcoderdataPython |
1606726 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright 2020, <NAME>, UIUC.
Find the next permutation of an array.
'''
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
... | StarcoderdataPython |
97236 | import os
import h5py
import pickle
import numpy as np
from termcolor import colored
from torch.utils.data import Dataset, DataLoader
class CIFAR10Loader(Dataset):
'''Data loader for cifar10 dataset'''
def __init__(self, data_path='data/cifar-10-batches-py', mode='train', transform=None):
self.data_... | StarcoderdataPython |
5024094 | <reponame>javiermas/BCNAirQualityDatathon<filename>airquality/models/validate_lstm.py<gh_stars>0
from airquality.data.read_data import read_obs, read_targets
from airquality.models.LSTM_keras import LSTM_K
from airquality.data.prepare_data import create_model_matrix
from airquality.models.split import tt_split, reshape... | StarcoderdataPython |
378313 | <reponame>xiaorancs/notebooks
# _*_coding:utf-8_*_
# Author: xiaoran
# Time: 2018-12-13
import numpy as np
def zero_one_loss(y_true, y_pred):
'''
param:
y_true: narray or list
y_pred: narray or list
return: double
'''
y_true = np.array(y_true)
y_pred = np.array(y_pred) ... | StarcoderdataPython |
12856922 | from django.core.management.base import NoArgsCommand, CommandError;
from ldap_login.ldapUtils import ldapManager;
from ldap_login.models import user,group,Role;
from datetime import datetime;
import traceback;
class Command(NoArgsCommand):
"""Import LDAP users from Active Directory.
Uses the ldapUtils back... | StarcoderdataPython |
58107 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 12:47:00 2017
@author: sakurai
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AffinityPropagation
from sklearn.metrics import f1_score
from sklearn.metrics import normalized_mutual_info_score
from sklearn.preprocessing import LabelE... | StarcoderdataPython |
1619462 | <filename>thesis-deadline-version/rings/1round/graphs/all/create-graph.py
from os import system, remove
with open("graf.gnuplot", "w") as graf:
graf.write ( "set terminal pngcairo size 350,262 enhanced font \'Verdana,10\'\n" +
"set output \"rings.png\"\n" +
# "f(x) = (10**(a*x + b))\n" +
# "f... | StarcoderdataPython |
121426 | print('Accessing private members in Class:')
print('-'*35)
class Human():
# Private var
__privateVar = "this is __private variable"
# Constructor method
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"... | StarcoderdataPython |
9609398 | <reponame>learningmatter-mit/gulpy
import numpy as np
import networkx as nx
from networkx.algorithms.traversal.depth_first_search import dfs_edges
from typing import List
from pymatgen.core import Molecule, Structure
from pymatgen.analysis.graphs import StructureGraph
from pymatgen.analysis.local_env import JmolNN
... | StarcoderdataPython |
67253 | # Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, visit
# https://nvlabs.github.io/stylegan2/license.html
"""Custom TensorFlow ops for efficient resampling of 2D images."""
import os
import numpy as... | StarcoderdataPython |
8055056 | <filename>sky_model/snrs/snrs_to_xml.py
"""
Convert SNRs to XML format.
"""
from pathlib import Path
import numpy as np
import astropy.units as u
from astropy.table import Table, Column
SOURCE_LIBRARY_TEMPLATE = """\
<?xml version="1.0" standalone="no"?>
<source_library title="CTA 1DC simulated supernova remnants">
... | StarcoderdataPython |
100173 | ## An Eve optimizer implementation in Chainer
# By <NAME>
# https://github.com/muupan/chainer-eve
# Modified by <NAME>
from __future__ import division
import math
import numpy
from chainer import optimizer
from chainer.optimizers import adam
_default_hyperparam = optimizer.Hyperparameter()
_default_hyperparam.alp... | StarcoderdataPython |
6633385 | import asyncio
from wampify.wamp_client import WAMPClient
async def main():
client = WAMPClient(
'http://1192.168.127.12:8080/call',
'http://127.0.0.1:8080/publish',
'client',
'secret'
)
print(await client.call('com.example.pow', 10))
print(await client.publish('com.ex... | StarcoderdataPython |
11240113 | """
PipelineNode instances are used to track and manage subprocesses run by shtk
Shells.
"""
import abc
import asyncio
import signal
import sys
from .util import export
__all__ = []
@export
class PipelineNode(abc.ABC):
"""
Abstract base class for subprocess management nodes
Attributes:
children... | StarcoderdataPython |
1665942 | <reponame>stanislavkozlovski/python_wow<filename>models/characters/saved_character.py<gh_stars>10-100
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from models.items.item_template import ItemTemplateSchema
from entities import Character
from constants import (... | StarcoderdataPython |
89997 | <filename>util/postprocessing.py
import sys
import os
import pickle
sys.path.append("..")
import util.structural as structural
import util.verilog as verilog
import dgl
if __name__ == "__main__":
folder = "../GCN/predicts/io/plus2/nl55"
total = 0
total_matched = 0
tried = 0
# find input from outp... | StarcoderdataPython |
9600691 | __all__ = ("NewDatabase", "clear_cache")
__version__ = (1, 1, 7)
from pathlib import Path
DATA_DIR = Path(__file__).resolve().parent / "data"
INVENTORY_DIR = Path(__file__).resolve().parent / "data" / "additional_inventories"
from .ecoinvent_modification import NewDatabase, clear_cache
| StarcoderdataPython |
9733897 | <filename>pixel_perturbation.py
from torchvision import datasets, transforms, utils, models
from misc_functions import *
from gradcam import grad_cam
from functools import reduce
from saliency.inputgradient import Inputgrad
import gc
import argparse
import matplotlib.pyplot as plt
import numpy as np
import torch.nn.fun... | StarcoderdataPython |
5004011 | import numpy as np
import math
import random
class MountainCar_SARSA:
def __init__(self, settings):
self.num_actions = 3
self.gamma = settings['gamma']
self.num_tilings = settings['num_tilings']
self.num_x_tiles = settings['num_x_tiles']
self.num_v_tiles = settings['num_v_t... | StarcoderdataPython |
12840349 | <gh_stars>0
# coding: utf-8
#Import the necessary Python modules
import pandas as pd
import folium
from folium.plugins import TimestampedGeoJson
from shapely.geometry import Point
import os
from datetime import datetime
from branca.element import Template, MacroElement
import html
from scripts.location_map_constants im... | StarcoderdataPython |
5010035 | import calendar
from gettext import ngettext
from pathlib import Path
import arrow
from flask import (
abort,
current_app,
g,
redirect,
render_template,
request,
Response,
url_for,
)
from flask_login import current_user, login_required
from lemonade_soapbox import db
from lemonade_soap... | StarcoderdataPython |
8046060 | <reponame>spire-allyjweir/beeline-python
import beeline
from beeline.propagation import Request
from beeline.middleware.wsgi import WSGIRequest
class HoneyWSGIMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
wr = WSGIRequest("werkzeug",... | StarcoderdataPython |
1896380 | <reponame>AndreasGeiger/hackerrank-python
first, second = [int(x) for x in input().split()]
arrayN = []
for _i_ in range(first):
arrayN.append([int(x) for x in input().split()][1:])
from itertools import product
possible_combination = list(product(*arrayN))
def func(nums):
return sum(x*x for x in nums) % seco... | StarcoderdataPython |
3287288 | # This file is automatically generated. Do not edit.
glyph2tile = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 28, 29, 30, 31, 32, 34, 35, 36, 37,
38, 39, 40, 41, 42, ... | StarcoderdataPython |
5052478 | '''
To do: Merge into data_script
'''
import getopt
import sys
import tourroute
def main(argv):
help_str = 'tr_exec.py -api <apikey>'
try:
opts, args = getopt.getopt(argv, 'api:', 'apikey=')
except getopt.GetoptError:
print(help_str)
sys.exit(2)
for opt, arg in opts:
... | StarcoderdataPython |
4821119 | <reponame>morozoffnor/govnoed_grisha_rewritten<gh_stars>0
import discord
from discord.ext import commands
import random
import sys
import json
sys.path.insert(1, '../functions')
from functions.cmd_print import cmd_print
class Korona(commands.Cog):
def __init__(self, client):
self.client = client
@co... | StarcoderdataPython |
3231856 | #!/usr/bin/python
import os
import sys
import time
def i2s(bridge):
print ("i2s.py execution on-going")
addrWavOutHead = os.popen("riscv32-unknown-elf-nm test |grep -w 'I2sOutHeader$'").read()
addrWavOutHead = (addrWavOutHead.split())[0]
time.sleep(3)
input("Press return to start sound acquisition... | StarcoderdataPython |
6605625 | #Problem Link: https://www.hackerrank.com/challenges/defaultdict-tutorial/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
n,m = map(int,raw_input().split())
A = defaultdict(list)
index =1
for i in range(n):
word = raw_input()
A[word].append(inde... | StarcoderdataPython |
229431 | import sys, getopt
from LexicalReplacement import LexicalReplacement
from ModelTesting import Test
config = {"mappings":"../mappings/w2v_50.json",
"embeddings":"../models/w2v_50"}
def text_to_tests(texts):
for line in texts:
yield Test.from_tsv(line)
def generate(model, texts):
tests = ... | StarcoderdataPython |
1643184 | default_app_config = "apps.api.notice.apps.NoticeConfig"
| StarcoderdataPython |
6672218 | from __future__ import print_function
import numpy as np
import sys
from tqdm import tqdm
import os
import pickle
import cv2
import itertools
from six.moves import xrange
from feature_match import computeNN
from utils import saveh5, loadh5
from geom import load_geom, parse_geom, get_episym
from transformations import q... | StarcoderdataPython |
1662124 | from .shared import compute_stats
__all__ = ["compute_stats"]
| StarcoderdataPython |
8115518 | <gh_stars>10-100
from . node import Node
class NodeVisitor(object):
"""
A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found. This function may return a value
which is forwarded by the `visit` method.
This class is meant to be subclassed,... | StarcoderdataPython |
9740728 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from api.management.commands.importbasics import *
def import_en_events(opt):
local = opt['local']
print '### Import EN events T1/T2 cutoffs from decaf wiki'
if local:
f = open('eventsEN.html', 'r')
else:
f = urllib2.urlopen('http://decaf.kouhi.m... | StarcoderdataPython |
246143 | #打印1到100之间的整数,跳过可以被7整除的,以及数字中包含7的整数
for i in range(1,101):
if i % 7 == 0 or i % 10 == 7 or i // 10 == 7:
continue
else:
print(i)
| StarcoderdataPython |
1632994 | <reponame>anotherbyte-net/gather-vision<gh_stars>0
from urllib.parse import urlparse, parse_qs
from environ import FileAwareEnv, ImproperlyConfigured
from gather_vision.process.item.playlist_conf import PlaylistConf
class GatherVisionEnv(FileAwareEnv):
DEFAULT_EXTERNAL_HTTP_CACHE_ENV = "EXTERNAL_HTTP_CACHE_URL... | StarcoderdataPython |
6608180 | import numpy as np
import random
from skimage import transform, exposure
from preprocessing.utils import make_folder
def random_rotation(img):
""" Randomly rotate the image.
Pick a random degree of rotation between.
25% on the left and 25% on the right.
Args:
img (numpy array): Array of imag... | StarcoderdataPython |
1797565 | <gh_stars>1-10
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from nlp.keyPhraseApi import KeyPhrases
# from nlp.syntaxApi import WordSyntax
from src.tl_gan.script_generation_interactive import gen_image
from nlp.text_to_feature import get_closest_feature
import io
import base64
im... | StarcoderdataPython |
5036240 | # -*- coding: utf-8 -*-
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import check_that, is_
from common.base_test import BaseTest
SUITE = {
"description": "Method 'get_block_virtual_ops'"
}
@lcc.prop("main", "type")
@lcc.prop("positive", "type")
@lcc.tags("api", "database_api", "database_api_... | StarcoderdataPython |
1857693 | <filename>utils/mysql_stat.py<gh_stars>1-10
# coding: utf-8
from __future__ import print_function
from starter_app.utils import setup_django
setup_django('starter_app')
from django.db import connection
from django.conf import settings
import pprint
def execute_print(cursor, sql):
cursor.execute(sql)
print(s... | StarcoderdataPython |
5035162 | # -*- coding: utf-8 -*-
import pytest
import random
import time
import sys
sys.path.extend(["../"])
from bbc1.core import bbclib
from testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility
from bbc1.core import domain0_manager, user_message_routing
from bbc1.core.message_key_t... | StarcoderdataPython |
6601295 | """Create plots for option learning."""
import os
from functools import partial
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from predicators.scripts.analyze_results_directory import create_dataframes, \
get_df_for_entry
pd.options.mode.chained_assignment = None # default='warn'
# plt.... | StarcoderdataPython |
9618603 | <filename>build/lib/dupecheck/utils.py
def v_print(verbose=False, msg=""):
print(msg)
| StarcoderdataPython |
66016 | <reponame>patrickfung/microsoft-authentication-library-for-python
"""This OAuth2 client implementation aims to be spec-compliant, and generic."""
# OAuth2 spec https://tools.ietf.org/html/rfc6749
import json
try:
from urllib.parse import urlencode, parse_qs, quote_plus
except ImportError:
from urlparse import ... | StarcoderdataPython |
8082285 | <filename>hikari_clusters/info_classes.py
# MIT License
#
# Copyright (c) 2021 TrigonDev
#
# 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 th... | StarcoderdataPython |
355449 | <gh_stars>0
#!/usr/local/bin/python
import math
import os
from pathlib import Path
from configs import Configurator
CONFIG_FILE = 'duet_pressure_advance.cfg'
class GCodeGen:
def __init__(self, config):
self.cfg = config
def extrusion_volume_to_length(self, volume):
return volume / (self.cfg... | StarcoderdataPython |
3285032 | """TLA+ parser and syntax tree."""
from tla.parser import parse
from tla.parser import parse_expr
try:
from tla._version import version as __version__
except:
__version__ = None
| StarcoderdataPython |
3247292 | import os
import tensorflow as tf
from keras.models import load_model
import numpy as np
from datetime import datetime
from flask import Blueprint, request, render_template, jsonify
from modules.dataBase import collection as db
import cv2
mod = Blueprint('backend', __name__, template_folder='templates', static_folder=... | StarcoderdataPython |
3287918 | # cob: type=views mountpoint=/index
from cob import route
from . import mymodels
from flask import jsonify
@route('/purge', methods=['POST'])
def purge():
mymodels.Person.query.delete()
mymodels.db.session.commit()
return 'ok'
@route('/list_models')
def get_all_models():
return jsonify([{'id': p.id}... | StarcoderdataPython |
9670863 | <filename>navigator/resources.py
#!/usr/bin/env python
import asyncio
import json
from functools import wraps
from pathlib import Path
import aiohttp
from aiohttp import WSCloseCode, WSMsgType, web
from aiohttp.http_exceptions import HttpBadRequest
from aiohttp.web import Request, Response
from aiohttp.web_exceptions ... | StarcoderdataPython |
348410 | <gh_stars>0
import pytest
import numpy as np
from io2048.io_offline import IOOffline
def test_reset():
io = IOOffline()
state = io.reset()
assert(len(np.where(state != 0)[0]) == 2)
assert(np.sum(state) >=4 and np.sum(state) <= 8)
def test_step():
io = IOOffline()
state = io.reset()
next_st... | StarcoderdataPython |
6702360 | def transform_list(iterable, func):
return [func(i) for i in iterable]
LEN_SUFFIXES = {
1: 'meth',
2: 'eth',
3: 'prop',
4: 'but',
5: 'pent',
6: 'hex',
7: 'hept',
8: 'oct',
}
COUNT_SUFFIXES = {
2: 'di',
3: 'tri',
4: 'tetra',
}
helptxt = \
"""
... | StarcoderdataPython |
3230651 | import json
import falcon
from models import Ticket
from config import session
from repo import Repo
class CreateTicket:
@staticmethod
def on_post(req, resp):
request_payload = json.loads(req.stream.read().decode('utf-8'))
ticket_type = request_payload.get('ticket_type')
message = r... | StarcoderdataPython |
1826792 | import os
import sys
import shutil
import subprocess
import xarray as xr
import numpy as np
# Current, parent and file paths
CWD = os.getcwd()
CF = os.path.realpath(__file__)
CFD = os.path.dirname(CF)
# Import library specific modules
sys.path.append(os.path.join(CFD,"../"))
sys.path.append(os.path.join(CFD,"../pys... | StarcoderdataPython |
6562817 | <filename>mrn_rdpgw_service_discovery.py
#!/usr/bin/env python
# |-----------------------------------------------------------------------------
# | This source code is provided under the Apache 2.0 license --
# | and is provided AS IS with no warranty or guarantee of fit for purpose. --
# | ... | StarcoderdataPython |
11250143 | import urwid
from console.modes import default_global_mode, modemap
class HelpDialog(urwid.Pile):
def __init__(self):
items = []
items += self.get_mode_help("Global Keys", default_global_mode)
items.append(urwid.BoxAdapter(urwid.SolidFill(' '), 1))
mode_title = "{} Keys".format(m... | StarcoderdataPython |
4921566 | <filename>dmt_lib_test.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 14:29:44 2019
@author: dongxucz
"""
from random import randint
import numpy as np
import csv as csvlib
from locale import atoi, atof
from core.dmt_lib import DmtMod, DmtDeMod
from bitstring import BitArray
import matplotlib.pyplo... | StarcoderdataPython |
1921929 | import os
import pickle
from copy import deepcopy
from .Train import Optimizer
from .Workers import FillGradientsWorker
class Graph:
def __init__(self, adj = {}, logging = True, optimizable_variables = [], tags = {}, optimization_configs = {}, from_pickle=False, pickle_name = "model", pickle_path = "./models/"):
... | StarcoderdataPython |
9756950 | import datetime
from typing import Optional, Tuple
import pandas as pd
from python import DOCUMENT_ID, PUBLISH_DATE, SUBTOPIC, MENTION_ID, SENTENCE_IDX, TOKEN_IDX_FROM, TOKEN_IDX_TO, EVENT, \
SENTENCE_TYPE, TOKEN_IDX, TOKEN, EVENT_ID, TOPIC_ID
from python.util.ftfy import clean_string
def load_gvc_dataset(path:... | StarcoderdataPython |
5040033 | <filename>Lab1/Main.py
import math
import numpy as np
import time
from corpus import get_dict
from metrics import Metrics
def dist_hemming(seq1, seq2):
if seq1 == seq2:
return 0
ml = max(len(seq1), len(seq2))
ml_check = seq1.ljust(ml)
ml_word = seq2.ljust(ml)
dist = 0
f... | StarcoderdataPython |
3315663 | from __future__ import unicode_literals
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile
from ..utils import get_image_metadata_from_file_ext
EXIF_ORIENTATION_KEY = 274
class ProcessedImage(object):
"""
A base class for processing/saving different renditions of an imag... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.