id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
9729321
<gh_stars>1-10 """ Codemonk link: https://www.hackerearth.com/practice/basic-programming/recursion/recursion-and-backtracking/practice-problems/algorithm/question-2-38-cf73c1b4/ You are given a, b and c. You need to convert a to b. You can perform following operations: 1) Multiply a by c. 2) Decrease a by 2. 3) ...
StarcoderdataPython
9710524
# -*- coding: utf-8 -*- import numpy as np from numpy.testing import assert_allclose, assert_array_almost_equal import pytest from africanus.constants import c as lightspeed pmp = pytest.mark.parametrize def _l2error(a, b): return np.sqrt(np.sum(np.abs(a-b)**2)/np.maximum(np.sum(np.abs(a)**2), ...
StarcoderdataPython
1889622
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (t...
StarcoderdataPython
6680018
<gh_stars>1-10 from django.conf.urls import patterns, url from .views import Home urlpatterns = patterns('', url(r'^$', 'apps.users.views.userlogin', name="login"), url(r'^salir/$', 'apps.users.views.LogOut', name = 'logout'), url(r'^home', Home.as_view(), name='home'), )
StarcoderdataPython
71592
<reponame>Jos33y/student-performance-knn """ Public API for extending pandas objects. """ from pandas._libs.lib import no_default from pandas.core.dtypes.dtypes import ExtensionDtype, register_extension_dtype from pandas.core.accessor import ( register_dataframe_accessor, register_index_accessor, ...
StarcoderdataPython
11280167
<filename>tests/test_api_schema.py # -*- coding: UTF-8 -*- """ A suite of tests for the HTTP API schemas """ import unittest from jsonschema import Draft4Validator, validate, ValidationError from vlab_inventory_api.lib.views import inventory class TestInventoryViewSchema(unittest.TestCase): """A set of tes cases...
StarcoderdataPython
339846
import pandas as pd from datetime import datetime import psycopg2 from fbprophet import Prophet from ETLPipelines.InsertData import * # Connect to database conn = psycopg2.connect(host='localhost', port=5432, database='postgres') # Obtain trade days between 2019 and 2020 query_test = """select tradedate from stock.s...
StarcoderdataPython
171638
import re from collections import defaultdict, namedtuple from pathlib import Path from openpecha.formatters.layers import AnnType, SubText from openpecha.utils import load_yaml INFO = "[INFO] {}" class Serialize(object): """ This class is used when serializing the .opf into anything else (Markdown, TEI, et...
StarcoderdataPython
4980242
from . _model import WalkBot from . _env import WalkBotEnv from . _sc_model import WalkBotSC from . _sc_env import WalkBotSCEnv
StarcoderdataPython
392958
import json import jsonpickle from powernad.Connector.restapi import RestApi from powernad.Object.Ad.AdObject import AdObject from powernad.Object.Ad.RequestObject.CreateAdObject import CreateAdObject from powernad.Object.Ad.RequestObject.UpdateAdObject import UpdateAdObject from powernad.Common.CommonFunctions import ...
StarcoderdataPython
199510
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
1938557
<filename>codes/2018-05-07-identidad.py import numpy as np respuestas = [] tamaño = (int(input())) while tamaño: matriz = [] for _ in range(tamaño): matriz.append([int(x) for x in input().split()]) matriz = np.array(matriz, dtype=int) identidad = np.identity(tamaño, int) if np.array_equal(m...
StarcoderdataPython
3269439
from flask import Flask, request from flask_mongoengine import MongoEngine import json db = MongoEngine() app = Flask(__name__) app.config['MONGODB_SETTINGS'] = { 'db': 'musity', 'host': 'ds139979.mlab.com', 'port': 39979, 'username': 'mxkhsbfewijdfepokdf', 'password': '<PASSWORD>' } db.init_app(...
StarcoderdataPython
3320634
<gh_stars>0 import numpy as np import cv2 def chrToNum(chr): if '9' >= chr >= '0': return ord(chr) - ord('0') elif 'A' <= chr <= 'F': return ord(chr) - ord('A') + 10 def decodeJPG(path="H://zj_pic.txt"): string = open(path).read() string = string.split(" ") toarray = np.asarray(s...
StarcoderdataPython
3487406
<reponame>laurens-in/magenta # Copyright 2019 The Magenta 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 by ap...
StarcoderdataPython
3312079
import dateutil.parser import flask from jinja2 import evalcontextfilter, Markup, escape from datetime import datetime import re PARAGRAPH_RE = re.compile(r'(?:\r\n|\r|\n){2,}') filters = flask.Blueprint('filters', __name__) @filters.app_template_filter("join_list") def join_list(value): values = list(value...
StarcoderdataPython
290391
<gh_stars>0 # Generated by Django 1.10.1 on 2016-10-03 18:17 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Seat', fields...
StarcoderdataPython
1797953
import time from apscheduler.schedulers.background import BackgroundScheduler import requests from bs4 import BeautifulSoup # crawling job def job_crawling(): print('start crawling') url = 'https://news.daum.net/breakingnews/digital' #param = '?page=2' response = requests.get(url) return Beautiful...
StarcoderdataPython
5071734
"""Models (only one, actually) for communication with the database.""" import uuid from datetime import datetime from sqlalchemy import Column, DateTime, String from .database import Base class RedditPicture(Base): """Represents a picture post in the database.""" __tablename__ = "history" id = Column(...
StarcoderdataPython
6476919
<gh_stars>1-10 from .schema import HwSchema from .schema import SchemaLatest from .schema import SchemaId from .schema import SchemaDropVersion from .schema import SchemaNew from .schema import SchemaNewMeta from .schema import SchemaMetaData from .schema import SchemaGetVersions from .schema import SchemaGetVersion fr...
StarcoderdataPython
198231
<reponame>xaptum/xtt-python<gh_stars>0 # Copyright 2018 Xaptum, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
StarcoderdataPython
3466090
# #!/usr/bin/env python3 # import socket # HOST = '127.0.0.1' # The server's hostname or IP address # PORT = 65432 # The port used by the server # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # s.connect((HOST, PORT)) # s.sendall(b'Hello, world') # data = s.recv(1024) # print('Re...
StarcoderdataPython
364220
<filename>kmeans_torch.py<gh_stars>1-10 # Using pytorch to implement K-means clustering, since Sklearn is too slow for calculation of large scale of kmeans. # Batch technique and GPU are benefitial for acclerating the calculation. import torch import numpy as np from tqdm import trange from torch import Tensor import ...
StarcoderdataPython
8195839
<reponame>isenilov/avro-to-python<filename>avro_to_python/utils/avro/types/record.py from typing import Tuple from avro_to_python.classes.field import Field from avro_to_python.utils.avro.helpers import ( _get_namespace, _create_reference ) kwargs = { 'name': None, 'fieldtype': None, 'avrotype': None...
StarcoderdataPython
8051486
#!/usr/bin/env python3 from jagerml.helper import * class Dropout: def __init__(self, rate): self.rate = 1 - rate def forward(self, inputs, training): self.inputs = inputs if not training: self.output = inputs.copy() return self.binaryMask = np.rand...
StarcoderdataPython
1643787
"""GrailQA: The Strongly Generalizable Question Answering Dataset.""" import json import os import datasets logger = datasets.logging.get_logger(__name__) _CITATION = """\ @inproceedings{gu2021beyond, title={Beyond IID: three levels of generalization for question answering on knowledge bases}, ...
StarcoderdataPython
9710425
<reponame>leikareipa/vcs-doxy-theme<gh_stars>0 # # 2021 <NAME> # # Software: VCS Doxygen theme # from xml.etree import ElementTree from typing import Final from functools import reduce from html import escape from src import xml2html import sys import re # The sub-components used in this component. childComponents:Fi...
StarcoderdataPython
12864283
<filename>Leetcode/res/Longest Common Prefix/2.py # Author: allannozomu # Runtime: 56 ms # Memory: 13 MB class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: res = "" max_length = -1 for s in strs: if max_length < 0: max_length = len(s) ...
StarcoderdataPython
5115077
<reponame>worldbank/SDG-big-data<filename>twitter-analytics/code/3-model_evaluation/expansion/preliminary/calibration_uncertainty.py import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt from config import * import pickle import warnings import os imp...
StarcoderdataPython
3416574
<filename>arbiter/event/base.py<gh_stars>0 # Copyright 2020 getcarrier.io # # 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 # # Un...
StarcoderdataPython
5154512
"""Data reset tool End-Points. Get, post, and delete business, including all sub-objects - filings, addresses, etc. """ import os from flask import Flask from legal_api.models import db from legal_api.schemas import rsbc_schemas from legal_api.utils.logging import setup_logging from data_reset_tool import config fro...
StarcoderdataPython
5088331
from django.urls import path, include from rest_framework.routers import DefaultRouter from apps.spider_view.views import * router = DefaultRouter() router.register('entry', EntryViewSet, basename='entry') urlpatterns = [ path('', include(router.urls)), path('site-type/', SiteTypeView.as_view()) ]
StarcoderdataPython
5064547
# Generated by Django 3.2.7 on 2021-09-29 11:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
StarcoderdataPython
360706
<gh_stars>10-100 import unittest from unittest.mock import Mock import test.factories as factories from flask import Flask, json from src.stocks import stocks_api class ApiTest(unittest.TestCase): def setUp(self): app = Flask(__name__) app.config['DEBUG'] = True self.domain_mock = Mock(...
StarcoderdataPython
5197469
<reponame>ismailbozkurt/libheap<filename>libheap/ptmalloc/malloc_state.py import sys import struct from libheap.frontend.printutils import color_title from libheap.frontend.printutils import color_value from libheap.frontend.printutils import print_error class malloc_state: "python representation of a struct mal...
StarcoderdataPython
9788520
<reponame>tenthirtyone/BountiesAPI # -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-16 11:58 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user', '0012_rankedskill'), ] operations = [ mi...
StarcoderdataPython
1603516
<filename>Udacity/poker/test_poker.py # Test File for Poker # Author: <NAME> # Start Date : 14th December 2014 # Last Update: 14th December 2014 import poker def test_Poker(): "Test cases for the functions in poker program" sf = "6C 7C 8C 9C TC".split() # Straight Flush fk = "9D 9H 9S 9C 7D".split() # Four of a Kind...
StarcoderdataPython
11364381
<gh_stars>1-10 import hashlib class BadMAC: def __init__(self, key, message): self.key = key self.message = message self.hashfunction = hashlib.md5(self.key + self.message) def digest(self): return self.hashfunction.digest() def hexdigest(self): return self.hashf...
StarcoderdataPython
1814043
import clr def process_input(func, input): if isinstance(input, list): return [func(x) for x in input] else: return func(input) def journalSysInfoKey(jsysinfo): if hasattr(jsysinfo, 'SystemInformationType'): return jsysinfo.Key else: return None OUT = process_input(journalSysInfoKey,IN[0])
StarcoderdataPython
1997942
from __future__ import division __copyright__ = "Copyright (C) 2009-2013 <NAME>" __license__ = """ 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 limitatio...
StarcoderdataPython
6646833
import numpy as np import maxflow import copy from profilehooks import profile import time class Segmentor: def __init__(self, img): self.img = copy.copy(img) self.mask_color = (255, 1, 255) @profile def max_flow_gray(self): start = time.time() height, width = self.img.s...
StarcoderdataPython
9752438
<filename>python/dedup_all.py from dedup import nonemail_pstitems_tofile as nepi_tofile from dedup import nonemail_pstitems as nepi from dedup import email_pstitems as epi from dedup import fileitems as fi def main(): nepi_tofile.run() nepi.run() epi.run() fi.run() if __name__ == '__main__': main()
StarcoderdataPython
5009597
<filename>tests/homework/test_homework9.py import unittest #Write the import statement for the Die class from src.homework.homework9.die import Die class TestHomework9(unittest.TestCase): def test_rolls_values_1_to_6(self): ''' Write a test case to ensure that the Die class only rolls values from ...
StarcoderdataPython
357562
import cronjobs from users.models import RegisterProfile, ACTIVATION_EMAIL_SUBJECT @cronjobs.register def resend_activation(): """ Resends the activation email to every user who hasn't activated their account. """ for profile in RegisterProfile.objects.all(): RegisterProfile.objects._send...
StarcoderdataPython
24612
<filename>mydb/test_postgres.py #!/usr/bin/python import time import psycopg2 import argparse import postgres_util import container_util import admin_db import volumes from send_mail import send_mail from config import Config def full_test(params): admin_db.init_db() con_name = params['dbname'] dbtype = ...
StarcoderdataPython
11311785
import requests import json import sys from bs4 import BeautifulSoup as bs hosts = { "wikipedia": "https://en.wikipedia.org/w/api.php", "wikidata": "https://www.wikidata.com/w/api.php", "wikibooks": "https://en.wikibooks.org/w/api.php" } responses = { "wikipedia": "https://en.wikipedia.org/?curid=", ...
StarcoderdataPython
11386378
<filename>terrascript/data/scaleway.py # terrascript/data/scaleway.py import terrascript class scaleway_bootscript(terrascript.Data): pass class scaleway_image(terrascript.Data): pass class scaleway_security_group(terrascript.Data): pass class scaleway_volume(terrascript.Data): pass class sca...
StarcoderdataPython
5139698
def extract_translated_sentences(json_response): translations = json_response["result"]["translations"] translated_sentences = [ translation["beams"][0]["postprocessed_sentence"] for translation in translations ] return translated_sentences def extract_split_sentences(json_response): ...
StarcoderdataPython
1937041
import os import datetime import json import magic import shutil import base64 from pathlib import Path from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, timeline, kmlgen, is_platform_windows, media_to_html def get_icloudReturnsphotolibrary(files_found, report_folder...
StarcoderdataPython
12842238
<filename>leavable_wait_page/pages.py import time from django.http import HttpResponseRedirect from otree.models import Participant from . import models from ._builtin import Page, WaitPage class DecorateIsDisplayMixin(object): def __init__(self): super(DecorateIsDisplayMixin, self).__init__() # ...
StarcoderdataPython
4861431
<reponame>xugaoxiang/FlaskTutorial from flask import jsonify from flask_restful import Resource, reqparse from flask_jwt_extended import create_access_token, jwt_required from app.models import User from app import jwt @jwt.expired_token_loader def expired_token_callback(): return jsonify({ 'code': 201, ...
StarcoderdataPython
198803
<gh_stars>10-100 from django.conf import settings from django.core.mail import send_mail from django.core.urlresolvers import reverse # Send mail validation to user, the email should include a link to continue the # auth process. This is a simple example, it could easilly be extended to # render a template and send a...
StarcoderdataPython
4943597
<reponame>PacktPublishing/Machine-Learning-and-Data-Science-with-Python-A-Complete-Beginners-Guide # -*- coding: utf-8 -*- """ @author: abhilash """ #load the csv file using read_csv function of pandas library from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection impo...
StarcoderdataPython
6540954
def is_matched(expr): """Return True if all the delimiters are properly match. False otherwise.""" lefty = '({[' righty = ')}]' S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False ...
StarcoderdataPython
122286
<filename>test/test_sparse_input.py<gh_stars>0 import pytest import numpy as np from scipy import sparse from ordreg.ordinal import OrdinalRegression N = 100 P = 4 J = 3 @pytest.fixture def X_dense(): return np.random.normal(size=(N, P)) @pytest.fixture def X_sparse(X_dense): return sparse.csr_matrix(X_de...
StarcoderdataPython
12846572
<reponame>wynterwang/restful-falcon # -*- coding: utf-8 -*- # __author__ = "wynterwang" # __date__ = "2020/9/18" from __future__ import absolute_import from datetime import datetime from celery import states from restful_falcon.core.db.model import Column from restful_falcon.core.db.model import Model from restful_f...
StarcoderdataPython
277625
<filename>code/12_get_guess_repr.py #!/usr/bin/env python3 import os import sys import argparse import numpy as np from pyscf import scf from utils import readmol,compile_repr,unix_time_decorator from guesses import * parser = argparse.ArgumentParser(description='This program computes the chosen initial guess for a s...
StarcoderdataPython
5134324
from django.utils.translation import gettext_lazy from rest_framework import serializers from datahub.company.serializers import NestedAdviserField from datahub.core.constants import Country from datahub.core.serializers import NestedRelatedField from datahub.core.validate_utils import DataCombiner from datahub.event....
StarcoderdataPython
11237536
<filename>_dependencies/library/blockdevmap.py<gh_stars>10-100 # Copyright 2020 <NAME> <<EMAIL>> # BSD 3-Clause License # https://github.com/dseeley/blockdevmap # Copyright 2017 Amazon.com, Inc. and its affiliates. All Rights Reserved. # Licensed under the MIT License. See the LICENSE accompanying this file # for the ...
StarcoderdataPython
3396642
<gh_stars>1-10 from collections import defaultdict def autovivi(): return defaultdict(autovivi) class addlist(list): def add(self, item): return self.append(item) def parse_data(data): acc = autovivi() section = None for line in data.splitlines(): if line.startswith("#"): ...
StarcoderdataPython
8022134
from pyrh import Robinhood from dotenv import load_dotenv from tweepy import OAuthHandler from tweepy import API from tweepy import Cursor from datetime import datetime, timedelta import urllib.request import os # disable tensorflow debug information os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from imageai.Detection.Custo...
StarcoderdataPython
1884003
from pynvrtc.interface import NVRTCInterface, NVRTCException src = ... ## Populate CUDA source code inter = NVRTCInterface() try: prog = inter.nvrtcCreateProgram(src, 'simple.cu', [], []); inter.nvrtcCompileProgram(prog, ['-ftz=true']) ptx = inter.nvrtcGetPTX(prog) except NVRTCException as e: print('...
StarcoderdataPython
9667819
""" Test to validate that pylint_django doesn't produce Instance of 'SubFactory' has no 'pk' member (no-member) warnings """ # pylint: disable=attribute-defined-outside-init, missing-docstring, too-few-public-methods import factory from django import test from django.db import models class Author(models.Model): ...
StarcoderdataPython
3242520
<filename>src/sql_names.py #sql table connection import sqlite3 as sql conn = sql.connect("../tmp/nameset.db") cursor = conn.cursor() ## cursor.execute('SELECT name FROM otpy_names WHERE num = 1') result = cursor.fetchall() mm1 = result[0][0] ## cursor.execute('SELECT name FROM otpy_names WHERE num = 2') result = curso...
StarcoderdataPython
8088317
<gh_stars>1-10 from transformers import AutoTokenizer, AutoModelForCausalLM,AutoModelForSeq2SeqLM import torch import json import argparse parser = argparse.ArgumentParser() parser.add_argument('--model_type',type=str,default="t5") parser.add_argument('--device', type=str, default='any') parser.add_argument('--input_...
StarcoderdataPython
6668383
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import sys import os from pathlib import Path # The code being tested in this test file is in the poprithms/notes directory # of the source tree: currentSourceDir = Path(os.path.dirname(__file__)) projectDir = currentSourceDir.parent.parent.parent.parent shiftN...
StarcoderdataPython
1754080
<reponame>eriksore/sdn<filename>OdlApplication/frontend.py import restconf import json from lxml import etree #Base URLs for Config and operational baseUrl = 'http://192.168.231.255:8080' confUrl = baseUrl + '/restconf/config/' operUrl = baseUrl + '/restconf/operational/' findTopology = operUrl + '/network-topology:net...
StarcoderdataPython
6475925
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import logging import os from typing import Any, List, Tuple, Union import numpy as np import pytest from sklearn.datase...
StarcoderdataPython
6452300
<gh_stars>0 """Config file.""" import logging import os from typing import TypedDict import dash # type: ignore import dash_bootstrap_components as dbc # type: ignore import flask CSV = "./data/used-data.csv" CSV_META = "./data/used-data-meta.txt" CSV_BACKUP = "./data/used-data-bkp.csv" CSV_BACKUP_META = "./data/u...
StarcoderdataPython
6498200
<reponame>kjaymiller/pit_publisher from pymongo import MongoClient from config import DATABASE_URL, PORT, DATABASE, USERNAME, PASSWORD from urllib.parse import quote_plus password = quote_plus(PASSWORD) conn = MongoClient(DATABASE_URL, PORT) db = conn[DATABASE] auth = db.authenticate(USERNAME, PASSWORD)
StarcoderdataPython
134983
""" Contains the Artist class """ __all__ = [ 'Artist', ] class Artist(object): """ Represents an artist """ def __init__(self): """ Initiate properties """ self.identifier = 0 self.name = '' self.other_names = '' self.group_name = '' ...
StarcoderdataPython
11231345
""" Extracts list of IO domains from iogames.fun, a creates strings for DNS blackholes (BIND9) style. """ from requests import get from contextlib import closing from bs4 import BeautifulSoup URI = "http://iogames.fun/list" bind_rule_start = 'zone "' bind_rule_end = '" { type master; file "/etc/bind/zones/db.blackho...
StarcoderdataPython
1649475
# Bootloader (and Beyond) Instrumentation Suite package name = 'fiddle'
StarcoderdataPython
4926503
<filename>convert_tf_to_tflite.py # Copyright 2021 The Kalray Authors. All Rights Reserved. # # Licensed under the MIT License; # you may not use this file except in compliance with the License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ...
StarcoderdataPython
6587097
<reponame>spiegelm/smart-heating-server # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('smart_heating', '0005_raspberrydevice_thermostatdevice'), ] op...
StarcoderdataPython
5023727
<reponame>Brandon-HY-Lin/deep-reinforcement-learning import numpy as np import pickle from collections import namedtuple import matplotlib.pyplot as plt import torch ScoreParcels = namedtuple('ScoreParcels', ['comment', 'path_scores', 'color']) ScoreParcelsV2 = namedtuple('ScoreParcels', ['comment', 'path_scores', '...
StarcoderdataPython
4957295
"""Gaussian process utilities for Torch code.""" import math from typing import Tuple import torch def real_fourier_basis(n: int) -> Tuple[torch.Tensor, torch.Tensor]: """Make a Fourier basis. Args: n: The basis size Returns: An array of shape `(n_domain, n_funs)` containing the basis f...
StarcoderdataPython
3535357
from tnetwork.DCD.pure_python.static_cd.louvain import * from tnetwork.dyn_community.communities_dyn_sn import DynCommunitiesSN from tnetwork.utils.community_utils import * import tnetwork as tn import multiprocessing as mp import progressbar import sys # def CD_each_step_non_parallel(dynNetSN: tn.DynGraphSN, method=N...
StarcoderdataPython
8140353
import os.path def check_file(dir, file): ''' Checks the existence of a given filename in a given directory. Return `True` if the file exists and `False` otherwise. ''' if os.path.isfile(os.path.join(dir, file)): return True else: return False
StarcoderdataPython
1779104
<reponame>MelonDLI/ATSPrivacy import torch import os import cv2 import torchvision import numpy as np def psnr(img_batch, ref_batch, batched=False, factor=1.0): """Standard PSNR.""" def get_psnr(img_in, img_ref): mse = ((img_in - img_ref)**2).mean() # if mse > 0 and torch.isfinite(mse): ...
StarcoderdataPython
1681633
<reponame>saadhamidml/gpytorch<filename>gpytorch/variational/independent_multitask_variational_strategy.py #!/usr/bin/env python3 import warnings from ..distributions import MultitaskMultivariateNormal from ..module import Module from ._variational_strategy import _VariationalStrategy class IndependentMultitaskVari...
StarcoderdataPython
66619
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 1 19:34:51 2018 @author: karthik """ import cv2 import os import csv PATH_IMAGE = "./JPEGImages/" PATH_annot = "./annotations_car_only_txt/" PATH_IMAGE_4 = "./JPEGImages_split_5000_0.15/" PATH_ANNOT_4 = "./Annotation...
StarcoderdataPython
9731116
<filename>src/api/post_contact/post_contact.py import json import logging import os import uuid import time import boto3 _logger = logging.getLogger() _logger.setLevel(logging.DEBUG) logging.getLogger('boto3').setLevel(logging.WARN) logging.getLogger('botocore').setLevel(logging.WARN) logging.getLogger('urllib3').setL...
StarcoderdataPython
4884418
<reponame>Str3et/APIask from pymongo import MongoClient client = MongoClient() database = client.database data_db = database.email
StarcoderdataPython
5199178
""" $ pytest -s -v test_extensions.py """ def test_conf(): from sagas.nlu.anal import build_anal_tree, Doc, AnalNode from sagas.nlu.anal_corpus import model_info f = build_anal_tree('Ördek filin üzerinde.', 'tr', 'stanza') # f.draw() assert 'AnalNode_tr'==type(f).__name__ assert 'Doc' == type(f....
StarcoderdataPython
3249026
<gh_stars>0 import math from typing import Optional import torch import torch.nn as nn from torch import Tensor from step03_positional_encoding import PositionalEncoding # https://blog.csdn.net/SangrealLilith/article/details/103527408 num_layers = 4 d_model = 128 dff = 512 num_heads = 8 dropout_rate = 0.1 class ...
StarcoderdataPython
11284087
from django.urls import path from petstagram_django.accounts.views import login_user, logout_user, register_user urlpatterns = ( path('login/', login_user, name='login user'), path('logout/', logout_user, name='logout user'), path('register/', register_user, name='register user'), )
StarcoderdataPython
1696035
#! /usr/bin/env python2.7 from pylab import * data_jamrt = genfromtxt('jamrt_atm_NH3_2.7_H2O_2.0.txt') temp_jamrt = data_jamrt[:,0] pres_jamrt = data_jamrt[:,1]*1.E-1 cp_jamrt = data_jamrt[:,2]*1.E-7 # erg -> J/ data_armada = genfromtxt('armada_atm_NH3_2.7_H2O_2.7.txt', skip_header = 2) temp_armada = data_armada[::-...
StarcoderdataPython
8189920
import os import time from dotenv import load_dotenv from mev.azure.run import get_auth_ws, run_train, run_featurize load_dotenv() ENVIRONMENT_VARIABLES = dict( TENANT_ID=os.getenv("TENANT_ID"), ) if __name__ == "__main__": # Params compute_target_name_1 = "mev-compute" compute_target_name_2 = "m...
StarcoderdataPython
6441413
<reponame>JoaoCarabetta/waze-dash #!/usr/bin/env python3 import argparse from slapdash.app import app def argparser(): parser = argparse.ArgumentParser() parser.add_argument("--port", metavar="PORT", default=8050, type=int) parser.add_argument("--host", metavar="HOST", default='0.0.0.0') parser.add_...
StarcoderdataPython
3553480
from tkinter import * window=Tk() def km_miles(): print(e1_value.get()) t1.insert(END,e1_value.get()) b1=Button(window,text='execute',command=km_miles) b1.grid(row=0,column=1) e1_value=StringVar() e1=Entry(window,textvariable=e1_value) e1.grid(row=3,column=1) t1=Text(window,width=20) t1.grid(row=0,column=2)...
StarcoderdataPython
4812035
<reponame>EnzoSoares73/meuSite<filename>authentication/forms.py<gh_stars>0 from django import forms from authentication.models import User class EmailForm(forms.Form): emaildummy = '<EMAIL>' name = forms.CharField( widget=forms.TextInput(attrs={ 'placeholder': 'Nome', 'class':...
StarcoderdataPython
9660958
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from labelseg import imgs_rc from labelseg import imgLabel class Ui_MainWin...
StarcoderdataPython
1717138
<gh_stars>0 from collections import namedtuple import csv import os import tweepy from config import CONSUMER_KEY, CONSUMER_SECRET from config import ACCESS_TOKEN, ACCESS_SECRET DEST_DIR = 'data' EXT = 'csv' NUM_TWEETS = 100 Tweet = namedtuple('Tweet', 'id_str created_at text') class UserTweets(object): def ...
StarcoderdataPython
9767487
from math_helpers import is_pandigital as mh_is_pandigital INT_WORDS_BELOW_20 = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] INT_WORDS_TENS_DIGIT = ["ten", "twenty", "thirty...
StarcoderdataPython
79279
<reponame>MJ89490/assetallocation_test1<gh_stars>0 import math import pandas as pd import numpy as np import itertools as it def dataimport_settings (file): data=pd.read_excel(file+".xlsx",sheet_name="Sheet1", index_col=[0], header=0) return data def discretise(data, freq): # Reduce frequency of a series...
StarcoderdataPython
6540768
import sys class Logger: def __init__(self,file_name): self.terminal = sys.stdout self.logfile = open(file_name,"a") def write(self,message): self.terminal.write(message) self.logfile.write(message) def flush(self): pass sys.stdout = Logger("/root/Documents/a.log...
StarcoderdataPython
6411873
import matplotlib.pyplot as plt import numpy as np from msemu.server import get_client from argparse import ArgumentParser def main(filename='../data/iladata.csv', time_exponent=-47): # read in command-line arguments parser = ArgumentParser() parser.add_argument('--dco_init', type=int, default=1000) pa...
StarcoderdataPython
1686560
<gh_stars>1-10 import pytest import itachip2ir from itachip2ir import VirtualDevice, iTach class TestiTach(object): def test_itach(self): itach = iTach(ipaddress="192.168.1.111") assert itach.ipaddress == "192.168.1.111" assert itach.port == 4998 assert itach.devices == {} de...
StarcoderdataPython
3313821
class UnionFind(object): def __init__(self,n): self.parent=[-1]*n self.ranking=[0]*n self.unioncnt=n for i in xrange(n): self.parent[i]=i def find(self,x): if self.parent[x]==x: return x self.parent[x]=self.find(self.parent[x]) ret...
StarcoderdataPython