id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
87623
#!/usr/bin/env python # # A lightweight Telegram Bot running on Flask # # Copyright 2020 <NAME> <<EMAIL>> # # 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/license...
StarcoderdataPython
3341792
<reponame>unparalleled-js/py42 from requests import Session from py42._internal.initialization import SDKDependencies from py42._internal.session_factory import AuthHandlerFactory from py42._internal.session_factory import SessionFactory from py42._internal.session_factory import SessionModifierFactory def from_loca...
StarcoderdataPython
3396210
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a new model on one or across multiple GPUs. """ import collections import math import random import os imp...
StarcoderdataPython
3300133
# Copyright 2013-2017 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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 # https://www.apache.org/licenses/LICENSE-...
StarcoderdataPython
79988
# -*- coding: utf-8 -*- from pathlib import Path import requests from packratt.cache import CacheEntry class UrlCacheEntry(CacheEntry): def __init__(self, url, sha_hash, filename): self.url = url self.sha_hash = sha_hash self.filename = filename def download(self, destination: Path) -...
StarcoderdataPython
1649426
# -*- coding:utf-8 -*- # author: hpf # create time: 2020/10/22 9:38 # file: 111_二叉树的最小深度.py # IDE: PyCharm # 题目描述: # 给定一个二叉树,找出其最小深度。 # # 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 # # 说明: 叶子节点是指没有子节点的节点。 # # 示例: # # 给定二叉树 [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # 返回它的最小深度  2. # 解法一: BFS # Def...
StarcoderdataPython
1610788
<reponame>StevenZ315/Optimization-Algorithms """ heuristic_algorithm module implements a variety of heuristic_algorithms """ from ._genetic_algorithm import GeneticAlgorithm from ._pso import PSO from ._local_search import HillClimbing, Annealing __all__ = ['GeneticAlgorithm', 'PSO', 'HillClimbi...
StarcoderdataPython
1740336
<reponame>raulgranja/Python-Course def area(l, c): print(f'A área de um terreno {l} x {c} é de {l * c:.2f} m².') # main print('Controle de Terrenos') print('--------------------') l = float(input('LARGURA (m): ')) c = float(input('COMPRIMENTO (m): ')) area(l, c)
StarcoderdataPython
4805860
import RPi.GPIO as GPIO import time import threading interruptPin_A = 20; interruptPin_B = 21; GPIO.setmode(GPIO.BCM) GPIO.setup(interruptPin_A, GPIO.IN) GPIO.setup(interruptPin_B, GPIO.IN) absoluteSteps = 0; direction = 0; global prev_A, prev_B, A, B A = prev_A = 0; B = prev_B = 0; def interruptA(channel): ...
StarcoderdataPython
82094
<filename>images/get_images.py import os import urllib, urlparse import simplejson as json # query for images url = 'http://www.panoramio.com/map/get_panoramas.php?order=popularity&\ set=public&from=0&to=20&minx=-77.037564&miny=38.896662&\ maxx=-17.035564&maxy=18.898662&size=medium' c = urllib.urlopen(url) # get the ur...
StarcoderdataPython
1712677
<reponame>manliu1225/Facebook_crawler ############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL sh...
StarcoderdataPython
156813
<filename>App/components/entradas.py<gh_stars>0 import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * dato_entrada = [2,3,4,1] class entradas(QDialog): def __init__(self): super(entradas ,self).__init__() layout = QGridLayout() self.setLayout(layout...
StarcoderdataPython
1624529
def get_temperature_edit_string(temperature_init, temperature_final, data_fraction, iter_): if (temperature_init is None) or (temperature_final is None): return temperature = temperature_init*(temperature_final/temperature_init)**data_fraction edit_config_lines = [] temperature_i...
StarcoderdataPython
184572
from functools import wraps import json, click import os from os import mkdir from instacli import BASE_DIR class Settings(): SETTINGS_DIR = f'{BASE_DIR}/instacli.json' def __init__(self) -> 'Settings': """Class that reppresents an abstraction of the settings of the `instacli` package. ...
StarcoderdataPython
1641419
import re import os import logging import requests import threading import xml.etree.ElementTree as ET from .models import Process from django.conf import settings from pathlib import Path import time #Initialisation des logs logger = logging.getLogger(__name__) class WhereIs(threading.Thread): def __init__(self...
StarcoderdataPython
159984
from flask import Blueprint, make_response, render_template, request, session, abort, send_from_directory from jinja2.exceptions import TemplateNotFound from .service_page import render_template_wo_statistics # Инициализируем модуль Game game_bp = Blueprint('Game', __name__, template_folder='../games', static_fol...
StarcoderdataPython
1707018
# Universal Power System Controller # USAID Middle East Water Security Initiative # # Developed by: <NAME> # Primary Investigator: <NAME> # # Version History (mm_dd_yyyy) # 1.00 07_13_2018_NW # ###################################################### import logging import inspect import sys #global logger #logger = funct...
StarcoderdataPython
1724255
<reponame>StevenHuang2020/ML import matplotlib.pyplot as plt import numpy as np from distributions import Binomial_distribution, Discrete_uniform_distribution def plotDistributeBar(ax, data, label='', width=0.3, offset=0, title='Probability Distribution of true'): ax.bar(np.arange(len(data))+offset,data,width=widt...
StarcoderdataPython
1690457
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
StarcoderdataPython
1740800
<reponame>wise-east/LAUG<gh_stars>1-10 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ The ``evaluate`` subcommand can be used to evaluate a trained model against a dataset and report any metrics calculated by the model. """ import argparse import json import logging from typing...
StarcoderdataPython
1796215
<gh_stars>1-10 from .keyp_head import * # noqa F401
StarcoderdataPython
3335159
# Basic Calculator: https://leetcode.com/problems/basic-calculator/ # Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. # Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, suc...
StarcoderdataPython
1773580
from django.core.management.base import BaseCommand from actors.get_actors import actors, import_data class Command(BaseCommand): help = 'Import Actors data' ACTORS = staticmethod(actors) IMPORT_DATA = staticmethod(import_data) def handle(self, *args, **options): i = 1 for actor in ...
StarcoderdataPython
3240702
<gh_stars>0 from django.db import models from django.http import HttpResponse # Create your models here. def index(request): return HttpResponse("Hello, world. You're at the polls index.") class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_lengt...
StarcoderdataPython
4839162
"""api_gw_test""" # Remove warnings when using pytest fixtures # pylint: disable=redefined-outer-name import json from test.conftest import ENDPOINT_URL # warning disabled, this is used as a pylint fixture from test.elasticsearch_test import ( # pylint: disable=unused-import es_client, populate_es_test_case...
StarcoderdataPython
1681448
import csv import math import random import pandas as pd from sklearn.naive_bayes import GaussianNB ,BernoulliNB from sklearn import preprocessing,linear_model import sklearn import numpy as np #from sklearn.utils import shuffle from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors impor...
StarcoderdataPython
11322
<reponame>junoteam/TelegramBot<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # -*- author: Alex -*- from Centos6_Bit64 import * from SystemUtils import * # Checking version of OS should happened before menu appears # Check version of CentOS SystemUtils.check_centos_version() # Clear screen before to sh...
StarcoderdataPython
1699963
<reponame>sdpython/papierstat<filename>_unittests/ut_datasets/test_tweet.py # -*- coding: utf-8 -*- """ @brief test log(time=13s) """ import unittest from pyquickhelper.pycode import ExtTestCase, get_temp_folder from papierstat.datasets import load_tweet_dataset class TestTweet(ExtTestCase): def test_tweets...
StarcoderdataPython
41135
<gh_stars>1-10 import torch import torch.nn as nn class LeNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=(5, 5), padding=2, stride=1) self.pool1 = nn.AvgPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0) se...
StarcoderdataPython
1734258
from watchdog.observers import Observer from watchdog.watchmedo import observe_with from leanpub.shellcommandtrick import ShellCommandTrick def pandoc_cmd(book): """Create the command to convert the files (listed in `book`) into a pdf. This is wrapped with echos that the build has started and is complete...
StarcoderdataPython
148659
# This caused an error in py2 because cupy expect non-unicode str # from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() ...
StarcoderdataPython
174653
import numpy as np from sklearn import model_selection from sklearn.metrics import confusion_matrix, mean_squared_error from sklearn import metrics from sklearn import model_selection, metrics #Additional sklearn functions from sklearn.metrics import accuracy_score,f1_score,roc_auc_score,log_loss from sklearn.metrics...
StarcoderdataPython
4814833
import logging from typing import Dict, List from django.conf import settings from apps.authentication.models import OnlineUser as User from apps.gsuite.mail_syncer.utils import ( get_excess_groups_for_user, get_excess_users_in_g_suite, get_g_suite_users_for_group, get_missing_g_suite_group_names_for_...
StarcoderdataPython
1757004
# coding: utf-8 # In[1]: #!/usr/bin/env python2 #Inspire du fichier train_fcn8.py import os import argparse import time from getpass import getuser from distutils.dir_util import copy_tree import pickle import numpy as np import random import theano import theano.tensor as T from theano import config import lasa...
StarcoderdataPython
3268181
<filename>controllers/project.py # -*- coding: utf-8 -*- """ Project @author: <NAME> (<EMAIL>) @date-created: 2010-08-25 Project Management """ module = request.controller response.menu_options = org_menu #============================================================================== ...
StarcoderdataPython
1686825
<gh_stars>1000+ # -*- coding: utf-8 -*- from django.test import TestCase from django_dynamic_fixture import get, new from readthedocs.builds.constants import ( BRANCH, LATEST, STABLE, TAG, EXTERNAL, ) from readthedocs.builds.models import Version from readthedocs.projects.constants import REPO_TYPE...
StarcoderdataPython
1717717
<gh_stars>1-10 from enum import IntEnum import typer class LinterLevel(IntEnum): """ Linter output severity levels. Rough definitions: Notice: Likely not a problem, but worth noting. Caution: May be a problem. Warning: Likely a problem. Failure: Should be considered a test failure. ...
StarcoderdataPython
167109
<gh_stars>0 #!/usr/bin/env initPy import sys import myProj.newYears as nye nCount = int(sys.argv[1]) \ if len(sys.argv) > 1 else 10 nye.countdown(nCount)
StarcoderdataPython
98513
import os import requests import json import discord from discord.ext import commands client = commands.Bot(command_prefix=commands.when_mentioned_or("d/","D/"),help_command=None) #api key references my_secret = os.environ['TOKEN'] apiSecret = os.environ['apexApi'] #notify me when bot has come online @client.event...
StarcoderdataPython
196758
# ---------------------------------------------------------------------- # Test core.clickhouse package # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- #...
StarcoderdataPython
4808928
<filename>vision/ssd/config/vgg_ssd_config640.py import numpy as np from vision.utils.box_utils import SSDSpec, SSDBoxSizes, generate_ssd_priors image_size = 640 image_mean = np.array([123, 117, 104]) # RGB layout image_std = 1.0 iou_threshold = 0.45 center_variance = 0.1 size_variance = 0.2 specs = [ SSDSpe...
StarcoderdataPython
1792891
# Copyright 2014 CloudFounders NV # # 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 writ...
StarcoderdataPython
1671326
<reponame>ingmarschuster/JaxRK<gh_stars>0 from ..core.typing import Array import jax.numpy as np import numpy.random as random def inv_blockmatr(P:Array, P_inv:Array, Q:Array, R:Array, S:Array) -> Array: """Given P and P^{-1}, compute the inverse of the block-partitioned matrix P Q R S and return it. B...
StarcoderdataPython
1764863
import unittest from app.models import User, Post, Comment class CommentModelTest(unittest.TestCase): def setUp(self): self.user_James = User(username='James', password='<PASSWORD>', email='<EMAIL>') self.new_post = Post(id=1, post_title='Test', post_content='This is a test post', category="interv...
StarcoderdataPython
1765590
# -*- coding: utf-8- -*- from OOPHerySchool.school import Student,Tesla,SpecialStudent,Teacher from OOPHerySchool.newschool import Test
StarcoderdataPython
3334315
<filename>agents/mem_net.py ''' Implementation of augmented memory network ''' import torch import torch.nn as nn from torchvision import models import numpy as np import torch.nn.functional as F from torch.nn.parameter import Parameter class Net(nn.Module): def __init__(self, MemNumSlots, MemFeatSz, model_config...
StarcoderdataPython
96421
# Copyright 2017 Brocade Communications Systems, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
StarcoderdataPython
3235101
#!/usr/bin/env python3 from deid.dicom import get_files, replace_identifiers from deid.data import get_dataset # This is an example of replacing fields in dicom headers, # but via a function instead of a preset identifier. # This will get a set of example cookie dicoms base = get_dataset("dicom-cookies") dicom_files...
StarcoderdataPython
184391
from typing import List, Any, Dict import numpy as np from swd.bonuses import BONUSES, ImmediateBonus, SCIENTIFIC_SYMBOLS_RANGE from swd.cards_board import AGES, CardsBoard from swd.entity_manager import EntityManager from swd.game import Game, GameState from swd.player import Player class StateFeatures: @stati...
StarcoderdataPython
1756504
<gh_stars>1-10 # THIS FILE IS FOR CHECKING IF THE CODE RUNS WHEN THE TEST IMAGE WILL HAVE MORE THAN ONE FACE from cv2 import cv2 import face_recognition # 1ST IMAGE imgJohnny = face_recognition.load_image_file('assets/johnny-depp.jpg') imgJohnny= cv2.cvtColor(imgJohnny, cv2.COLOR_BGR2RGB) johnnyLocation = face_recogn...
StarcoderdataPython
53241
<filename>runtests.py #!/usr/bin/env python import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings' exampleproject_dir = os.path.join(os.path.dirname(__file__), 'example') sys.path.insert(0, exampleproject_dir) from django.test.utils import get_runner from django.conf import settings def runt...
StarcoderdataPython
4837252
class Solution: def solve(self, heights, k): pq = [] ans = [] for i in range(len(heights)-1,-1,-1): while pq and pq[0][1] > i+k: heappop(pq) if not pq or heights[i] > -pq[0][0]: ans.append(i) heappush(pq, [-heights[i],i]) return sorted(ans)
StarcoderdataPython
1693158
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from scipy import misc import tensorflow as tf import numpy as np import sys import os import argparse import align.detect_face import glob from pdb import set_trace as bp from six.moves import x...
StarcoderdataPython
4801096
<reponame>tmtsoftware/csw-python<filename>csw/EventTime.py from datetime import datetime,timezone from dataclasses import dataclass, asdict @dataclass class EventTime: """ Creates an EventTime containing seconds since the epoch (1970) and the offset from seconds in nanoseconds """ seconds: int nan...
StarcoderdataPython
4817654
<gh_stars>10-100 import numpy as np import nibabel as nib import random import itertools def generate_permutation_keys(): """ This function returns a set of "keys" that represent the 48 unique rotations & reflections of a 3D matrix. Each item of the set is a tuple: ((rotate_y, rotate_z), flip_x, ...
StarcoderdataPython
3323490
from django.conf.urls import include, url from fir_irma.settings import settings api_urlpatterns = [ url(r'^$', 'fir_irma.views.not_found', name='base'), url(r'^scans$', 'fir_irma.views.irma_scan_new'), url(r'^scans/(?P<scan_id>[^/]+)/files$', 'fir_irma.views.irma_scan_upload'), url(r'^scans/(?P<scan_...
StarcoderdataPython
1703053
<filename>bookstore/apps/catalog/admin.py from django.contrib import admin from django.utils.translation import gettext_lazy as _ from mptt.admin import DraggableMPTTAdmin from image_cropping import ImageCroppingMixin from bookstore.apps.catalog.models import ( BookImages, AuthorImages, Category, Pub...
StarcoderdataPython
3268042
<reponame>RandallLDavis/SQLAlchemy--Challenge<gh_stars>0 import datetime as dt import numpy as np import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect from flask import Flask, jsonify engine = crea...
StarcoderdataPython
3298796
<reponame>SDM-TIB/korona-graph-partitioning<filename>1_data_processing/4. author similarity.py<gh_stars>0 from __future__ import division from openpyxl import Workbook from array import array #from openpyxl.utils import coordinate_from_string, column_index_from_string from openpyxl.utils import column_index_from_string...
StarcoderdataPython
3277284
""" Apply a transformation matrix produced by align_epi_anat.py. Created 11/16/2021 by <NAME>. <EMAIL> """ from os import PathLike import subprocess def main(in_image: PathLike, in_matrix: PathLike, out_prefix: PathLike) -> None: """ Apply a 1D transformation matrix to an image. Args: ...
StarcoderdataPython
189338
<reponame>vascoalramos/misago-deployment from django.core.cache import cache from ..cache.versions import invalidate_cache from . import MENU_ITEMS_CACHE def get_menus_cache(cache_versions): key = get_cache_key(cache_versions) return cache.get(key) def set_menus_cache(cache_versions, menus): key = get_...
StarcoderdataPython
18899
<filename>CollabMoodle.py import datetime from webService import WebService import Utilidades as ut import sys if __name__ == "__main__": param = ut.mainMoodle(sys.argv[1:]) #param = 'moodle_plugin_sessions.txt', '', '2020-08-01 00:00:00,2020-12-31 00:00:00' webService = WebService() report = [] re...
StarcoderdataPython
20813
from cv2 import fastNlMeansDenoisingColored from cv2 import cvtColor from cv2 import bitwise_not,threshold,getRotationMatrix2D from cv2 import warpAffine,filter2D,imread from cv2 import THRESH_BINARY,COLOR_BGR2GRAY,THRESH_OTSU from cv2 import INTER_CUBIC,BORDER_REPLICATE,minAreaRect from numpy import column_stack,array...
StarcoderdataPython
4811968
''' This file contains function definitions for language translation ''' import os from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from dotenv import load_dotenv load_dotenv() apikey = os.environ['apikey'] url = os.environ['url'] version = os.environ['v...
StarcoderdataPython
89618
"""Renaming delimiters table to limiters Revision ID: 17346cf564bc Revises: <PASSWORD> Create Date: 2014-03-07 14:45:27.909631 """ # revision identifiers, used by Alembic. revision = '17346cf564bc' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): op.rename_table('deli...
StarcoderdataPython
3341487
<reponame>mrsixw/git-statistics from collections import Counter import dateparser def _get_branch_id(query_func, branch): __BRANCH_SQL = """ SELECT branch_id FROM git_branches WHERE git_branches.branch_name = ? """ branch_id = query_func(__BRANCH_...
StarcoderdataPython
3286088
<filename>resource/admin_node.py # Copyright (c) 2010-2011 Lazy 8 Studios, LLC. # All rights reserved. import csv from restish import http, resource, templating from front import VERSION, gift_types from front.lib import get_uuid, utils, forms, xjson, urls, gametime, money from front.data import assets from front.mode...
StarcoderdataPython
1650875
import argparse import sys import os import ggutils.s3_access as s3_access import smalltrain as st try: # For the case smalltrain is installed as Python library print('try to load smalltrain modules from Python library') from smalltrain.model.nn_model import NNModel print('smalltrain modules are rea...
StarcoderdataPython
194265
<filename>matrix/common/aws/sqs_handler.py import json import boto3 from matrix.common.exceptions import MatrixException class SQSHandler: """ Interface for interacting with SQS. """ def __init__(self): self.sqs = boto3.resource('sqs') def add_message_to_queue(self, queue_url: str, pay...
StarcoderdataPython
3224385
from Queue import Queue from domain import DomainUtils from domain.ErrorTypes import ErrorTypes from pipeline_generator.preprocessing.task import SpecialCaseHandler # No need to keep data/state, so I did not make it a class.. # This will be safe for multi-thread use as well~ # Improve this... def determine_generation...
StarcoderdataPython
1706051
#!/usr/bin/python import os import collections AAs = set(["alanine", "arginine", "asparagine", "aspartate", "cysteine", "glutamine", "glycine", "leucine", "lysine", \ "methionine", "phenylalanine", "isoleucine", "histidine", "serine", "threonine", "tyrosine", "valine", "tryptophan", \ "glutamate", "proline"]) RECEPT...
StarcoderdataPython
3230721
<filename>optimization/particle_swarm_plotter.py<gh_stars>1-10 #!/usr/bin/env python """Plotter displays positions of the particles during each iteration as well as the evolution of the best value. author: jussiks """ import numpy import matplotlib.pyplot as plt class Plotter: """Plotting object for diplaying ...
StarcoderdataPython
1747745
<gh_stars>10-100 from amitools.vamos.error import * from amitools.vamos.log import log_mem_alloc from amitools.vamos.label import LabelRange, LabelStruct from amitools.vamos.astructs import AccessStruct class Memory: def __init__(self, addr, size, label, access): self.addr = addr self.size = size ...
StarcoderdataPython
126749
<gh_stars>100-1000 """ CMT Unit Test framework. """ from cmt.test.mayaunittest import TestCase __all__ = ["TestCase", "run_tests"]
StarcoderdataPython
20741
<reponame>linuxluigi/success-backup-check import pytest import success_backup_check def test_project_defines_author_and_version(): assert hasattr(success_backup_check, '__author__') assert hasattr(success_backup_check, '__version__')
StarcoderdataPython
70091
# %% [1221. Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/) class Solution: def balancedStringSplit(self, s: str) -> int: res = cnt = 0 for c in s: cnt += (c == "L") * 2 - 1 res += not cnt return res
StarcoderdataPython
3352956
<gh_stars>1-10 from Crypto.Protocol.KDF import PBKDF2 from Crypto.Cipher import AES from Crypto.Random import random g_salt1 = b"12345678" g_salt2 = bytes("12345678", "utf8") def p_example1_hard_coded1(password, data): key = PBKDF2(password, b"<PASSWORD>", 16, count=1000) cipher = AES.new(key, AES.MODE_ECB)...
StarcoderdataPython
39924
#!/usr/bin/env python # Copyright (c) 02004, The Long Now Foundation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # ...
StarcoderdataPython
3340020
#!/usr/bin/env python from setuptools import setup import versioneer setup(name='gglsbl', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description="Client library for Google Safe Browsing Update API v4", classifiers=[ "Operating System :: POSIX", "Environment :...
StarcoderdataPython
76026
<filename>trx/__init__.py<gh_stars>1-10 # -*- coding: utf-8 -*- from __future__ import print_function,division,absolute_import from . import azav from . import utils from . import mask from . import cell from . import filters from . import id9 from . import dataReduction from . import center from datastorage import Dat...
StarcoderdataPython
3200349
<filename>torch_geometric/__init__.py __version__ = '1.2.2' __all__ = ['__version__']
StarcoderdataPython
3236700
<filename>test/unit/mysql_log_admin/run_program.py #!/usr/bin/python # Classification (U) """Program: run_program.py Description: Unit testing of run_program in mysql_log_admin.py. Usage: test/unit/mysql_log_admin/run_program.py Arguments: """ # Libraries and Global Variables # Standard imp...
StarcoderdataPython
1741181
#!/usr/bin/env python3 r""" This module provides functions which are useful for running plug-ins. """ import sys import os import glob import gen_print as gp import gen_misc as gm # Some help text that is common to more than one program. plug_in_dir_paths_help_text = \ 'This is a colon-separated list of plug-in...
StarcoderdataPython
1605700
<filename>util/datadog.py from Utility import resources as ex from datadog import initialize, api import time class DataDog: @staticmethod def initialize_data_dog(): """Initialize The DataDog Class""" initialize() @staticmethod def send_metric(metric_name, value): """Send a me...
StarcoderdataPython
1634184
import asyncio from copy import deepcopy from dataclasses import dataclass from importlib.resources import path from subprocess import Popen from typing import List, Optional import google.protobuf from multiaddr import Multiaddr import hivemind.hivemind_cli as cli import hivemind.p2p.p2p_daemon_bindings.p2pclient as...
StarcoderdataPython
131659
<reponame>panther-labs/panther-cli<gh_stars>1-10 import ipaddress import panther_event_type_helpers as event_type from panther_base_helpers import deep_get def get_event_type(event): # currently, only tracking a few event types if ( event.get("eventName") == "ConsoleLogin" and deep_get(event,...
StarcoderdataPython
120961
<gh_stars>0 # -*- coding: utf-8 -*- from flask import Blueprint, render_template, current_app from flask.ext.login import current_user blueprint = Blueprint('admin.dashboard', __name__) @blueprint.before_request def restrict_blueprint_to_admins(): """ .. seealso:: http://flask.pocoo.org/snippets/59/ "...
StarcoderdataPython
3278257
from asyncpg.exceptions import UniqueViolationError from starlette.background import BackgroundTask from starlette.responses import JSONResponse from admin.audit_logs import AuditColour, send_audit_log from admin.route import Route from admin.models import ShortURL from admin.utils import is_authorized, is_json from a...
StarcoderdataPython
1782122
from datetime import datetime, timedelta import simplejson from django.db import models class RecentManager(models.Manager): def get_query_set(self): return super(RecentManager, self).get_query_set().filter(updated__gt=datetime.utcnow() - timedelta(14)) class Geocode(models.Model): lon = models.Floa...
StarcoderdataPython
3337017
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import logging import unittest from copy import deepcopy import torch from pytorchvideo.layers.accelerator.mobile_cpu.activation_functions import ( supported_act_functions, ) from pytorchvideo.layers.accelerator.mobile_cpu.attention import Sq...
StarcoderdataPython
52071
from .models import Signal from rest_framework import viewsets from dashboard.quickstart.serializers import SignalSerializer from django.utils import timezone class SignalViewSet(viewsets.ModelViewSet): """ API endpoint that allows Signal to be viewed or edited. """ queryset = Signal.objects.filter( ...
StarcoderdataPython
1631571
<reponame>ASVO-TAO/SS18B-PLasky """ Distributed under the MIT License. See LICENSE.txt for more info. """ import ast from collections import OrderedDict from ...utility.display_names import OPEN_DATA from ..dynamic import field from ...models import DataParameter, Data from ..dynamic.form import DynamicForm from ...u...
StarcoderdataPython
2915
<filename>sc2/bot_ai.py import itertools import logging import math import random from collections import Counter from typing import Any, Dict, List, Optional, Set, Tuple, Union # mypy type checking from .cache import property_cache_forever, property_cache_once_per_frame from .data import ActionResult, Alert, Race, R...
StarcoderdataPython
3219475
<gh_stars>1-10 """ PyWRM Layout Widget implementation """ from external_widgets.dhx.dhx_layout import Layout as dhx_layout from external_widgets.w2ui.w2ui_layout import Layout as w2ui_layout class Panel: """ Panel object for placement into a Layout Widget""" def __init__(self, panel_type, panel_id, **kwargs)...
StarcoderdataPython
22651
<reponame>EnjoyLifeFund/macHighSierra-py36-pkgs # -*- coding: utf-8 -*- # Copyright (c) 2013, <NAME> # All rights reserved. # This file is part of PyDSM. # PyDSM 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 Foundati...
StarcoderdataPython
1764210
from rule import * from expr_tree import * from typing import Optional, Set class Reduce: @staticmethod def reduce_expr_string(ex_str: str): ex = parse_expr(ex_str) return Reduce.reduce(ex) @staticmethod def reduce(ex: BooleanFunction): # Step 0 rules_1, rules_2, rule...
StarcoderdataPython
1759308
#!/user/bin/python # -*- coding: utf-8 -*- # program# : Name # => # Write a program that computes the value of a+aa+aaa+aaaa # with a given digit as the value of a. # Suppose the following input is supplied to the program: # 9 # Then, the output should be: # 11106 # Hints: # In case of input data being supplied to th...
StarcoderdataPython
1694874
"""TF lite converter for larq models.""" import tensorflow as tf import numpy as np import larq as lq from larq_compute_engine import bsign, bconv2d64 from larq_compute_engine.tf.python.utils import tf_2_or_newer from tensorflow.keras.utils import get_custom_objects get_custom_objects()["bsign"] = bsign quantizer_re...
StarcoderdataPython
3343428
""" An unofficial native Python wrapper for the LivePerson Engagement History API Documentation: https://developers.liveperson.com/data-engagement-history-methods.html Brands can now search, filter and keep copies of chat transcripts and related data, for example surveys, to later integrate and further analyze their ...
StarcoderdataPython
1610766
<reponame>NaHCO314/api-client<filename>tests/get_problem_csacademy.py import unittest from onlinejudge_api.main import main class GetProblemCSAcademyTest(unittest.TestCase): def test_k_swap(self) -> None: url = 'https://csacademy.com/contest/round-39/task/k-swap/' expected = { "status...
StarcoderdataPython