id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3303918
import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning import sys def main(): print("Simple F5 Vulnerablity Scanner by @TheCyberViking and Anon-Researcher") print("This is for scanning f5 BIG-IP aka CVE-2020-5902") print("This is in attempt to scan without compr...
StarcoderdataPython
3380619
import numpy as np import matplotlib.pyplot as plt import imageio data = np.loadtxt("adveccion.dat") print(np.shape(data)) n_times = np.shape(data)[0] x = np.linspace(0.0, 1.0, np.shape(data)[1]) t = np.linspace(0.0, 2.0, np.shape(data)[0]) for i in range(n_times): print(i, n_times) filename = "snap_{}.png"....
StarcoderdataPython
3340338
# Copyright (c) 2019 Beta Five Ltd # # SPDX-License-Identifier: Apache-2.0 # """Example code using the subtest decorator.""" import os import sys import unittest # Expect to find betatest in the working directory when running these examples # pylint: disable=wrong-import-position sys.path.insert(0, os.getcwd()) from...
StarcoderdataPython
3349694
from ssh2net.core.cisco_iosxe.driver import IOSXEDriver my_device = {"setup_host": "172.18.0.11", "auth_user": "vrnetlab", "auth_password": "<PASSWORD>"} iosxe_driver = IOSXEDriver with IOSXEDriver(**my_device) as conn: output = conn.send_command("show version") # send_inputs returns a list of results; print...
StarcoderdataPython
63233
import logging from .utils.plugins import Plugins, Proxy from .utils.decos import GenLimiter from typing import Iterator class ProxyQuery(Plugins): """Handles the querying and operations of plugins""" @GenLimiter def exec_iter_plugin(self, method_name: str, sort_asc_fails: bool = True, *args, **kwargs) -...
StarcoderdataPython
1786968
<filename>app/api/api_interface.py from abc import ABC, abstractmethod class ApiInterface(ABC): """ This interface is dedicated for modules processing image dataset annotations. Every annotation reader object, which implements these functions, should work properly within the app. Object implementing t...
StarcoderdataPython
4841984
# Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # Imports from this application from app import app # 1 column layout # https://dash-bootstrap-components.opensource...
StarcoderdataPython
35305
<filename>mrobpy/examples/vis_utils.py import numpy as np import pandas as pd import mrob from test_utils import get_mc from sys import platform import matplotlib if platform == "darwin": matplotlib.use('PS') import matplotlib.pyplot as plt # Here the Cholesky decomposition for singular covariance matrix is i...
StarcoderdataPython
41767
# Notes from this experiment: # 1. adapt() is way slower than np.unique -- takes forever for 1M, hangs for 10M # 2. TF returns error if adapt is inside tf.function. adapt uses graph inside anyway # 3. OOM in batch mode during sparse_to_dense despite of seting sparse in keras # 4. Mini-batch works but 15x(g)/20x slower ...
StarcoderdataPython
3331752
# mapping from itemid -> treasure chest subtype, 0 is normal, 1 is small, 2 is boss, 3 is goddess chest tboxSubtypes = [ 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,...
StarcoderdataPython
4834
#!/usr/bin/env python # # Copyright (c) 2018, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information # see the Pycom Licence v1.0 document supplied with this file, or # available at https://www.pycom.io/opensource/licensing ...
StarcoderdataPython
3281665
import asyncio import numpy as np import ucp.utils async def worker(rank, eps, args): futures = [] # Send my rank to all others for ep in eps.values(): futures.append(ep.send(np.array([rank], dtype="u4"))) # Recv from all others recv_list = [] for ep in eps.values(): recv_lis...
StarcoderdataPython
107093
<reponame>devolksbank/AWS-IoT-Fresh-Cloud-Coffee import boto3 import logging from time import time from boto3.dynamodb.conditions import Key statusTableName = "<insert-device-status-table-here>" deviceIdTableName = "deviceIds" snsTopic = "<insert-topic-arn-here>" logger = logging.getLogger() ddb = boto3.resource('dyn...
StarcoderdataPython
3353011
"""Define tests for the "Node" object.""" import tempfile from unittest.mock import MagicMock, PropertyMock, mock_open import aiohttp import pytest import smb from pyairvisual import CloudAPI from pyairvisual.errors import NodeProError from pyairvisual.node import NodeSamba from tests.async_mock import patch from te...
StarcoderdataPython
4814733
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Pre-renders templates (for both collaborative filtering and content-based use) for all products and saves them in the database. **Command-line parameters** *environment* The intended environment, as defined in mongoid.yml. ...
StarcoderdataPython
1707198
<reponame>dimartinot/P3-Collaborative<gh_stars>1-10 import numpy as np import random import copy from collections import namedtuple, deque from model import Actor, Critic import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(1e6) # replay buffer size BATCH_SIZE = 256 # mi...
StarcoderdataPython
4829457
<filename>qutip/tomography.py # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <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...
StarcoderdataPython
1670594
<gh_stars>0 #define a dictionary data structure #dictionaries have key: value for the elements example_dict = { 'class' : 'Astr 119', 'prof' : 'Brant', 'awesomeness' : 10 } print(type(example_dict)) #gives data type #get a value via key course = example_dict['class'] #assign a vari...
StarcoderdataPython
3300129
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] def backtrack(nums, subset, ans): if len(subset) == len(nums): ans.append(subset) return for i in range(len...
StarcoderdataPython
1767243
from django import forms from django.contrib.auth import get_user_model from .send import send_templated_mail from . import models class MailForm(forms.Form): template_name = forms.CharField() users = forms.ModelMultipleChoiceField( queryset=get_user_model().objects.all(), widget=forms.Checkb...
StarcoderdataPython
3354856
<gh_stars>1-10 """ Copy the output to clipboard as a list or single string. this is a handy way of pasting your newly found subdomains into other tools that does not accept file input. """ import pyperclip def clipboard_output(subdomain_list, output_style): """Copy to clipboard, 's' for string and 'l' for list....
StarcoderdataPython
39038
<reponame>guillaume-martin/exercism<filename>python/rna-transcription/rna_transcription.py def to_rna(dna_strand): pairs = {'G':'C','C':'G','T':'A','A':'U'} return ''.join(pairs[n] for n in dna_strand)
StarcoderdataPython
162339
from abc import ABCMeta, abstractmethod from liteflow.core.builders import WorkflowBuilder class Workflow(metaclass=ABCMeta): @property @abstractmethod def id(self): return None @property @abstractmethod def version(self): return 1 @abstractmethod def build(self, bui...
StarcoderdataPython
4812000
#programa de alistamento Militar from datetime import date atual = date.today().year ano = int(input('Digite o Ano de Nascimento: ')) idade = atual - ano print(f'Você tem {idade} anos') if idade < 18: falta = 18 - idade print('Voce ainda não tem idade de se Alistar') print(f'Falta {falta} anos') elif idade ...
StarcoderdataPython
3248079
from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["SmartCapabilities"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class SmartCapabilities: """ SmartCapabilities Codes that define what the ser...
StarcoderdataPython
10498
<reponame>gchiesa/cfmacro<filename>cfmacro/_resources/examples/lambda.py # -*- coding: utf-8 -*- from cfmacro.processors import SgProcessor from cfmacro.core.engine import ProcessorEngine from cfmacro.core.template import TemplateProcessor def lambda_handler(event, context): """ Implement a core handler for ...
StarcoderdataPython
83080
<filename>test/unit/test_config.py import os import unittest import yaml import dbt.config if os.name == 'nt': TMPDIR = 'c:/Windows/TEMP' else: TMPDIR = '/tmp' class ConfigTest(unittest.TestCase): def set_up_empty_config(self): profiles_path = '{}/profiles.yml'.format(TMPDIR) with open(...
StarcoderdataPython
3310147
<filename>python/maheen_code/pascal_3d.py # import os; import scipy; import mat4py; from scipy import misc; import scipy.io import visualize; import numpy as np; import glob import script_nearestNeigbourExperiment import cPickle as pickle; import matplotlib.pyplot as plt; from pascal3d_db import Pascal3D, Pascal3D_Man...
StarcoderdataPython
1643546
import numpy as np import pandas as pd import matplotlib.pyplot as plt #Data Source import yfinance as yf import time, datetime, math from datetime import datetime import sqlite3 con = sqlite3.connect("DB/stocks.db") #con.row_factory = sqlite3.Row stocks = ['UBER'] #data = pd.read_sql_query("select DISTINCT symbol FRO...
StarcoderdataPython
35037
<gh_stars>1-10 from setuptools import setup, find_packages setup( name = 'Flask-Digest', version = '0.2.1', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/vctandrade/flask-digest', description = 'A RESTful authentication service for Flask applications', long_descri...
StarcoderdataPython
3304744
from ipykernel.kernelapp import IPKernelApp from .kernel import YottaDBKernel IPKernelApp.launch_instance(kernel_class=YottaDBKernel)
StarcoderdataPython
28715
import numpy as np from napari_plugin_engine import napari_hook_implementation from napari_tools_menu import register_function from napari_time_slicer import time_slicer, slice_by_slice import napari from napari.types import ImageData, LabelsData @napari_hook_implementation def napari_experimental_provide_function()...
StarcoderdataPython
1699985
<reponame>Nurul-GC/powfu_file_organizer """ This script is to install the program in Windows machine. Its function is to create a new Folder in C:\\Program Files\\ and copy the program. After this, create a new RegeditKey to help users to use the program by clicking on the right button. """ import os impo...
StarcoderdataPython
121204
<gh_stars>1-10 from player_commands.bazaar import bazaar_cog from player_commands.sky import sky_cog from player_commands.wiki import wiki_cog from player_commands.dungeons import dungeons_cog from player_commands.kills import kills_cog from player_commands.lowest_bin import lo...
StarcoderdataPython
1769661
<reponame>homeoffice-ys/EliteQuant_Python<filename>source/gui/ui_log_window.py #!/usr/bin/env python # -*- coding: utf-8 -*- from PyQt5 import QtCore, QtWidgets, QtGui from ..event.event import GeneralEvent class LogWindow(QtWidgets.QTableWidget): msg_signal = QtCore.pyqtSignal(type(GeneralEvent())) def __ini...
StarcoderdataPython
1624199
import unittest import torch from torch import nn from ner.active_heuristic import ( Random, Uncertantiy, KNNEmbeddings, ) from . import utils class TestActiveHeuristics(unittest.TestCase): ''' Test cases for active_heuristics ''' def test_random(self): ''' run test c...
StarcoderdataPython
1799792
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** <NAME> **Copyright(c):** MakeHuman Team 2001-2019 **Licensing:** A...
StarcoderdataPython
4819503
<reponame>bitfort/mlmetrics """Definition of metric structure and seiralization/deserialization. Read and write a metrics structure to/from files and strings. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json # A structur...
StarcoderdataPython
1753640
<filename>third_party/houdini/scripts/python/husdshadertranslators/arnold.py import hou import husdshadertranslators.utils as utils from husdshadertranslators.default import DefaultShaderTranslatorHelper, renderContextName, RampParmTranslator from pxr import Usd, UsdShade, Sdf, Vt from itertools import izip # TODO(...
StarcoderdataPython
3276518
<filename>ChessGui/main.py import pygame as pg pg.init() pg.display.init()
StarcoderdataPython
1700233
<filename>sources/mss/wrwe/xwr14xx_capturedemo.py # # Copyright (c) 2019, <NAME> # This file is licensed under the terms of the MIT license. # # # TI IWR1443 ES2.0 EVM @ capture demo of SDK 1.1.0.2 # import os, time, sys, threading, serial from lib.probe import * from lib.shell import * from lib.helper import * from...
StarcoderdataPython
97409
#!/usr/bin/env python """ check out chapter 2 of cam """
StarcoderdataPython
3329787
from twittertennis.handler import * from twittertennis.tennis_utils import * __version__ = '0.1.2' __all__ = [ '__version__', ]
StarcoderdataPython
3322162
class AnaplanVersion: _api_major_version: int = 2 _api_minor_version: int = 0 @staticmethod def major(): return AnaplanVersion._api_major_version @staticmethod def minor(): return AnaplanVersion._api_minor_version
StarcoderdataPython
1769674
<filename>all_functions/new ddos similar/citeulike-parser-master/python/ieee.py #!/usr/bin/env python2.6 # Copyright (c) 2010 <NAME> <<EMAIL>> # All rights reserved. # # This code is derived from software contributed to CiteULike.org # by # <NAME> # # Redistribution and use in source and binary forms, with or witho...
StarcoderdataPython
93304
<filename>test.py import unittest from giig import * # define some languages to test for: EXAMPLE_LIST = ["linux", "python", "c", "java", "intellij", "eclipse"] class TestStringMethods(unittest.TestCase): def test_get_list(self): result = giig._get_list() for item in EXAMPLE_LIST: se...
StarcoderdataPython
1775376
# # # from copy import deepcopy # # class A: # # def __init__(self): # # self.a = 5 # # # # class B: # # def __init__(self, z): # # self.z = z # # def foo(self): # # self.z.a += 1 # # # # AA = A() # # BB = B(AA) # # CC = deepcopy(BB) # # CC.z.a += 1 # # print(BB.z.a, CC.z.a) # # BB.f...
StarcoderdataPython
3328169
# Generated by Django 3.1.12 on 2021-06-28 08:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0018_cachesettings'), ] operations = [ migrations.AddField( model_name='section', name='show_progress_bar',...
StarcoderdataPython
85452
<reponame>utcsilab/eq-net #!/usr/bin/env python3 # -*- coding: utf-8 -*- from keras.callbacks import TerminateOnNaN, EarlyStopping, ModelCheckpoint from keras.callbacks import ReduceLROnPlateau from keras.optimizers import Adam from keras import backend as K from sklearn.model_selection import train_test_split import ...
StarcoderdataPython
163932
<gh_stars>1-10 import os import cv2 import numpy as np import types import json import codecs import threading import pprint as pp class Chunk(): def __init__(self, video_root, video_filename, value_loader_config, repeats): self.file = os.path.join(video_root, video_filename) self.repeats = repeats...
StarcoderdataPython
1626330
<filename>awq.py #!//usr/bin/env python3 import requests import json import os from common import * username = "tritlo" fxmlUrl = "https://flightxml.flightaware.com/json/FlightXML3/" with open('aircraft-2.0.json','r') as f: aircraftInfo = json.loads(f.read()) # Fix inconsistencies in naming from FlightAware de...
StarcoderdataPython
3284533
<reponame>Aerex/GamestonkTerminal # IMPORTATION STANDARD # IMPORTATION THIRDPARTY import pytest import numpy as np import pandas as pd # IMPORTATION INTERNAL from gamestonk_terminal.stocks.fundamental_analysis.financial_modeling_prep import ( fmp_model, ) @pytest.fixture(scope="module") def vcr_config(): re...
StarcoderdataPython
3294360
"""Pytest plugin entry point. Used for any fixtures needed.""" import pytest from .pytest_selenium_enhancer import add_custom_commands @pytest.fixture(scope='session') def selenium_patcher(): """Add custom .""" add_custom_commands()
StarcoderdataPython
1673292
<filename>game/finding highest bidder.py import os clear = lambda: os.system('clear') logo = ''' ___________ \ / )_______( |"""""""|_.-._,.---------.,_.-._ | | | | ...
StarcoderdataPython
3327605
<gh_stars>1-10 # Copyright 2013-2018 CERN for the benefit of the ATLAS collaboration. # # 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 # # Unl...
StarcoderdataPython
173758
import pkga.pkgb.modc as c_me print c_me.stuff print c_me.things
StarcoderdataPython
3360343
<filename>src/events/api/views.py import collections from typing import List, Union from rest_framework.generics import RetrieveAPIView, ListAPIView from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from django.conf import sett...
StarcoderdataPython
19716
# !/usr/bin/env python # _*_ coding:utf-8 _*_ from django.conf.urls import url from . import views urlpatterns = [ # 1. 结算订单 orders/settlement/ url(r'^orders/settlement/$', views.OrdersSettlementView.as_view(), name='settlement'), # 2. orders/commit/ 提交订单 url(r'^orders/commit/$', views.OrdersCo...
StarcoderdataPython
1654389
<reponame>KodingKurriculum/level-0-python-coding-interview from plumbum import cli class MergeSort(cli.Application): _list = [8, 100, 99, 5, 15, 99, 85, 15, 25, 5, 99, 97, 10, 35, 36] def main(self): if list is None or len(self._list) is 0: print("List should have at least one element") ...
StarcoderdataPython
3389010
<gh_stars>10-100 # Adapted from pytorch examples from __future__ import print_function from torch import nn, optim from railrl.core import logger import numpy as np from railrl.pythonplusplus import identity from railrl.torch.core import PyTorchModule from railrl.torch.networks import Mlp import railrl.torch.pytorch_u...
StarcoderdataPython
1706006
import pytest from _voronoi import recompute_segment_segment_segment_circle_event as bound from hypothesis import given from tests.integration_tests.hints import (BoundPortedCircleEventsPair, BoundPortedSiteEventsPair) from tests.integration_tests.utils import are_bound_porte...
StarcoderdataPython
168498
from collections import OrderedDict import cPickle import os def prototype_state(): state = {} # ----- CONSTANTS ----- # Random seed state['seed'] = 1234 # Logging level state['level'] = 'DEBUG' # Out-of-vocabulary token string state['oov'] = '<unk>' # These are end-of-s...
StarcoderdataPython
1611442
<reponame>manuelmusngi/machine_learning_algorithms_for_development<filename>preprocessing_template.py # Preprocessing Template # Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_('') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].value...
StarcoderdataPython
3338552
def parse_currency_to_eur(quantity, currency): """ Translate a given quantity of a determinate currency to its equivalent in euros. :param quantity: quantity of the currency :param currency: the indentifier of the currency :return: the quantity in euros """ euros = -1 if currency == 'z...
StarcoderdataPython
1758201
<reponame>Naman-Bhalla/os-file-system-python<gh_stars>0 from file_system import FileSystem from user import User class OS: def __init__(self): self.open_files_table = {} self.process_files_table = {} self.users = set() self.system_user = User() self.users.add(self.system_u...
StarcoderdataPython
3262757
import asyncio import functools import logging import multiprocessing import os import textwrap import time from queue import Empty as QueueEmpty import tweepy import discord import discord.ext.commands as commands import discord.utils as dutils from discord.ext.commands.formatter import Paginator import paths from ...
StarcoderdataPython
1716332
#!/usr/bin/env python3 # coding: utf-8 from rdbox.k8s_response_helper import K8sResponseHelper from rdbox.rdbox_node_formatter import RdboxNodeFormatter from logging import getLogger r_logger = getLogger('rdbox_cli') r_print = getLogger('rdbox_cli').getChild("stdout") class AnsibleRdboxNodeFormatter(RdboxNodeFormat...
StarcoderdataPython
138841
<gh_stars>10-100 from abc import ABC import warnings import contextlib from genie.conf.base.attributes import UnsupportedAttributeWarning,\ AttributesHelper from genie.conf.base.cli import CliConfigBuilder from genie.conf.base.config import CliConfig from genie.libs.conf.interface import BviInterface from genie....
StarcoderdataPython
85709
<gh_stars>1-10 import time from threading import Thread import RPi from RPi import GPIO from collections import Iterable import itertools HIGH = GPIO.HIGH LOW = GPIO.LOW def set_pin_mode(mode): """ Set pin numbering mode for all pins. Args: mode (str): mode to set, must be 'BOARD' or 'BCM' "...
StarcoderdataPython
4804293
import time from pathlib import Path import cv2 from ir_tracker.utils import calibration_manager, debug_server, picam_wrapper def draw_info(image, text): cv2.putText(image, text, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2, cv2.LINE_AA) CHESSBOARD_HEIGHT = 8 CHESSBOARD_WIDTH = 5 PIC...
StarcoderdataPython
3290754
<filename>bin/ivar_variants_to_vcf.py #!/usr/bin/env python import os import sys import re import errno import argparse import numpy as np from scipy.stats import fisher_exact def parse_args(args=None): Description = "Convert iVar variants TSV file to VCF format." Epilog = """Example usage: python ivar_varia...
StarcoderdataPython
3281312
<reponame>hatchetjackk/artemis import random import re import time from collections import OrderedDict from discord.ext import commands import cogs.utilities as utilities class Karma(commands.Cog): def __init__(self, client): self.client = client self.karma_blacklist = ['Knights of Karma'] ...
StarcoderdataPython
1642543
# Generated by Django 2.0 on 2017-12-08 17:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('feedback', '0002_auto_20160104_1521'), ] operations = [ migrations.AlterModelOptions( name='feedback', options={'order...
StarcoderdataPython
1638657
<filename>devops/cluedo/create_object_relations.py import csv import os import sys import Queue import xml.etree.ElementTree as ET from xml.sax.saxutils import escape from cswaExtras import * # from loadCSpace import * username = os.environ['LOGIN'] password = os.environ['PASSWORD'] server = os.environ['CSPACEURL'] re...
StarcoderdataPython
1716060
<gh_stars>1-10 from django.views.generic import View from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.core.urlresolvers import reverse from django.contrib import messages from items.models import ItemPost, BookList class PostDelete(LoginRequiredMixin...
StarcoderdataPython
5062
<gh_stars>1-10 from django.db import models class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on...
StarcoderdataPython
3357245
from django.template.response import TemplateResponse from oscar.apps.checkout.views import (PaymentMethodView as CorePaymentMethodView, PaymentDetailsView as CorePaymentDetailsView, OrderPreviewView as CoreOrderPreviewView) from oscar.apps.payment.f...
StarcoderdataPython
1789758
import os import unittest import json import trebek import entities import fakeredis import time import datetime # Reference this SO post on getting distances between strings: # http://stackoverflow.com/a/1471603/98562 def get_clue_json(): with open('test-json-output.json') as json_data: clue = json.load(j...
StarcoderdataPython
1701374
<reponame>sinhmd/raster-vision import unittest import numpy as np from rastervision2.core.data import SegmentationClassTransformer from rastervision2.core.data.utils import color_to_triple from rastervision2.core.data.class_config import ClassConfig class TestSegmentationClassTransformer(unittest.TestCase): def...
StarcoderdataPython
3376692
<reponame>Vector35/traceapi #!/usr/bin/env python import sys import json import os import tarfile import base64 import operator from Crypto.Hash import * if len(sys.argv) < 3: print "Expected challenge name and tar path" sys.exit(1) desired_cs = sys.argv[1] files = sys.argv[2:] for tar_path in files: tar = tarfi...
StarcoderdataPython
59501
from htm_rl.modules.htm.pattern_memory import PatternMemory from htm.bindings.sdr import SDR import numpy as np from tqdm import tqdm EPS = 1e-12 def get_labels(pm: PatternMemory, data, input_size): labels = dict() input_pattern = SDR(input_size) for i, item in enumerate(data): input_pattern.spa...
StarcoderdataPython
1632600
import abc import re import urllib2 from cave import Cave from lxml import html class CaveService(object): _user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' \ '(KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36' _regex_number = re.compile("[0-9]+") _regex_namespac...
StarcoderdataPython
184651
import numpy as np class MiniBatch: def __init__(self, X: np.array, y: np.array, n, batch_size=1, shuffle=True): """ Creates iterator throw given data :param X: features array :param y: marks array :param n: number of elements :param batch_size: mini-batch size ...
StarcoderdataPython
1651398
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ from odoo.exceptions import ValidationError class Sessions(models.Model): _name = "my_modulee.sessions" _description = "my_modulee.sessions" name = fields.Text( string='Name' ) start_date = fields.Date( string='Start Date', default=lambda sel...
StarcoderdataPython
3333559
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-27 13:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0015_s3upload_is_valid'), ('team...
StarcoderdataPython
1700239
# Copyright 2007-2014 University Of Southern California # # 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...
StarcoderdataPython
3250205
from collections import OrderedDict, Counter import hashlib from utils import gethostname, getpath import networkx as nx import matplotlib.pyplot as plt class SimpleSiteMap(object): gr = None tokens = OrderedDict() tokens_counter = 0 edges = [] def __init__(self, site, exceptions=None): s...
StarcoderdataPython
1795419
import importlib import logging import os from contextlib import contextmanager import yadageschemas from .steering_object import YadageSteering from .strategies import get_strategy log = logging.getLogger(__name__) def run_workflow(*args, **kwargs): """ convenience function around steering context, when n...
StarcoderdataPython
3349664
from typing import Optional, List, Union from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, Session from autofit.database import query as q from .scrape import scrape_directory from .. import model as m from ..query.query import AbstractQuery, Attribute class NullPredicate(AbstractQuery):...
StarcoderdataPython
90608
""" LC 6014 You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s. Return the lexicographically largest repeatLimitedString possible. A str...
StarcoderdataPython
4818994
from Graph.Graph import Graph class BreadthFirstPaths: def __init__(self, graph, s): self._marked = [False] * graph.V() self.edgeTo = [None] * graph.V() self.bfs(graph, s) def bfs(self, graph, v): queue = [] queue.append(v) self._marked[v] = True whil...
StarcoderdataPython
55966
<gh_stars>10-100 from benchmarkstt.segmentation import core from benchmarkstt.schema import Item import pytest @pytest.mark.parametrize('text,expected', [ ('hello world! how are you doing?! ', ['hello ', 'world! ', 'how ', 'are ', 'you ', 'doing?! ']), ('\nhello world! how are you doing?! ',...
StarcoderdataPython
3252331
<reponame>kuldeepaman/tf-pose # -*- coding: utf-8 -*- """ Shows use of PlotWidget to display panning data """ import initExample ## Add path to library (just for examples; you do not need this) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np win = pg.GraphicsLayoutWidget(s...
StarcoderdataPython
3201342
""" Draws a window filled with BG_COLOR """ import pygame import constants as con TITLE = "beasties" TILES_HORIZONTAL = 4 TILES_VERTICAL = 4 TILESIZE = 128 WINDOW_WIDTH = TILESIZE * TILES_HORIZONTAL WINDOW_HEIGHT = TILESIZE * TILES_VERTICAL class Game: def __init__(self): pygame.init() self.clock ...
StarcoderdataPython
3256860
import matplotlib.pyplot as plt import os def summarize_performance(history, Model_path): print(history.history.keys()) if('lr' in history.history.keys()): plt.plot(history.history['lr']) plt.title('Model lr') plt.ylabel('lr') plt.xlabel('Epoch') plt.savefig(os.path...
StarcoderdataPython
4838410
import numpy as np import argparse from glob import glob from copy import copy import random import pickle # network import torch import torch.nn.functional as F torch.manual_seed(0) # GPU config GPU = False device = torch.device("cuda" if GPU else "cpu") hidden_dim = 128 mb = 32 opt = "Adam" # SGD, Adam C = 3 # w...
StarcoderdataPython
1768453
# coding:utf-8 ''' @author = super_fazai @File : str_utils.py @Time : 2018/8/4 13:15 @connect : <EMAIL> '''
StarcoderdataPython
3363586
''' 说明:多进程 + 协程的例子 ''' import asyncio from multiprocessing import Process, Queue, current_process import aiofiles from aiohttp import ClientSession async def req1(session: ClientSession, i): async with session.get(f'http://httpbin.org/get?a={i}') as resp: async with aiofiles.open(f'data/{i}.log', mode='...
StarcoderdataPython
3329976
import time import random import itertools # import gc import os import sys import datetime import numpy as np import yaml import pickle from operator import itemgetter from optparse import OptionParser from sklearn.model_selection import KFold from sklearn.metrics import roc_curve, auc, average_precision_score sys....
StarcoderdataPython
124692
<filename>attention_to_gif/visualizer.py # importing matplot lib import matplotlib.pyplot as plt import numpy as np import torch # importig movie py libraries from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage class AttentionVisualizer: """ Creates a GIF of the t...
StarcoderdataPython