id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1649085
#!/usr/bin/env python # -*- coding: utf-8 -*- """tests for __main__.py""" import argparse import logging import pytest from kootkounter.__main__ import get_parser, log_level, main def test_get_parser(): parser = get_parser() assert isinstance(parser, argparse.ArgumentParser) @pytest.mark.parametrize( ...
StarcoderdataPython
3371384
<gh_stars>1-10 # -*- coding: utf-8 -*- import pytest from emmett.orm import Field, Model class Sample(Model): str = Field() int = Field.int(default=0) float = Field.float(default=0.0) @pytest.fixture(scope='function') def db(migration_db): return migration_db(Sample) @pytest.fixture(scope='funct...
StarcoderdataPython
3339518
<gh_stars>0 numero = int(input('Digite um número para calcular seu fatorual: ')) contador = numero fatorial = 1 while contador > 0: print('{}'.format(contador), end='') print(' x ' if contador >1 else ' = ', end='') fatorial *= contador contador -=1 print('{}'.format(fatorial))
StarcoderdataPython
1738136
import pytest from oic.oic.message import AuthorizationRequest from pyop.util import should_fragment_encode class TestShouldFragmentEncode(object): @pytest.mark.parametrize('response_type, expected', [ ('code', False), ('id_token', True), ('id_token token', True), ('code id_token'...
StarcoderdataPython
3341485
<reponame>ADGiuliano/DevAndCompForRecSys2016<gh_stars>0 """ @author: <NAME> @contact: <EMAIL> @organization: University of Padua """ # File contenente le funzioni riguardanti il calcolo temporale riguarndanti gli eventi def Max_T_int(c): c.execute('select Max(created_at) as Max_time \ ...
StarcoderdataPython
3318765
# Copyright (c) 2016. Mount Sinai School of Medicine # # 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 o...
StarcoderdataPython
3308751
from sqlalchemy.orm import Session from . import models, schemas def get_journal(db: Session, journal_id: int): return db.query(models.Journal).filter(models.Journal.id == journal_id).first() def get_journals(db: Session, skip: int = 0, limit: int = 100): return db.query(models.Journal).offset(skip).limit(...
StarcoderdataPython
3247899
#here we summarize the read file functions, just put read optimal file and normal file together import json ''' number of nodes (switch) number of edges (core) number of demand pairs average budgets #====TODO====what is this? seems flow entry limitation? time elapsed during path selection time elapsed during first ste...
StarcoderdataPython
13150
<gh_stars>10-100 from collections import defaultdict from enum import Enum import json import pprint from typing import Dict, List, Union, Any, Set, DefaultDict from arche.tools import s3 import perfect_jsonschema EXTENDED_KEYWORDS = {"tag", "unique", "coverage_percentage"} SchemaObject = Dict[str, Union[str, bool, ...
StarcoderdataPython
3386119
import itertools from typing import List, Optional, Dict from collections import Counter import numpy as np from hotpot.data_handling.dataset import ListBatcher, Dataset, QuestionAndParagraphsSpec, QuestionAndParagraphsDataset, \ Preprocessor, SampleFilter, TrainingDataHandler from hotpot.data_handling.relevance_...
StarcoderdataPython
158690
<gh_stars>10-100 from keras.layers import Input, Dense from keras.models import Model from IntegratedGradients import * X_train = np.array([[float(j) for j in i.rstrip().split(",")] for i in open("train.csv").readlines()]) Y_train = X_train[:,-1] X_train = X_train[:,0:-1] X_test = np.array([[floa...
StarcoderdataPython
150610
# Copyright: (c) 2018, Pluribus Networks # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible_collections.community.general.tests.unit.compat.mock import patch from ansible_coll...
StarcoderdataPython
48773
<filename>tests/test_json_schema.py<gh_stars>100-1000 from opta.json_schema import check_schemas def test_returns_without_error() -> None: check_schemas()
StarcoderdataPython
1640636
<gh_stars>0 # Copyright (c) 2021 Graphcore Ltd. All rights reserved. import subprocess import argparse import numpy as np def run_demo(batch_size, available_memory_proportion): cmd = ["python", "pytorch_demo.py", "--available-memory-proportion", str(available_memory_proportion), "--batch-size", str(batch_size)] ...
StarcoderdataPython
75366
#!/usr/bin/env python3 import unittest import torch from gpytorch.priors import NormalPrior from gpytorch.test.utils import least_used_cuda_device from torch.distributions import Normal class TestNormalPrior(unittest.TestCase): def test_normal_prior_to_gpu(self): if torch.cuda.is_available(): ...
StarcoderdataPython
629
import torch import torchvision.transforms as transforms from torch.utils.data import Dataset import glob from PIL import Image import random class SUN397EncodableDataset(Dataset): """SUN397 encodable dataset class""" def __init__(self, train=True): super().__init__() path = 'data/SUN397/trai...
StarcoderdataPython
3264215
import logging import traceback import typing as t from databind.core import Context, ConversionError, Converter, ImplicitUnionType logger = logging.getLogger(__name__) def _get_log_level(logger: t.Optional[logging.Logger]) -> int: while logger and logger.level == 0: logger = logger.parent if logger: re...
StarcoderdataPython
162382
# -*- coding: utf-8 -*- """Test the gettext manipulation methods.""" from os import remove from os.path import exists from fixtures import fixture_wowsdir # pylint: disable=unused-import from wren.pomo import backup_original_mo, restore_original_mo LC = "res/texts/en/LC_MESSAGES" def test_backup_original_mo(wows...
StarcoderdataPython
177127
from typing import List from deeppavlov.core.common.registry import register @register("sentseg_restore_sent") def SentSegRestoreSent(batch_words: List[List[str]], batch_tags: List[List[str]]) -> List[str]: ret = [] for words, tags in zip(batch_words, batch_tags): if len(tags) == 0: ret.a...
StarcoderdataPython
37894
#Calculadora de tabuada n = int(input('Deseja ver tabuada de que numero?')) for c in range(1, 13): print('{} X {:2}= {} '. format(n, c, n * c))
StarcoderdataPython
1658945
from aiohttp import web from aiohttp_security import authorized_userid, permits async def test_authorized_userid(loop, aiohttp_client): async def check(request): userid = await authorized_userid(request) assert userid is None return web.Response() app = web.Application() app.rout...
StarcoderdataPython
1633598
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #645. Set Mismatch #The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplica...
StarcoderdataPython
98092
import pandas import matplotlib.pyplot as plt from ETF import get_split_name_and_isin, get_combined_name_and_isin from pypfopt import expected_returns, risk_models, plotting, discrete_allocation from pypfopt.efficient_frontier import EfficientFrontier import base64 import io import numpy as np import math from timeit i...
StarcoderdataPython
66226
# boto3-lambda/src/lambda_functions.py import boto3 import json import os from helpers import Zipper from helpers import lambda_client, iam_client from settings import PYTHON_LAMBDA_API_PERMISSION_STATEMENT_ID, LAMBDA_POLICY_NAME, LAMBDA_ROLE, LAMBDA_TIMEOUT, LAMBDA_MEMORY, PYTHON_36_RUNTIME, PYTHON_LAMBDA_NAME def re...
StarcoderdataPython
3290014
<filename>VOCdevkit/VOC2007/filename_index.py import os annotate_files = os.listdir("Annotations") file_name = [] for n in annotate_files: file_name.append(n.split(".")[0]) print(file_name) train_rate = 0.95 test_rate = 0.5 train_amount = round(len(file_name) * train_rate) test_amount = round((len(file_name)-train...
StarcoderdataPython
134141
<filename>0000_huri/tro/tro_suc.py<gh_stars>0 import pickle import copy import utiltools.thirdparty.o3dhelper as o3dh import utiltools.robotmath as rm import numpy as np class PcdGrab(object): def __init__(self, directory=None): if directory is None: self.bgdepth = pickle.load(open("../databa...
StarcoderdataPython
3230844
<filename>award_app/migrations/0002_rename_image_profile_profile_pic_and_more.py # Generated by Django 4.0.3 on 2022-03-13 15:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('award_app', '0001_initial'), ] operations = [ migrations.RenameFiel...
StarcoderdataPython
1649244
import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv("data_tf_samples.txt", sep='\t') df2 = pd.read_csv("data_samples.txt", sep='\t') plt.rcParams.update({'font.size': 12}) fig, ax = plt.subplots() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.set_asp...
StarcoderdataPython
73612
from rts.core.task import Task from rts.core.ts import TaskSet import unittest class TaskSetTestCase(unittest.TestCase): """ Tests for `taskset.py`.""" def test_id_does_not_overlap(self): ts1 = TaskSet() ts2 = TaskSet() self.assertNotEqual(ts1.id, ts2.id) def test_task_is_counte...
StarcoderdataPython
155505
<filename>botshop/model_evaluator.py<gh_stars>0 import abc from basics.base import Base class ModelEvaluatorBase(Base, metaclass=abc.ABCMeta): @abc.abstractmethod def reset_state(self): self._log.error("Please implement this method in a child class") @abc.abstractmethod def update_context(s...
StarcoderdataPython
3398437
import numpy as np import time def multi_list(a,b): c=[] for i in a: c.append(i*b[i]) return c def multi_array(a,b): c=a*b return c a=range(1000) b=range(1000) time_start=time.time() for i in range(10000): c=multi_list(a,b) time_end=time.time() print('multi list totally cost',time_end...
StarcoderdataPython
1748051
<reponame>khchine5/avanti from lino_xl.lib.courses.workflows import * from .choicelists import ReminderStates ReminderStates.draft.add_transition(required_states="ok final") ReminderStates.sent.add_transition(required_states="draft") ReminderStates.ok.add_transition(required_states="sent") ReminderStates.final.add_tr...
StarcoderdataPython
40249
from .. import db from .base import Base, BaseSchema from typing import Dict, Union from datetime import datetime class Calculation(Base): __table_name__ = 'calculation' calc_id = db.Column(db.Integer, primary_key=True) num1 = db.Column(db.Integer, nullable=False) num2 = db.Column(db.Integer, nullable...
StarcoderdataPython
3387523
<filename>utils.py import time import torch import random import functools import numpy as np from typing import Any, Callable, TypeVar, cast def random_seed(seed_value: int) -> None: """ Random Seeds Numpy, Random and Torch libraries Args: seed_value (int): Number for seeding """ np.rand...
StarcoderdataPython
3376070
"""Analysis module.""" class AnalysisException(Exception): """Generic Analysis Exception.""" pass
StarcoderdataPython
3323982
<reponame>vascoalramos/misago-deployment from datetime import timedelta import pytest from django.utils import timezone from ...conf.test import override_dynamic_settings from ..api.postingendpoint import PostingEndpoint, PostingInterrupt from ..api.postingendpoint.floodprotection import FloodProtectionMiddleware fro...
StarcoderdataPython
3376085
<gh_stars>1-10 # coding: utf-8 '''# Say we have dir-tree below: a / b / c.py x / y / z.py # Now in "z.py", if we want to do this: from a.b import c # We can put the lines below ahead of "z.py" from adaptpath import adaptpath adaptpath.adapt_from_path(2, __file__) # ''' import sys import os import...
StarcoderdataPython
53068
""" 07-hilbert-transform.py - Barberpole-like phasing effect. This example uses two frequency shifters (based on complex modulation) linearly shifting the frequency content of a sound. Frequency shifting is similar to ring modulation, except the upper and lower sidebands are separated into individual outputs. """ fr...
StarcoderdataPython
4825190
<gh_stars>100-1000 # Copyright (c) 2018 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of...
StarcoderdataPython
1611820
# Anatomy of a Response # The HTTP response structure mirrors that of the HTTP request. It contains: # # A response line (line 2), which includes the three-digit HTTP status code; # # A header line or lines (line 3), which include further information about the server and its response; # # The body (line 5 and line 6), ...
StarcoderdataPython
171324
input_data = '1901,12.3\n1902,45.6\n1903,78.9' print('input data is:') print(input_data) as_lines = input_data.split('\n') print('as lines:') print(as_lines) for line in as_lines: fields = line.split(',') year = int(fields[0]) value = float(fields[1]) print(year, ':', value)
StarcoderdataPython
175904
import os from ..train import da_learner from ..train import networks from ..data import mnist from ..data import usps DEFAULT_LOG_DIR = os.path.join(os.getenv('HOME', '/'), 'tmp/da-relax/test') class Config(da_learner.DALearnerConfig): def _set_default_flags(self): super()._set_default_flags() ...
StarcoderdataPython
1653997
import os import functools import PythonQt from PythonQt import QtCore, QtGui import director from director.componentgraph import ComponentFactory from director import consoleapp import director.objectmodel as om import director.visualization as vis from director.fieldcontainer import FieldContainer from director impo...
StarcoderdataPython
1682807
<filename>examples/pytorch/__temporary__/dglnew/__init__.py from . import graph from . import storages
StarcoderdataPython
1632856
<reponame>agy-why/daiquiri<filename>daiquiri/core/permissions.py from django.core.exceptions import ImproperlyConfigured from rest_framework.permissions import BasePermission, DjangoModelPermissions class HasModelPermission(DjangoModelPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)...
StarcoderdataPython
1736615
<filename>python exercises/dek_program026.py<gh_stars>1-10 # !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) <NAME> # Define a function which can compute the sum of two numbers. # Hints: # Define a function with two numbers as arguments. # You can compute the sum in the function and return the value. de...
StarcoderdataPython
136357
import utils from elements import BoolElement from lib.sysfont import sysfont from lib.ST7735 import TFT from machine import Pin import utime from displaylib import MenuSwitcher from utils import tft, buzz button1 = Pin(2, Pin.IN, Pin.PULL_UP) button2 = Pin(3, Pin.IN, Pin.PULL_UP) button3 = Pin(22, Pin.IN, Pin.PULL_UP...
StarcoderdataPython
1694139
<reponame>saedx1/Maha __all__ = ["ExpressionGroup"] from typing import Iterable, List, Optional, Set, Tuple, Union, overload import maha.rexy as rx class ExpressionGroup: """A group of expressions that match the same dimension. Expressions are evaluated in the order they were added. Parameters ----...
StarcoderdataPython
3249880
<reponame>Dinas-Kominfo-Kota-Tangerang/AUTO_IDOR_v2<gh_stars>0 import requests import json from bs4 import BeautifulSoup from IPython.utils import text __author__ = '<NAME> - <NAME> Kota Tangerang' kies = {'ci_session': 'AAABBBCCCDDD'} while True: kue = {"cookie": kies} payload = { 'id': '1234567890', '...
StarcoderdataPython
145023
# -*- coding: utf-8 -*- from django.forms import ModelForm from django.core.exceptions import ValidationError from django import forms from apps.titulos.models import CohorteEstablecimiento class CohorteEstablecimientoConfirmarForm(forms.ModelForm): inscriptos = forms.IntegerField(required=True, min_value=1) class...
StarcoderdataPython
166067
<reponame>zhangtravis/IntSys-Education import torch import torch.nn as nn import torch.optim as optim import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from data_loader import get_data_loaders class LinearRegressionModel(nn.Module): """LinearRegression...
StarcoderdataPython
1693619
<filename>tests/reducers/test_do_nothing_reducer.py import unittest import torch from pytorch_metric_learning.reducers import DoNothingReducer class TestDoNothingReducer(unittest.TestCase): def test_do_nothing_reducer(self): reducer = DoNothingReducer() loss_dict = {"loss": {"losses": torch.randn(1...
StarcoderdataPython
3286164
# encoding: utf-8 import datetime import pytest import six import hashlib from ckan.common import config import ckan.lib.helpers as h WITH_HTML = u"""Data exposed: &mdash; Size of dump and data set: size? Notes: this is the classic RDF source but historically has had some problems with RDF correctness. """ WITH_U...
StarcoderdataPython
3285958
<reponame>NeuroRoboticTech/Jetduino #!/usr/bin/env python ######################################################################## # Calibration and read of the CO2 sensor MH-Z16 # according to the datasheet : http://www.seeedstudio.com/wiki/images/c/ca/...
StarcoderdataPython
1707743
'''author@esilgard''' # # Copyright (c) 2013-2016 <NAME> Cancer Research Center # # Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 # import re import os import global_strings as gb import make_datetime PATH = os.path.dirname(os.path.realpath(__file__)) + os.path.sep class O...
StarcoderdataPython
124078
<filename>src/test/test-ec-python.py #!/usr/bin/env python # coding=utf-8 ##################################################################### import sys reload(sys) sys.setdefaultencoding('utf-8') import os os.sys.path.append(os.path.dirname(__file__)) ###############################################################...
StarcoderdataPython
150573
import datetime from polls.models import QuestionTuple, Choice def meal441(): print("++++++++++++++++++++++++") question_tuple = QuestionTuple.objects.get(pk=441) questions = question_tuple.question_set.all() now = datetime.datetime.now() print("Time: " + str(now)) today = datetime.date.today...
StarcoderdataPython
55961
#!/usr/bin/env python # Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import os import json from util import build_path def read_json(filename): with open(filename) as json_file: return json.load(json_file) def write_json(filename, data): with open(filename, 'w') as outfile...
StarcoderdataPython
1756539
from OpenGLCffi.GLES1 import params @params(api='gles1', prms=['matrixpaletteindex']) def glCurrentPaletteMatrixOES(matrixpaletteindex): pass @params(api='gles1', prms=[]) def glLoadPaletteFromModelViewMatrixOES(): pass @params(api='gles1', prms=['size', 'type', 'stride', 'pointer']) def glMatrixIndexPointerOES(s...
StarcoderdataPython
1612000
<filename>function/python/brightics/function/regression/penalized_linear_regression.py """ Copyright 2019 Samsung SDS 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 ...
StarcoderdataPython
3391882
<filename>anyway/infographics_dictionaries.py driver_type_hebrew_dict = dict( professional_driver="נהג מקצועי", private_vehicle_driver="נהג פרטי", other_driver="לא ידוע" ) head_on_collisions_comparison_dict = dict( head_to_head_collision="התנגשות חזית בחזית", others="אחרות", head_to_head="חזיתיות" ) english_acc...
StarcoderdataPython
3258029
import numpy as np import keras.models from keras.models import model_from_json from keras.applications import VGG16,imagenet_utils from keras.preprocessing.image import load_img,img_to_array import argparse preprocess=imagenet_utils.preprocess_input parser = argparse.ArgumentParser(description='Enter the Image Path')...
StarcoderdataPython
110536
from unittest.mock import Mock, ANY from click.testing import CliRunner from taskit.infrastructure.cli.taskit import cli, State def test_cli_state(state): assert isinstance(state, State) def test_cli(): runner = CliRunner() result = runner.invoke(cli, []) assert result.exit_code == 0
StarcoderdataPython
1791736
from neat import SOVTree, NET import neat.netsim as netsim from datarep import neuronmodel as neurm from _matplotlibsettings import * from _sovloader import * import numpy as np ## parameters ################################################################## # morph_name = 'N19ttwt.CNG.swc' # morph_name = 'stellate....
StarcoderdataPython
3214201
import binaryninja as bn from typing import * import json from .CompleteObjectLocator import CompleteObjectLocator from . import ClassHierarchyDeduction from ..Common import Utils from .. import Config from .ClassMemoryLayout import ClassStructCreation ##################################################################...
StarcoderdataPython
31004
<filename>autoflow/workflow/components/classification/lda.py from copy import deepcopy from typing import Dict from autoflow.workflow.components.classification_base import AutoFlowClassificationAlgorithm __all__=["LinearDiscriminantAnalysis"] class LinearDiscriminantAnalysis(AutoFlowClassificationAlgorithm): cla...
StarcoderdataPython
93096
from enum import IntEnum from eth_typing.evm import HexAddress from eth_utils.units import units from raiden_contracts.utils.signature import private_key_to_address MAX_UINT256 = 2 ** 256 - 1 MAX_UINT192 = 2 ** 192 - 1 MAX_UINT32 = 2 ** 32 - 1 FAKE_ADDRESS = "0x03432" EMPTY_ADDRESS = HexAddress("0x000000000000000000...
StarcoderdataPython
3227559
<reponame>azimuth-san/pdaf-tracking from .constant_velocity import ConstantVelocity2d
StarcoderdataPython
3256144
<filename>run.py # Author: <NAME> # Author: <NAME> import os import importlib import sys from oslo_config import cfg __all__ = ['make_enviroment'] def import_opts(project_name): # Make setup.cfg url dir_path = os.getcwd() sys.path.insert(0, dir_path) setup_cfg = "{}/setup.cfg".format(dir_path) ...
StarcoderdataPython
1764465
<gh_stars>1-10 # # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/extractcode for support or download. # See https://aboutcode.org f...
StarcoderdataPython
1733488
class PlacementData: def __init__(self, placement, board): self.placement = placement self.board = board self.curr_x = None self.curr_y = None self.next_x = None self.next_y = None self.obj_number = None self.placement_type = None self.set_p...
StarcoderdataPython
3241089
<filename>etc/alfred/Alfred.alfredpreferences/workflows/user.workflow.509B298A-C692-4BC0-8E14-AAB1A9EFB725/common.py #!/usr/bin/env python # encoding: utf-8 # # Copyright © 2014 <EMAIL> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2014-03-21 # """ """ from __future__ import print_function, u...
StarcoderdataPython
149872
#/usr/bin/env python from math import log2 from typing import List def get_primes(n: int) -> List[int]: """Return a list of all prime numbers less than n. This function determines if each integer is prime with efficiency O(sqrt(n)). Memory consumption for each prime is O(1). Arguments: ...
StarcoderdataPython
4803047
<filename>bert/core/__init__.py from .modeling import * from .optimization import * from .tokenization import *
StarcoderdataPython
3386531
from PIL import Image import json import os import numpy as np import cv2 ocrNet = cv2.dnn.readNetFromCaffe('models/ocr.prototxt', 'models/ocr.caffemodel') def read_characters(): p = 'models/ocr.json' if os.path.exists(p): with open(p,encoding='utf-8') as f: characters = json.loads(f.read...
StarcoderdataPython
53684
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name =...
StarcoderdataPython
4836838
from __future__ import absolute_import, print_function from builtins import object, str import copy, numpy, pandas, pyarrow as pa, sys, uuid from .pygraphistry import PyGraphistry from .pygraphistry import util from .pygraphistry import bolt_util from .nodexlistry import NodeXLGraphistry from .tigeristry import Tigeri...
StarcoderdataPython
70209
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
StarcoderdataPython
3374849
<gh_stars>0 from base64 import b64decode from flask import Flask, request import cv2 import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt app = Flask(__name__) @app.route('/value', methods=['POST']) def post(): data = request.stream inp = data.read() b64imgfile = open('img.jpg',...
StarcoderdataPython
92579
<gh_stars>1-10 from pwn import * io = remote("chall.pwnable.tw", 10304) libc = ELF('./libc_64.so.6') def add_page(size, content, contin = True): io.recvuntil('Your choice :') io.sendline('1') io.recvuntil('Size of page :') io.sendline(str(size)) if contin: io.recvuntil('Content :') ...
StarcoderdataPython
1664563
<reponame>kyang18/Python-challenge #Create file paths across operating systems and read the csv file import os import csv # Module for reading the csv file csvFile = os.path.join('..','resources','election_data.csv') # Set variables csvDataset = [] csvDataset_Candidate = [] csvDataset_VoterID = [] summary_votes = []...
StarcoderdataPython
1756986
## 11, r+g, on s with gzip.open('../TrainModels/TrainedModels/model11_rg5r.pklz', 'r') as f: wac = pickle.load(f) testdf = filter_by_filelist(srefdf, ssplit90['test']) this_model = '11_rg5r->s; mult' print strftime("%Y-%m-%d %H:%M:%S") print 'Now evaluating:', this_model results.append((this_model, ...
StarcoderdataPython
3290562
# # Copyright (C) 2019 GreenWaves Technologies # # 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 agree...
StarcoderdataPython
7868
from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Task(models.Model): CLOSE = 'cl' CANCEL = 'ca' LATER = 'la' UNDEFINED = 'un' CHOICES = ( ...
StarcoderdataPython
41304
import time from datetime import datetime as dt import colorama from colorama import Fore, Back, Style import socket import os import sys def CS(X): time.sleep(X) os.system("clear") def socknames(): myHostName = socket.gethostname() myIP = socket.gethostbyname(myHostName) print("\033[35m[\033...
StarcoderdataPython
1657763
from argparse import ArgumentParser from torch import nn import pytorch_lightning as pl from util.network_utils import conv_layer, transpose_conv_layer class ResnetBlock(nn.Module): def __init__( self, channel, ): super(ResnetBlock, self).__init__() sequence = [] ...
StarcoderdataPython
196693
<reponame>takelifetime/competitive-programming n = int(input()) a = list(map(int, input().split())) xor = a[0] for x in a[1:]: xor ^= x ans = print(*[xor ^ x for x in a])
StarcoderdataPython
1714974
<gh_stars>1-10 from .quantum_estimator import QuantumEstimator from .kernel_method_mixin import KernelMethodMixin from .qknn import QKNeighborsClassifier, QKNeighborsRegressor from .qsvm import QSVClassifier from .qkmeans import QKMeans from .qridge import QRidgeRegressor __all__ = [ "QuantumEstimator", "Kerne...
StarcoderdataPython
3353185
from app.models.profile.score.count_score import count_score def test_count_score(): assert count_score(['python'], ['android']) == 0.5
StarcoderdataPython
1797009
<filename>lstail/dto/query.py # -*- coding: utf-8 -*- # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from copy import deepcopy ######################################################################## class Query: # ---------------------...
StarcoderdataPython
1757584
""" <NAME>, Jan 20 """ import argparse import logging import json import requests from io import TextIOWrapper from csv import DictReader import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.io.gcp.gcsio import GcsIO from apache_beam.io import WriteToBigQuery ...
StarcoderdataPython
56157
from dnnv.properties import * import numpy as np N = Network("N") True
StarcoderdataPython
1791442
<gh_stars>0 from tkinter import Tk import threading import websockets import asyncio import json import argparse from ImageFrame import ImageFrame from SetupWindow import SetupWindow parser = argparse.ArgumentParser() parser.add_argument("--ip", default="127.0.0.1") parser.add_argument("--port", default=80) args = ...
StarcoderdataPython
4843009
from django.db.models.signals import post_save from .models import Page def version_update(instance, raw=False, **kwargs): # Don't update on loaddata if raw: return obj = instance.content_object if isinstance(obj, Page): # Page save method recalculates the unpublished pages ...
StarcoderdataPython
1655208
<gh_stars>0 # 12. Integer to Roman - LeetCode # https://leetcode.com/problems/integer-to-roman/description/ class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ d = [ ("M",1000), ("CM",900), ("D",500), ...
StarcoderdataPython
1700775
import requests import re from bs4 import BeautifulSoup def get_info(): '''获取one的照片和一句话''' one_url = 'http://www.wufazhuce.com' r = requests.get(one_url) html = r.text soap = BeautifulSoup(html, "html.parser") # 下载图片 pic_url = soap.find(class_='fp-one-imagen').get('src') pic = reques...
StarcoderdataPython
29277
def binary_search(collection, lhs, rhs, value): if rhs > lhs: mid = lhs + (rhs - lhs) // 2 if collection[mid] == value: return mid if collection[mid] > value: return binary_search(collection, lhs, mid-1, value) return binary_search(collection, mid+1, rhs, v...
StarcoderdataPython
107264
<gh_stars>1-10 # Import library import osisoftpy # Authenticate webapi = osisoftpy.webapi('https://dev.dstcontrols.com/piwebapi/')#, authtype='basic', username='ABCDEF', password='<PASSWORD>') # Get points point_list = webapi.points(query='name:SINU*') point_list2 = webapi.points(query='name:CDT*') for individual_poi...
StarcoderdataPython
187106
#!/usr/bin/env python from __future__ import division from __future__ import absolute_import from __future__ import print_function # -*- coding:UTF-8 -*- __author__ = '<NAME>' import HTSeq import pysam import sys def readGTF(gtfFile,stranded): gtf = HTSeq.GFF_Reader(gtfFile) start_codon_sites = {} stop_codon_site...
StarcoderdataPython
1694788
<reponame>mrakitin/xrt # -*- coding: utf-8 -*- import os, sys; sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore #import matplotlib as mpl import copy import numpy as np import matplotlib.pyplot as plt try: import xlwt except ImportError: xlwt = None import xrt.backends.raycing.sources as rs ...
StarcoderdataPython