id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3396690
<gh_stars>0 import string import time def showShip(displayName): # This block has a lot of the code we've looked at. Try to # see if you can understand how and why it makes the choices it does. # # Why pick 20 to subtract from? Then why 21 later? # Are those the correct numbers? # Why ...
StarcoderdataPython
56023
"""handle requests relative to mu-calculus checking""" from flask import Blueprint, Response, request import json from base.webserver_utils import apply_on_node import flex from flex.loading.schema.paths.path_item.operation.responses.single.schema\ import schema_validator import os import subprocess mu_blueprin...
StarcoderdataPython
1674441
<reponame>linkdew/ida-labs<gh_stars>0 import matplotlib.pyplot as plt import numpy as np def setIntValue(value): while not isinstance(value, int): try: value = int(input()) if value < 1: while value < 1: print("Enter positive integer value: ", en...
StarcoderdataPython
1640838
# Generated by Django 3.0.7 on 2020-06-10 11:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Hashcat', '0002_auto_20200610_1150'), ] operations = [ migrations.AlterField( model_name='hash', name='hash', ...
StarcoderdataPython
194258
<filename>src/modules/hunting/certificates.py from ...core.types import Hunter, KubernetesCluster, InformationDisclosure from ...core.events import handler from ...core.events.types import Vulnerability, Event, Service import ssl import logging import base64 import re from socket import socket email_pattern = re.com...
StarcoderdataPython
1785267
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2021-12-06 # @Filename: acquire.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) from __future__ import annotations from functools import partial from typing import TYPE_CHECKING import click from cher...
StarcoderdataPython
4815851
import json from six import text_type as str from . import DictSource class JSONFile(DictSource): def __init__(self, jsonfilename=None, writable=True, **kwargs): """Loads and optionally saves configuration files in JSON format. Since JSON has some support for typed values (supports numbe...
StarcoderdataPython
3347164
import unittest from datetime import timedelta from display_timedelta import display_timedelta class CheckVersionTest(unittest.TestCase): def testAllFour(self): self.assertEqual("4 days, 3 hours, 5 minutes, and 2 seconds", display_timedelta(timedelta(days=4, hours=3, minutes=5, ...
StarcoderdataPython
1775369
<filename>sqlconfig/tests/tests.py import tempfile import unittest from ..lib import load, dump import os class RoundtripTest(unittest.TestCase): def compare_dirs(self, expected, received): expected_files = set(os.listdir(expected)) received_files = set(os.listdir(received)) self.assertEqual(expected_fil...
StarcoderdataPython
32946
<reponame>ActionAnalytics/mds import base64 import requests from werkzeug.exceptions import BadRequest, NotFound from flask import request, current_app, Response from flask_restplus import Resource from app.extensions import api from ...mine.models.mine import Mine from ....documents.mines.models.mine_document import...
StarcoderdataPython
1794015
<filename>lib/view.py #!/usr/bin/env python3 # pylint: disable=no-member, too-many-branches, too-many-locals, too-many-statements, broad-except """ Generate plots using BlobToolKit Viewer. Usage: blobtools view [--format STRING...] [--host STRING] [--interactive] [--out PATH] [--param STRING...] [--ports RANGE] ...
StarcoderdataPython
1789933
import pytest import os from src.syn_reports.commands.user_project_access_report import UserProjectAccessReport @pytest.fixture(scope='session') def syn_user(syn_client): return syn_client.getUserProfile(os.environ.get('SYNAPSE_USERNAME')) def assert_user_success_from_print(capsys, *users): captured = capsy...
StarcoderdataPython
3244155
import pytest from uuid import UUID, uuid4 from domains.user.user import User @pytest.fixture(scope="class") def set_fields() -> (UUID, str, str, str, str, str): id = uuid4() nickname = "nickname" first_name = "first_name" last_name = "last_name" email = "<EMAIL>" password = "password" re...
StarcoderdataPython
4274
<gh_stars>1-10 """ Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test. These are the examples that are distributed with MODFLOW-USG. """ import os import flopy # make the working directory tpth = os.path.join("temp", "t038") if not os.path.isdir(tpth): os.makedirs(tpth) # build list of na...
StarcoderdataPython
1757066
import datetime import decimal import logging import uuid import warnings from django.conf import settings from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.base.client import BaseDatabaseClient from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends...
StarcoderdataPython
3229188
import glob import os files = glob.glob(os.path.join('D*')) files.sort() print ('editing \n',len(files),' of files\n ',files) for idx,fil in enumerate(files): print (fil[:2]) with open(fil) as data: lines = data.readlines() new_file = open(fil,'w') for i, line in enumerate(lines): new_line = line if i == 1...
StarcoderdataPython
3202658
from sys import getsizeof import os import multiprocessing def map(func, items, ordered=False): pool = multiprocessing.Pool(processes=_get_core_count()) items = list(items) chunk_size = _calculate_chunk_size(items) map_function = pool.imap if ordered else pool.imap_unordered return map_function(fun...
StarcoderdataPython
3245320
import torch from torchtext.vocab import build_vocab_from_iterator from sentiment_anomaly.db import session from sentiment_anomaly.vectors import CommentsWords def train_torch_vocab(vectors=None, dim=50): """ Build a Vocab for use with pytorch With vectors generated by CoreNLP GloVe as below dimension...
StarcoderdataPython
3362351
<gh_stars>1-10 from panel.pane import Perspective data = { 0: ['1981 01 01 00 161 28 10173 270 21 0 0 0', '1981 01 01 01 111 33 10175 270 21 0 0 -9999', '1981 01 01 02 111 39 10183 330 26 0 0 -9999', '1981 01 01 03 94 39 10192 ...
StarcoderdataPython
1659067
<reponame>kurpenok/Labs<filename>2 semester/PW/Coursera/Python/3 Week/6.py p = int(input()) x = int(input()) y = int(input()) money = x * 100 + y money += money * (p / 100) print(int(money // 100), int(money % 100))
StarcoderdataPython
3248918
<filename>plugins/fileSize.py # fileName : plugins/fileSize.py # copyright ©️ 2021 nabilanavab #---------------> #--------> SIZE FORMATER (TO HUMAN READABLE FORM) #-------------------> async def get_size_format( b, factor=2**10, suffix="B" ): for unit in ["", "K", "M", "G", "T"]: if b < factor: ...
StarcoderdataPython
1754663
# # 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, Version 2.0 (the # "License"); you m...
StarcoderdataPython
3203331
class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: heap_size = len(nums) self.buld_max_heap(nums, heap_size) if k > len(nums): return nums[0] for _ in range(0, k-1): nums[0], nums[heap_size-1] = nums[heap_size-1], nums[0] hea...
StarcoderdataPython
3390301
import os from ast import NodeVisitor, parse from io import StringIO class YieldSearch(NodeVisitor): def visit_Yield(self, node): self.has_yield = True def visit_FunctionDef(self, node): pass # do not visit nest function definition to determine # if a function has a yield or n...
StarcoderdataPython
3293240
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() with open("requirements.txt", "r") as fh: requirements = fh.readlines() setup( name="scpscraper", packages=['scpscraper'], version="1.0.1", license="MIT", author="JaonHax", ...
StarcoderdataPython
4992
<filename>sdk/videoanalyzer/azure-mgmt-videoanalyzer/azure/mgmt/videoanalyzer/models/_models.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root fo...
StarcoderdataPython
3276916
# Generated by Django 3.0.7 on 2020-07-29 17:10 import django.contrib.sites.managers from django.db import migrations import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('permafrost', '0011_auto_20200506_2128'), ] operations = [ migrations.AlterModel...
StarcoderdataPython
3351854
<filename>candle/parsing_utils.py from __future__ import absolute_import import argparse import os import sys import warnings from pprint import pprint import numpy as np if sys.version_info >= (3, 8): from typing import TypedDict # pylint: disable=no-name-in-module else: from typing_extensions import Typed...
StarcoderdataPython
4807515
<reponame>baikov/allflags # Generated by Django 3.1.8 on 2021-10-18 19:58 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('flags', '0061_auto_20211018_2227'), ] operations = [ migrations.AddField( ...
StarcoderdataPython
3334606
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filer.fields.image import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('filer', '0002_auto_20150606_2003'), ] operations = [ migrations.C...
StarcoderdataPython
3224062
<gh_stars>0 import requests class GitRepository: GITHUB_API_URL = "https://api.github.com" def __init__(self, repo_name, access_token): self.repo_name = repo_name self.access_token = access_token def retrieve_change_commits(self, since, until): request_uri = f"{self.GITHUB_API_UR...
StarcoderdataPython
1600722
from benchmarks.htap.lib.controller import HTAPController def add_parser(subparsers): parser = subparsers.add_parser('htap') parser.add_argument( '--oltp-workers', default=32, type=int, help=( 'The number of OLTP workers executing TPC-C-like transactions (i.e. simulated clients), default: 32.'...
StarcoderdataPython
3233412
<filename>client.py # -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: client Description : ^_^ !!! Author : anglemiku Eamil : <EMAIL> date: 2019-09-09 ------------------------------------------------- Change Activity: 20...
StarcoderdataPython
1614090
import os.path as path from pathlib import Path from dslib.helpers import replace_csv_header def create_path(p, reference=__file__): ref = Path(path.abspath(reference)) return Path( ref.parent if ref.is_file() else ref, p ) def create_data_file(data, header): """Create CSV file wit...
StarcoderdataPython
3320226
<reponame>KesleyK/projeto-redes-unb2020<filename>exemplos-aulas/sockets/client/ip_resolve.py<gh_stars>1-10 import socket ip = "192.168.3.11" dn = socket.gethostbyaddr(ip) print(dn[0])
StarcoderdataPython
1796499
<filename>bot.py # Реализация бота, который проводит исследовательское тестирование приложения # TODO: # > реализовать класс фильтров # > реализовать получение списка элементов через getEventListeners (ищем элементы, которые в # теории отреагируют на наше действие) # > реализовать получение списка элементов ч...
StarcoderdataPython
4809001
<filename>scrapy_plus/project_dir/spiders_middlewares.py<gh_stars>1-10 class BaiduMiddleware: def process_request(self, request): '''处理请求头,添加默认的user-agent''' print("BaiduMiddleware: process_request") return request def process_response(self, response): '''处理数据对象''' pr...
StarcoderdataPython
34135
<reponame>theblueskies/prose import os from newspaper import Article url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/' article = Article(url) article.download() article.parse() with open(os.path.join('testdata', 'article.txt'), 'w') as f: f.write(article.text)
StarcoderdataPython
3340836
<gh_stars>1-10 import os import shutil caminho_original = r'C:\Users\Gustavo\Desktop\Legendas temp' caminho_novo = r'C:\Users\Gustavo\Desktop\Legendas temp criada Python' try: os.mkdir(caminho_novo) except FileExistsError as error: print(f'A pasta {caminho_novo} já existe.') for root, dirs, files in os.walk...
StarcoderdataPython
1688788
<filename>source/AI/KI_versions/multiAgent.py<gh_stars>0 # stable baselines from stable_baselines3 import A2C, PPO from stable_baselines3.common.env_util import make_vec_env # threading import threading from threads.socketHandler import * # import env import KI_v01 # important # other import os class KI(): d...
StarcoderdataPython
3298054
<gh_stars>0 """This module implements helper methods for generating docs.""" from __future__ import annotations import os def building_docs() -> bool: """Return true if currently building documentations.""" if 'READTHEDOCS' in os.environ: return True if '__SPHINX_BUILD__' in os.environ: ...
StarcoderdataPython
1683093
from rest_framework import viewsets, permissions from .models import SiteDatingProfile from .serializers import SiteDatingProfileSerializer from .paginators import DatingProfilePagination class SiteDatingProfileModelViewSet(viewsets.ModelViewSet): queryset = SiteDatingProfile.objects.all() serializer_class =...
StarcoderdataPython
3260179
<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # # Import Libraries # In[23]: #Importing and Installing Required Modules and Libraries get_ipython().system('pip install tensorflow') get_ipython().system('pip install basic_image_eda') import os import pandas as pd import numpy as np import matplotlib.pyplot as pl...
StarcoderdataPython
3288637
from glob import glob from pippi import dsp def fetch(): samps = glob('samples/wes/*.wav') return dsp.read(dsp.randchoose(samps)).data def make(length): return dsp.fill(fetch(), length)
StarcoderdataPython
3209632
from unittest.mock import patch from athenian.api.hacks.show_email import main def test_show_email(capsys): with patch("sys.argv", ["show_sql.py", "af253b50a4d7b2c9841f436fbe4c635f270f4388653649b0971f2751a441a556fe63a9dabfa150a444dd"]): # noqa main() assert capsys.readouterr().out == "<EMAIL>\n"
StarcoderdataPython
138077
<reponame>UBCS-LCP/auxiliary from numpy import zeros, array_equal from ubcs_auxiliary import save_object, load_object def test_save_load(tmpdir): arr_in = zeros((10,5)) str_in = 'this is string' dict_in = {'1':1,'2':2} list_in = [1,2,3,4] compound_in = {} compound_in['arr'] = arr_in compou...
StarcoderdataPython
109692
import random from discord.ext import commands import discord from cogs.menus import Menus def get_role(guild): return discord.utils.get(guild.roles, name='Giveaway') async def get_entrants(guild, remove=True): role = get_role(guild) entrants = [] for m in guild.members: if role in m.roles...
StarcoderdataPython
3370047
<gh_stars>1-10 from django.utils.translation import gettext_lazy as _ from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from db.models import SoftSkill from .permissions import ValidationPermissionHelper class SoftSkillAdmin(ModelAdmin): model = SoftSkill menu_label = _('Soft Ski...
StarcoderdataPython
115144
from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from .views import ( MapSettingsView, OverlayMetaView, OverlayList, ) urlpatterns = [ url(r'^$', OverlayList.as_view(), name='overlay-list'), url(r'^metadata/$', OverlayMetaView.as_view(), name='o...
StarcoderdataPython
12190
<filename>tests/data/program_analysis/PyAST2CAST/import/test_import_3.py # 'from ... import ...' statement from sys import exit def main(): exit(0) main()
StarcoderdataPython
133094
<gh_stars>1-10 """Unit testing for the application's modules."""
StarcoderdataPython
1661052
#!-*-encoding:UTF-8-*- import socket import msvcrt from os import system import ctypes ctypes.windll.kernel32.SetConsoleTitleA("LED kijelzo") HOST = '192.168.0.1' PORT = 23 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Socket successfully created" except socket.error as err: print ...
StarcoderdataPython
1771790
from app import create_app,db from flask_script import Manager,Server from app.models import User,Post,Comment from flask_migrate import Migrate,MigrateCommand #creating app instance app = create_app('development') manage = Manager(app) migrate = Migrate(app,db) manage.add_command('db',MigrateCommand) manage.add_comm...
StarcoderdataPython
35838
<filename>shrike/pipeline/telemetry_utils.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging from opencensus.ext.azure.log_exporter import AzureLogHandler log = logging.getLogger(__name__) class TelemetryLogger: """Utils class for opencensus azure monitor""" def __in...
StarcoderdataPython
80042
"""Tests that basis kets are working properly""" import Python.density_matrix as DM import Python.measurements as mes class TestMeasurements: """ Testing that measurements produce the expected results. """ def test_temp(self): """Tests the creation of a simple ket and validates its properties...
StarcoderdataPython
3241078
from django import template from django.forms.fields import MultipleChoiceField from copy import copy from wagtail.core.models import Page from molo.surveys.models import ( MoloSurveyPage, SurveysIndexPage, PersonalisableSurvey) from molo.core.templatetags.core_tags import get_pages from django.shortcuts import g...
StarcoderdataPython
1786649
# Author: <NAME> # Collaborators: Prof. <NAME>, Prof. <NAME>, Dr. <NAME> # Email : <EMAIL>/<EMAIL> # Affiliation : Imperial Centre for Inference and Cosmology # Status : Under Development ''' Setup for the redshift distributions ''' import numpy as np import scipy.stats as ss # our scripts import settings as st cl...
StarcoderdataPython
3331061
x=input("enter name:") for i in range (0,len(x)): print(x[i],i)
StarcoderdataPython
4806562
#! /usr/bin/env python3 from aksetup_helper import configure_frontend configure_frontend()
StarcoderdataPython
3235800
<filename>lecture_13.py # -*- coding: utf-8 -*- __author__ = 'wnduan' # def fib(n): # global numCalls # numCalls += 1 # # print 'Call fib with', n # if n <= 1: # return 1 # else: # return fib(n-1) + fib(n-2) # # numCalls = 0 # print fib(30) # print 'Number of calls:', numCalls # # d...
StarcoderdataPython
174537
<reponame>andkononykhin/plenum<gh_stars>100-1000 from common.serializers.json_serializer import JsonSerializer def testJsonSerializer(): sz = JsonSerializer() m1 = {'integer': 36, 'name': 'Foo', 'surname': 'Bar', 'float': 14.8639, 'index': 1, 'index_start_at': 56, 'email': '<EMAIL>', 'full...
StarcoderdataPython
80654
<gh_stars>0 """ Welcome The User To Masonite """ from masonite.request import Request from masonite.view import View from events import Event from app.League import League from masonite import Broadcast class WelcomeController: """ Controller For Welcoming The User """ def __init__(self, view: View, request:...
StarcoderdataPython
1729484
<gh_stars>0 from .abstract_auto import AbstractAuto class Nano(AbstractAuto): def start(self): print("Nano started") def stop(self): print("Nano stopped")
StarcoderdataPython
4830584
import numpy as np from libs.kernel import Kernel from libs.optimizer import Optimizer ### class SVM(): def __init__(self, kernel='linear', C=None, deg=None): self._kernel = None self._kernel_type = kernel self._kernel_function = None self._multipliers = None self._lambd...
StarcoderdataPython
4833776
# uid.py - functions for handling Swiss business identifiers # coding: utf-8 # # Copyright (C) 2015 <NAME> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the Li...
StarcoderdataPython
1711184
from blockchain import * def main(): bc = Blockchain([]).new_blockchain() bc.add_block("Send 1 BTC to Ivan") bc.add_block("Send 2 more BTC to Ivan") for block in bc.blocks: print("Prev. hash: %s\n" % (block.PrevBlockHash), type(block.PrevBlockHash)) print("Data: %s\n" % (block.Data)) print("Hash:...
StarcoderdataPython
1727564
from django.urls import path from . import views urlpatterns = [ # Run data mining path('get-driving-features', views.GetDrivingFeatures.as_view()), path('get-driving-features-epsilon-moea', views.GetDrivingFeaturesEpsilonMOEA.as_view()), path('get-driving-features-with-generalization', views.GetDrivi...
StarcoderdataPython
41471
import gi import ctypes as pyc from ctypes import pythonapi from gi.repository import GObject as GO pyc.cdll.LoadLibrary('libgobject-2.0.so') lego = pyc.CDLL('libgobject-2.0.so') lego.g_type_name.restype = pyc.c_char_p lego.g_type_name.argtypes = (pyc.c_ulonglong,) pythonapi.PyCapsule_GetName.restype = pyc.c_char_p pyt...
StarcoderdataPython
116056
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured try: from edw.models.related.entity_image import EntityImageModel EntityImageModel() # Test pass if model materialized except (ImproperlyConfigured, ImportError): pass else: from .u...
StarcoderdataPython
3207324
<reponame>cffbots/ewatercycle # -*- coding: utf-8 -*- """Documentation about ewatercycle_parametersetdb""" from typing import Any from ewatercycle.parametersetdb.config import CONFIG_FORMATS, AbstractConfig from ewatercycle.parametersetdb.datafiles import DATAFILES_FORMATS, AbstractCopier class ParameterSet: def...
StarcoderdataPython
3213403
from django.conf.urls import url from django.views.generic import TemplateView from .views import ( sponsor_apply, sponsor_add, sponsor_list, sponsor_zip_logo_files, sponsor_detail, sponsors_by_level_json, sponsors_json, individual_sponsors_json ) urlpatterns = [ url(r"^$", sponsor...
StarcoderdataPython
4827814
from app.database.base_class import Base from app.models.product import product
StarcoderdataPython
810
<filename>framework/database/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- import functools import httplib as http import markupsafe from django.core.paginator import Paginator from django.db.models import Q, QuerySet from framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted...
StarcoderdataPython
3306808
from SublimeLinter.lint import Linter from SublimeLinter.lint.linter import PermanentError from threading import Lock import os import sublime import logging import requests import time import subprocess logger = logging.getLogger('SublimeLinter.plugin.checkstyle') lock = Lock() CURRENT_LATEST_CS_VERSION = None DOWN...
StarcoderdataPython
3398596
<filename>save4life/settings.py<gh_stars>0 from __future__ import absolute_import """ Django settings for save4life project. Generated by 'django-admin startproject' using Django 1.10.1. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and t...
StarcoderdataPython
3269342
from django.test import TestCase from django.core.urlresolvers import reverse from utils.auth_tokens import new_auth_token import json # Create your tests here. class GetPricesTestCase(TestCase): def test_missing_exchange(self): """When there is no 'exchange' parameter, an error should be return...
StarcoderdataPython
3232525
<gh_stars>0 """Routes for logged-in application.""" from flask import Blueprint, redirect, jsonify, request, render_template from datetime import date, timedelta, datetime from databases.models import Users, Funnels, Sku, Parentsku, Quantities, Sales, Emails, Notifs, SuppressedEmails import smtplib, ssl from email.mim...
StarcoderdataPython
70877
from rknn.api import RKNN class RKNN_model_container(): def __init__(self, model_path, target=None, device_id=None) -> None: rknn = RKNN() # Direct Load RKNN Model rknn.load_rknn(model_path) print('--> Init runtime environment') if target==None: ret = rknn.ini...
StarcoderdataPython
3264763
from django.contrib.postgres.fields import JSONField from django.db import models class ContentType(models.Model): slug = models.CharField(max_length=100, unique=True) format = models.CharField(max_length=100, unique=True) def __str__(self): return "{} : {}".format(self.slug, self.format) class...
StarcoderdataPython
3337322
<filename>src/lock_peak.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Program: Lock the peaks at same energy location Version: 20210219 @author: <NAME> (GitHub: @pranabdas) data = suv.lock_peak(data, refdata, x1='', x2='', E_col=0, I_col=9, I0_col=4) """ def lock_peak(data, refdata, x1='', x2='', E_...
StarcoderdataPython
100788
<reponame>saneletm/sample_chat_app<filename>lib/server/client.py """ This is a server implementation of a chat app This is only safe to use on the same machine (as in run both the server and client on the same machine) Further cleanup would need to be done to support real clients on different machines (as of Jan 4 2019...
StarcoderdataPython
3225325
<reponame>anderson-attilio/runbook ###################################################################### # Cloud Routes Web Application # ------------------------------------------------------------------- # Forms Class ###################################################################### from wtforms import Form fr...
StarcoderdataPython
3324457
<reponame>praekeltfoundation/mc2 # models go here
StarcoderdataPython
3201552
<reponame>YangXiaoo/NoteBook<gh_stars>10-100 def solver(N, K, bins): orig = [0 for _ in range(N)] mat = [[-1 for _ in range(N + K -1)] for _ in range(K)] # print(mat) for i in range(N): curValue = [] for r in range(K): if mat[r][i] != -1: curValue.append(mat[r...
StarcoderdataPython
3343493
<gh_stars>10-100 """app: handle requests.""" from typing import Dict, Tuple import typing.io import json from lambda_proxy.proxy import API app = API(name="app", debug=True) @app.get("/", cors=True) def main() -> Tuple[str, str, str]: """Return JSON Object.""" return ("OK", "text/plain", "Yo") @app.get(...
StarcoderdataPython
3225422
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('locations', '0001_initial'), ] operations = [ migrations.AddField( model_...
StarcoderdataPython
1799726
from FluGibson.nucleotide_protein_converter import NucleotideProteinConverter from Levenshtein import distance from Bio import SeqIO from Bio.Alphabet import DNAAlphabet, ProteinAlphabet import os import pytest package_directory = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(package_directory, 'tes...
StarcoderdataPython
1791632
import claripy from ..shellcode import Shellcode class X86SetRegister(Shellcode): os = ["cgc", "unix"] arches = ["X86"] name = "setregister" codes = { 'eax': [b"\xb8", b"\xbb", b"\xff\xe3"], 'ebx': [b"\xbb", b"\xb8", b"\xff\xee"], 'ecx': [b"\xb9", b"\xbb", b"\xff\...
StarcoderdataPython
1667682
from functools import wraps import tracer_deco from app_tree import App, UnfinishedLeaf, Leaf, UNFINISHED_APP # # Nested Monte Carlo Search # # adapted from: # <NAME>: Monte-carlo expression discovery. # International Journal on Artificial Intelligence Tools 22.01 (2013): 1250035. APA <EMAIL>(force_...
StarcoderdataPython
1601021
''' Pretty print: python3 -m json.tool < some.json ''' import json import argparse import os import numpy as np import cv2 import matplotlib.pyplot as plt def load_json(data_path, jsfile): with open(os.path.join(data_path, jsfile), 'r') as f: js = json.load(f) return js def generate_dataset(arg...
StarcoderdataPython
3250196
#!/usr/bin/env python3 import re def merge_intervals(intervals): # make sure they are sorted by first element removing need to compare. # intervals[i][0] <= intervals[i+1][0] after sort intervals.sort(key=lambda interval: interval[0]) result = [intervals[0]] for current in intervals: previ...
StarcoderdataPython
4813878
file = open("c:\myfile.txt", "r") print(file.read())
StarcoderdataPython
1613446
from typing import Type, TypeVar from eth_typing import BLSSignature from eth_utils import humanize_hash from ssz.hashable_container import HashableContainer from ssz.sedes import bytes32, bytes96, uint64 from eth2.beacon.constants import EMPTY_SIGNATURE from eth2.beacon.typing import ( Root, Slot, Valida...
StarcoderdataPython
4831794
<reponame>tychoish/mongo-python-driver # Copyright 2011-2012 10gen, 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 ...
StarcoderdataPython
55607
<filename>ception/articles/urls.py<gh_stars>1-10 from django.conf.urls import patterns, url urlpatterns = patterns('ception.articles.views', url(r'^$', 'articles', name='articles'), url(r'^write/$', 'write', name='write'), url(r'^preview/$', 'previe...
StarcoderdataPython
3283608
<reponame>Kedyn/SpaceInvaders class Scene: """Game scene template.""" def __init__(self, director): self.director = director def keydown(self, key): pass def keyup(self, key): pass def mousebuttondown(self, button, position): pass def reset(self): pas...
StarcoderdataPython
3354061
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import numpy as np from sklearn.metrics.cluster import (contingency_matrix, normalized_mutual_info_score) from sklearn.metrics import (precision_score, recall_score) __all__ = ['pairw...
StarcoderdataPython
3318834
import logging from dataclasses import dataclass from typing import Any, Dict, List, Union from ideal_learning_env.defs import ILEConfigurationException, ILEException from ideal_learning_env.numerics import MinMaxFloat from .choosers import choose_random from .components import ILEComponent from .decorators import il...
StarcoderdataPython
3218650
"""Zookeeper status interface.""" import socket import logging import click import kazoo import websocket as ws_client from treadmill import cli from treadmill import context from treadmill import admin from treadmill import restclient from treadmill import zknamespace as z _LOGGER = logging.getLogger(__name__) ...
StarcoderdataPython
3226328
""" Copyright 2019 Southern California Edison Copyright 2019 Pacific Gas and Electric Company ALL RIGHTS RESERVED """ import uuid try: import urlparse except ImportError: import urllib.parse as urlparse import json import requests class GlobalSettings: name = "PacketCap" SNIFFER_INTERFACE = "en4" ...
StarcoderdataPython