id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
8134162
''' weights_acc.py Given a set of gold standard rankings, and a set of generated pairwise weights, calculate: - The coverage of the generated weighted pairs against all comparable pairs in the gold rankings - The directional accuracy of the generated weighted pairs (i.e. if weight for (w1,w2) is positive, the...
StarcoderdataPython
6701760
<filename>homeassistant/components/duckdns/__init__.py<gh_stars>1-10 """Integrate with DuckDNS.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event...
StarcoderdataPython
240765
<reponame>bksahu/dsa<gh_stars>0 """ Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement. Example 1: Input: String="aabccbb", k=2 Output: 5 Explanation: Replace the two 'c...
StarcoderdataPython
11279348
<reponame>rinikerlab/reeds #!/usr/bin/env python3 import os, sys, glob sys.path.append(os.getcwd()) from global_definitions import fM, bash from global_definitions import name, root_dir from global_definitions import gromosXX_bin, gromosPP_bin, ene_ana_lib from global_definitions import in_top_file, in_pert_file, in_d...
StarcoderdataPython
8112904
<reponame>CBIIT/NCI-DOE-Collab-Pilot2-Autoencoder_MD_Simulation_Data from typing import Dict, List, Callable import torch import torch.nn as nn import torch.nn.functional as F from darts.api import Model from darts.modules import Cell from darts.modules.classifier import MultitaskClassifier from darts.genotypes impor...
StarcoderdataPython
5128670
""" Module used to produce generalized sql out of given query """ import re import sqlparse class Generalizator: """ Class used to produce generalized sql out of given query """ def __init__(self, sql: str = ""): self._raw_query = sql # SQL queries normalization (#16) @staticmethod ...
StarcoderdataPython
11228926
#!/usr/bin/env python import psycopg2 import os import sqlalchemy from sqlalchemy import create_engine from time import sleep #http://www.fec.gov/finance/disclosure/metadata/DataDictionaryCandidateMaster.shtml candidate_master_sql = """CREATE TABLE candidate_master_%s ( \ ID ...
StarcoderdataPython
1728269
<reponame>vishalbelsare/MVPR import numpy as np from sklearn.preprocessing import PolynomialFeatures from scipy.linalg import svd class MVPR_forward(): def __init__(self,training_data, training_targets, validation_data,validation_targets, regularisation = 'TSVD', verbose=False, search='exponent'): ...
StarcoderdataPython
9608325
from datetime import time import factory import factory.fuzzy from django.contrib.auth.models import User from .models import GroceryRequest, MealRequest from core.models import Cities from volunteers.models import Volunteer class VolunteerFactory(factory.django.DjangoModelFactory): class Meta: model = V...
StarcoderdataPython
9712188
"""Download Chicago food inspection data""" from urllib.request import urlopen import bz2 url = ( 'https://data.cityofchicago.org/api/views/4ijn-s7e5/' 'rows.csv?accessType=DOWNLOAD' ) with bz2.open('food.csv.bz2', 'w') as out, urlopen(url) as resp: for i, line in enumerate(resp): if i > 3001: ...
StarcoderdataPython
386858
import numpy as np from .data_list import ImageList import torch.utils.data as util_data from torchvision import transforms class ResizeImage(): def __init__(self, size): if isinstance(size, int): self.size = (int(size), int(size)) else: self.size = size def __call__(se...
StarcoderdataPython
107933
<reponame>jiz148/rift-projects<filename>tests/test_utils_stack.py import unittest from interview.utils.stack import Stack class TestStack(unittest.TestCase): def setUp(self): self.example_basic_stack = Stack() self.example_empty_item_stack = Stack() pass def test_has_space(self): ...
StarcoderdataPython
4905699
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Midokura PTE LTD. # All Rights Reserved # # 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/LICENS...
StarcoderdataPython
5127726
<reponame>JzHuai0108/kalibr<gh_stars>1-10 import numpy as np from . import BSplineIO def testSerializePoses(): timeList, smTList = BSplineIO.generateRandomPoses() testFile = "testPoses.txt" BSplineIO.savePoses(timeList, smTList, testFile) newTimeList, newsmTList = BSplineIO.loadPoses(testFile) ass...
StarcoderdataPython
4957028
"""A simple wrapper class for the icalendar package""" from icalendar import Calendar, Event, Alarm from datetime import datetime, timedelta from shotglass2.shotglass import get_site_config from shotglass2.takeabeltof.date_utils import getDatetimeFromString class ICal(Calendar): def __init__(self,**kwargs): ...
StarcoderdataPython
5109811
''' Created by auto_sdk on 2016.03.17 ''' from top.api.base import RestApi class LogisticsAddressSearchRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.rdef = None def getapiname(self): return 'taobao.logistics.address.search'
StarcoderdataPython
4818116
import tempfile import os import subprocess import tensorflow as tf from tensorflow import keras from new_train_model import returnCompiledModel as model def generate_serve_files(model): MODEL_DIR = tempfile.gettempdir() version = 2 export_path = os.path.join(MODEL_DIR, str(version)) print('export_path = {}\n'.f...
StarcoderdataPython
8041252
import csv import json import os from sys import stdout import nni from time import sleep import sys from datetime import datetime f = open("curr_pwd", "wt") cwd = os.getcwd() f.write(cwd) f.close() sys.path.insert(1, os.path.join(cwd, "..")) sys.path.insert(1, os.path.join(cwd, "..", "..", "graph-measures")) sys.pat...
StarcoderdataPython
1700336
<filename>hoomd/integrate.py # Copyright (c) 2009-2021 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause # License. """Implement BaseIntegrator.""" from hoomd.operation import Operation class BaseIntegrator(Operation): """Defines the base fo...
StarcoderdataPython
3213746
# -*- coding: utf-8 -*- # PyMeeus: Python module implementing astronomical algorithms. # Copyright (C) 2018 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
StarcoderdataPython
4813728
<gh_stars>1-10 from .cronohub import main main()
StarcoderdataPython
175472
#!/usr/bin/env python # requires rg (aka ripgrep) to be installed import argparse import re import subprocess CVIOLET = "\33[35m" CEND = "\33[0m" def get_output(cmd): return subprocess.check_output(cmd, shell=True, text=True).strip() parser = argparse.ArgumentParser( description="Finds instances where do...
StarcoderdataPython
4916591
import MySQLdb import operator import urllib2 from sets import Set # Open database connection db = MySQLdb.connect("localhost","root","shubham","market") cursor = db.cursor() def num(s): try: return int(s) except ValueError: return float(s) cursor.execute("select (b.percentage - a.percentage)...
StarcoderdataPython
6505511
#!/usr/bin/env python3 from bs4 import BeautifulSoup, Comment import os, os.path for root, dirs, files in os.walk('.'): for file in files: if file.endswith('.html'): try: fname = os.path.join(root, file) print(f'Doing {fname}') with open(fname) as...
StarcoderdataPython
1747791
<gh_stars>1-10 # Python solution for 'Consecutive letters' codewars question. # Level: 7 kyu # Tags: FUNDAMENTALS. # Author: <NAME> # Date: 06/07/2020 import unittest def solve(st): """ In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each...
StarcoderdataPython
11221852
############################################################################# ### Python script for plotting 1D data (x,y) for particle trajectory codes. ### Data is read from given file. ### Plot is created using matplotlib. ### Produces the following plots: ### 1. (x(t) - t), (v(t) - t), ### 2. (v(t) - x(t...
StarcoderdataPython
6466047
import math i = 1 while i <= 5: print("Samarth", end="") j = 1 while j <= 4: print("devops", end="") j = j + 1 i = i + 1 print()
StarcoderdataPython
1745143
class HttpApiError(Exception): def __init__(self, code, message = None): Exception.__init__(self) self.message = message self.code = code def __str__(self): return '%s: %s (%s)' % (self.code, self.__class__.__name__, self.message) class UrlArgsValidationError(HttpApiErr...
StarcoderdataPython
123366
# Wrong answer 10% name = input() YESnames = [] NOnames = [] first = "" biggestName = 0 habay = "" while name != "FIM": name, choice = name.split() if choice == "YES": if first == "": first = name l = len(name) if biggestName < l: biggestName = l if ...
StarcoderdataPython
3538713
<reponame>PrincetonUniversity/FastTemplatePeriodogram<gh_stars>10-100 """ Reads `<package>/version.py`, and replaces all instances of `${UPPER_CASE_VARIABLE}` in files with the `.in` suffix with their corresponding values. Useful for, e.g., keeping the version up-to-date in the README. """ import os import glob import ...
StarcoderdataPython
3398696
from flask import Flask from flask_restful import Api from config import Config debug=True import logging app = Flask(__name__) app.config.from_object(Config) api = Api(app, catch_all_404s=True) from modules.OnLoadActions import OnLoadActions app.logger.debug('weird call I need to enable logging') ola = OnLoadAct...
StarcoderdataPython
3393780
<gh_stars>0 # Advent of Code 2020 # Day 16 from ticket_parser import * from functools import reduce from pathlib import Path # input with open(Path(__file__).parent / "input.txt") as f: rules, your_ticket, nearby_tickets = parse_tickets(f) # part 1 # Find values in nearby tickets that do not satisfy any rule. ...
StarcoderdataPython
3346220
""" :codeauthor: <NAME> <<EMAIL> """ import pytest import salt.utils.json import salt.utils.path from tests.support.case import ModuleCase from tests.support.helpers import slowTest from tests.support.mixins import SaltReturnAssertsMixin from tests.support.unit import skipIf @skipIf(salt.utils.path.which("bower"...
StarcoderdataPython
1811166
<reponame>sseaky/seakylib<filename>seakylib/func/log.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Seaky # @Date: 2019/8/26 11:38 # pip install concurrent-log-handler import logging import logging.config from copy import deepcopy from pathlib import Path from .time import datetime_to_string from ..os...
StarcoderdataPython
324065
from collections import namedtuple from raincoat import source from raincoat.match import NotMatching from raincoat.match.python import PythonChecker, PythonMatch PyGithubKey = namedtuple("PyGithubKey", "repo commit") class PyGithubChecker(PythonChecker): def __init__(self, *args, **kwargs): super(PyGit...
StarcoderdataPython
3303126
<gh_stars>10-100 """ This script downloads text data from https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz, generates experiments, and trains models using the trojai pipeline and a GloVE+LSTM architecture. The experiments consist of four different poisonings of the dataset, were a poisoned dataset consi...
StarcoderdataPython
242021
""" tpa crowdin repository. """
StarcoderdataPython
8150842
<filename>Full Counting Sort.py # -*- coding: utf-8 -*- """ Created on Sun May 10 03:01:04 2020 @author: Ravi """ dic = {} for i in range(100): dic[i]=[] n = int(input()) for i in range(n): x = input().split() num = int(x[0]) st = x[1] if i < n//2: dic[num].append('-') else: ...
StarcoderdataPython
3490157
<gh_stars>10-100 # !/usr/bin/env python # coding=utf-8 # @Time : 2020/4/25 19:44 # @Author : <EMAIL> # @File : test_eval_utils.py import unittest from aispace.utils.hparams import Hparams from aispace.utils.eval_utils import evaluation class TestEvalUtils(unittest.TestCase): def test_eval(self): h...
StarcoderdataPython
9673952
""" enwik9 dataset analysis """ import random import tqdm import gzip import numpy as np import wandb import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from transformers import TransformerWrapper, Decoder from autoregressive_wrapper import AutoregressiveWrapper ## wandb se...
StarcoderdataPython
303949
<gh_stars>0 #! /usr/bin/env python # Software License Agreement (BSD License) # # Copyright (C) 2016, <NAME>, <NAME> # 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 so...
StarcoderdataPython
12845740
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging my_api_key = "Your API Key(Link: https://console.developers.google.com/apis/dashboard)" my_cse_id = "Your Custo...
StarcoderdataPython
3413943
import glob import numpy as np import matplotlib.pyplot as plt import analysistools filenames = sorted(glob.glob('../03-fundamentals-of-python/inflammation*.csv')) for f in filenames[:3]: print(f) analysistools.analyse(f) analysistools.detect_problems(f)
StarcoderdataPython
174952
<filename>xchange/models/kraken.py from decimal import Decimal from xchange.models.base import ( Ticker, AccountBalance, OrderBook, Order, Position) class KrakenTicker(Ticker): """ Original JSON response (transformed): {'a': ['3809.00000', '1', '1.000'], 'b': ['3803.60000', '1', '1.000'], '...
StarcoderdataPython
60598
<reponame>Asa-Nisi-Masa/movie-recommender """ create_table """ from yoyo import step __depends__ = {} steps = [ step("CREATE TABLE movies \ (\ id SERIAL,\ imdb_id VARCHAR(255) NOT NULL,\ title VARCHAR(255) NOT NULL,\ encoding FLOAT4[32]\ )", ...
StarcoderdataPython
8063226
#!/usr/bin/env python3 import os LENGTH = 12 def read(relative_filepath): """For day 3, returns... """ with open(relative_filepath, 'r+') as f: data = f.read() clean_data = data.strip() lines = clean_data.split('\n') return lines def bitsToInt(bitstring): """Takes a st...
StarcoderdataPython
11247619
<filename>dagster-with-django-orm/test_hello_django_orm.py<gh_stars>1-10 from contextlib import ExitStack from unittest.mock import patch from dagster import execute_pipeline, execute_solid from hello_django_orm import hello_django_orm, hello_django_orm_pipeline def test_hello_django_orm_solid(): with ExitStack...
StarcoderdataPython
6407112
<filename>from_python_community/gen_hashtag.py # Условие: # Ваша задача — написать функцию, которая превращает строку в hashtag. # У них есть парочка правил: никаких символов из string.punctuation быть не должно, пробелы отсутствуют, а длина обязана быть не более 140 символов. # Если последнее правило нарушено, выбр...
StarcoderdataPython
9664828
from typing import Optional, Any, Dict, List, Tuple, Union from qcodes import Instrument, Parameter from .. import QtWidgets, QtCore, QtGui from ..serialize import toParamDict from ..params import ParameterManager, paramTypeFromName, ParameterTypes, parameterTypes from ..helpers import stringToArgsAndKwargs, nestedAt...
StarcoderdataPython
9717477
<reponame>84KaliPleXon3/transistor # -*- coding: utf-8 -*- """ transistor.managers.base_manager ~~~~~~~~~~~~ This module implements BaseWorkGroupManager as a fully functional base class which can assign tasks and conduct a scrape job across an arbitrary number of WorkGroups. Each WorkGroup can contain an arbitrary numb...
StarcoderdataPython
6628877
from functools import reduce from whereamigeo.mappings import map, word_to_plus_code_mapping sep = '.' def get_word(code: str): return map[code] def get_code(word: str): return word_to_plus_code_mapping[word] def get_olc_array(olc: str, inc: int): code = olc.replace('+', '') return [code[i: i +...
StarcoderdataPython
4911140
<filename>tests/test_auth.py from tino import Tino, Auth, AuthRequired from pydantic import BaseModel import datetime from typing import List, Dict, Optional import pytest from aioredis import ReplyError async def authorize(password): if password == b"<PASSWORD>": return password api = Tino(auth_func=au...
StarcoderdataPython
73074
<filename>option.py import argparse import os class Options(): def __init__(self): # Training settings parser = argparse.ArgumentParser(description='Tank Shot') parser.add_argument('--dataset', default='CUB1', type=str, help='dataset to be processed') ...
StarcoderdataPython
5129357
<reponame>chesterharvey/StreetSpace ############################################################################## # Module: streetscape.py # Description: Functions to analyze streetscapes. # License: MIT ############################################################################## import numpy as np from .geometry ...
StarcoderdataPython
59648
msg = str(input('Digite uma mensagem')) n = 0 n = len(msg) def escreva(): print('-'*n) print(msg) print('-'*n) escreva()
StarcoderdataPython
1837506
<filename>search.py # Binary Search def binary_search(array, key): first = 0 last = len(array) - 1 while first <= last: mid = (first + last) // 2 if array[mid] == key: return True else: if array[mid] < key: first = mid + 1 else: ...
StarcoderdataPython
3496565
# Copyright (c) 2016 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S...
StarcoderdataPython
147276
<gh_stars>10-100 __author__ = '<NAME>' ''' https://codeforces.com/problemset/problem/1080/A Solution: Calculate the number of red, green and blue papers needed. Since each book provides k sheets, we divide each color's paper needed by k to get the number of books. To take care of remainder as well we do ceil divisio...
StarcoderdataPython
3368090
#!/usr/bin/env python3.5 import sys import os import argparse import enforce sys.path.insert(0, os.path.abspath('..')) from LSA.LSA import LSA from LSA.document_embedding import document_embedding def main(): """ Manage Execution """ args = get_args() print(args) if args.embedding: document...
StarcoderdataPython
167615
<gh_stars>0 # Copyright (c) 2020 AllSeeingEyeTolledEweSew # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRAN...
StarcoderdataPython
4939797
<reponame>PoqXert/godot-appodeal-ios-module def can_build(env, platform): if platform == "iphone": return True return False def configure(env): if env['platform'] == "iphone": env.Append(FRAMEWORKPATH=['#modules/appodeal/ios/lib']) env.Append(CPPPATH=['#core']) env.Append(LI...
StarcoderdataPython
6518912
<reponame>ajenie/sawtooth-core<filename>validator/tests/test_scheduler/tests.py # Copyright 2016, 2017 Intel Corporation # # 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.apa...
StarcoderdataPython
6516243
<filename>make_json.py import os import random import numpy as np import json import traceback from tqdm import tqdm ''' i decide to merge more data from CelebA, the data anns will be complex, so json maybe a better way. ''' data_dir = '/home/ubuntu/300W_LP_Out' ########points to your director,300w train_json = '...
StarcoderdataPython
20724
<reponame>KongoPL/lego-rc-car # Yea, there is probably some good framework waiting for me, # but I just want to have fun. Sometimes reinventing the wheel will serve you. # But...don't do that in professional work :) import config import time from Controller import Controller print("Hello!") root = Controller() # tr...
StarcoderdataPython
4922582
<filename>sliding_window/num_nice_arrays.py """ Leetcode 1248. Count Number of Nice Subarrays Leetcode 992. Subarrays with K Different Integers The idea is the same for many problems similar to K exact or K distinct etc. It is hard to find out the exact K number using sliding windows. Same time, atmost K is kind of...
StarcoderdataPython
4822140
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'net_options_dialog.ui' # # Created: Tue Sep 20 01:37:39 2016 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! import sys from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString....
StarcoderdataPython
5198077
""" Extends GenericSupport with the calls that assume a Linux or Mac environment How this works: http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html https://docs.python.org/3.6/library/termios.html https://docs.python.org/3.6/library/tty.html """ import sys import termios import tt...
StarcoderdataPython
8006225
<gh_stars>0 from typing import List from portia_utils import file_handler as fh def dlbcl_1000() -> List[str]: return fh.readfile('sample_datasets/dlbcl-sd-1000-attributes.txt', True) def gse412_1000() -> List[str]: return fh.readfile('sample_datasets/gse412-sd-1000-attributes.txt', True)
StarcoderdataPython
11268442
<reponame>fireclawthefox/DirectGuiEditor #!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "<NAME>" __license__ = """ Simplified BSD (BSD 2-Clause) License. See License.txt or http://opensource.org/licenses/BSD-2-Clause for more info """ import logging import sys import copy from panda3d.core import ( VBase4...
StarcoderdataPython
8083234
<reponame>hpsim/plot_ogl_data #!/usr/bin/env python3 import os import pandas as pd import Owls as ow from pathlib import Path from packaging import version from helpers import idx_larger_query def clean_hash(s): return s.replace("hash: ", "").replace("\n", "") def read_logs(folder): """Reads the logs fil...
StarcoderdataPython
3536411
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
StarcoderdataPython
173357
<reponame>bhavinjawade/project-euler-solutions<gh_stars>1-10 # -*- coding: utf-8 -*- ''' File name: code\maximum_quadrilaterals\sol_538.py Author: <NAME> Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #538 :: Maximum quadrilaterals # # For more information see:...
StarcoderdataPython
345772
from mamba.core.rmap_utils.crc_8 import crc_8 def test_crc_8(): # Test patterns from ECSS-E-50-11 assert crc_8(b'\x01\x02\x03\x04\x05\x06\x07\x08') == b'\xb0' assert crc_8( b'\x53\x70\x61\x63\x65\x57\x69\x72\x65\x20\x69\x73\x20\x62\x65\x61\x75\x74\x69\x66\x75\x6C\x21\x21' ) == b'\x84' asse...
StarcoderdataPython
9760371
from graphene import relay, ObjectType, Schema from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from django.contrib.auth.models import User from blog.models import Publication, Post, Profile, Class, Volunteer, Student from graphene_django.rest_framework.mutatio...
StarcoderdataPython
1747542
from pydantic.main import BaseModel from morpho.rest.models import ( ListServicesResponse, ServiceInfo, TransformDocumentPipeRequest, TransformDocumentPipeResponse, TransformDocumentRequest, TransformDocumentResponse, ) from morpho.util import decode_base64, encode_base64 class TestTransformDo...
StarcoderdataPython
11213367
<reponame>lucaspdroz/Relembrando-Python-com-Curso-Em-Video<filename>010/ex010.py<gh_stars>0 real = float(input('Quantos Reais você tem?\n')) dolar = real / 5.55 print('\nCom R${:.2f} você terá ${:.2f}'.format(real, dolar))
StarcoderdataPython
1815606
""" Copyright (c) 2017, <NAME>. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on May 20, 2017 @author: jrm """
StarcoderdataPython
3208818
<reponame>Opentrons/ot3-emulator """robots package."""
StarcoderdataPython
3585906
#!/usr/bin/python from __future__ import division from functools import lru_cache from persistent_lru_cache import persistent_lru_cache import timeit @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) @persistent_lru_cache(filename='fib.db', maxsize=None) def pfib(n):...
StarcoderdataPython
5032569
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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 applica...
StarcoderdataPython
1795297
<gh_stars>0 import pandas as pd from pathlib import Path # Input parameters category = 'Clothing' dataset = 'offers_corpus_english_v2_non_norm' # Settings inputfile = 'dataset/{}.json.gz'.format(dataset) outputpath = 'output/{}'.format(dataset) outputfile = '{}/{}.json.gz'.format(outputpath,category) chunksize = 1000...
StarcoderdataPython
11341780
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 buy = -prices[0] sell = float('-inf') wait = 0 buy_l = 0 sell_l = 0 wait_l = 0 for i,...
StarcoderdataPython
6548664
<reponame>dfm/rmhmc __all__ = ["hmc"] from typing import Callable, Dict, Optional, Union import jax import jax.numpy as jnp from jax import random from jax.flatten_util import ravel_pytree from rmhmc.base_types import ( HMCState, MCMCKernel, Position, ProposalStats, SamplerCarry, SamplerTunin...
StarcoderdataPython
11363306
<reponame>alexandrvicente/OEAIndice<filename>oeaindice/index.py from hashlib import sha256 from struct import Struct from collections import Counter import os import click class Index: INDEX_SIZE = 9000001 INDEX_STRUCT = Struct('<IQQ') CEP_STRUCT = Struct('72s72s72s72s2s8s2s') @staticmethod def ce...
StarcoderdataPython
6536449
<reponame>Kayra/atlas # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from datetime import timedelta from django.db import models from atlas.users.models import User # from django.utils.translation import ugettext_lazy as _ class Skill(models.Model): name = models...
StarcoderdataPython
6433739
# encoding: utf-8 from collections import namedtuple from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.shortcuts import redirect, render, get_object_or_404 from django.utils.translation import ugettext_lazy as _ from django.views.decor...
StarcoderdataPython
261074
import math import liburing def test_time_convert(): # int test assert liburing.time_convert(1) == (1, 0) # float test assert liburing.time_convert(1.5) == (1, 500_000_000) assert liburing.time_convert(1.05) == (1, 50_000_000) # float weirdness test result = liburing.time_convert(1.005) ...
StarcoderdataPython
9675766
""" Ffjord lite: a minimal working example of Free-Form Jacobian of Reversible Dynamics Ffjord was introduced in: > <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. > (2018). Ffjord: Free-form continuous dynamics for scalable reversible > generative models. arXiv preprint arXiv:1810.01367. > https://arxiv.org/abs/1810.01...
StarcoderdataPython
6519161
import io import json import os import requests import requests_mock import six import tempfile import unittest import zipfile six.add_move(six.MovedModule('mock', 'mock', 'unittest.mock')) from six.moves import mock # noqa from cromwell_tools import utilities as utils # noqa from cromwell_tools.cromwell_auth impo...
StarcoderdataPython
3209942
<reponame>IgalMilman/DnDHelper<filename>dndhelper/urls.py """dndhelper URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to...
StarcoderdataPython
342377
from phidl.device_layout import Device from gdsfactory.component import Component, ComponentReference, Port from gdsfactory.config import call_if_func from gdsfactory.types import Layer def from_phidl(component: Device, port_layer: Layer = (1, 0), **kwargs) -> Component: """Returns gf.Component from a phidl Devi...
StarcoderdataPython
9650672
<filename>keypoints/higgham.py import torch import numpy as np from numpy import linalg as la def np_nearestPD(A): """Find the nearest positive-definite matrix to input A Python/Numpy port of <NAME>'s `nearestSPD` MATLAB code [1], which credits [2]. [1] https://www.mathworks.com/matlabcentral/fileexch...
StarcoderdataPython
356942
<gh_stars>0 from patchstar import PatchStar
StarcoderdataPython
9643148
from .mobile_test_case import MapMobileTestCase class TestMapRoute(MapMobileTestCase): """test route functions""" def test_route_by_car(self): """MMap-2: test route by car""" with self.precondition(): self.main_page.start_route() destination = u"环球中心停车场" ...
StarcoderdataPython
1680925
<reponame>hobson/pug-dj from django.conf.urls import patterns, url #, include #from django.conf import settings #from django.views.generic import TemplateView #import django.views.static #from views import JSONView import views from pug.nlp.util import HIST_NAME hist_name_re = '|'.join([name for name in HIST_NAME]) ...
StarcoderdataPython
8074709
<reponame>WatsonWangZh/CodingPractice # Write an algorithm to determine if a number is "happy". # A happy number is a number defined by the following process: # Starting with any positive integer, replace the number by the sum of the squares of its digits, # and repeat the process until the number equals 1 (where it ...
StarcoderdataPython
3201876
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-19 07:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('qa', '0006_auto_20180210_2138'), ] operations = [ ...
StarcoderdataPython
8149117
''' Function: 训练文明话生成器 Author: Charles 微信公众号: Charles的皮卡丘 ''' import os import torch import argparse import torch.nn as nn from modules import Poem, CreateDataloader, Logger, touchdir '''命令行参数解析''' def parseArgs(): parser = argparse.ArgumentParser(description='训练文明话生成器') parser.add_argument('--bat...
StarcoderdataPython
113257
<filename>pns/controllers/device.py # -*- coding: utf-8 -*- from flask import Blueprint, request, jsonify from pns.app import app from pns.models import db, User, Device from pns.forms import CreateDeviceForm, UpdateDevice device = Blueprint('device', __name__) PLATFORMS = ['gcm', 'apns'] @device.route('/devices/<...
StarcoderdataPython
3462032
<reponame>michcioperz/nyuuuspace-public-release from django.apps import AppConfig class NyuuusteadConfig(AppConfig): name = 'nyuuustead'
StarcoderdataPython