id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
256705
<gh_stars>1-10 # -*- coding: utf-8 -*- from api_x.zyt.vas import user def get_user_cash_balance(account_user_id): # FIXME: # 在application成为真正独立子系统时,这里应该使用api交互 return user.get_user_cash_balance(account_user_id)
StarcoderdataPython
158148
<reponame>rockman/learn-python-flask from simple_forum.db import db tags_to_posts = db.Table('tags_to_posts', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')), db.Column('post_id', db.Integer, db.ForeignKey('post.id')) ) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) name...
StarcoderdataPython
3552294
import io import os from unittest import mock import numpy as np import pytest import tempfile from mlagents_envs.communicator_objects.demonstration_meta_pb2 import ( DemonstrationMetaProto, ) from mlagents.trainers.tests.mock_brain import ( create_mock_3dball_behavior_specs, setup_test_behavior_specs, ) f...
StarcoderdataPython
11246207
import unittest from ..context import zoia import zoia.parse.normalization class TestNormalization(unittest.TestCase): def test_strip_diacritics(self): self.assertEqual( zoia.parse.normalization.strip_diacritics('foo'), 'foo' ) self.assertEqual( zoia.parse.normaliz...
StarcoderdataPython
4873319
n = int(input()) matriz = input().split() mult = [2,3,4,5] n2, n3, n4, n5 = 0, 0, 0 ,0 for x in range(n): for y in range(4): n1 = int(matriz[x]) if n1 % mult[y] == 0: pos = y if pos == 0: n2 += 1 elif pos == 1: n3 += 1 ...
StarcoderdataPython
8177758
<filename>cli/medperf/commands/dataset/__init__.py from .associate import DatasetBenchmarkAssociation from .submit import DatasetRegistration from .list import DatasetsList from .create import DataPreparation all = [DatasetBenchmarkAssociation, DatasetRegistration, DatasetsList, DataPreparation]
StarcoderdataPython
1997407
<filename>sme_material_apps/proponentes/migrations/0010_auto_20200730_1420.py # Generated by Django 2.2.9 on 2020-07-30 17:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proponentes', '0009_auto_20200729_1628'), ] operations = [ mig...
StarcoderdataPython
5116980
# -*- coding: utf-8 -*- """ // Copyright 2020 PDF Association, Inc. https://www.pdfa.org // // This material is based upon work supported by the Defense Advanced // Research Projects Agency (DARPA) under Contract No. HR001119C0079. // Any opinions, findings and conclusions or recommendations expressed // in this materi...
StarcoderdataPython
163657
<gh_stars>1-10 from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ @plugin_pool.register_plugin class Disqus(CMSPluginBase): model = CMSPlugin render_template = "core/disqu...
StarcoderdataPython
6657213
<gh_stars>1-10 import numpy as np import sys import cv2 import tensorflow as tf # settings input_model = "./models/output.pb" input_name = "model_input" output_node_name = "mobilenetv2_1.00_224/Logits/Softmax" output_model = "./models/output_quant.tflite" # load validation set import glob image_folder = "../calibr...
StarcoderdataPython
5080459
<gh_stars>0 IDENTITY = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) def inverse(a): return [value[1] for value in sorted([(n - 1, i + 1) for i, n in enumerate(a)])] def composition(a, b): return [a[v - 1] for v in b]
StarcoderdataPython
3350496
#program to calculate midpoints of a line. x1 = float(input('The value of x1: ')) y1 = float(input('The value of y1: ')) x2 = float(input('The value of x1: ')) y2 = float(input('The value of y2: ')) x_m_point = (x1 + x2)/2 y_m_point = (y1 + y2)/2 print(); print( "The midpoint's x value is: ",x_m_point) print( "The mi...
StarcoderdataPython
5011671
<reponame>Tabor-Research-Group/ChemOS __all__ = ['bot']
StarcoderdataPython
12824557
<gh_stars>0 # Standard lib imports import logging # Third party imports # None # Project level imports # None log = logging.getLogger(__name__) class Dashboard(object): def __init__(self, connection): """ Initialize a new instance """ self.conn = connection def get_local_...
StarcoderdataPython
5095427
<filename>app/models.py from sqlalchemy.ext.hybrid import hybrid_property from flask.ext.login import UserMixin from app import db, bcrypt class Requesters(db.Model, UserMixin): ''' A requester who needs help ''' __tablename__ = 'requesters' username = db.Column(db.String, primary_key=True) lat = ...
StarcoderdataPython
5085272
import typing from collections import OrderedDict from flytekit import ContainerTask from flytekit.common.translator import get_serializable from flytekit.core import context_manager from flytekit.core.base_task import kwtypes from flytekit.core.context_manager import Image, ImageConfig from flytekit.core.launch_plan ...
StarcoderdataPython
8158276
from app.instances import db class Theme(db.Model): """ A theme for the web view """ __tablename__ = "themes" __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(20), unique=True, nullable=False)
StarcoderdataPython
4815489
from itertools import product import copy initialRows = [] with open("./11/input.txt") as inputFile: for line in inputFile: row = list(line.replace("\n","")) initialRows.append(row) def getSeat(x,y, rows): if x < 0 or y < 0 or x >= len(rows[0]) or y >= len(rows): return 0 return 0 if rows[y][x] in ["L", "."]...
StarcoderdataPython
4811546
# -*- coding: utf-8 -*- from datetime import date, time import pytest from ..fixtures import parametrize from korona.html.tags import Input from korona.templates.html.tags import input as tag from korona.exceptions import TagAttributeError, AttributeValueError @parametrize('attributes', [ # accept attribute ...
StarcoderdataPython
4983684
<filename>deltabot/plugins/hitokoto/__init__.py<gh_stars>10-100 from nonebot import on_command, CommandSession from .data_source import get_hitokoto __plugin_name__ = 'hitokoto(一言)' __plugin_usage__ = r""" 获取「一言」(附庸风雅利器) 数据来源 hitokoto.cn Command(s): - /hitokoto """.strip() @on_command('hitokoto', aliases=('每日一句', '...
StarcoderdataPython
1797032
<gh_stars>0 import math import pickle import numpy as np from helper.utils import logger from tasks import register_task from tasks.base_task import BaseTask from dataclass.configs import BaseDataClass from dataclass.choices import BODY_CHOICES from dataclasses import dataclass,field from typing import Optiona...
StarcoderdataPython
12824445
<reponame>aideyisu/english_study import json import xlwt # 单词乱序 import random from datetime import datetime from get_words import get_lines from side import site_write_line_style import get_words # 获取当前日期 # dd/mm/YY H:M:S def get_datetime(): return datetime.now().strftime("%Y-%m-%d") # 保存当日全部单词 def save_toda...
StarcoderdataPython
5129500
""" Deploy Docker containers with Fabric. """ from setuptools import find_packages, setup with open('requirements.txt') as f: dependencies = f.read().splitlines() setup( name='fabdocker', version='0.3.6', url='https://github.com/newmotion/fabdocker', license='MIT', author='<NAME>', author_...
StarcoderdataPython
1854761
<reponame>emschimmel/BrainPi file_path = '../img/' max_token_time_seconds = 60 # less is more secure eigen_trainer_file = './Data/eigen_trainer.yml' fisher_trainer_file = './Data/fisher_trainer.yml' lbph_trainer_file = './Data/lbph_trainer.yml' eigen_data_path = './Dat...
StarcoderdataPython
11232515
<filename>branched_lineages.py import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import time app = dash.Dash(__name__) server = app.server app.layout = html.Div([ dcc.Input(id='grandparent', value='input 1'), dcc.Input(id='parent-a'),...
StarcoderdataPython
106657
import torch import torch.nn as nn from pysot.utils.latency import predict_latency,compute_latency table = [] class ReLUConvBN(nn.Module): """ Stack of relu-conv-bn """ def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True): """ :param C_in: :param C_out: :param kernel_si...
StarcoderdataPython
134838
<filename>ngym_shaping/utils/tasktools.py<gh_stars>100-1000 from __future__ import division from collections import OrderedDict import numpy as np def to_map(*args): "produces ordered dict from given inputs" if isinstance(args[0], list): var_list = args[0] else: var_list = args od = O...
StarcoderdataPython
6651927
""" Base class for GeoJSON services. Fetches GeoJSON feed from URL to be defined by sub-class. """ import geojson import logging import requests from geojson import Point, GeometryCollection, Polygon from haversine import haversine from json import JSONDecodeError from typing import Optional _LOGGER = logging.getLog...
StarcoderdataPython
9746371
<filename>src/jcsclient/dss_connection.py # Copyright (c) 2016 Jiocloud.com, Inc. or its affiliates. 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...
StarcoderdataPython
9787039
<gh_stars>0 # Матрица 5x4 заполняется вводом с клавиатуры, кроме последних элементов строк. # Программа должна вычислять сумму введенных элементов каждой строки и # записывать ее в последнюю ячейку строки. В конце следует вывести полученную # матрицу. M = 5 N = 4 matrix = [] for i in range(N): row = [] summ =...
StarcoderdataPython
8184219
from dataclasses import dataclass from pathlib import Path @dataclass class VinaPublicOptions: receptor: Path center_x: float center_y: float center_z: float size_x: float size_y: float size_z: float flex: str = None cpu: int = None seed: int = None exhaustiveness: int = No...
StarcoderdataPython
1862862
from functools import wraps from telegrambot.models import Chat, Bot from django.core.urlresolvers import reverse def login_required(view_func): """ Decorator for command views that checks that the chat is authenticated, sends message with link for authenticated if necessary. """ @wraps(view_func...
StarcoderdataPython
323446
<gh_stars>0 import unittest import pandas as pd from unittest.mock import patch from managealooma.inputs import Inputs class TestInputs(unittest.TestCase): """ Tests the functions that retrieve and manipulate inputs from the API """ @patch('managealooma.inputs.Inputs') def setUp(self, inputs_class):...
StarcoderdataPython
5142940
<gh_stars>10-100 from mhkit.wave import resource from mhkit.wave import io from mhkit.wave import graphics from mhkit.wave import performance
StarcoderdataPython
1968075
<reponame>pak21/mtga-scripts #!/usr/bin/env python3 import contextlib import os import sys import mysql.connector as mysql DECKS_SQL = ''' select deck_id from decks ''' DIFF_SQL = ''' select a.name, a.main as a, coalesce(b.main, 0) as b from deck_cards as a left join deck_cards as b on a.name = b.name and b.d...
StarcoderdataPython
6546564
#!/usr/bin/python3 # You are to retrieve the following document using the HTTP protocol # in a way that you can examine the HTTP Response headers. # http://data.pr4e.org/intro-short.txt import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) cmd = 'GET http://d...
StarcoderdataPython
188306
<reponame>mkhalil7625/capstone-week3 def camelcase(sentence): """ Convert sentence to camelCase, for example, "Display all books" is converted to "displayAllBooks" """ title_case = sentence.title() # Uppercase first letter of each word upper_camel_cased = title_case.replace(' ', '') # remove spaces # Lowe...
StarcoderdataPython
11239763
class QaEntry: def __init__(self, corresponds = None, question = None, answer = None): self.corresponds = corresponds self.question = question self.answer = answer self.questionVector = None self.answerVector = None def __str__(self): return "%s %s -- %s" % (sel...
StarcoderdataPython
4991565
from azureml.core import Workspace from fairlearn.metrics import selection_rate, MetricFrame from fairlearn.reductions import GridSearch, EqualizedOdds import joblib import numpy as np import os from sklearn.metrics import accuracy_score, recall_score, precision_score from sklearn.model_selection import train_test_spli...
StarcoderdataPython
16945
<gh_stars>0 """Primary application. """ import json import logging import logging.config import os import sys from flask import url_for, render_template, redirect, request from i_xero import Xero2 from i_xero.i_flask import FlaskInterface from utils import jsonify, serialize_model # initialize logging # The SlackBot...
StarcoderdataPython
1763437
<filename>back/found/models.py from django.db import models from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFill from datetime import datetime from django_extensions.db.models import TimeStampedModel from django.contrib.auth import get_user_model User = get_user_model() def fo...
StarcoderdataPython
6423788
<filename>hash_code.py # Importing the hashing library import hashlib # Importing the visual libraries from PyInquirer import Separator, prompt from termcolor import colored # Defining the hash function. def hash_func(): # Asking the user for further data regarding algoritms hash_info = prompt([ { ...
StarcoderdataPython
1724124
import torch.nn from torch import nn import torch class KLWithMask: def __call__(self, logits, soft_targets, label_target, ignore_index=-1): b, c, w, h = soft_targets.shape # soft_targets = torch.clamp(soft_targets, 0, 1) # soft_targets = torch.softmax(soft_targets, dim=1) # print(s...
StarcoderdataPython
8077163
import numpy as np from PIL import Image import matplotlib.pyplot as plt from skimage import measure import nibabel as nib import SimpleITK as sitk import glob def brain_bbox(data, gt): mask = (data != 0) brain_voxels = np.where(mask != 0) minZidx = int(np.min(brain_voxels[0])) maxZidx = int(np.max(br...
StarcoderdataPython
3470522
<reponame>JankoTreuner/track-my-time<filename>trackmytime/timetracker/migrations/0004_workday_workinghours.py # Generated by Django 3.2.4 on 2021-06-22 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('timetracker', '0003_auto_20210622_1444'), ]...
StarcoderdataPython
3366693
<reponame>sephrat/mealie<gh_stars>0 import json import pytest from fastapi.testclient import TestClient from slugify import slugify from tests.app_routes import AppRoutes from tests.utils.recipe_data import RecipeTestData, build_recipe_store recipe_test_data = build_recipe_store() @pytest.mark.parametrize("recipe_d...
StarcoderdataPython
4963022
<reponame>vvikal/folium # -*- coding: utf-8 -*- from branca.element import CssLink, Element, Figure, JavascriptLink, MacroElement from jinja2 import Template _default_js = [ ('leaflet_draw_js', 'https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js') ] _default_css = [ ('leaflet...
StarcoderdataPython
8015164
<filename>preprocess.py<gh_stars>1-10 """ @version: 2.0 @author: Jonah @file: __init__.py @time: 2021/11/10 12:56 """ import os import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm import math import multiprocessing import argparse import time from multiprocessing import cpu_count import sys from ...
StarcoderdataPython
1980753
# <NAME>, 100% # performance, O(d + n log*n) # since all information is avaliable before a plan has to be made, # there is no reason to make a plan at all. # keep track of sets of nodes that a soldier *could* have travelled between # everytime two nodes are fogged over together, merge them into one new node # ...
StarcoderdataPython
6415999
<reponame>techsparksguru/python_ci_automation import json from datetime import timedelta from flask_httpauth import HTTPBasicAuth from werkzeug.security import safe_str_cmp from flask_jwt import JWT, jwt_required, current_identity from flask import Flask, jsonify, make_response, request, abort, url_for class User(o...
StarcoderdataPython
3439720
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-06-18 19:02 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), (...
StarcoderdataPython
4927441
<filename>letsadd/haversine/models.py from django.db import models from django.urls import reverse from .managers import ParkQuerySet class Park(models.Model): name = models.CharField(max_length=254) slug = models.SlugField(unique=True) location = models.CharField(max_length=254) latitude = models.Fl...
StarcoderdataPython
11392060
<gh_stars>0 # code golf challenge # https://code.golf/happy-numbers#python # wren 20210608 # A happy number is defined by the following Sequence: # Starting with any positive integer, replace the number # by the sum of the squares of its digits in base-ten, # and repeat the process until the number either equals 1 # (...
StarcoderdataPython
301963
<gh_stars>1-10 # Generated by Django 3.1 on 2020-11-10 15:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("manager", "0006_auto_20201105_1007"), ] operations = [ migrations.RemoveField( model_name="credentialdefinition", ...
StarcoderdataPython
1811548
""" This is the Entry point for Twitoff.""" from .app import create_app APP = create_app()
StarcoderdataPython
11394321
<gh_stars>1-10 from fontbakery.codetesting import (assert_PASS, assert_results_contain, CheckTester, TEST_FILE) from fontbakery.checkrunner import FAIL from fontbakery.profiles import opentype as opentype_profile...
StarcoderdataPython
4991372
#!/usr/bin/env python from __future__ import print_function import skimage as skimage from skimage import transform, color, exposure, io from skimage.viewer import ImageViewer import random from random import choice import numpy as np from collections import deque import time import math import os import pandas as pd ...
StarcoderdataPython
5158614
from typing import List, Optional from fastapi.encoders import jsonable_encoder from .enums import ReportTypes from .models import Report, ReportCreate, ReportUpdate def get(*, db_session, report_id: int) -> Optional[Report]: """ Get a report by id. """ return db_session.query(Report).filter(Report....
StarcoderdataPython
6491408
<reponame>robot-1/demuxts<filename>DemuxTS/dvbobjects/descriptors.py class descriptor(): def __init__(self, stream): self.stream = stream self.tag = None self.length = None class AssociationTagDescriptor(descriptor): def __init__(self): super(AssociationTagDescriptor, self).__...
StarcoderdataPython
11237747
#!/usr/bin/python """ All hardcoded values across weatherSensor is handled here """ class Constant(object): """ Each constant holds its unique text, all text values stored here and these are used throughout weatherSensor. """ CONFIG_SECTION_APP = 'APP' USE_MOCK_SENSOR = 'use_mock_sensor' ...
StarcoderdataPython
8117612
<filename>benchmarks/SimResults/_bigLittle_hrrs_spec_tugberk_ml/SystemIPC/cmp_lbm/power.py power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.06...
StarcoderdataPython
309350
from Utility import resources as ex from module.keys import bot_support_server_id, patreon_role_id, patreon_super_role_id # noinspection PyBroadException,PyPep8 class Patreon: @staticmethod async def get_patreon_users(): """Get the permanent patron users""" return await ex.conn.fetch("SELECT u...
StarcoderdataPython
11323797
<reponame>aryarm/happler #!/usr/bin/env python import sys import time import numpy as np from pgenlib import PgenReader variant_ct_start = 3220890 variant_ct_end = 3253426 variant_ct = variant_ct_end - variant_ct_start pgen = PgenReader(bytes("/projects/ps-gymreklab/resources/datasets/ukbiobank/array_imputed/pfile_co...
StarcoderdataPython
9745479
<gh_stars>100-1000 import tensorflow.keras as keras from omlt.io import write_onnx_model_with_bounds import pytest # from conftest import get_neural_network_data from keras.layers import Dense, Conv2D from keras.models import Model, Sequential from pyomo.common.fileutils import this_file_dir from tensorflow.keras.optim...
StarcoderdataPython
238791
from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from cms_opencomparison import models import httplib def get_grid(request, grid_id): grid = None try: grid = models.Grid.objects.get(pk=grid_id) h = None if grid.is...
StarcoderdataPython
1764086
# vim:fileencoding=utf-8:noet """ python function """ # Copyright (c) 2010 - 2019, © Badassops LLC / <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code...
StarcoderdataPython
6513707
<filename>src/os_rotatefile/rotatefile.py<gh_stars>1-10 import os import sys from io import BytesIO _PY3 = sys.version_info[0] == 3 if _PY3: string_types = str integer_types = int else: string_types = basestring integer_types = (int, long) def _complain_ifclosed(closed): if closed: raise...
StarcoderdataPython
5133713
<filename>bot.py #!/usr/bin/env python3 # -*- coding:utf-8 -*- import fnmatch import logging import os import sys import time from collections import defaultdict from pathlib import Path from shutil import rmtree import telegram from geoip import geolite2 try: from telegram import Bot except Exc...
StarcoderdataPython
3295783
# -*- coding: utf-8 -*- from __future__ import unicode_literals import frappe import json from six import string_types from toolz.curried import merge, excepts, first, compose, filter, map @frappe.whitelist() def apply_price_list(args, as_doc=False): from erpnext.stock.get_item_details import apply_price_list ...
StarcoderdataPython
6617486
<reponame>ravihuang/rfdbbot<filename>atests/libraries/RobotSqliteDatabase.py import sqlite3 class RobotSqliteDatabase: def __init__(self): self._connection = None def connect_to_database(self, db_file_path): self._connection = sqlite3.connect(db_file_path) def close_connection(self): ...
StarcoderdataPython
1843514
#!/usr/bin/python3 from logic import AND, OR, NOT, ATOM def at_least_one(formulas): return OR(formulas) def all_pairs(lst): return [ (lst[i],lst[j]) for i in range(0,len(lst)) for j in range(i+1,len(lst)) ] def at_most_one(formulas): return AND([NOT(AND([f1, f2])) for (f1, f2) in all_pairs(formulas)]) de...
StarcoderdataPython
5098704
import logging import threading from abc import ABC from abc import abstractmethod from time import sleep from typing import Optional from typing import Union from kubernetes.client import V1beta1PodDisruptionBudget from kubernetes.client import V1DeleteOptions from kubernetes.client import V1Deployment from kubernete...
StarcoderdataPython
4906114
<reponame>ravngr/jtfadump2 #!/usr/bin/env python3 # -- coding: utf-8 -- import argparse import code import logging import logging.config import os import sys import time import serial import pyvisa import yaml import capture import experiment import exporter import post_export import post_process import util __auth...
StarcoderdataPython
3465015
<reponame>iTeam-co/pytglib from ..utils import Object class UpgradeBasicGroupChatToSupergroupChat(Object): """ Creates a new supergroup from an existing basic group and sends a corresponding messageChatUpgradeTo and messageChatUpgradeFrom; requires creator privileges. Deactivates the original basic group ...
StarcoderdataPython
9781808
from typing import Any, Callable, Dict, List, Union import numpy from ppq.core import (DataType, OperationMeta, QuantizationStates, TargetPlatform, TensorMeta, TensorQuantizationConfig, empty_ppq_cache, ppq_warning) from ppq.IR import BaseGraph, Operation, QuantableOperation...
StarcoderdataPython
6401006
import discord, os, dotenv from discord.ext import commands dotenv.load_dotenv() TOKEN = os.getenv('TOKEN') PREFIX = os.getenv('PREFIX') bot = commands.Bot( command_prefix=PREFIX, case_insensitive=True ) # Events @bot.event async def on_ready(): print(f"Logged in as {bot.user.name} in {len(bot.guilds)} ...
StarcoderdataPython
3291145
<reponame>bethunebtj/BigDL<gh_stars>1-10 from bigdl.nn.layer import * from optparse import OptionParser from bigdl.nn.criterion import * from bigdl.nn.initialization_method import * from bigdl.optim.optimizer import * from bigdl.transform.vision.image import * from math import ceil def t(input_t): if type(input_t...
StarcoderdataPython
9711608
<reponame>philip-schrodt/ICEWS-to-jsonl """ utilDEDI2021.py jsonl read/write for the DEDI programs and other utilities NOTE 19.10.22: Those customized writeedit()/writesrc() -- originally there is provide a more readable JSONL format for manual editing, which wasn't needed after a while -- were a bad ...
StarcoderdataPython
4893285
import os import pandas as pd from scipy.stats import spearmanr from larval_gonad.normalization import tpm from larval_gonad.constants import L3_BULK, L3_SC def main(): df = pd.concat( [read_l3_sc(), read_l3_bulk()], sort=True, axis=1, join="inner" ) # type: pd.DataFrame _, pval = spearmanr(df....
StarcoderdataPython
3382460
<filename>password.py import random symbols = 'abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWYZ012456789!@#$%^&*()_+}{|":<>?' while True: password_len = int(input('How many characters in the password do you want: ')) password_count = int(input('How many passwords do you want to generate: ')) for ...
StarcoderdataPython
3424738
""" Show help on a pysoilmap command or show a list of all available commands. """ import pysoilmap.cli as cli import click @click.command('help', context_settings={'ignore_unknown_options': True}) @click.argument('command', nargs=-1) def main(command): """Show pysoilmap command line help.""" cli.main(comma...
StarcoderdataPython
9690958
# -*- coding: utf-8 -*- """Format int of float.""" from fractions import Fraction class Format: # pylint: disable=R0903 """Output Formats for int or float.""" @staticmethod def get_fraction(val_float: float) -> str: # noqa: WPS602 """Format a fraction from a float.""" return str(Fracti...
StarcoderdataPython
8074926
<filename>src/testing/TestON/tests/FUNCintentRest/FUNCintentRest.py # Testing the basic intent functionality of ONOS # TODO: Replace the CLI calls with REST API equivalents as they become available. # - May need to write functions in the onosrestdriver.py file to do this # TODO: Complete implementation of ca...
StarcoderdataPython
225656
<gh_stars>0 # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Photutils is an Astropy affiliated package to provide tools for detecting and performing photometry of astronomical sources. It also has tools for background estimation, ePSF building, PSF matching, centroiding, and morphological measureme...
StarcoderdataPython
155594
<reponame>ThomasDoukas/NTUA_ATDS from pyspark.sql import SparkSession from io import StringIO import csv def split_complex(x): res = list(csv.reader(StringIO(x), delimiter=','))[0] return (res[0], tuple(res[1:])) spark = SparkSession.builder.appName("Q1RDD").getOrCreate() sc = spark.sparkContext # filter(dat...
StarcoderdataPython
6557755
"""Plot the COOP Precipitation Reports, don't use lame-o x100""" import datetime import psycopg2.extras from pyiem.reference import TRACE_VALUE from pyiem.plot import MapPlot from pyiem.util import get_dbconn def n(val): """pretty""" if val == TRACE_VALUE: return 'T' if val == 0: return ...
StarcoderdataPython
1879537
from math import dist, inf from random import shuffle from sklearn.datasets import load_iris as load from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score class KNN: def __init__(self, k=5): self.__k = k ...
StarcoderdataPython
3539471
<gh_stars>10-100 #!/usr/bin/env python3 # Copyright 2019 <NAME>, <NAME> # 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...
StarcoderdataPython
4897303
<reponame>m-stoeckel/argos-train<filename>argostrain/data.py from argostrain.dataset import * def prepare_data(source_path: Path, target_path: Path, run_path: Path, valid_size=2000): # Build dataset dataset = FileDataset(source_path.open(), target_path.open()) print("Read data from file") # Split and...
StarcoderdataPython
188443
<gh_stars>1-10 from .launch_tools import * from .arg_parse import get_args
StarcoderdataPython
1646736
import inspect import logging from datetime import datetime from typing import Optional, Set, Callable from celery.utils import uuid from server.queue.celery.task_metadata import TaskMetadata from server.queue.celery.task_status import task_status from server.queue.framework import TaskQueue, BaseObserver from server...
StarcoderdataPython
4800458
<filename>tracalchemy/ticket.py<gh_stars>0 # -*- coding: utf-8 -*- # # Copyright (c) 2012-2013 <NAME> <<EMAIL>> # # The MIT License # 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 re...
StarcoderdataPython
3297875
<gh_stars>0 """Make test fixtures for testing tree_intersection.""" import pytest from .bst import BST @pytest.fixture def first_bst(): """Make the first bst.""" b = BST([20, 17, 21, 18, 22, 19]) return b @pytest.fixture def second_bst(): """Make the second bst.""" b = BST([13, 17, 21, 2, 22, 29...
StarcoderdataPython
1832014
# --------------------------------------------Assignment Day 7 | 8th September 2020------------------------------------------------------- '''Question 1: Write a program to copy the contents of one file to another using a for loop.Do not use built-in copy function''' # Answer 1 ------------------ with open("in...
StarcoderdataPython
3552309
<filename>new/src/30.01.2021/functions.py def equate(number1, number2): resalt = (number1+4*number2)*(number1-3*number2)+number1 return resalt print(equate(5, 3)) def find_speed(kilometers, hours): resalt2 = kilometers / hours return resalt2 print(find_speed(100, 3)) def smallest(number1, number2, numbe...
StarcoderdataPython
3343288
from . import classification, segmentation, object_detection from .metric_keys import DetailMetricKey
StarcoderdataPython
349491
#!/usr/bin/env python import time, struct,sys import bluetooth from mindwavemobile.MindwaveDataPoints import AttentionDataPoint, EEGPowersDataPoint from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader import numpy as np import pylab as pl def main(): mdpr = MindwaveDataPointReader() mdpr.st...
StarcoderdataPython
11362456
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r"D:\BMSIS_YSP\reac-space-exp\neo4j_loader_and_queries\output\2021-01-26_17-18-42-588599\all_generations_abundance_scores.csv") print(df.head()) df.plot.area(x='rank_node_deg_by_gen', y='count_relationships') plt.show()
StarcoderdataPython
5103545
#!/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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
11397167
<filename>Logicals/May2019/29/textwrap.py<gh_stars>0 import textwrap def wrap(string, max_width): return '\n'.join(textwrap.wrap(string, max_width)) def wrap_v2(string, max_width): list_data = textwrap.wrap(string, max_width) return '\n'.join(list_data) def main(): string, max_width = input(), int...
StarcoderdataPython