id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3312583
<gh_stars>0 """ TODO """ import asyncio from biothings.web.query.builder import ESScrollID from elasticsearch import NotFoundError, RequestError from elasticsearch_dsl import MultiSearch, Search class ResultInterrupt(Exception): def __init__(self, data): super().__init__() self.data = data c...
StarcoderdataPython
3280948
# Licensed under a 3-clause BSD style license - see LICENSE.rst # This file defines the AngleFormatterLocator class which is a class that # provides both a method for a formatter and one for a locator, for a given # label spacing. The advantage of keeping the two connected is that we need to # make sure that the forma...
StarcoderdataPython
1733661
<reponame>minrk/binderhub<filename>testing/minikube/binderhub_config.py # config file for testing with minikube-config.yaml import subprocess try: minikube_ip = subprocess.check_output(['minikube', 'ip']).decode('utf-8').strip() except (subprocess.SubprocessError, FileNotFoundError): minikube_ip = '192.168.1.10...
StarcoderdataPython
189674
<filename>app/core/migrations/0003_auto_20210922_1112.py # Generated by Django 3.2.7 on 2021-09-22 11:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0012_alter_user_first_name...
StarcoderdataPython
1733423
import argparse from pybedtools import BedTool if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("bed12") parser.add_argument("introns") args = parser.parse_args() bed = BedTool(args.bed12) introns = bed.introns() introns.remove_invalid().saveas(args.intron...
StarcoderdataPython
3228438
<reponame>ChangjieChen/lucis_qgis<filename>algorithms/zonal_stats.py import sys import os from PyQt5.QtCore import QCoreApplication from qgis.core import (QgsProcessing, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, QgsProcessingParameterRasterLayer, ...
StarcoderdataPython
3309208
<reponame>jlfranklin/python-acquia-cloud-2<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- from unittest.mock import patch from acapi2.http_request import HttpRequest from acapi2.tests import BaseTest class TestHttpRequest(BaseTest): def test_session(self): http_request = HttpRequest() ...
StarcoderdataPython
1670387
<reponame>isudox/leetcode-solution """688. Knight Probability in Chessboard https://leetcode.com/problems/knight-probability-in-chessboard/ """ import functools def knight_probability(self, n: int, k: int, row: int, column: int) -> float: @functools.lru_cache(None) def dfs(x: int, y: int, steps: int) -> int: ...
StarcoderdataPython
1687572
import dataclasses import enum import re from typing import Mapping, List, Optional, Set from icontract import require, ensure # crosshair: on from python_by_contract_corpus.common import Lines class Operation(enum.Enum): """Represent an operation corresponding to an instruction.""" NOP = "nop" ACC = "...
StarcoderdataPython
1752746
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --------------------------------------- # Project: PKUYouth Webserver v2 # File: types.py # Created Date: 2020-07-28 # Author: <NAME> # --------------------------------------- # Copyright (c) 2020 PKUYouth import redis from .pool import REDIS_CONNECTION_POOL class Red...
StarcoderdataPython
3236853
''' Python program to split a given string (s) into strings if there is a space in the string, otherwise split on commas if there is a comma, otherwise return the list of lowercase letters with odd order (order of a = 0, b = 1, etc.) Input: a b c d Split the said string into strings if there is a space in the string, ...
StarcoderdataPython
106805
from typing import Optional from ._price import Price from ._response import Response class Security(Response): @property def _sec(self) -> dict: return self @property def bid(self) -> Price: return Price(self._sec['bid']) @property def closing_bid(self) -> Price: re...
StarcoderdataPython
3355131
import numpy as np from sklearn.preprocessing import scale,StandardScaler import torch import torch.utils.data as Data import math import torch.nn as nn from sklearn.metrics import confusion_matrix, classification_report,accuracy_score def gpu_available(): use_gpu = torch.cuda.is_available() return use_gpu de...
StarcoderdataPython
3224451
<reponame>myousefi2016/slepc4py<filename>test/test_object.py from slepc4py import SLEPc from petsc4py import PETSc import unittest # -------------------------------------------------------------------- class BaseTestObject(object): CLASS, FACTORY = None, 'create' TARGS, KARGS = (), {} BUILD = None de...
StarcoderdataPython
4816207
from sense_hat import SenseHat import sys sense = SenseHat() if len(sys.argv) != 4: sys.error("Arguments r g b missing") else: sense.clear((int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3])))
StarcoderdataPython
3212213
<filename>Django/Cycl/migrations/0002_auto_20190804_1641.py # Generated by Django 2.2.3 on 2019-08-04 14:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Cycl', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
StarcoderdataPython
3210997
<reponame>mrkday/SATOSA from unittest.mock import mock_open, patch import pytest from satosa.metadata_creation.description import ContactPersonDesc, UIInfoDesc, OrganizationDesc, MetadataDescription class TestContactPersonDesc(object): def test_to_dict(self): desc = ContactPersonDesc() desc.cont...
StarcoderdataPython
4806947
<filename>tutorial_edge/loop_event/simple_coroutine.py import asyncio # Define a coroutine that takes in a future async def myCoroutine(): print("My Coroutine") # Spin up a quick and simple event loop # and run until completed loop = asyncio.get_event_loop() try: loop.run_until_complete(myCoroutine()) fina...
StarcoderdataPython
191840
<filename>utils/py2.py<gh_stars>1-10 from PyQt4 import QtGui, QtCore class RenderManagement(QtGui.QWidget): def __init__(self): super(RenderManagement, self).__init__() self.v_layout = QtGui.QVBoxLayout(self) # Create 5 dynamic items for i in range(5): item = LightIte...
StarcoderdataPython
132109
from django import forms from Apis.canino.models import Perro class PerroForm(forms.ModelForm): # TODO: Define other fields here class Meta: model = Perro fields = [ 'nombre', 'sexo', 'raza', 'edad', 'rescate', 'adoptante', 'vacuna', ...
StarcoderdataPython
3372779
<gh_stars>0 import datetime from collections import OrderedDict from unittest import TestCase from .collect_information import ( deduplicate_msisdns, get_addresses, process_change, process_identity, process_optout, process_registration, process_subscription, ) class GetAddressesTests(Test...
StarcoderdataPython
4837332
import logging from hdx.scraper.base_scraper import BaseScraper from hdx.utilities.dictandlist import dict_of_lists_add from hdx.utilities.text import get_numeric_if_possible logger = logging.getLogger(__name__) class CovaxDeliveries(BaseScraper): def __init__(self, datasetinfo, countryiso3s): super()._...
StarcoderdataPython
1710509
<filename>scraper.py import urllib.request import re import webbrowser from bs4 import BeautifulSoup from functools import partial import fire class HNScraper(object): def __show_in_browser(self, results): output_file_path = '/tmp/jobs.html' with open(output_file_path, 'w+') as f: f.wr...
StarcoderdataPython
131622
<filename>1/q6_expectation_maximization_python/parameters.py def parameters(): epsilon = 0.0001 # regularization K = 3 # number of desired clusters n_iter = 5 # number of iterations skin_n_iter = 5 skin_epsilon = 0.0001 skin_K = 3 theta = 2.0 # threshold for skin detection return eps...
StarcoderdataPython
114718
######################################################### #讀取檔案 ######################################################### #csv file import csv import os script_dir = os.path.dirname(__file__) rel_path = "../data/raw/" abs_file_path = os.path.join(script_dir, rel_path) # 開啟 CSV 檔案 f = open("%stest.csv"%...
StarcoderdataPython
38944
from .changemanager_base import BaseChangeManager from ..utils.psdict import PsDict from ..table.tablechanges import TableChanges from .slot import Slot import copy class DictChangeManager(BaseChangeManager): """ Manage changes that occured in a DataFrame between runs. """ def __init__(self, ...
StarcoderdataPython
3202840
<reponame>ZaoLahma/DockerizeMe class ServiceDiscoveryCtxt: multicast_address = (None, None)
StarcoderdataPython
1685220
from alegra.resources import Contact from alegra.resources import Invoice from alegra.resources import Item from alegra.resources import Retention from alegra.resources import Tax user = None token = None api_base = "https://api.alegra.com/api" api_version = "v1"
StarcoderdataPython
1798347
<reponame>WANGOMES/visors ''' ################################################################################################# AUTOR: <NAME> TRABALHO ACADEMICO: VIGILANCIA SOCIOASSISTENCIAL: MONITORAMENTO DE RISCOS E VULNERABILIDADES EM TEMPO REAL POR MEIO DE MINERAÇÃO DE TEXTO NO TWITTER UNIVERSIDADE: PONTIFÍCI...
StarcoderdataPython
3248824
import sys import boto3 from src.helper import Helper class EFSCleanup: def __init__(self, logging, whitelist, settings, execution_log, region): self.logging = logging self.whitelist = whitelist self.settings = settings self.execution_log = execution_log self.region = reg...
StarcoderdataPython
1678210
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 26 20:59:22 2020 @author: utsav """ import numpy as np import cv2 import base64 import requests import json def to_image_string(image_filepath): return base64.b64encode(open(image_filepath, 'rb').read())#.encode('base64') def from_base64(base...
StarcoderdataPython
179216
# To import required modules: import numpy as np import time import os import sys import matplotlib import matplotlib.cm as cm #for color maps import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec #for specifying plot attributes from matplotlib import ticker #for setting contour plots to log scale im...
StarcoderdataPython
195364
import dataclasses from rentomatic.domain.room import Room @dataclasses.dataclass class MemRepo: data: list def list(self): return [Room.from_dict(d) for d in self.data]
StarcoderdataPython
3289610
<gh_stars>1-10 # -*- coding: utf-8 -*- import datetime from .client import ETGClient from .models import ( GuestData, ) class ETGHotelsClient(ETGClient): def autocomplete(self, query, language=None): """Finds regions and hotels by a part of their names. :param query: par...
StarcoderdataPython
3288633
<gh_stars>0 """Module to connect to the sqlserver database.""" import pymssql from config import _Config class SqlServerConnect: # pylint: disable=too-few-public-methods """Provides the connector to the sqlserver database.""" @staticmethod def connect(app_config: _Config): """Establishes the con...
StarcoderdataPython
19403
""" Train ===== Defines functions which train models and write model artifacts to disk. """ from __future__ import print_function import os import tempfile import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow_mnist import model, paths def train(path): """ Train...
StarcoderdataPython
189475
from django.test import TestCase, Client from django.urls import reverse from blog_crypto.crypto_auth.models import CryptoUser, Profile class ProfileViewTest(TestCase): def test_profile_view_create_user_and_access_profile_page_return_success(self): data_sign_up = { 'email': '<EMAIL>', ...
StarcoderdataPython
3308189
"""Contains function :func:`~.measure` for measuring states""" import random import numpy as np from collections import namedtuple from qualg.scalars import is_number from qualg.states import State from qualg.operators import Operator MeasurementResult = namedtuple("MeasurementResult", ["outcome", "probability", "po...
StarcoderdataPython
1660295
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: mn = math.inf ans = [] arr.sort() n = len(arr) for i in range(n - 1): if arr[i + 1] - arr[i] < mn: mn = arr[i + 1] - arr[i] ans = [[arr[i], arr[i + 1...
StarcoderdataPython
1624856
# -*- coding: utf-8 -*- """Augmentation methods. - Author: Curt-Park - Email: <EMAIL> - Reference: https://arxiv.org/pdf/1805.09501.pdf https://github.com/kakaobrain/fast-autoaugment/ """ from abc import ABC from itertools import chain import random from typing import List, Tuple from PIL.Image import Image ...
StarcoderdataPython
1776906
<filename>browserdb.py #!/usr/bin/python __author__ = 'kilroy' # (c) 2014, WasHere Consulting, Inc. # Written for Infinite Skills import sqlite3 conn = sqlite3.connect("cookies.sqlite") sites = [] # need a cursor to keep track of where we are cur = conn.cursor() for row in cur.execute("SELECT * FROM moz_cookies"):...
StarcoderdataPython
1661839
import ConfigParser from flask import Flask, jsonify, request import json from twilio.rest import TwilioRestClient app = Flask(__name__) config = ConfigParser.ConfigParser() config.read('config.ini') @app.route('/sms/<recipient>', methods=['POST']) def sms_send(recipient): auth = ( config.get('Twilio', ...
StarcoderdataPython
4809340
# Test open and close. ${library_name_suffix}_${type_name}.open(test_source) ${library_name_suffix}_${type_name}.close() # Test open and close a second time to validate clean up on close. ${library_name_suffix}_${type_name}.open(test_source) ${library_name_suffix}_${type_name}.close() if ...
StarcoderdataPython
3344724
<reponame>bvezilic/Transformer from torchtext.data import Field, LabelField from torchtext.datasets import SST def load_SST(root_dir): TEXT = Field(lower=True, tokenize="toktok", eos_token="<eos>") LABEL = LabelField() train, val, test = SST.splits(TEXT, LABEL, root=root_dir) TEXT.build_vocab(train)...
StarcoderdataPython
3278615
#!/usr/bin/env python3 import cgi import hashlib import io import json import multiprocessing.pool import time import zlib from urllib import parse from wsgiref import util from wsgiref.simple_server import WSGIRequestHandler, WSGIServer from passlib import hash def application(env, start_response): request_u...
StarcoderdataPython
1715591
# -*- coding:utf-8 -*- """ 【说明】 (1)由于pyspark不提供Hbase相关api,本样例使用Python调用Java的方式实现 (2)如果使用yarn-client模式运行,请确认Spark2x客户端Spark2x/spark/conf/spark-defaults.conf中 spark.yarn.security.credentials.hbase.enabled参数配置为true """ import sys from py4j.java_gateway import java_import from pyspark.sql import SparkSession if __name...
StarcoderdataPython
4808604
<gh_stars>1-10 ''' area_curves.py Find the area enclosed by two curves between two points ''' from sympy import Integral, Symbol, SympifyError, sympify def find_area(f1x, f2x, var, a, b): a = Integral(f1x-f2x, (var, a, b)).doit() return a if __name__ == '__main__': f1x = input('Enter the upper function ...
StarcoderdataPython
1688758
# Copyright 2017 Adobe. All rights reserved. import ast import hashlib import os import re from collections import OrderedDict from fontTools.misc import etree as ET from fontTools.misc import plistlib from fontTools.ufoLib import UFOReader from fontTools.ufoLib.glifLib import Glyph from psautohint.ufoFont import (n...
StarcoderdataPython
3339184
<reponame>FRC-1721/LAPIS #!/usr/bin/env python """ Copyright (c) 2019-2020, Concord Robotics Inc 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 mu...
StarcoderdataPython
3377614
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys from wxalarmlib import application, config, utils if __name__ == '__main__': # avoid throw [UnicodeEncodeError: 'ascii' codec can't encode characters] _unicode = None if sys.version_info < (3, 0): _unicode = unicode ...
StarcoderdataPython
1678435
<reponame>andbortnik/thenewboston-node import logging from typing import Optional from thenewboston_node.business_logic.models import Node from thenewboston_node.core.utils.types import hexstr from .base import BaseMixin logger = logging.getLogger(__name__) class NetworkMixin(BaseMixin): def get_node_by_ident...
StarcoderdataPython
32007
<filename>saleor/app/management/commands/install_app.py import json from typing import Any, Optional import requests from django.core.exceptions import ValidationError from django.core.management import BaseCommand, CommandError from django.core.management.base import CommandParser from ....app.validators import AppU...
StarcoderdataPython
188302
#!/usr/bin/env python # -*- coding: utf-8 -*- from rest_framework import serializers from csdn.models import CsdnArticle, CsdnAuthor __author__ = 'wfy' __date__ = '2017/10/14 18:50' class ArticleSerializer(serializers.ModelSerializer): class Meta: model = CsdnArticle fields = '__all__' class A...
StarcoderdataPython
86651
<gh_stars>0 """ ****** ###### ****** ###### """ # 4 6 for r in range(4): # 0 1 2 3 for c in range(6): if r % 2 == 0: print("*", end="") else: print("#", end="") print()
StarcoderdataPython
3346827
<reponame>DAIM-ML/autotf import time import logging from tuner.initial_design.init_random_uniform import init_random_uniform from tuner.parallel_solver.base_parallel_solver import BaseParallelSolver from tuner.parallel_solver.base_parallel_solver import evaluate_func logger = logging.getLogger(__name__) class Async...
StarcoderdataPython
1665124
from datetime import datetime, timedelta import time import requests import json from matplotlib.pylab import date2num from matplotlib import pyplot as plt import mpl_finance as mpf from pandas import DataFrame import talib as ta import sys sys.path.append('..') import DictCode as dc plt.rcParams['font.family'] = 'sa...
StarcoderdataPython
1674847
<reponame>Unity05/WebCrawler<filename>crawler.py from selenium import webdriver import requests import nltk from bs4 import BeautifulSoup from bs4.element import Comment import time import json def split_to_sentences(content): sentences = nltk.sent_tokenize(content) return sentences def search_for_keywords(...
StarcoderdataPython
3202625
from utils import readYaml from os import path import collections from field_names import FieldNames line_fields_names = FieldNames() def read_text(text_file, yaml_dir): XC = "\u001b" iBIBINFO = "bibinfo" iSCROLLINFO = "scrollinfo" iSCROLLNAME = "scrollname" iSCROLLREF = "scrollref" iTRANS = "...
StarcoderdataPython
1766038
<reponame>DemjanUA/uchkin_diploma import os import numpy # scipy.special for the sigmoid function expit() from scipy import special # neural network class definition class neuralNetwork: # initialise the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): # set n...
StarcoderdataPython
3242533
import os from flask import ( Flask, flash, render_template, redirect, request, session, url_for) from flask_pymongo import PyMongo from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.utils import secure_filename import urllib.reques...
StarcoderdataPython
91975
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys sys.dont_write_bytecode = True import os import re import posixpath try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension def get_str(var_name): src_py = open('litefs.py').read() return re....
StarcoderdataPython
3295780
__all__ = ['neuralnet']
StarcoderdataPython
80455
<gh_stars>0 print('My name is') for i in range(5): print('elgun',i) print('letsdo it') # total=0 # for i in range(11): # total=total+i # print('Value of i: ',i) # print('Value of total: ',total) # print(total) # i=0 # while i<6: # print('The value of i:'+str(i)) # i+=2 # Stat=4, End=...
StarcoderdataPython
3203115
# Copyright (c) 2014 OpenStack Foundation. # # 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...
StarcoderdataPython
76413
<gh_stars>10-100 from .quality_metric_classes.metric_data import MetricData from .quality_metric_classes.amplitude_cutoff import AmplitudeCutoff from .quality_metric_classes.silhouette_score import SilhouetteScore from .quality_metric_classes.num_spikes import NumSpikes from .quality_metric_classes.firing_rate import F...
StarcoderdataPython
176355
<reponame>S-Gholami/geometry-python # author: @s.gholami # ----------------------------------------------------------------------- # read_matrix_input.py # ----------------------------------------------------------------------- # Accept inputs from console # Populate the list with the inputs to form a matrix def equa...
StarcoderdataPython
3212589
from datetime import timedelta from sqlalchemy.sql import func from flask import request from zeus.api.utils import stats from zeus.config import db from zeus.models import Build, User from zeus.utils import timezone from .base import Resource STAT_CHOICES = frozenset( ("builds.errored", "builds.total", "users....
StarcoderdataPython
1734686
<gh_stars>0 # -*- coding: utf-8 -*- import mysql.connector import logging class MySQLPipeline(object): def open_spider(self, spider): # Set your database connection details self.connection = mysql.connector.connect(host="localhost", user="root", password="<PASSWORD>") # Craeting a curso...
StarcoderdataPython
3327957
name = str(input('Digite um nome: ')).upper() for i in range(0, len(name)+1): print(name[:i])
StarcoderdataPython
60722
from django.contrib import admin from .models import Vote, Blog # Register your models here. admin.site.register(Vote) admin.site.register(Blog)
StarcoderdataPython
1795767
<reponame>mikusjelly/saam<gh_stars>1-10 import os import configparser import yaml __version__ = '0.0.1' HOME = os.path.join(os.path.dirname(__file__), '..') __cfg = configparser.ConfigParser() __cfg.read(os.path.join(HOME, 'conf.ini')) # ../tools/apktool/apktool.jar __APKTOOL_DEFAULT = os.path.join(HO...
StarcoderdataPython
1611207
#!/usr/bin/env python from __future__ import division from __future__ import absolute_import from __future__ import print_function from madgraph.interface import reweight_interface from six.moves import map from six.moves import range from six.moves import zip #########################################################...
StarcoderdataPython
1698130
<reponame>weijiadeng-uber/neuropod<filename>source/bazel/python.bzl # https://docs.bazel.build/versions/master/skylark/repository_rules.html def _impl(repository_ctx): # The `or` pattern below handles empty strings and unset env variables # Using a default value only handles unset env variables version = re...
StarcoderdataPython
87721
<reponame>gguilherme42/Livro-de-Python def menu(): print("") print(f'''<------ MENU ------> A - para adição S - para subtração D - para divisão M - para múltiplicação X - para sair''') def Aritmetica(a, operacao): arit = {'A': lambda a, b: a + b, 'S': lambda a, b: a - b, ...
StarcoderdataPython
4839140
<filename>Python3/config.py # DEVELOPER CONFIG (EDIT NOT RECOMMENDED) BUILD_VERSION = "v1.13.23-public" AUTHOR = "<NAME>" PROGRAM_NAME = "GUI Hangman" TOTAL_GUESSES_ALLOWED = 5 BLANK = "_____" """ CREDITS: 'back.png' Icon made by 'Kiranshastry' from www.flaticon.com (24px) GUI HANGMAN """ """ MIT License Copyrig...
StarcoderdataPython
3374695
<gh_stars>1-10 import logging from flask import Flask, render_template, request, flash, redirect, url_for from esipy import App, EsiClient, EsiSecurity from lib import CharacterExplorer, all_esi_read_scopes app = Flask(__name__) app.config.from_json('config.json') esi_headers = {'User-Agent': 'EVE Character Explor...
StarcoderdataPython
3262575
<filename>setup.py from setuptools import setup setup( name="pyprince", version="0.5", license="MIT", url="https://github.com/sufio/python-pyprince", description="Prince xml python wrapper for converting HTML to PDF", author="Sufio.com", author_email="<EMAIL>", tests_require=["pytest"],...
StarcoderdataPython
3301937
<filename>network_model.py import numpy as np import pandas as pd import geopandas as gpd class network_model(): def __init__(self, lines, subs, util, gen, bbox=None, loads=None, pop_dens=None): self.lines = gpd.read_file(lines) self.subs = gpd.read_file(subs) self.util = gpd.read_file(ut...
StarcoderdataPython
1636423
<reponame>fweissberg/xous-core #!/usr/bin/python3 import argparse from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Random import get_random_bytes import binascii import logging import sys """ Reverse the order of bits in a word that is bitwidth bits wide """ def bitflip(data_block, bitwidth=3...
StarcoderdataPython
128055
<filename>algos/patterns/bitWiseXor/complement_base_10.py # Every non-negative integer N has a binary representation, for example, 8 can be represented as “1000” in binary and 7 as “0111” in binary. # The complement of a binary representation is the number in binary that we get when we change every 1 to a 0 and every ...
StarcoderdataPython
180224
<reponame>ZhouXing19/ContAnalysisFinalProj #All these packages need to be installed from pip import gensim#For word2vec, etc import argparse import math import numpy as np #For arrays import pandas as pd #Gives us DataFrames pd.options.mode.chained_assignment = None import os #For looking through files import os.path ...
StarcoderdataPython
1752664
import os import numpy as np import sys, unicodedata # In[2]: tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')) # In[4]: for root,dirs, files in os.walk('tsv_files/'): tsv_list = [file for file in files if file[-3:]=="tsv"] whole_class_info=[[]...
StarcoderdataPython
3287110
<reponame>jdfergusson/ReChorder<filename>rechorder/rechorder/migrations/0004_auto_20200407_1140.py # Generated by Django 3.0.4 on 2020-04-07 11:40 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rechorder', '0003_auto_20200...
StarcoderdataPython
133799
from bs4 import BeautifulSoup import requests from datetime import datetime from urllib.parse import urljoin # ask questions # change variables in the next sections # use those variables to change outcomes in what is being scraped # if there are mistakes, catch them ####### ####### Hey! What's your name? user_name = ...
StarcoderdataPython
1742528
<filename>t5/evaluation/eval_utils.py # Copyright 2020 The T5 Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
StarcoderdataPython
1609301
<filename>utils/nth_root.py def nth_root(x,n): # credit http://stackoverflow.com/questions/356090/, <NAME> """Finds the integer component of the n'th root of x, an integer such that y ** n <= x < (y + 1) ** n. """ high = 1 while high ** n < x: high *= 2 low = high/2 while low < high:...
StarcoderdataPython
1652374
# apps/listings/admin.py # Django modules from django.contrib import admin # Locals from apps.listings.models import Category, Product # Register your models here. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'slug') prepopulated_fields = {'slug': ('name',)} @admin.r...
StarcoderdataPython
3285577
<reponame>anu-ka/coding-problems # https://leetcode.com/problems/can-place-flowers/submissions/ # You have a long flowerbed in which some of the plots are planted, and some are not. # However, flowers cannot be planted in adjacent plots. # Given an integer array flowerbed containing 0's and 1's, where 0 means empty and...
StarcoderdataPython
3310498
# -*- coding: utf-8 -*- __author__ = "<NAME>, <NAME>, <NAME>" __copyright__ = "Copyright 2019, The Information Security and Privacy Lab at the University of Lausanne (https://www.unil.ch/isplab/)" __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] __version__ = "1" __license__ = "MIT" __maintainer__...
StarcoderdataPython
11585
from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from cart.models import Cart from django.views import View from .forms import LoginForm, RegistrationForm, CreateCompanyForm from customer.models import Customer, ShippingAddress from src.utils.mixins import CustomerMixin ...
StarcoderdataPython
1602488
## set up logging import logging, os logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO")) log = logging.getLogger(__name__) ## import modules import octvi.exceptions, octvi.array, gdal from gdalnumeric import * import numpy as np def getDatasetNames(stack_path:str) -> list: """ Returns list of...
StarcoderdataPython
1683783
<filename>tests/v0x01/test_controller2switch/test_stats_reply.py """Test for StatsReply message.""" import unittest from pyof.v0x01.controller2switch import common, stats_reply class TestStatsReply(unittest.TestCase): """Test for StatsReply message.""" def setUp(self): """Baisc Test Setup.""" ...
StarcoderdataPython
129944
<filename>tests/unit/test_views.py # 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, ...
StarcoderdataPython
1668013
from configuration import Configuration from html_reader import HTLMReader if __name__ == "__main__": text = "A<b>l</b>a ma <i>k</i>o<u>t</u>a" print(f"Oryginalny tekst:\n\t{text}\n") # 1)RemoveTag 2)TagToUppercase 3)CapitalizeTag 4)FormatTag builder_list = [Configuration().remove_tag, Config...
StarcoderdataPython
1647435
#!/usr/bin/env python3 import urllib.request as r import urllib.parse as p import json import time def get_with_dims(dims): return r.urlopen("http://0.0.0.0:30001/splat?dims=" + dims).read().decode('utf-8') print("\n\n" + str(get_with_dims("2,2")))
StarcoderdataPython
107225
import os import sys cwd = os.getcwd() sys.path.insert(0, cwd+'/../..') import pandas from plot.box.utils_plot import * from plot.box.paths_cartpoleNoisyA_test import * def sweep_model(): k10_far_cms = { "normal": cpn01_k10_far_reward002, "0.01 terminal": cpn01_k10_far_reward002_risk001, "0...
StarcoderdataPython
3263081
import logging LOGGER = logging.getLogger(__name__) def version(): """Return version number """ version = None try: import pkg_resources except ImportError as e: LOGGER.error("Can't find version number, please install setuptools") raise e try: version = pkg_res...
StarcoderdataPython
1606176
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import json import ConfigParser from flod_common.session.cookie_helper import get_auth_type_from_cookie, get_redirect_target_from_cookie, invalidate_redirect_target_cookie, set_auth_type_cookie, \ set_redirect_target_cookie import os from datetime import...
StarcoderdataPython
3227049
<reponame>SahandAslani/ballistica # Copyright (c) 2011-2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, cop...
StarcoderdataPython
1765284
"""Library for the conversion from NEMO output to XGCM data sets.""" import numpy as np import xarray as xr from . import orca_names def trim_and_squeeze(ds, model_config="GLOBAL", y_slice=None, x_slice=None, **kwargs): """Remove redundant grid poin...
StarcoderdataPython