id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
132896
<gh_stars>1-10 from retic.runtime import * from retic.transient import * from retic.typing import * def check1(val): try: val.N return val except: raise CheckError(val) def check0(val): try: val.setrecursionlimit return val except: raise CheckError(val) ...
StarcoderdataPython
6498513
from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import pandas as pd import json import pickle import numpy as np dataset = pd.read_csv('C:/xampp/h...
StarcoderdataPython
5024783
<filename>src/scMDC.py from sklearn.metrics.pairwise import paired_distances from sklearn.decomposition import PCA from sklearn import metrics from sklearn.cluster import KMeans import torch import torch.nn as nn from torch.autograd import Variable from torch.nn import Parameter import torch.nn.functional as F import t...
StarcoderdataPython
5052534
<reponame>jl45621/coach import mxnet as mx import numpy as np import os import pytest import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from rl_coach.architectures.mxnet_components.heads.head import NormalizedRSSInitializer @pytest.mark.unit_test def test_normalized_rss_initial...
StarcoderdataPython
8133275
<filename>assignment-5-discreteevent-simulation-marctheshark3/partB/monte-carlo-simulation(approximate).py import numpy as np from scipy.interpolate import UnivariateSpline import seaborn as sns import matplotlib.pyplot as plt import matplotlib.mlab as mlab import scipy.stats as st import TransitionMatrix as TM from T...
StarcoderdataPython
3391937
<reponame>kevinyuan/pymtl3 #========================================================================= # StructuralRTLIRGenL2Pass.py #========================================================================= # Author : <NAME> # Date : Apr 3, 2019 """Provide L2 structural RTLIR generation pass.""" from .StructuralRTLI...
StarcoderdataPython
9698615
<reponame>Katee/artman<filename>artman/pipelines/sample_pipeline.py # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org...
StarcoderdataPython
6478443
<reponame>heshu-by/likelib-ws<gh_stars>0 from tester import test_case, Env, NodeConfig, Id, TEST_CHECK, TEST_CHECK_EQUAL, ClientType @test_case("connection_legacy_grpc") def main(env: Env) -> int: node_id = Id(20101, grpc_port=50101) env.start_node(NodeConfig(node_id)) client = env.get_client(ClientType.L...
StarcoderdataPython
1663919
from django.conf.urls import url, include from .views import (TaskListAPIView, TaskDetailAPIView, TaskCreateAPIView, TaskUpdateAPIView, TaskDeleteAPIView, TaskWeekAPIView) urlpatterns = [ url(r'^$', TaskListAPIView.a...
StarcoderdataPython
1952040
ITEMS = { "1150": {"zh-cn": "安柏", "zh-tw": "安柏", "en-us": "Amber", "ja-jp": "アンバー", "ko-kr": "엠버"}, "1310": {"zh-cn": "凯亚", "zh-tw": "凱亞", "en-us": "Kaeya", "ja-jp": "ガイア", "ko-kr": "케이아"}, "1440": {"zh-cn": "丽莎", "zh-tw": "麗莎", "en-us": "Lisa", "ja-jp": "リサ", "ko-kr": "리사"}, "1240": {"zh-cn": "芭芭拉", "z...
StarcoderdataPython
11264798
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
StarcoderdataPython
5198321
<reponame>hbristow/django-arxiv from __future__ import absolute_import from django.template.loader import get_template from django.template import Context from celery.schedules import crontab import celery import collections from arxiv import feed, models, time CELERYBEAT_SCHEDULE = { # Executes on weekdays every...
StarcoderdataPython
4872611
<filename>vulcan.py import io print("some printinfo, then exit.") print("some more words!")
StarcoderdataPython
8111043
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, <NAME> and contributors # 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 must retain the above copyright notic...
StarcoderdataPython
335559
""" All question classes """ from typing import Optional, List, Union, Any from fuzzywuzzy.fuzz import ratio from string import ascii_lowercase import random from professor.utils.numeric import numeric_string from professor.core.base import QuestionBase from professor.core.wraps import Link class FreeResponse(Ques...
StarcoderdataPython
4968504
<gh_stars>0 import time import os.path as osp # import huepy as hue import torch from torch.nn.utils import clip_grad_norm_ from ignite.engine.engine import Engine, Events # can not use apex try: import apex from apex import amp except ImportError as e: # raise pass from .distributed import reduce_di...
StarcoderdataPython
6461302
# # This file is part of PyOLab. https://github.com/matsselen/pyolab # (C) 2017 <NAME> <<EMAIL>> # # SPDX-License-Identifier: BSD-3-Clause # (https://opensource.org/licenses/BSD-3-Clause) # """ Files starting with the name "user", like this one, are provided so that users can create their own analysis jobs. This ...
StarcoderdataPython
12005
<filename>xarray/backends/npy_io.py import numpy as np import xarray as xr import pandas as pd import sys import json import os import datetime from xarray.core.utils import ( decode_numpy_dict_values, either_dict_or_kwargs, ensure_us_time_resolution, ) from numpy.compat import ( asbytes, asstr, asun...
StarcoderdataPython
4985705
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ i = 0 nums1_copy = nums1[:m] while i < len(nums1): if nums1_copy and (not ...
StarcoderdataPython
3454400
# Copyright 2021 The ProLoaF Authors. All Rights Reserved. # # 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...
StarcoderdataPython
4916438
<filename>matador/fingerprints/similarity.py # coding: utf-8 # Distributed under the terms of the MIT License. """ This submodule implements filtering based on Fingerprint objects, although only PDF has been implemented so far. """ import copy from collections import defaultdict from typing import List, Dict, Tuple ...
StarcoderdataPython
9680794
from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('About/', views.AboutPageView.as_view(), name='about'), path('Projects/', views.ProjectsPageView.as_view(), name='projects'), path('Contact/', views.ContactPageView.as_view(), name='c...
StarcoderdataPython
11304500
from kapteyn import maputils import numpy from service import * fignum = 21 fig = plt.figure(figsize=figsize) frame = fig.add_axes(plotbox) theta_a = -45 t1 = -20.0; t2 = -70.0 eta = abs(t1-t2)/2.0 title = r"""Conic equal area projection (COE) with: $\theta_a=-45^\circ$, $\theta_1=-20^\circ$ and $\theta_2=-70^\circ$. ...
StarcoderdataPython
8000845
<filename>users.py from flask import Blueprint, current_app users_bp = Blueprint("users", __name__) @users_bp.route('/login') def login(): print(current_app.database) return "login page"
StarcoderdataPython
1909733
from django.urls import path from .views import LatestPostFeed, PostDetailView, PostListView app_name = 'blog' urlpatterns = [ path('feed/', LatestPostFeed()), path('', PostListView.as_view(), name='index'), path('<slug:slug>/', PostDetailView.as_view(), name='detail'), ]
StarcoderdataPython
153987
# Copyright 2020 StrongDM Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
StarcoderdataPython
9750488
<filename>meddlr/transforms/base/spatial.py import logging from typing import Sequence, Tuple import numpy as np import torch import torch.nn.functional as F import torchvision.transforms.functional as TF from PIL import Image import meddlr.ops.complex as cplx from meddlr.transforms.build import TRANSFORM_REGISTRY fr...
StarcoderdataPython
11246590
<filename>Advance_Python/Exception_Handling/Finally_Keyword.py # Finally Keyword try: a = int(input("Enter a : ")) b = int(input("Enter b : ")) c = a / b print(c) except ZeroDivisionError: print("Division by zero") else: print("Else Block") finally: print("Final block always execute")
StarcoderdataPython
1998645
<reponame>kauanmatos224/DATA_SCIENCE<filename>Python_Softwares_MachineLearning_/PIPELINE_MultipleLinearRegression_DistributionPlot_PolynomialRegression_MSE_RSquared.py import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression #IMPORTA BIBLIOTECA DE VISUALI...
StarcoderdataPython
9787249
<reponame>canokeys/yubikey-manager<filename>ykman/settings.py<gh_stars>1-10 # Copyright (c) 2017 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of sour...
StarcoderdataPython
3424935
<reponame>hsph-qbrc/mev-backend from rest_framework import serializers, exceptions from api.models import ResourceMetadata, \ Resource, \ ExecutedOperation from api.serializers.observation_set import NullableObservationSetSerializer from api.serializers.feature_set import NullableFeatureSetSerializer class R...
StarcoderdataPython
3499498
import functools import logging import time from datetime import datetime, timedelta from typing import Any, Callable, Dict, List, Optional, TypedDict import pandas as pd active_logger = logging.getLogger(__name__) class TimingResult(TypedDict): function: str count: int mean: timedelta min: timedelt...
StarcoderdataPython
5180383
"""files.filesize bigint Revision ID: 75b0775a8695 Revises: 26c2f6af45ab Create Date: 2021-03-03 00:08:00.895764 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '75b0775a8695' down_revision = '26c2f6af45ab' branch_labels = None depends_on = None def upgrade()...
StarcoderdataPython
5160238
<reponame>1byte2bytes/cpython # A class to help applications that do fancy text formatting. # You create an instance each time you must redraw the window. # Set the initial left, top and right coordinates; # then feed it words, font changes and vertical movements. # # This class should eventually be extended to support...
StarcoderdataPython
6482397
from functools import reduce def hexa(s): s = s.lower() if set(s) - set('0123456789abcdef'): raise ValueError('Invalid hexadecimal string') l = [ord(c) - ord('a') + 10 if c in 'abcdef' else ord(c) - ord('0') for c in s] return reduce(lambda x, y: x * 16 + y, l, 0)
StarcoderdataPython
278431
# -*- coding: utf-8 -*- """ Created on Thu Nov 23 13:21:34 2017 @author: HCHO """ import sqlite3 def convert(value): if value.startwith('~'): return value.strip('~') if not value: value='0' return float(value) conn=sqlite3.connect('food.db') curs=conn.cursor() curs.execute(''' CREATE TAB...
StarcoderdataPython
3387079
<gh_stars>0 from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.logsHome, name='logsHome'), url(r'^accessLogs', views.accessLogs, name='accessLogs'), url(r'^errorLogs', views.errorLogs, name='errorLogs'), url(r'^emaillogs', views.emailLogs, name='emaillogs'), url(r...
StarcoderdataPython
5054897
<filename>bblfsh_sonar_checks/checks/java/RSPEC-2447.py<gh_stars>1-10 import bblfsh_sonar_checks.utils as utils import bblfsh def check(uast): findings = [] methods = utils.get_methods(uast) for m in methods: # Should look at the roles to filter by Boolean but there is a bug in the # Jav...
StarcoderdataPython
5158573
<gh_stars>0 from __future__ import absolute_import from django.core.urlresolvers import reverse from exam import fixture from sentry.models import Team from sentry.testutils import TestCase, PermissionTestCase class TeamSettingsPermissionTest(PermissionTestCase): def setUp(self): super(TeamSettingsPermi...
StarcoderdataPython
63838
<reponame>herrywen-nanj/51reboot<gh_stars>0 # -*- coding:utf-8 -*- # author: lyl import check from prettytable import PrettyTable def list_user(): # 检测用户文件是否为空,如非空将结果转换为字典并返回 tag, user_dict = check.user_dict() if tag: # 格式化输出 xtb = PrettyTable() xtb.field_n...
StarcoderdataPython
1976247
<gh_stars>0 from __future__ import unicode_literals from frappe import _ import frappe def get_data(): return [ { "label": _("Main Menu"), "items": [ { "type": "report", "is_query_report": True, "name": "Monitoring Panel", "doctype": "Stock Ledger Entry", "onboard": 1, "d...
StarcoderdataPython
12845211
<filename>globals/mime.py # -*- coding: utf-8 -*- ## \package globals.mime # MIT licensing # See: docs/LICENSE.txt from globals.execute import GetCommandOutput from globals.execute import GetExecutable ## TODO: Doxygen def GetFileMimeType(filename): CMD_file = GetExecutable(u'file') if not CMD_file: return N...
StarcoderdataPython
6420148
"""Serveradmin - Servershell Copyright (c) 2019 InnoGames GmbH """
StarcoderdataPython
6682117
from .pathlib_ext import *
StarcoderdataPython
3299777
# Generated by Django 3.2.5 on 2021-07-08 07:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Company', ...
StarcoderdataPython
82362
<filename>tests/test_matrix.py from rigidbody import (Matrix, svd, approx) def test_matrix_equality(): A = Matrix(3, 3) B = Matrix(3, 3) assert(A == B) A = Matrix.identity(3, 3) B = Matrix.identity(3, 3) assert(A == B) A = Matrix.zero(3, 3) B = Matrix.zero(3, 3) assert(A == B)...
StarcoderdataPython
6413333
from diskspace import bytes_to_readable, subprocess_check_output, show_space_list, args, print_tree import os import unittest import StringIO import sys class TestMethods(unittest.TestCase): def setUp(self): self.largest_size = 8 self.total_size = 4 self.cmd = 'du ' self.path = os...
StarcoderdataPython
103199
<filename>tests/config.py import os from aiohttp import BasicAuth FHIR_SERVER_URL = os.environ.get("FHIR_SERVER_URL", "http://localhost:8080/fhir") FHIR_SERVER_AUTHORIZATION = os.environ.get( "FHIR_SERVER_AUTHORIZATION", BasicAuth("root", "secret").encode() )
StarcoderdataPython
1793404
<reponame>patdaburu/hoonds #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from hoonds.errors import CustomException class TestCustomException(CustomException): pass class TestCustomExceptionSuite(unittest.TestCase): def test_initWithoutInner_verify(self): ge = TestCustomException(me...
StarcoderdataPython
6417253
#!/usr/bin/python """ A simple script to install Leo on Linux. Contributed by <NAME> <<EMAIL>> """ import commands,os,sys # commands module is for Unix only. # We must be root to use this script. if os.getuid() != 0: print("You need to run this install script as root") sys.exit(1) # Create /usr/li...
StarcoderdataPython
3310837
import os import re def _create_path(base: str, tail: str) -> str: """ Creates a safe path according to which OS the program is running on :param base: The current path :param tail: The last part of the path that is to be added :return: A new OS safe path """ return base + ('\\' if os.name...
StarcoderdataPython
11300298
# MetaPerson.py from collections import defaultdict from utils.utils import dump_json from utils.timeprofile import TimeProfile as TP from utils.timeprofile import TimeProfileEntry as TPE from utils.timeprofile import PatDur as PD class MetaPerson: mid = 1 def __init__(self, tps, capacity, pro...
StarcoderdataPython
192697
<gh_stars>10-100 import time import numpy as np import os import pickle as pkl import re from collections import OrderedDict from openbox.utils.constants import SUCCESS from openbox.optimizer.smbo import SMBO from solnml.components.optimizers.base_optimizer import BaseOptimizer, MAX_INT cur_dir = os.path.dirname(__fi...
StarcoderdataPython
3215798
# Crie um programa que tenha a função leiaInt(), que vai funcionar # de forma semelhante ‘a função input() do Python, só que fazendo a # validação para aceitar apenas um valor numérico. Ex: n = leiaInt(‘Digite um n: ‘) # Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora a # possibilidade da digi...
StarcoderdataPython
96699
<filename>SRC/engine/IO/GUI/skeletonselectiontoolboxGUI.py # -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification ...
StarcoderdataPython
281746
<filename>immunopy/MMCorePyFake.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on 2014-05-28 @author: <NAME> """ import os import Tkinter as tk import ttk import tkFileDialog import threading import numpy as np from scipy import misc try: import MMCorePy base = MMCorePy.CMMCore MM_INSTALL...
StarcoderdataPython
9652160
""" Copyright (c) 2018 ARM Limited SPDX-License-Identifier: Apache-2.0 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 ...
StarcoderdataPython
5125360
<reponame>franciscomcdias/SpoKlient from spoklient.outlookservices.item import Item class Event(Item): """An event in a calendar."""
StarcoderdataPython
9623191
<gh_stars>1-10 from app.common.command_handler import CommandHandler from app.event.publisher import IntegrationEventPublisher from app.tweet.application.dislike_tweet.command import DislikeTweet from app.tweet.domain.repository import TweetAggregateRepository from app.tweet.event import TweetDisliked class DislikeTw...
StarcoderdataPython
29976
<reponame>ExpressApp/pybotx """Implementation for bot classes.""" import asyncio from dataclasses import InitVar, field from typing import Any, Callable, Dict, List from weakref import WeakSet from loguru import logger from pydantic.dataclasses import dataclass from botx import concurrency, exception_handlers, excep...
StarcoderdataPython
8074103
<filename>gym_environments/plot.py import os import numpy as np import matplotlib.pyplot as plt import argparse import fnmatch import gym import gym_shadow_hand ALGOS = ["DDPG", "HER+DDPG", "DDPGfED", "HER+DDPGfED"] ALGOS.extend([algo.lower() for algo in ALGOS]) def moving_average(values, window): """ Smooth ...
StarcoderdataPython
1747248
<reponame>asears/opt_einsum # -*- coding: utf-8 -*- import setuptools import versioneer short_description = "Optimizing numpys einsum function" try: with open("README.md", "r") as handle: long_description = handle.read() except: long_description = short_description if __name__ == "__main__": set...
StarcoderdataPython
6463994
<reponame>parnurzeal/openml-python import collections import io import json import os import sys import time import warnings import numpy as np import sklearn.pipeline import six import xmltodict import sklearn.metrics import openml import openml.utils import openml._api_calls from ..exceptions import PyOpenMLError f...
StarcoderdataPython
1944657
<reponame>elyashiv3839/compare_objects<gh_stars>0 from ..compare_objects.CompareObjectsWithInfo import compare_objects_with_info # ######################### WITH INFORMATION ######################### # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NATIVE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # def test_two_strings_val_compare_with_in...
StarcoderdataPython
6422806
<filename>scenegraph/exp-official/taskographyv5medium5bagslots5_FD-lama-first/taskographyv5medium5bagslots5_FD-lama-first_test.py STATS = [ { "num_node_expansions": 320, "plan_cost": 84, "plan_length": 84, "search_time": 0.201463, "total_time": 1.57179 }, { "n...
StarcoderdataPython
9768356
<filename>chtc_runners/simulation_runner.py """ Runs an iterative screening simulation. Usage: python simulation_runner.py \ --pipeline_params_json_file=../param_configs/general_pipeline_config.json \ --nbs_params_json_file=../param_configs/ClusterBasedWCSelector_params_reduced.json...
StarcoderdataPython
4826818
<reponame>sundials-codes/PeleLM<filename>Testing/Scaling/extractWeakScalingData.py #!/usr/bin/env python3 import sys import os import shutil import argparse import socket import numpy as np import subprocess import fnmatch # Script used to extract weak scaling data from PeleLM log files # Simply ./extractWeakScalingD...
StarcoderdataPython
9774492
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.keras.applications.inception_v3 namespace. """ from __future__ import print_function as _print_function import sys as _sys from keras.applications.inception_v3 import...
StarcoderdataPython
241098
#!/usr/bin/env python # -*- coding: utf-8 -*- ## Project: SCRIPT - February 2018 ## Contact: <NAME> - <EMAIL> import sys import os import glob from argparse import ArgumentParser import imp import numpy as np from utils import spectrogram2wav # from scipy.io.wavfile import write import soundfile import tqdm fro...
StarcoderdataPython
6568873
from toontown.toonbase.ToontownGlobals import * from otp.level import BasicEntities class MintProduct(BasicEntities.NodePathEntity): Models = {CashbotMintIntA: 'phase_10/models/cashbotHQ/MoneyBag', CashbotMintIntB: 'phase_10/models/cashbotHQ/MoneyStackPallet', CashbotMintIntC: 'phase_10/models/cashbotHQ/...
StarcoderdataPython
257250
from django.db import models from pydis_site.apps.api.models.bot.user import User from pydis_site.apps.api.models.utils import ModelReprMixin class Nomination(ModelReprMixin, models.Model): """A helper nomination created by staff.""" active = models.BooleanField( default=True, help_text="Whe...
StarcoderdataPython
3410625
#!/usr/bin/env python3 #This sample demonstrates turning relays on and off. #Install Relay uHAT library with "pip3 install turta-relayuhat" from time import sleep from turta_relayuhat import Turta_Relay #Initialize relay = Turta_Relay.RelayController() try: while 1: #Turn on relay 1 relay.write(...
StarcoderdataPython
6599615
# encoding: utf-8 '''🐱 PDS GitHub Utilities: Python Version determination''' import logging, os, packaging.version, re, sys, subprocess _logger = logging.getLogger(__name__) _detectives = set() # Classes # ------- class NoVersionDetectedError(ValueError): '''😦 Raised when we cannot detect a version from ...
StarcoderdataPython
242986
import setuptools setuptools.setup( name="liblora", version="0.0.3", author="<NAME>", author_email="<EMAIL>", description="A library with functions related to LoRaWAN, derived from Basic MAC", url="https://github.com/mkuyper/liblora", packages=setuptools.find_pac...
StarcoderdataPython
8014284
<filename>tests/h/admin/views/nipsa_test.py # -*- coding: utf-8 -*- from pyramid import httpexceptions import pytest from h.admin.views import nipsa as views @pytest.mark.usefixtures('nipsa_service', 'routes', 'users') class TestNipsaIndex(object): def test_lists_flagged_usernames(self, pyramid_request): ...
StarcoderdataPython
11342341
<gh_stars>1-10 class Solution: def partitionLabels(self, S): """ :type S: str :rtype: List[int] """ res, n = [], len(S) idx_dict = {} for i in range(n): idx_dict[S[i]] = i i = 0 while i < n: start = j = i whi...
StarcoderdataPython
6675760
<reponame>zabir-nabil/data-viz<gh_stars>0 # coding: utf-8 # In[16]: import pandas as pd # In[17]: excel_ds = 'dataset.xlsx' subjects = pd.read_excel(excel_ds, index_col = 0) # In[18]: subjects.shape # In[19]: subjects.head() # In[20]: subjects.tail() # In[21]: best_composite_index = subjects.sort_valu...
StarcoderdataPython
1610611
#from Python import time import csv import os import math import numpy as np import sys from shutil import copyfile #from Pytorch import torch import torchvision import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets from torchvision import transforms...
StarcoderdataPython
6643992
<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-06 09:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields import modelcluster.contrib.taggit import modelcluster.fields import wagtail.wagta...
StarcoderdataPython
3299666
import tweepy import os import sys ckey= '' csecret= '' atoken='' asecret= '' auth = tweepy.OAuthHandler(ckey,csecret) #Authenticating with twitter auth.set_access_token(atoken,asecret) #Access tokens api = tweepy.API(auth) #Performing Auth filename = os.path.abspath(sys.argv[1]) status = sys.argv[2] print "Posti...
StarcoderdataPython
12858800
import configparser import logging from flask import Flask from flask_pymongo import PyMongo from Crypto.PublicKey import RSA # Value mapping LOG_LEVELS = {'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'WARN': logging.DEBUG, 'ERROR': logging.ERROR} # Create application app = Flask(__name__) # Read external config co...
StarcoderdataPython
4875293
<gh_stars>0 from pipelining.pipe_root import ConfigRoot from etl import maxqdata_manager, gold_data_transform_rules from pipelining import data_flow_registry from IPython import embed import main ConfigRoot.articles_xml_directory = data_flow_registry.maxqdata_data["md1"]["articles_xml_directory"] ConfigRoot.annotatio...
StarcoderdataPython
1616327
""" This module provides different kinds of iterators, all wrapped by the DataIterator class which should generally be the only one used in practice. The BaseIterator class allows "peeking" `checklines` lines into the data -- even if it's a consumable iterator -- in order to figure out what the dialect is and therefor...
StarcoderdataPython
3242399
# Copyright (c) 2017, <NAME>, and <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 must retain the above copyright # notice, this list of conditions and the...
StarcoderdataPython
3298179
""" author: <NAME> time: link: """ import numpy as np from scipy import stats from sklearn.metrics import f1_score, classification_report def select_threshold(X, Xval, yval): """ use CV data to find the best epsilon """ # create multivariate model using training data mu = X.mean(axis=0) cov = ...
StarcoderdataPython
3869
<reponame>sflippl/patches<gh_stars>0 """Datasets of latent predictability tasks. """ from .pilgrimm import *
StarcoderdataPython
11229454
#-*-coding:utf-8-*- import os from app import app from models import db , User, Role, Device, Platforms_info, Ip, Project, App from werkzeug.security import generate_password_hash def build_first_db(): """ Populate a small db with some example entries. """ db.drop_all() db.create_all() anonymou...
StarcoderdataPython
5164613
import json class ResponseOverride(Exception): def __init__(self, status_code: int = None, url: str = None, link: str = None, provider: str = None, message: str = None): self.status_code = status_code self.url = url self.text = link self.provider = provider ...
StarcoderdataPython
3529514
no_of_teams = int(input()) teams = {} for i in range(no_of_teams): team = input() teams[team] = [0,0.0] num_of_matches = int(input()) for i in range(num_of_matches): pointsA,pointsB = 0,0 teamA,teamA_runrate, teamB,teamB_runrate = input().split(" ") teamA_runrate,teamB_runrate = float(teamA_runrat...
StarcoderdataPython
11274983
# -*- coding: utf-8 -*- """Tests for the cli interface.""" import pytest import shutil import os import stat import tarfile from pathlib import Path from click.testing import CliRunner from clitools import fs_lint @pytest.fixture def change_test_dir(request): """Bla.""" os.chdir(request.fspath.dirname) ...
StarcoderdataPython
3440462
<reponame>project-k-0-1/project-k """ Font awesome """ def get_font_awesome(): """ Gdt fontawsome library """ f_a = '<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">' return_data = f_a return return_data
StarcoderdataPython
11373362
<gh_stars>10-100 import torch.utils.data import torch.backends.cudnn as cudnn from src.configs.setters.set_enums import * DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") cudnn.benchmark = True # set to true only if inputs to model are fixed size; otherwise lot of computational overhead # task ...
StarcoderdataPython
9773348
<filename>tests/providers/aws/project_resources/key_pair.py<gh_stars>1-10 import unittest import boto3 import os from moto import mock_ec2 from spotty.providers.aws.deployment.project_resources.key_pair import KeyPairResource class TestKeyPairResource(unittest.TestCase): def test_key_path(self): region =...
StarcoderdataPython
8078148
<reponame>koyo-jakanees/qgis-stac-browser import os import json from ..models.api import API class Config: def __init__(self): self._json = None self.load() def load(self): if not os.path.exists(self.path): self._json = {} self.save() else: ...
StarcoderdataPython
6520714
import json import os from collections import OrderedDict def load_characters(): fname = os.path.join(os.path.dirname(__file__), 'charactersdata.json') with open(fname, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict) def load_locations(): fname = os.path.join(os.p...
StarcoderdataPython
3292460
<gh_stars>1-10 from google.cloud import language_v1 from google.cloud.language_v1 import enums from concurrent.futures import ThreadPoolExecutor from functools import partial import csv, os, datetime, asyncio # define only once client = language_v1.LanguageServiceClient() _executor = ThreadPoolExecutor() async def ...
StarcoderdataPython
5176152
#!/usr/bin/env python import os from os.path import join as pjoin, abspath import torch import numpy as np import numpy.random as rand from numpy import genfromtxt import pandas as pd from .dataset import Dataset _default_folder = abspath(pjoin(__file__, "..", "..", "..", "datasets")) DATASET_FOLDER = os.environ.g...
StarcoderdataPython
11303862
from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('folders/', views.FolderList.as_view()), path('folders/<int:pk>/', views.FolderDetail.as_view()), path('files/', views.File...
StarcoderdataPython
8016510
__test__ = False if __name__ == '__main__': import MySQLdb as m from eventlet import patcher from eventlet.green import MySQLdb as gm patcher.monkey_patch(all=True, MySQLdb=True) patched_set = set(patcher.already_patched) - set(['psycopg']) assert patched_set == frozenset(['MySQLdb', 'os', 'sel...
StarcoderdataPython
3566650
import os import sys import random import math import numpy as np import skimage.io import pickle import matplotlib.pyplot as plt import logging logging.getLogger().setLevel(level=logging.INFO) # Root directory of the project ROOT_DIR = os.path.abspath("../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find lo...
StarcoderdataPython