id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
156226
import random def pick_random_move(board): """Takes in an array_board and returns a random index in that board that contains None.""" possible_moves = get_available_moves(board) number_of_possible_moves = len(possible_moves) if number_of_possible_moves < 1: return -1 random_index_into...
StarcoderdataPython
1778779
<filename>elmo-chainer/bilm/elmo.py<gh_stars>100-1000 import json import logging # from typing import Union, List, Dict, Any import warnings import numpy import h5py import tqdm import chainer from chainer import cuda from chainer import functions as F from chainer import links as L from chainer import Variable from...
StarcoderdataPython
1617542
from segmentation.data.dataset import get_segmentation_dataset from segmentation.data.augmentation import Augmentor, sequences from segmentation.data.preprocessing.mask_functions import ( convert_to_tensors_float, reduce_to_semantic_mask_add_xy, append_semantic_mask_add_xy, ) from segmentation.data.preproce...
StarcoderdataPython
3327597
<reponame>Steve-YJ/sagemaker-studio-end-to-end from pyspark.sql.session import SparkSession from pyspark.sql.dataframe import DataFrame # You may want to configure the Spark Context with the right credentials provider. spark = SparkSession.builder.master('local').getOrCreate() mode = None def capture_stdout(func, *a...
StarcoderdataPython
15734
<reponame>yamanogluberk/ConnectedClipboard import select import socket import json import threading import time import clipboard import math from datetime import datetime ip = "" localpart = "" name = "" tcp = 5555 udp = 5556 buffer_size = 1024 broadcast_try_count = 3 ping_try_count = 3 members = [] # item - (str) ip...
StarcoderdataPython
3270827
import numpy as np from multi_affine.datagenerators import indicator, load_volfile, select_index_atlas def datagenerator_nonrigid(gen, diffeomorphic=False, atlas_shape=[64,64,64], batch_size=1, test=False): """ function to generate data for training. Args: gen: image generator to load image and a...
StarcoderdataPython
3369019
<reponame>jzmq/minos<gh_stars>100-1000 import json import logging import logging.config import os import sys import time import tsdb_register import urllib from tsdb_register import collect_period from tsdb_register import metrics_url from tsdb_register import opentsdb_bin_path from tsdb_register import opentsdb_extra...
StarcoderdataPython
3299978
from abc import ABC, abstractmethod from dataclasses import dataclass, field # Added list for typing for back compatibility to 3.8 and 3.7 from typing import Union, List from .component import AbstractComponent @dataclass class AbstractBuilder(ABC): builder_component: Union[None, AbstractComponent] = None #...
StarcoderdataPython
1791506
<reponame>fogleman/DCPU-16 import distutils import os import py2exe import shutil import sys def run_py2exe(): py2exe.__version__ sys.argv.append('py2exe') distutils.core.setup( options = {"py2exe":{ "compressed": True, "optimize": 1, "bundle_files": 1, ...
StarcoderdataPython
1641227
<gh_stars>100-1000 #!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
StarcoderdataPython
3247272
# -*- coding: utf-8 -*- """ .. module:: entry :platform: Unix :synopsis: Yify film entry model .. moduleauthor:: <NAME> <<EMAIL>> """ import re class Entry: """Represents a film entry""" def __init__(self, data): """ Args: data (dict): entry data """ self....
StarcoderdataPython
179987
#!/usr/bin/env python3 import sys def validate(expr) -> str: try: if expr == 'true': return 'Did you mean \'True\'?' if expr == 'false': return 'Did you mean \'False\'?' x = eval(expr) typ = type(x) if typ == str or typ == int or typ == bool: return if typ == list: if len(x) == 0: return ...
StarcoderdataPython
152222
"""Uses the same strategy as ``adjacency_list.py``, but associates each DOM row with its owning document row, so that a full document of DOM nodes can be loaded using O(1) queries - the construction of the "hierarchy" is performed after the load in a non-recursive fashion and is more efficient. """ # PART...
StarcoderdataPython
73047
<gh_stars>1-10 # -*- coding: utf-8 -*- """ flask_caching.backends.rediscache ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The redis caching backend. :copyright: (c) 2018 by <NAME>. :copyright: (c) 2010 by <NAME>. :license: BSD, see LICENSE for more details. """ from flask_caching.backends.base import Bas...
StarcoderdataPython
99238
""" This file does three things: - It implements a simple PyTorch model. - Exports in to ONNX using a combination of tracing and scripting - Converts it to MDF """ import torch import onnx from onnx import helper from modeci_mdf.interfaces.onnx import onnx_to_mdf class SimpleIntegrator(torch.nn.Module):...
StarcoderdataPython
108755
<gh_stars>1-10 from fv3gfs.util import Timer, NullTimer import pytest import time @pytest.fixture def timer(): return Timer() @pytest.fixture def null_timer(): return NullTimer() def test_start_stop(timer): timer.start("label") timer.stop("label") times = timer.times assert "label" in time...
StarcoderdataPython
1777769
<gh_stars>0 import scrapy import regex from bs4 import BeautifulSoup import urllib import pandas class QuotesSpider(scrapy.Spider): name = "CO_Spider" Search_Url = r"http://www.coloradoshines.com/search?location={0}" Main_Url = r"http://www.coloradoshines.com/search" Detail_Url = r"http://www.colorado...
StarcoderdataPython
3242366
<gh_stars>1-10 from grit.common.model.core.rich_version import RichVersion class LineageGraphVersion(RichVersion): def __init__(self, json_payload): super().__init__(json_payload) self._lineage_graph_id = json_payload.get('lineageGraphId', 0) self._lineage_edge_version_ids = json_payload....
StarcoderdataPython
3337589
import base64 import os import smtplib from email.header import Header from email.mime.text import MIMEText import requests from lxml import etree requests = requests.session() # 设置变量开始 user_id = os.environ.get('login_account') # 教务系统登录账号 user_pwd = os.environ.get('password') # 教务系统登录密码 term = os.environ.get('sc...
StarcoderdataPython
3334139
<gh_stars>1-10 #!/usr/bin/python # -*- coding: UTF-8 -*- # KagurazakaYashi import sys import urllib import urllib2 class Nikkiup2u3word: argv = [] #可以在init前配置此属性以接入使用 argumentdict = {} datasource = "" output = "" separate = "" def __init__(self): self.argv = sys.argv self.a...
StarcoderdataPython
1682686
import os import shutil import subprocess import sys from pathlib import Path URL_PREFIX = "aurin://" ILLEGAL_PKG_NAME_CONTENTS = (".", "..", "/") temp_dir = Path("/var", "tmp", "aurin") def error_out(message: str): print(f"ERROR: {message}", file=sys.stderr) sys.exit(1) def notify(icon: str, title: str, ...
StarcoderdataPython
3311165
<gh_stars>0 import unittest from app import app import json from app.views import user_info class CreateUserTestCase(unittest.TestCase): def setUp(self): self.client = app.test_client self.user = {"username": "patrick", "password": "<PASSWORD>!@#", "first_name"...
StarcoderdataPython
4823895
<filename>tests/integration/__init__.py altapay_account = '' altapay_password = '' altapay_url = '' altapay_test_terminal_name = '' altapay_invoice_test_terminal_name = '' altapay_contract_identifier = ''
StarcoderdataPython
160428
from django.urls import path from . import views urlpatterns = [ path('', views.about_page, name='about_page_uid'), path('hidden/', views.hidden_about, name='about_page_hidden_uid'), ]
StarcoderdataPython
157482
#!/usr/bin/env python # -*- coding: utf-8 -*- class PodiumUser(object): """ Object that represents a particular User. **Attributes:** **user_id** (int): User id **uri** (string): URI for the User. **username** (string): The User's username. **description** ...
StarcoderdataPython
165946
from unittest import mock, TestCase from mort.download_utils import get_filename_from_url, download class TestUtils(TestCase): URL = "https://www.browserstack.com/screenshots/fdd01e6683e0474ede370b753f870542f364f8ba/" + \ "android_Google-Nexus-6_5.0_portrait.jpg" def test_get_filename_from_url(sel...
StarcoderdataPython
109412
<gh_stars>10-100 from setuptools import setup, find_packages, Command import re import sys import subprocess install_requires = [] pyversion = sys.version_info[:2] def read_module_contents(): with open('ceph_medic/__init__.py') as f: return f.read() module_file = read_module_contents() metadata = dict...
StarcoderdataPython
173721
""" Mocsár Environment File name: envs/gmocsar.py Author: <NAME> Date created: 3/27/2020 """ from rlcard3 import models from rlcard3.envs.env import Env from rlcard3.games.mocsar.game import MocsarGame as Game from rlcard3.games.mocsar.utils import action_to_string, \ string_to_action, payoff_func...
StarcoderdataPython
3339625
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Viagem, Motorista, Veiculo from .form import VeiculoForm, Motoris...
StarcoderdataPython
1606074
<reponame>DumisaniZA/Axelrod<filename>axelrod/tournament.py<gh_stars>10-100 import multiprocessing from game import * from result_set import * from round_robin import * import logging class Tournament(object): game = Game() def __init__(self, players, name='axelrod', game=None, turns=200, rep...
StarcoderdataPython
83244
import torch from morphosearch.core import Explorer from tqdm import tqdm class RandomExplorer(Explorer): """Performs random explorations of a system.""" def run(self, n_exploration_runs): print('Exploration: ') for run_idx in tqdm(range(n_exploration_runs)): if run_idx not in s...
StarcoderdataPython
15523
<reponame>feevos/incubator-mxnet<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, ...
StarcoderdataPython
123979
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: t...
StarcoderdataPython
89728
"""Setup script for SWITCH. Use "pip install --upgrade ." to install a copy in the site packages directory. Use "pip install --upgrade --editable ." to install SWITCH to be run from its current location. Optional dependencies can be added during the initial install or later by running a command like this: pip instal...
StarcoderdataPython
1750897
handle = '20141103\ All\ IRD' def get_header(n_nodes): header = '\ #!/bin/sh \n\ #$ -S /bin/sh \n\ #$ -cwd \n\ #$ -V\n\ #$ -m e\n\ #$ -M <EMAIL> \n\ #$ -pe whole_nodes {0}\n\ #$ -l mem_free=2G\n\ #############################################\n\n'.format(n_nodes) return header import os import pickle as pkl import...
StarcoderdataPython
3206648
<gh_stars>10-100 import torch import torch.nn as nn import torch.optim as optim import numpy as np import random import os import logging from transformers import get_cosine_schedule_with_warmup, DistilBertTokenizer from args import get_args from model.multimodal_transformer import MMT_VideoQA from loss impor...
StarcoderdataPython
3204729
<gh_stars>1-10 from django.contrib import admin from django.urls import path, include from rest_framework import routers, serializers, viewsets from rest_framework.authtoken.views import obtain_auth_token from surfsara.views import user, tasks, shares, permissions # Routers provide an easy way of automatically determ...
StarcoderdataPython
88245
<reponame>Xenovortex/Text-Analytics-Project import os from os.path import abspath, dirname, join, exists import multiprocessing import time import pickle import torch import numpy as np from sklearn.metrics import r2_score from torch.utils.data import DataLoader, TensorDataset import torch.optim as opt import matplotl...
StarcoderdataPython
3378382
<filename>Tfidf/SVM/test.py # -*- coding: utf-8 -*- """crtest.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/19z0CxLn52gS1kQjdA-JhmSkp1-uWSjOg """ from google.colab import drive drive.mount('/content/drive') # Download the StanfordCoreNLP packa...
StarcoderdataPython
3206712
<reponame>iiasceri/people-app-api from django.urls import path from django.conf.urls import url from user import views app_name = 'user' urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageU...
StarcoderdataPython
4814991
import os,time, pdb import datetime as dt import sqlalchemy import numpy as np import pandas as pd import statsmodels.api as sm class LongShortWeighted(object): def __init__(self): self._industry_styles = ['Bank','RealEstate','Health','Transportation','Mining', 'NonFerMetal...
StarcoderdataPython
1784028
<gh_stars>1-10 #!python import sys import gzip ctl_filename = sys.argv[1] max_length = 100 def shorten_conll_file(filename): assert (filename.endswith('.gz')) new_filename = "%s.%d.gz"%(filename[:-3], max_length) file = gzip.open(filename) new_file = gzip.open(new_filename, 'wb') count = 0 f...
StarcoderdataPython
4809797
<reponame>avim2809/CameraSiteBlocker # encoding: utf-8 try: import ttk except ImportError: # For some reason the future version of tkinter.ttk does not seem to have Widget! from tkinter import ttk class Spinbox(ttk.Widget): def __init__(self, master, **kw): ttk.Widget.__init__(self, master, '...
StarcoderdataPython
24940
#<NAME> #<EMAIL> #12/Sept/2018 myList = ['Hi', 5, 6 , 3.4, "i"] #Create the list myList.append([4, 5]) #Add sublist [4, 5] to myList myList.insert(2,"f") #Add "f" in the position 2 print(myList) myList = [1, 3, 4, 5, 23, 4, 3, 222, 454, 6445, 6, 4654, 455] myList.sort() #Sort the list from lowest t...
StarcoderdataPython
3227588
<gh_stars>0 # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
StarcoderdataPython
117547
# coding: utf-8 import pytest if __name__ == "__main__": # import os # import sys # sys.path.append(os.path.realpath('..')) pytest.main([__file__]) from tests.import_check import ImportCheck def test_single(): # from ooobuild.lo.document.filter_options_request import FilterOptionsRequest # ns =...
StarcoderdataPython
1638526
from logging import getLogger import httpx from fastapi import FastAPI from app.models.orm import Base, Entry, RegisteredActor from app.services.service_worker import ServiceWorker from app.util.data_import.data_importer import create_regular logger = getLogger(__name__) def clear_db(session): engine = session...
StarcoderdataPython
3311246
# 角谷定理。输入一个自然数,若为偶数,则把它除以2, # 若为奇数,则把它乘以3加1。经过如此有限次运算后,总可以得到自然数值1。求经过多少次可得到自然数1 # 如:输入22, # # 输出 STEP=16 def caculateStep(step, number): if number == 1: return step + 1 if number % 2 == 0: number = number / 2 else: number = number * 3 + 1 return caculateStep(step + 1, number) ...
StarcoderdataPython
1607368
<gh_stars>1-10 #!/usr/bin/env python def get_help_data_12586(): """ Vocabulary help. Data store of information to be presented when a help request is made for port 12586. Returns a list of dictionaries associated with various requests supported on that port. Sample response: [ { ...
StarcoderdataPython
1779667
<filename>settings.py #Please create a local_settings.py which should include, at least: # - ADMINS # - DEFAULT_FROM_EMAIL # - DATABASES # - SECRET_KEY # - FT_DOMAIN_KEY # - FT_DOMAIN_SECRET # - EMAIL_HOST # - EMAIL_HOST_USER # - EMAIL_HOST_PASSWORD # - EMAIL_PORT # - EMAIL_USE_TLS import os DEBUG = True TEMPLATE_DE...
StarcoderdataPython
117542
import frappe def execute(): for i in frappe.get_all('Asset',{'docstatus':1},['location','name','serial_no']): if len(frappe.get_all('Asset Serial No',{'name':i.get("serial_no")})) == 0: if i.get("serial_no"): print("1111",i.get("serial_no")) asset_...
StarcoderdataPython
24857
#Template of the Purkinje cell model, Zang et al. 2018 #Templating by Lungsi 2019 based on ~/PC2018Zang/purkinje.hoc #purkinje.hoc has been converted from original purkinje_demo and using readme.html as a guide from neuron import h #from pdb import set_trace as breakpoint from random import randint class Purkinje(obje...
StarcoderdataPython
4814985
<filename>main.py # -*- coding: utf-8 -*- """ Created on Sun Jan 19 23:54:40 2020 @author: Tarit """ import pandas as pd import sys import topsis as tp cla=sys.argv datafile=str(cla[1]) weights=cla[2].split(',') pn=cla[3].split(',') ds=pd.read_csv(datafile) n=len(ds.columns) if len(weights)!=n-1 o...
StarcoderdataPython
75484
#!/usr/bin/env python3 import argparse from game.game import Game def main(): """ Reversi game with human player vs AI player. """ parser = argparse.ArgumentParser() parser.add_argument('--timeout', help="Number of seconds the brain is allowed to think before making its move", ...
StarcoderdataPython
181760
from __future__ import absolute_import, division, print_function import cv2 import numpy as np import six def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False, docla=False, projection=None, **kwargs): """ http://matplotlib.org/users/gridspec.html Args: fnum (int...
StarcoderdataPython
3267439
'''Copyright (c) 2020, TDK Electronics All rights reserved. Author: <NAME>, https://github.com/mciepluc Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met (The BSD 2-Clause License): 1. Redistributions of source code must r...
StarcoderdataPython
3299053
<gh_stars>0 #!/usr/bin/env python3 # Copyright 2019 RaptorRants # This was for inputing dice but only accepted dice in format x x instead of x'd'x # print(DiceMainC) # UniqueCount = 'Y' # print("Provide your die rolls in format diecount dies1ize (Example: 2 12 is 2d12)") # count = 1 # ...
StarcoderdataPython
3251488
<reponame>JongGuk/BOJ '''예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. 예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다. dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다. 첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문...
StarcoderdataPython
3318503
<filename>code/hf_creator.py import glob import json import cv2 import h5py import numpy as np import tqdm IMAGE_SIZE = (512, 256) # Resolution of the images in the annotation_set SKELETON_SIZE = 20 HOME = 'C:/Users/<NAME>/Desktop/IntellIj Local Files/Convert-BADJA-json/' def replace_slash(path): return path.r...
StarcoderdataPython
4809892
import logging from pydano.cardano_cli import CardanoCli class PolicyIDTransaction(CardanoCli): def __init__(self, testnet: bool = True): super().__init__(testnet) @property def base_command(self): return ["cardano-cli", "transaction", "policyid"] def policyID(self, script_file): ...
StarcoderdataPython
1629350
import gin import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten,\ BatchNormalization from tensorflow.keras.initializers import GlorotUniform tf.random.set_seed(1234) def conv_net(nbr_classes, img_size = 128): """Reproduce the...
StarcoderdataPython
3792
from django.test import TestCase # Create your tests here. from crawler.download import * from crawler.models import * class AnimalDownloadTestCase(TestCase): def setUp(self): self.stopWords = ["CVPR 2019", "Computer Vision Foundation."] self.url = "/Users/tuannguyenanh/Desktop/cvpr2019.html"#"htt...
StarcoderdataPython
4807794
<reponame>jmhubbard/quote_of_the_day_custom_user from shows.models import Show #Returns a QuerySet of only active shows def getActiveShows(): return Show.objects.filter(is_active = True)
StarcoderdataPython
1693343
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User class Signupform(UserCreationForm): class Meta: model=User fields=('email','first_name','last_name','role','avatar','Mobile_Number','profession')
StarcoderdataPython
4802380
from fastapi import FastAPI app = FastAPI() @app.get("/users") async def get_user(page: int = 1, size: int = 10): return {"page": page, "size": size}
StarcoderdataPython
3355721
<filename>txircd/modules/server/metadatasync.py from twisted.plugin import IPlugin from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import timestamp from zope.interface import implements from datetime import datetime class ServerMetadata(ModuleData, Command): implements...
StarcoderdataPython
126227
<filename>layers/pool.py """ Pooling layers. """ import numpy as np import tensorflow as tf from central import layers_base class Pooling(layers_base.NNLayer): """ Maxpool and Averagepool layers. """ def __init__(self, input_var, layer_name, kernel_size, ...
StarcoderdataPython
95073
<filename>crawler/python newwork data collection/3/3.2.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from urllib.request import urlopen from bs4 import BeautifulSoup import re pages = set() def getLinks(pageUrl): global pages html = urlopen('http://en.wikipedia.org'+pageUrl) bsobj = BeautifulSoup(ht...
StarcoderdataPython
3378773
<filename>xlson/scheme/setup_xlson.py from functools import reduce from operator import getitem from jsondler import JsonEntry class XLSonScheme(JsonEntry): # json keys main_sheet_key = "main_sheet" supp_sheets_key = "supp_sheets" source_path_key = "source_path" # default values main_sheet_...
StarcoderdataPython
198626
<gh_stars>0 def convert(s): s_split = s.split(' ') return s_split def niceprint(s): for i, elm in enumerate(s): print('Element #', i + 1, ' = ', elm, sep='') return None c1 = 10 c2 = 's'
StarcoderdataPython
59732
<filename>web/backend/models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight from django.conf import settings from django....
StarcoderdataPython
132995
<reponame>Daph1986/postfly_jouw_online_drukkerij<gh_stars>0 # Generated by Django 3.2.6 on 2021-11-17 13:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('checkout', '0014_alter_order_artwork'), ] operations = [ migrations.AlterField( ...
StarcoderdataPython
1600545
<filename>test/test_add_contact.py # -*- coding: utf-8 -*- from model.contact import Contact def test_enter_contact(app): app.session.login(username = "admin", password = "<PASSWORD>") app.contact.create(Contact(firstname ="Anton", middlename ="Wiktor", lastname ="Lund", nickname ="alund", title ="Cola", comp...
StarcoderdataPython
177441
<reponame>pwwang/biopipen from bioprocs.utils import FileConn infile = {{i.infile | quote}} outfile = {{o.outfile | quote}} chrom = {{args.chr | quote}} with FileConn(infile) as f, open(outfile, 'w') as fout: for line in f: if line.startswith('##contig='): contig = line.rstrip('>\n')[10:].split(',') items...
StarcoderdataPython
1722890
#!/usr/bin/env python import pytest """ Test 1771. Maximize Palindrome Length From Subsequences """ @pytest.fixture(scope="session") def init_variables_1771(): from src.leetcode_1771_maximize_palindrome_length_from_subsequences import Solution solution = Solution() def _init_variables_1771(): ...
StarcoderdataPython
3317927
<reponame>OCHA-DAP/hdx-data-freshness<filename>tests/hdx/freshness/test_freshness_day0.py """ Unit tests for the freshness class. """ import os from os.path import join import pytest from hdx.database import Database from hdx.freshness.database.dbdataset import DBDataset from hdx.freshness.database.dbinfodataset imp...
StarcoderdataPython
1746879
# ************************************************************************* # # Copyright (c) 2021 <NAME>. All rights reserved. # # This file is licensed under the terms of the MIT license. # For a copy, see: https://opensource.org/licenses/MIT # # site: https://agramakov.me # e-mail: <EMAIL> # # ******************...
StarcoderdataPython
86525
class RoutingRulesList: TITLE = "Maintain case routing rules" CREATE_BUTTON = "Create new routing rule" NO_CONTENT_NOTICE = "There are no registered routing rules at the moment." ACTIVE = "Active" DEACTIVATED = "Deactivated" DEACTIVATE = "Deactivate" REACTIVATE = "Reactivate" EDIT = "Edi...
StarcoderdataPython
149177
<filename>chemotaxis/plots/transport_metabolism.py import os import matplotlib.pyplot as plt from vivarium.plots.simulation_output import set_axes from vivarium.library.dict_utils import get_value_from_path def plot_glc_lcts_environment(timeseries, settings={}, out_dir='out'): external_path = settings.get('exte...
StarcoderdataPython
167828
<filename>workflow/scripts/make_conference_schedule.py import pandas as pd tickets = pd.read_csv(snakemake.input["tickets"]) conferences = pd.read_csv(snakemake.input["conferences"]) schedule = conferences[conferences["City"].isin(tickets["city"])] schedule.to_csv(snakemake.output["schedule"])
StarcoderdataPython
1661962
<reponame>czczup/PVT<filename>configs/pvt/pvt_small.py cfg = dict( model='pvt_small', drop_path=0.1, grad_clip=None, output_dir='checkpoints/pvt_small', )
StarcoderdataPython
1620386
from cornell_word_seq2seq_glove_predict import CornellWordGloveChatBot from cornell_word_seq2seq_glove_predict_gru import CornellWordGloveChatBotGRU from cornell_char_seq2seq_predict import CornellCharChatBot from gunthercox_word_seq2seq_glove_predict import GunthercoxWordGloveChatBot from twitter_word_seq2seq_glov...
StarcoderdataPython
1732956
"""This module reads files from disk""" import os def crawl_files(): file_dic = [] dir = os.path.dirname(__file__) for root, dirs, files in os.walk(dir + '/../articles'): for file in files: file_path = os.path.join(root, file) file_dic.append({'name': file_path}) retur...
StarcoderdataPython
3271584
import cxphasing.cxparams.CXParams as CXP import cxphasing.CXPhasing as CXPh import cxphasing.CXData as CXData from data_exchange import DataExchangeFile, DataExchangeEntry import scipy as sp import pdb def pack_data_exchange(): f = DataExchangeFile(CXP.io.data_exchange_filename, mode='w') sim = DataExchangeEn...
StarcoderdataPython
1742329
<reponame>wwxFromTju/hierarchical-marl """Implementation of hierarchical cooperative multi-agent RL with skill discovery. High-level Q-function Q(s,\zbf) is trained with QMIX (with decentralized execution) using global environment reward Low-level policies are either 1. parameterized as policy networks pi(a^n|o^n,z^...
StarcoderdataPython
3325373
<reponame>SMattfeldt/probeye<filename>tests/unit_tests/definition/test_prior.py # standard library imports import unittest # local imports from probeye.definition.prior import PriorBase class TestProblem(unittest.TestCase): def test_prior_template(self): prior_template = PriorBase( "a", ["loc...
StarcoderdataPython
3323423
import os from testcontainers.postgres import PostgresContainer import psycopg2 from contextlib import contextmanager def get_migration_files(): path = os.path.join(os.path.dirname(__file__), os.pardir, "migration") files = os.listdir(path) files.sort() for f in files: yield os.path.join(path,...
StarcoderdataPython
107530
# Copyright (c) 2012-2016 <NAME> # Copyright (c) 2012-2018 The Bitmessage developers """ This is not what you run to run the Bitmessage API. Instead, enable the API ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. """ import base6...
StarcoderdataPython
4803634
from . import xmltodict from pymatgen import Structure
StarcoderdataPython
143894
<reponame>CodePsy-2001/hanshift JONG_COMP = { 'ㄱ': { 'ㄱ': 'ㄲ', 'ㅅ': 'ㄳ', }, 'ㄴ': { 'ㅈ': 'ㄵ', 'ㅎ': 'ㄶ', }, 'ㄹ': { 'ㄱ': 'ㄺ', 'ㅁ': 'ㄻ', 'ㅂ': 'ㄼ', 'ㅅ': 'ㄽ', 'ㅌ': 'ㄾ', 'ㅍ': 'ㄿ', 'ㅎ': 'ㅀ', } } DEFAULT_COMPOSE_SEPA...
StarcoderdataPython
3294436
import gitlab import dateutil.parser import reader.cache import hashlib import logging from pandas import DataFrame, NaT from datetime import datetime class Gitlab: def __init__(self, gitlab_config: dict, workflow: dict): self.gitlab_config = gitlab_config self.workflow = workflow def cac...
StarcoderdataPython
1745356
import logging from unittest import TestCase from parameterized import parameterized, param from hvac import exceptions from tests import utils from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase from tests.utils.mock_ldap_server import MockLdapServer class TestLdap(HvacIntegrationTestCase, T...
StarcoderdataPython
91623
<reponame>yishantao/DailyPractice<gh_stars>0 # -*- coding:utf-8 -*- """This module is used for cross validation""" from xgboost import XGBClassifier # 加载LibSVM格式数据模块 from sklearn.datasets import load_svmlight_file # from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold # 对给定参数的...
StarcoderdataPython
36393
<gh_stars>0 def none_check(value): if value is None: return False else: return True def is_empty(any_type_value): if any_type_value: return False else: return True
StarcoderdataPython
170468
<gh_stars>0 from django.test import TestCase from .models import Bucketlist from rest_framework.test import APIClient from rest_framework import status from django.core.urlresolvers import reverse class ModelTestCase(TestCase): """This class defines the test suite for the bucketlist model.""" def setUp(self): ...
StarcoderdataPython
1673231
<gh_stars>0 import math import tor4 from ...tensor import Tensor from .. import functional as F from .. import init from ..parameter import Parameter from .module import Module class Linear(Module): def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None: self.in_features = in...
StarcoderdataPython
101488
<reponame>pytexas/PyTexas import csv import random from django.conf import settings from django.core.management.base import BaseCommand, CommandError from conference.event.models import Conference, PrizeWinner import requests class Command(BaseCommand): help = 'Pick A Random Prize Winner' def add_arguments(se...
StarcoderdataPython
28037
""" Spacer components to add horizontal or vertical space to a layout. """ import param from bokeh.models import Div as BkDiv, Spacer as BkSpacer from ..reactive import Reactive class Spacer(Reactive): """ The `Spacer` layout is a very versatile component which makes it easy to put fixed or responsive ...
StarcoderdataPython
3259581
<gh_stars>0 from db import DB import nltk import random import classifiers import dill, os.path def getClassifier(all=True): if os.path.isfile("classifier.pkl"): with open("classifier.pkl", 'rb') as file: classifier = dill.load(file) classifier.show_most_informative_features(15) ...
StarcoderdataPython
3284292
<gh_stars>1-10 import logging logger = logging.getLogger('root') ''' def read(conn, cursor, sql): try: cursor.execute(sql) rows = cursor.fetchall() for row in rows: print("ADMISSION =", row[0]) print("NAME =", row[1]) print("AGE =", row[2]) p...
StarcoderdataPython