id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3224664
import unittest import responses from connectedcar import connectedcar, const class Testconnectedcar(unittest.TestCase): def setUp(self): self.client_id = 'apiKey' self.client_secret = "clientSecret" self.redirect_uri = "redirectUri" self.scope = ['profile'] self.client =...
StarcoderdataPython
3299198
<reponame>lmee/hello # /usr/local/bin/python3 # --*-- coding: utf-8 --*-- # __Author__ = 'Jieer' poem = '''There was a young lady named Bright, Whose speed was far faster than light; She started one day In a relative way, And returned on the previous night.''' print(len(poem)) fout = open('relativity','wt') fout.wr...
StarcoderdataPython
7873
""" A :py:mod:`filter <tiddlyweb.filters>` type to limit a group of entities using a syntax similar to SQL Limit:: limit=<index>,<count> limit=<count> """ import itertools def limit_parse(count='0'): """ Parse the argument of a ``limit`` :py:mod:`filter <tiddlyweb.filters>` for a count and index...
StarcoderdataPython
1729987
from multixrank import MultiplexAll import numpy import scipy class TransitionMatrix: def __init__(self, multiplex_all: MultiplexAll, bipartite_matrix: numpy.array, lamb: numpy.array): self.multiplex_all = multiplex_all self.bipartite_matrix = bipartite_matrix self.lamb = lamb ...
StarcoderdataPython
1682116
import numpy as np # 计算转移矩阵对应平稳分布 ''' 转移矩阵如下,分布为列向量 |1 0.5| |x| |0 0.5| |y| ''' def calc_stationary_distribution(M): matrix_shape = np.shape(M) if matrix_shape[0] == matrix_shape[1]: pass else: print("平稳分布计算错误:输入应该为方阵") return # 减去对角阵 C = M - np.identity(...
StarcoderdataPython
1655891
<gh_stars>10-100 # ED25519 curve constants from constants import * SHA = 'sha256' # hash type to use with this curve EFS = 32 # elliptic curve field size in bytes CurveType = EDWARDS # field modulus p = 2**255 - 19 r = 2**252 + 27742317777372353535851937790883648493 # elliptic curve A = -1 B = 0x52036CEE2B6FFE7...
StarcoderdataPython
1665467
<reponame>pospx/external_skia #!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Add the checkout root to sys.path, provide mechanisms for adding others.""" import os import sy...
StarcoderdataPython
1714772
""" Module that contains the command line app. Why does this file exist, and why not put this in __main__? You might be tempted to import things from __main__ later, but that will cause problems: the code will get executed twice: - When you run `python -mpvct` python will execute ``__main__.py`` as a scrip...
StarcoderdataPython
3244894
<filename>sample2/join1_reducer.py #!/usr/bin/env python import sys last_key = "" running_total = 0 filter_key = "ABC" # ----------------------------------- # Loop thru file # -------------------------------- for input_line in sys.stdin: input_line = input_line.strip() # -------------------------------- ...
StarcoderdataPython
1684471
import torch.nn as nn import torch class VGGsection(nn.Module): def __init__(self, num_of_blocks, previous_num_of_filters, current_num_of_filters): super(VGGsection, self).__init__() self.num_of_blocks = num_of_blocks self.blocks = nn.ModuleList() self.kernel_size = 3 self....
StarcoderdataPython
3266602
from .cassiemujoco import *
StarcoderdataPython
1609389
<reponame>CommonRoad/commonroad-io<filename>commonroad/visualization/icons.py """Module for drawing obstacle icons.""" from typing import Union import matplotlib as mpl import numpy as np import math from commonroad.geometry.transform import rotate_translate from commonroad.scenario.obstacle import ObstacleType __au...
StarcoderdataPython
1721594
<gh_stars>0 """Instanciando o app""" from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from ..routes import users, auth def create_app() -> FastAPI: """Funcao de criaçao do app""" app = FastAPI( title="MitMirrorApi", version="0.0.1", description=""" ...
StarcoderdataPython
23886
<reponame>pedrovelho/camp<gh_stars>0 # # CAMP # # Copyright (C) 2017, 2018 SINTEF Digital # All rights reserved. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # from unittest import TestCase from camp.commands import Command, Generate c...
StarcoderdataPython
4826754
#! /usr/bin/env python3 # -*-coding:utf-8 -*- # @Time : 2019/06/15 18:36:58 # @Author : che # @Email : <EMAIL> # 寻找某一路径下的重复文件 from os.path import getsize from checksum import create_checksum from diskwalk import DiskWalk def find_dupes(path='tmp'): dups = [] record = {} d = DiskWalk(path) fil...
StarcoderdataPython
3229804
from dal import autocomplete from django.db.models import Q from .models import Account class AccountAutocomplete(autocomplete.Select2QuerySetView): '''Basic autocomplete lookup, for use with django-autocomplete-light and :class:`mep.accounts.models.Account` in address many-to-many''' def get_queryset(se...
StarcoderdataPython
1631135
<reponame>Pervasive-Technologies/norfair<filename>setup.py # -*- coding: utf-8 -*- from setuptools import setup packages = ["norfair"] package_data = {"": ["*"]} install_requires = ["filterpy>=1.4.5,<2.0.0"] setup_kwargs = { "name": "norfair", "version": "0.3.1", "description": "Lightweight Python libra...
StarcoderdataPython
3262614
<gh_stars>1-10 # file: address/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from address import views app_name = 'address' urlpatterns = [ url( r'^(?P<logical_interface_id>[0-9]+)/create/ipv6_address/$', views.ipv6_address_create, name='ipv6...
StarcoderdataPython
3331705
import os import unittest import numpy as np from datetime import datetime from laticore.metricsets.metricsets import * class TestSupervisedTimeSeriesMetricSet(unittest.TestCase): def setUp(self): pass def metricset_factory(self, timesteps=4320): now = int(datetime.utcnow().timestamp()) ...
StarcoderdataPython
1751425
<gh_stars>0 import numpy as np import os def dot_product(a,b): return(a[0]*b[0]+a[1]*b[1]+a[2]*b[2]) a=np.zeros(3) b=np.zeros(3) for i in range(3): a[i]=int(input("write the"+str(i)+"element of a")) b[i]=int(input("write the"+str(i)+"element of b")) print("The vectors are\n",a,"\n",b) print("Dot Product ...
StarcoderdataPython
3215961
import requests, random, logging from kkbox_line_bot import app from kkbox_line_bot.nlp import olami from kkbox_line_bot.nlp.error import NlpServiceError from linebot import LineBotApi, WebhookHandler from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageMessage, ImageSendMessage, VideoMessage, ...
StarcoderdataPython
134067
# region IMPORTS from wplay.utils.helpers import whatsapp_selectors_dict # endregion # region FOR SCRIPTING async def get_last_seen_from_focused_target(page): #await page.waitForSelector(whatsapp_selectors_dict['status'], visible = True) try: status = await page.evaluate(f'document.querySelector("{wh...
StarcoderdataPython
3236544
from client import Client from transaction import Transaction from block import Block def display_transaction(transaction): # for transaction in transactions: transaction_dict = transaction.to_dict() print("sender: " + transaction_dict['sender']) print('-----') print("recipient: " + transaction_di...
StarcoderdataPython
165203
from ..buildcalculator import ItemSet def get_participant_item_events(match, participant): events = [] for frame in match.frames: for event in sorted(frame, key=lambda event: (event.timestamp, event.type.value)): if event.participant is participant and \ (event.item is not None...
StarcoderdataPython
159128
from python.enclave_interfaces import GlobalTensor as gt from python.timer_utils import NamedTimerInstance from python.torch_utils import compare_expected_actual from python.tensor_loader import TensorLoader import torch class SecretLayerBase(TensorLoader): PrevLayer = None NextLayer = None PlainForwardRe...
StarcoderdataPython
1779068
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Create the RenderWindow, Renderer and both Actors ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRender...
StarcoderdataPython
1612771
<reponame>marcinguy/quantifiedcode<filename>quantifiedcode/backend/commands/setup.py # -*- coding: utf-8 -*- from __future__ import absolute_import import click import logging import yaml from .data_model import _migrate_db from .checkmate import _import_issue_classes logger = logging.getLogger(__name__) from quant...
StarcoderdataPython
1787665
<gh_stars>0 from .account import Account from .character import Character from .facade import ApiError, \ account_get, characters_get, \ guild_get, guild_get_full, guild_search, worlds_get_by_ids, \ worlds_get_ids, worlds_get_one from .guild import AnonymousGuild, Guild from .world import World __all__ = [...
StarcoderdataPython
3389140
import os import copy import json import hashlib from typing import Any, Dict # noqa from chalice.deploy.swagger import CFNSwaggerGenerator from chalice.deploy.swagger import SwaggerGenerator # noqa from chalice.deploy.packager import LambdaDeploymentPackager from chalice.deploy.deployer import ApplicationPolicyHan...
StarcoderdataPython
1620110
import datetime from sqlalchemy import Column, DateTime, Integer, Float, ForeignKey import src.models.listing_observation as listing_observation from definitions import MYSQL_CASCADE, Base TABLE_NAME = 'bulk_price' PRIMARY_KEY = 'id' TABLE_NAME_AND_PRIMARY_KEY = TABLE_NAME+"."+PRIMARY_KEY class BulkPrice(Base): ...
StarcoderdataPython
1682827
#!/usr/bin/env python import os, os.path, json import shutil METRIC_DIR = "metrics" PROCESSED_DIR = "processed" CONFIG_FILE = "synchronizer.json" TS="ts" VAL="val" TIME_UNIT = "ms" def ls(dir): """ List a directory, returning full path. """ return ls_grep(dir, lambda x: True) def ls_grep(dir, filter...
StarcoderdataPython
67518
<filename>scripts/external_libs/scapy-2.4.5/scapy/layers/tuntap.py # -*- mode: python3; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) <NAME> <<EMAIL>> # Copyright (C) <NAME> <<EMAIL>> # This program is published under...
StarcoderdataPython
11826
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 17 16:12:56 2020 @author: dylanroyston """ # import/configure packages import numpy as np import pandas as pd #import pyarrow as pa import librosa import librosa.display from pathlib import Path #import Ipython.display as ipd #import matplotlib.pyp...
StarcoderdataPython
4834664
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Rdkit(CMakePackage): """RDKit is a collection of cheminformatics and machine-learning ...
StarcoderdataPython
3304893
import tweepy import wget twitter_consumer_key = "pTHQmNMSbD6BJnZ1XtA8sJXY8" twitter_consumer_secret = "<KEY>" twitter_access_token = "<KEY>" twitter_access_secret = "<KEY>" auth = tweepy.OAuthHandler(twitter_consumer_key, twitter_consumer_secret) auth.set_access_token(twitter_access_token, twitter_access_...
StarcoderdataPython
70699
# -*- coding: utf-8 -*- import scrapy from pyquery import * class SafariSpider(scrapy.Spider): name = 'safari' allowed_domains = ['oreilly.com'] # Get TOC of Book: Advanced Linux System Administration start_urls = ['https://www.oreilly.com/library/view/advanced-linux-system/9781789132748/'] def p...
StarcoderdataPython
3324084
from __future__ import annotations from typing import Optional class TreeNode: def __init__(self, val: int = 0, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None): self.val = val self.left = left self.right = right
StarcoderdataPython
147377
<reponame>vshumanov/django_task_mon from django.shortcuts import render, redirect from tasks.services import get_all_not_done_tasks, mark_task_as_done from tasks.forms import NewTaskForm def index(request): return render( request, "index.html", {"tasks": get_all_not_done_tasks(), "new_tas...
StarcoderdataPython
3265821
from talon import Module, actions, app, ctrl import os app.register("ready", lambda: actions.user.mouse_show_cursor()) default_cursor = { "AppStarting": r"%SystemRoot%\Cursors\aero_working.ani", "Arrow": r"%SystemRoot%\Cursors\aero_arrow.cur", "Hand": r"%SystemRoot%\Cursors\aero_link.cur", "Help": r"...
StarcoderdataPython
3296976
<reponame>serik1987/ihna_kozhuhov_image_analysis<filename>ihna/kozhukhov/imageanalysis/gui/synchronization/quasitimesynchronization.py # -*- coding: utf-8 import wx from ihna.kozhukhov.imageanalysis.synchronization import QuasiTimeSynchronization from .synchronization import SynchronizationEditor class QuasiTimeSyn...
StarcoderdataPython
1666064
# Runs a simple Metropolis-Hastings (ie MCMC) algoritm to simulate an # exponential distribution, which has the probability density # p(x)=exp(-x/m), where m>0. # # Author: <NAME>, 2019. # Website: hpaulkeeler.com # Repository: github.com/hpaulkeeler/posts import numpy as np; # NumPy package for arrays, random number...
StarcoderdataPython
4828985
from .models import Content, ContentLine from rest_framework import serializers class ContentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Content fields = ('id', 'type') class ContentLineSerializer(serializers.HyperlinkedModelSerializer): class Meta: model ...
StarcoderdataPython
73983
import os from setuptools import find_packages, setup from openwisp_ipam import get_version with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() def get_install_requires(): """ parse requirements.txt, ignore links, exclude comments """ requirements ...
StarcoderdataPython
1785253
<gh_stars>0 import numpy as np # Requires the following: # # thermo_style custom pe # thermo_modify line multi format float %.16g def parse_potential_from_lmp_stdout(stdout): pe_line, = [line for line in stdout.splitlines() if 'PotEng' in line] assert len(pe_line.split()) == 3 return float(pe_line.split()[...
StarcoderdataPython
26650
"""Solution for subdag_example.py. Uses a factory function to return a DAG that can be used as the subdag argument to SubDagOperator. Notice that: 1) the SubDAG's dag_id is formatted as parent_dag_id.subdag_task_id 2) the start_date and schedule_interval of the SubDAG are copied from the parent DAG. """ from airflo...
StarcoderdataPython
1669513
<gh_stars>0 # create a program that generates a random number using the random library # importing library import random as rnd print(f"random floating point {rnd.random()}") a =1 b =10 s=1 rnd.seed(s) print(f"using rnd.seed({s})") print(f"random int from {a} to {b} -> {rnd.randint(a, b)}") print(f"random int from {a...
StarcoderdataPython
9893
<gh_stars>0 #!/usr/bin/python # # Start dfplayer. import argparse import os import shutil import subprocess import sys import time _PROJ_DIR = os.path.dirname(__file__) def main(): os.chdir(_PROJ_DIR) os.environ['LD_LIBRARY_PATH'] = '/lib:/usr/lib:/usr/local/lib' arg_parser = argparse.ArgumentParser(descr...
StarcoderdataPython
1727472
<filename>pypeloton/utils.py import asyncio from functools import wraps from typing import Callable def async_to_sync(f: Callable) -> Callable: """Decorator to run async function as sync.""" @wraps(f) def wrapper(*args, **kwargs): return asyncio.run(f(*args, **kwargs)) return wrapper
StarcoderdataPython
1719525
<reponame>094459/building-data-pipelines-apache-airflow from airflow import DAG from datetime import datetime, timedelta from airflow.utils.dates import days_ago from airflow.operators.bash_operator import BashOperator from airflow.models import Variable import copy import os default_args = { 'owner': 'airflow', ...
StarcoderdataPython
3255118
<reponame>LibertyDream/algorithm_data_structure '''面试题11:旋转数组的最小数字 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。 ---------------- Example input:[3,4,5,1,2] output:1 --------------- 一旦有顺序性,最大最小值和二分查找多半会有用武之地 ''' def min_val(arr): if arr is None or len(arr) == 0: return None ret ...
StarcoderdataPython
1659876
import sys sys.stdout.buffer.write(("|\t "+ chr(9986) +" PySnipt'd " + chr(9986)+" \t|").encode('utf8')) from requests import request, ConnectionError from clients.models import Client # from mailin import mails ############### def save_profile_picture(backend, user, response, is_new, *args, **kwargs): if backend.n...
StarcoderdataPython
1603470
__all__ = ['find_replace', 'config_find_replace'] from plugins.atomio import * from core.path import register_path_prefix, user @register_path_prefix def ATOMDIR(): return user('.atom')
StarcoderdataPython
1769989
from setuptools import find_packages, setup setup( name='positron', packages=find_packages(include=['positron']), version='0.1.0', description='A blazingly fast ML library for Python', author='<NAME> (https://martinkondor.github.io)', license='MIT', install_requires=['numpy', 'pandas'], ...
StarcoderdataPython
101650
<gh_stars>0 #!/usr/bin/env python3 # vim: set fileencoding=utf-8 # Copyright © 2020, 2011 <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/LICEN...
StarcoderdataPython
1751459
<reponame>GDGSNF/PXXTF<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8 -*- # # Spaghetti: Web Server Security Scanner # # @url: https://github.com/m4ll0k/Spaghetti # @author: <NAME> (M4ll0k) # @license: See the file 'doc/LICENSE' import re from lib.net import http from lib.utils import printer from lib.net ...
StarcoderdataPython
9284
<reponame>dbinetti/captable from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(...
StarcoderdataPython
3380647
<filename>app/youtube/views.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import ( Blueprint, g, jsonify, render_template, request, ) from requests.exceptions import ( ConnectionError, HTTPError, ) from .controllers.latest_video import latest_video_func from ..utils import ( fix_url_for,...
StarcoderdataPython
1629121
from __future__ import unicode_literals from django.db import migrations, connection from bluebottle.utils.utils import update_group_permissions from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant def add_group_permissions(apps, sc...
StarcoderdataPython
3329308
from .utils import pkrTestCase class TestBaseDriver(pkrTestCase): PKR = "pkr" pkr_folder = "base_driver" kard_env = "dev" kard_driver = "base" kard_extra = {"flag": "flag_value"} def test_base_driver_values(self): self.kard_extra["src_path"] = self.src_path self.generate_kard(...
StarcoderdataPython
3224913
<filename>teste2e/test_indexing.py from .util import UrsadbTestContext, store_files, check_query, get_index_hash, UrsadbConfig from .util import ursadb # noqa import pytest def test_indexing_small(ursadb: UrsadbTestContext): store_files(ursadb, "gram3", {"kot": b"Ala ma kota ale czy kot ma Ale?"}) ursadb.ch...
StarcoderdataPython
1625144
<reponame>bakhshalipour/boost-python3-mac #!/usr/bin/env python3 import ctor c1 = ctor.Ctor("Bonjour") print (c1.greet()) c2 = ctor.Ctor(3.141592654, 1.0) print (c2.greet())
StarcoderdataPython
3248237
# Copyright The OpenTelemetry Authors # # 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 ...
StarcoderdataPython
156021
<filename>myo-emg.py # -*- coding: utf-8 -*- """ Created on Tue Aug 7 15:21:26 2018 @author: hassanyf and nabeelyousfi """ from __future__ import print_function from myo.utils import TimeInterval import myo import sys import pandas as pd # Implementing DeviceListener for EMG. class Listener(myo.DeviceListener): ...
StarcoderdataPython
79007
<reponame>kinoai/christmas_hackathon<filename>project/models/simple_mnist_classifier/models.py from torch import nn class SimpleMNISTClassifier(nn.Module): def __init__(self, hparams): super().__init__() # mnist images are (1, 28, 28) (channels, width, height) self.model = nn.Sequential(...
StarcoderdataPython
105012
<reponame>cu-swe4s-fall-2019/version-control-sahu0957<filename>calculate.py import argparse import math_lib as ml parser = argparse.ArgumentParser() parser.add_argument("numerator", help="first number to add, and numerator", type=int) parser.add_argument("denominator", help="second number to add, and denominator", typ...
StarcoderdataPython
3358721
<gh_stars>0 import torch pretrained_net = torch.load('../../experiments/pretrained_models/SRResNet_bicx2_in3nf64nb16.pth') # should run train debug mode first to get an initial model crt_net = torch.load('../../experiments/debug_SRResNet_bicx4_in3nf64nb16/models/8_G.pth') for k, v in crt_net.items(): print...
StarcoderdataPython
149012
<gh_stars>1-10 # Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import pyro.poutine.runtime from pyro.contrib.funsor.handlers.runtime import _DIM_STACK, DimRequest, DimType @pyro.poutine.runtime.effectful(type="to_funsor") def to_funsor(x, output=None, dim_to_name=None, dim_type=D...
StarcoderdataPython
4816693
<filename>shoptools/checkout/admin.py from datetime import date from django.contrib import admin from django.http import HttpResponse from django import forms from django.utils.text import mark_safe from shoptools.util import get_payment_module, get_vouchers_module from .models import Order, OrderLine, Address from ....
StarcoderdataPython
4801223
<reponame>gits00/raspberry-pi-computer-vision-programming import time import RPi.GPIO as GPIO import cv2 thresh = 127 cap = cv2.VideoCapture(0) GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) button1 = 7 button2 = 11 GPIO.setup(button1, GPIO.IN, GPIO.PUD_UP) GPIO.setup(button2, GPIO.IN, GPIO.PUD_UP) while True: ...
StarcoderdataPython
180727
from django.http import JsonResponse import time def index(request): return JsonResponse({ 'time': time.time() })
StarcoderdataPython
110761
<reponame>TanguyJeanneau/examples import torch from PIL import Image from threading import Thread import sys import cv2 from queue import Queue def load_image(filename, size=None, scale=None): img = Image.open(filename) if size is not None: img = img.resize((size, size), Image.ANTIALIAS) elif scal...
StarcoderdataPython
33781
import zope.interface class IFoldable(zope.interface.Interface): """Marker interface for a block which can be callapsed."""
StarcoderdataPython
1761347
<filename>initrd/usr/share/yum-cli/cli.py<gh_stars>1-10 #!/usr/bin/python -t # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later vers...
StarcoderdataPython
1718434
import os import sys import json import random from random import choice from jinja2 import Environment, select_autoescape, FileSystemLoader TOPOLOGY_PATH = "MulVAL_P/" GENERATION_TOPOLOGY_TEMPLATE = "topology_template.P" GENERATION_TOPO_GEN_TEMPLATE = "topo_gen_template.P" env = Environment(loader=FileSystemLoader('....
StarcoderdataPython
3361665
''' This example shows how the mutual exclusion works. The agent periodically prints messages in the screen. ''' from pade.behaviours.types import CyclicBehaviour from pade.core.agent import Agent from pade.misc.utility import display, start_loop import threading class MutualExclusionAgent(Agent): def setup(self): ...
StarcoderdataPython
4840057
from ml4ir.base.model.scoring.scoring_base import ScoringBase class PairwiseScoring(ScoringBase): def get_scoring_fn(self, **kwargs): """ Define a pointwise ranking scoring function with specified architecture """ def _scoring_fn(features): raise NotImplementedError ...
StarcoderdataPython
4828647
<gh_stars>1-10 #coding:utf-8 from myhdl import Signal,intbv, delay, instance,instances, always,now,Simulation,traceSignals,toVerilog import random #24-31 is not use #16-23 is opcode #8-15 is ope1 #0-7 is ope2 #xxxxxxxx b00000001 xxxxxxxxx xxxxxxx:add #xxxxxxxx b00000010 xxxxxxxxx xxxxxxx:sub #xxxxxxxx b00000011 xxxxxx...
StarcoderdataPython
3384870
from pgvbotLib import * import pywikibot from copy import deepcopy #from sys import argv import re, sys, os from pywikibot.exceptions import NoPageError from arywikibotlib import isHuman, hasPropertyXValue RECENT_LOG_FILE = "recent_log.txt" def load_pages_in_log(): if not os.path.exists(RECENT_LOG_FILE): ...
StarcoderdataPython
62508
<reponame>tdosreis/statistical-arbitrage<filename>src/statistical_arbitrage.py import numpy as np from statsmodels.tsa.stattools import adfuller from sklearn.linear_model import LinearRegression class Cointegrate(): def __init__(self, x, y): self.x = x self.y = y def regression...
StarcoderdataPython
24995
# Generated by Django 3.2.9 on 2021-11-13 14:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0005_authquery_password'), ] operations = [ migrations.AddField( model_name='profile', name='h...
StarcoderdataPython
3267045
from decimal import Decimal from django.contrib.gis.geos import Point import factory class UserFactory(factory.DjangoModelFactory): email = factory.Faker('email') password = factory.PostGenerationMethodCall('set_password', '<PASSWORD>') class Meta: model = 'users.User' class GameFactory(facto...
StarcoderdataPython
1730835
<gh_stars>1-10 class Solution(object): def checkIfExist(self, arr): """ :type arr: List[int] :rtype: bool """ sa = set() for a in arr: if 2 * a in sa or (a % 2 == 0 and a // 2 in sa): return True sa.add(a) return False ...
StarcoderdataPython
3207422
<gh_stars>0 import planckStyle as s import pylab as plt g = s.getSinglePlotter() g.settings.param_names_for_labels = 'clik_Hunits.paramnames' updated = True legacy = False if updated: g.add_y_bands(74.03, 1.42) g.add_text_left('Riess et al. (2019)', 0.03, 0.8, color='k', fontsize=7) else: g.add_y_bands(7...
StarcoderdataPython
1677867
<gh_stars>0 from setuptools import setup setup(name='inherit', entry_points={ 'console_scripts': [ 'inherit=inherit.inherit:main', ], }, version='0.0.3', description='', url='https://github.com/ke-zhang-rd/inherit.git', author='<NAME>', author_email...
StarcoderdataPython
3259235
<gh_stars>0 import cv2 import numpy as np import matplotlib as plt import os FACE_DETECTOR_PATH = r"{base_path}/haarcascades/haarcascade_frontalface_alt.xml".format( base_path=os.path.abspath(os.path.dirname(__file__))) EYE_DETECTOR_PATH = r"{base_path}/haarcascades/haarcascade_eye.xml".format( base_path=os.path.absp...
StarcoderdataPython
36893
import os from os.path import join, isfile, isdir, dirname, basename from os import environ, makedirs import sys import argparse import numpy as np import h5py from scipy import misc from keras import backend as K import tensorflow as tf from pspnet import PSPNet50 import utils from utils import image_utils from util...
StarcoderdataPython
3278060
<gh_stars>1-10 """Generic ANOVA .. helpdoc:: Performed ANOVA on any model or data received. This can result in errors if inappropriate models are supplied. """ """<widgetXML> <name> Generic ANOVA </name> <icon> default.png </icon> <summary> Performed ANOV...
StarcoderdataPython
30050
<reponame>david26694/sktools #!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['scikit-learn', 'pandas', 'scipy...
StarcoderdataPython
181013
import requests import json def read_province(): with open("./province.json", "r") as json_file: data = json.load(json_file) return data def transform_data(): data = read_province() for i, item in enumerate(data): item["description"] = "" item["displayOrder"] = i + 1 ...
StarcoderdataPython
1788739
# coding=utf-8 from __future__ import unicode_literals from tornado.web import URLSpec class urlpattens(object): """ 提供形如Django的树形url结构 urls = urlpattens('user', [ ("/login/,LoginHandler), ("/callback,CallbackHandler), ] ) TODO:只有一层的节点 """ def new_u...
StarcoderdataPython
95692
import FWCore.ParameterSet.Config as cms hcalNoiseRates = cms.EDAnalyzer('HcalNoiseRates', # outputFile = cms.untracked.string('NoiseRatesRelVal.root'), outputFile = cms.untracked.string(''), rbxCollName = cms.untracked.InputTag('hcalnoise'), minRBXEnergy = cms.untracked.double(20.0), minHitEne...
StarcoderdataPython
4820892
from __future__ import unicode_literals from bs4 import BeautifulSoup import requests import os from Models import Episode, Program, Channel class Parser(object): def __init__(self, baseUrl, url): self.__baseUrl = baseUrl self.__url = url.strip() @property def baseUrl(self): ...
StarcoderdataPython
3228154
<filename>src/code-challenges/codewars/7KYU/validatePin/validate_pin.py # https://www.codewars.com/kata/55f8a9c06c018a0d6e000132/train/python # ATM machines allow 4 or 6 digit PIN codes and PIN codes # cannot contain anything but exactly 4 digits or # exactly 6 digits. # If the function is passed a valid PIN strin...
StarcoderdataPython
67404
<gh_stars>0 # namespace declaration __import__("pkg_resources").declare_namespace(__name__)
StarcoderdataPython
1761192
<gh_stars>0 import unittest from ladygeek.graph.client import get_graph_url from ladygeek.graph.entities import User from py2neo import Graph class TestUser(unittest.TestCase): USER_DATA = {'contributors_enabled': False, 'created_at': 'Fri Jun 12 11:13:21 +0000 2009', 'default_p...
StarcoderdataPython
4819067
#!/usr/bin/python """ Python implementation of the icc method implemented originally by <NAME> in MATLAB from <NAME>, <NAME>. Agreement and reliability statistics for shapes. PLoS One. 2018; 13(8):e0202087. Published 2018 Aug 23. doi:10.1371/journal.pone.0202087 and extended to include F-Value and lower and uppe...
StarcoderdataPython
1686763
from dataclasses import dataclass @dataclass(frozen=True) class Radio: wifi_hw: bool wifi: bool wwan_hw: bool wwan: bool def to_json(self): return { 'wifi_hw': self.wifi_hw, 'wifi': self.wifi, 'wwan_hw': self.wwan_hw, 'wwan': self.wwan ...
StarcoderdataPython
40112
''' Created on May 28, 2018 @author: nishant.sethi ''' import math mean_x=0.88 mean_y=1.55 result_x=160+40*(mean_x+mean_x**2) result_y=128+40*(mean_y+mean_y**2) print(round(result_x,3)) print(round(result_y,3))
StarcoderdataPython
1774178
import copy from six.moves import http_client from drift.systesthelper import DriftBaseTestCase class ServersTest(DriftBaseTestCase): """ Tests for the /servers service endpoints """ def test_access(self): self.auth() resp = self.get("/servers", expected_status_code=http_cli...
StarcoderdataPython
4821845
from flask import Blueprint, jsonify, request from graphene import ObjectType, String, Schema import requests graphql_api = Blueprint('graphql_api', __name__) class Query(ObjectType): # this defines a Field `hello` in our Schema with a single Argument `name` hello = String(name=String(default_value="stranger"...
StarcoderdataPython