text
string
size
int64
token_count
int64
from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth import get_user_model from ckeditor.fields import RichTextField from autoslug.fields import AutoSlugField User = get_user_model() class Post(models.Model): """Post model""" STATUS_CHOICES ...
2,156
674
#!/usr/bin/env python import os import sys PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(PROJECT_ROOT) sys.path.append(os.getcwd()) import owcli __version__ = '0.1.0' def main(): owcli.run(cli="__yourapp", version=__version__, root=os.path.dirname(os.path.realpath...
373
149
n, m = map(int, input().split()) a_lst = list(map(int, input().split())) b_lst = list(map(int, input().split())) cnt = 0 for i in a_lst: for j in b_lst: if i > j: cnt += 1 print(cnt)
207
85
import json import time import numpy as np from collections import OrderedDict from larch import Group from ..fitting import Parameter, isParameter from ..utils.jsonutils import encode4js, decode4js from . import fix_varname def save(fname, *args, **kws): """save groups and data into a portable json file ...
3,191
1,085
from typing import Dict, List, Tuple import logging import json import glob import os import sqlite3 import random from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.common.util import START_SYMBOL, END_SYMBOL from allennlp.data.dataset_readers.dataset_reader import Datas...
8,251
2,366
import os import pytest import pandas as pd from pandas.testing import assert_frame_equal from main import ( calc_velocity, merge_datasets, filter_by, GRAV_CONST ) FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixtures') @pytest.fixture def dataset(): ds1 = pd.read_csv(os.path.join(FIX...
909
371
def extractKONDEETranslations(item): """ #'KONDEE Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None tagmap = [ ('Sakyubasu ni Tensei Shitanode Miruku o Shiborimasu', 'Sakyubasu ...
2,016
782
print("---SALARIO---") def salarioBruto(salarioHora, horasMes): return salarioHora * horasMes def irrf(brutoMes): return brutoMes * (11/100) def inss(brutoMes): return brutoMes * (8/100) def sindicato(brutoMes): return brutoMes * (5/100) def main(): nome = str(input("Digite seu nome: ")) ma...
1,302
555
#Write a function that computes the running total of a list. sum def sum_list(list_1): tong = 0 for num in range(len(list_1)): tong = tong + list_1[num] print(tong) list_2 = [1,2,3,4,5,2,23,2,4,32,42,324,324] sum_list(list_2)
245
112
from stepspy import STEPS, POUCH_CSV simulator = STEPS(is_default = False, log_file = 'test.log') simulator.info() simulator.set_toolkit_log_file("newtest.log", log_file_append_mode=False) simulator.set_parallel_thread_number(1) simulator.set_dynamic_model_database_capacity(10000000) max_bus = simulator.get_allowe...
5,235
1,920
from django.db.models import Manager from django_extmodels.query import ExtQuerySet class ExtManager(Manager.from_queryset(ExtQuerySet)): """ A subclassable Manager """ pass
181
58
''' test_tornado.py @summary: Comparing (RAM usage) of different webframeworks @since: 5 Mar 2016 @author: Andreas @home github.com/drandreaskrueger/pythonMicroframeworks @license: MIT but please donate: @bitcoin: 14EyWS5z8Y5kgwq52D3qeZVor1rUsdNYJy ''' import tornado.ioloop, tornado.web...
1,553
569
import os import numpy as np import scipy.sparse import scipy.optimize class Softmax: def __init__(self): self.path='G:\MACHINE_LEARNING_ALGORITHMS\Logistic_and_Stochastic_Regression'### insert your path here! self.C1=0.0001 #weight decay (regularization parameter) ...
4,065
1,413
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 new_class.append('Peter Warden') for name in new_class: if name == 'Carla Gentry': new_class.remove('Car...
1,222
468
class Node: """ A node on the computing graph. The node is the first argument to apl(node, ....) and jvp / vjp functions. node[argname] gives the input symbol """ def __init__(self, primitive, _frameinfo): self.primitive = primitive self.operator = primitive.operato...
3,759
1,021
import unittest import pyalveo import requests_mock import json CONTEXT = { "ausnc": "http://ns.ausnc.org.au/schemas/ausnc_md_model/", "corpus": "http://ns.ausnc.org.au/corpora/", "dc": "http://purl.org/dc/terms/", "dcterms": "http://purl.org/dc/terms/", "foaf": "http://...
5,111
1,573
# Generated by Django 3.2.7 on 2021-10-23 00:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("ratings", "0009_alter_group_name"), ] operations = [ migrations.AddField( model_name="station", name="contact_person...
5,182
1,289
from __future__ import unicode_literals, print_function from kivy.uix.widget import Widget from kivy.properties import (StringProperty, NumericProperty, ObjectProperty) from kivy.lang import Builder from flat_kivy.utils import construct_target_file_name Builder.load_file(construct_target_file_name('numpad.kv', _...
3,375
979
#!/usr/bin/env python3 import argparse import itertools import subprocess import sys import re from glob import glob from textwrap import dedent from typing import List, NamedTuple def main() -> None: parser = create_parser() args = parser.parse_args() # preview changes needed for file if not args.file_name...
10,271
3,367
from ...update_foursight import service import pytest import mock # TODO: This import relates to tests that need to move to dcicutils. See below. # These comments will go away when the move is accomplished. -kmp 10-Apr-2020 # from dcicutils.beanstalk_utils import create_foursight_auto @pytest.fixture def bs_pro...
3,727
1,352
from persistence.persistence import Persistence class CredentialsDao: persist = Persistence() def __init__(self) -> None: pass def find_by_host_id(self, host_id): return self.persist.find_by_field_in_table('Credentials', 'host_id', host_id)
274
90
import asyncio from motor import motor_asyncio from mongodeque import MongoDequeReflection, MongoDictReflection loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = motor_asyncio.AsyncIOMotorClient() db = client.test_db # you should 'await' while reflection instance is created # than there is no di...
2,467
763
# Copyright 2020 Ville Vestman # This file is licensed under the MIT license (see LICENSE.txt). import sys import numpy as np from asvtorch.src.settings.settings import Settings # This class is used to for storing and applying VAD and diarization labels. class FrameSelector: def __init__(self, boolean_selectors...
2,581
778
# -*- coding: iso-8859-1 -*- """ MoinMoin - text/xml file Filter @copyright: 2006 MoinMoin:ThomasWaldmann @license: GNU GPL, see COPYING for details. """ from MoinMoin.filter.text_xml import execute as xmlfilter def execute(indexobj, filename): return xmlfilter(indexobj, filename)
302
118
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('off_django', '0002_offfood_serving_quantity'), ] operations = [ migrations.AddField( model_name='offfood', ...
974
289
import datetime import pytest import mock from copy import deepcopy import os import json import shutil import tempfile import time import botocore.auth import ssmbotocredentialprovider.FakeMetadata FAKE_CRED_CONTENTS = """ [default] aws_access_key_id = fake_access_key aws_secret_access_key = fake_secret_key aws_sess...
3,497
1,128
import types from tkinter import * su = Tk() su.geometry('300x300+200+300') Label(root, text="Label a : x=0, y=0", bg="#FFFF00", fg="negro").place(x=0, y=0) Label(root, text="Label b : x=50, y=40", bg="#3300CC", fg="blanco").place(x=40, y=30) Label(root, text="Label c : x=75, y=80", bg="#FF0099", fg="negro").place(x=8...
864
417
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : http_process.py @Time : 2018/12/15 0015 16:50 @Author : Empty Chan @Contact : chen19941018@gmail.com @Description: @License : (C) Copyright 2016-2017, iFuture Corporation Limited. """ from utils.color import Colored class HTTPProce...
1,254
392
from functools import partial from dino.assets import DINO_DOUX, DINO_BART, DINO_MORT, DINO_VITA from dino.assets.sprites.spritesheet import SpriteSheet class DinoSpriteSheet(SpriteSheet): def __init__(self, file_name, entity_width, entity_height): super().__init__(file_name=file_name, ...
1,220
413
""" Test helpers """ from subprocess import check_output class Missing(object): """ Class to indicate missing info """ SYSCTL_KEY_TRANSLATIONS = dict( model='model_display', family='family_display', extmodel='extended_model', extfamily='extended_family') SYSCTL_FLAG_TRANSLATIONS = { 'sse4...
3,710
1,275
import requests target = 'http://gitbook.cn/' req = requests.get(target) print(req.text) # print(__name__)
108
39
import os from itertools import chain import gatenlphiltlab import explanatory_style as es def get_sentence(key_annotation): if key_annotation.type.lower() == "sentence": return sentence = next( ( annotation for annotation in tree.search(key_annotation) if an...
5,192
1,553
import FWCore.ParameterSet.Config as cms from EgammaAnalysis.CSA07Skims.EgammaSkimEventContent_cff import * from EgammaAnalysis.CSA07Skims.AODSIMEgammaSkimEventContent_cff import * egammaVeryHighEtOutputModuleAODSIM = cms.OutputModule("PoolOutputModule", AODSIMEgammaSkimEventContent, egammaVeryHighEtEventSelec...
555
208
import numpy as np if __name__ == '__main__': x = [1, 2, 3, 4] y = [5, 6, 7, 8] z = [] for i, j in zip(x, y): z.append(str(i) + str(j)) print(z) def myconcat(x, y): return int(str(x) + str(y)) uconcat = np.frompyfunc(myconcat, 2, 1) arrx = np.array(x).reshape(2, 2) a...
777
377
#!/usr/bin/env python3 import argparse import os import subprocess PARSER = argparse.ArgumentParser(description = "Bootstrap personal config") PARSER.add_argument( "-f", "--force", action = "store_true", help = "overwrite existing config files?", dest = "force", default...
2,632
889
""" LeetCode 422. Valid Word Square Given a sequence of words, check whether it forms a valid word square. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). Note: The number of words given is at least 1 and does not exceed 500...
3,137
1,020
import pytest from tests.compiler import compile_snippet, internal_call, STATIC_START, LOCAL_START from thinglang.compiler.errors import NoMatchingOverload, InvalidReference from thinglang.compiler.opcodes import OpcodePopLocal, OpcodePushStatic def test_inline_list_compilation(): assert compile_snippet('list<n...
1,106
341
# September 2016, Glenn F. Matthews # Copyright (c) 2013-2017 the COT project developers. # See the COPYRIGHT.txt file at the top-level directory of this distribution # and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt. # # This file is part of the Common OVF Tool (COT) project. # It is subject to t...
3,143
1,123
import requests import logging import time import json TIEBA_NAME = '' BDUSS = '' TIEBA_FID = 0 # 从 https://tieba.baidu.com/f/commit/share/fnameShareApi?fname=(贴吧名) 复制fid字段 session = requests.Session() def rewind(tid, pid=0): cookies = { 'BDUSS': BDUSS, } headers = { 'sec-ch-ua': '" No...
2,421
841
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You m...
5,250
1,629
from esteira.pipeline.service import Service def test_instance(): envs = { "POSTGRES_DB": "nice_marmot", "POSTGRES_USER": "runner", "POSTGRES_PASSWORD": "pass", "POSTGRES_HOST_AUTH_METHOD": "trust", } service = Service( 'postgres', external_envs=envs ) ...
396
137
from .miner import Miner
25
9
#!/usr/bin/env python3 import rosbag import sys import math def getEuclidianDistanceOfTwoDots(x1, y1, x2, y2): distance=math.sqrt(math.pow(x2-x1, 2)+math.pow(y2-y1, 2)) return distance def getTotalTurtleDistance(xPoses, yPoses): overallDistance=0 for i in range(len(xPoses)-1): distance=getEuc...
2,360
839
from threading import Thread import datetime import cv2 class FPS: """docstring for FPS""" def __init__(self): self._start = None self._end = None self._numFrames = 0 def start(self): self._start = datetime.datetime.now() return self def stop(self): self._end = datetime.datetime.now() def update(se...
2,176
952
############################################################################## # Copyright (c) 2016 EMC and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # ht...
6,592
2,154
# -*- coding: utf-8 -*- """ .. codeauthor:: Jaume Bonet <jaume.bonet@gmail.com> .. affiliation:: Laboratory of Protein Design and Immunoengineering <lpdi.epfl.ch> Bruno Correia <bruno.correia@epfl.ch> .. func:: format_Ipython .. func:: use_qgrid .. func:: add_column .. func:: split_values .. func:: make_roset...
16,381
5,149
import cv2 as cv import numpy as np url = '../Resources/Photos/cats.jpg' img = cv.imread(url) cv.imshow('Cat', img) blank = np.zeros(img.shape[:2], dtype='uint8') mask = cv.circle(blank, (img.shape[1]//2, img.shape[0]//2),100, 255, -1) masked = cv.bitwise_and(img, img, mask=mask) cv.imshow("Masked" ,masked) cv....
330
153
import torch import json import os, sys import linecache from torch.utils.data import DataLoader, TensorDataset, Dataset # required to access the python modules present in project directory currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) # no...
1,990
629
## Placeholder - SWORD modules go in this directory
51
12
#!/usr/bin/env python # encoding: utf-8 """ imguralbum.py - Download a whole imgur album or account in one go. MIT License Copyright Alex Gisby <alex@solution10.com>, Lorenz H-S <thinkscripts@4z2.de> """ import sys import re import urllib import os import math help_message = ''' Quickly and easily download an album ...
6,835
2,096
""" oblio.py: A framework to collect and trade algorithms with your friends to play Oblio. A talented and trained human get average about 12-15 guesses before converging on the solution. What can your algorithm do? To play Oblio: - There exists a secret 4-digit number in which no two digits are the same. ...
5,305
1,763
files = [] outFile = open("Out.csv",'w') numFiles = int(input("num of files: ")) samplePoints = int(input("num of sample points: ")) for i in range(numFiles): file = open("Run#"+str(i+1)+".csv",'r') files.append(file) #print(files[i].readline().strip()) i = 0 outFile.write("Ants,Larva,Foo...
3,907
1,440
# -*-coding:utf-8-*- ''' @author : qzylalala @file : FaceppApi.py @time : 2020-09-07 19:04 ''' import urllib.request import urllib.error import json import time http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect' key = "xxx" secret = "xxx" # use your own key and secret key #---------------------------...
2,597
953
# pacmanAgents.py # --------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst....
5,818
1,695
''' Tkinter implementation of Meta Noughts and Crosses. Requires Python >3.6, tkinter and mnac. 1.0: release 1.1: keyboard indicators / keyboard controls are like numpad 1.2: new status menu, controls, help menu 1.3: better mouse handling 1.4: UI tweaks and touchups ''' import random import os import tkinter as tk i...
8,898
2,793
from __future__ import absolute_import, print_function import pytest from pyros_schemas.ros.schemagic import create from . import six_long import hypothesis import hypothesis.strategies as st import std_msgs.msg as std_msgs import genpy from . import msg as pyros_schemas_test_msgs from .strategies.ros import st...
16,288
6,574
from GameObjects import * from settings import * class enemy(Creature): def __init__(self, position, textureSize, textureNames, textureParams, health, end): super().__init__(position, textureSize, textureNames, textureParams, health) self.end = end self.path = [self.x, self.end] sel...
1,974
605
from flask import Flask from config import config import os def create_app(config_name): app = Flask(__name__) config_name = os.getenv('FLASK_CONFIGURATION', 'default') app.config.from_object(config[config_name]) config[config_name].init_app(app) from .main import main as main_blueprint app.r...
374
122
""" gamd.py: Implements the GaMD integration method. Portions copyright (c) 2020 University of Kansas Authors: Matthew Copeland, Yinglong Miao Contributors: Lane Votapka """ from __future__ import absolute_import __author__ = "Matthew Copeland" __version__ = "1.0" from simtk import unit as unit from abc import ABC...
26,353
7,970
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
4,031
1,363
from .normalizer import OnlineNormalizer, NormalizerStd, NormalizerMax, NormalizerId from .tf_normalizer import tfNormalizer, tfNormalizerMax, tfNormalizerStd, tfNormalizerId def create_build_nor_from_str(nor_cls_str, nor_kwargs): nor_cls = globals()[nor_cls_str] def build_nor(shape): return nor_cls(...
391
131
"""Platform Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema from .Results import Results class PlatformShipmentTrack(BaseSchema): # Order swagger.json results = fields.Nested(Results, required=Fal...
330
97
from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from . import actions import json router = { 'create.appointment': actions.debug } def get_payload(request): # work out how to do this: request_json = request.body.decode('utf-8') ...
833
249
import pytest import gpgkeyring from ..helpers import testdata TRUST_VALUE_MAP = gpgkeyring.trust._TRUST_MAP.items() class TestEnum: @pytest.fixture(params=testdata.TRUST_LEVELS) def level(self, request): yield request.param def test_trust_level_value(self, level): assert getattr(gpgk...
874
312
from __future__ import absolute_import, print_function __all__ = ['SourceCache', 'SourceMapCache'] class SourceCache(object): def __init__(self): self._cache = {} self._errors = {} self._aliases = {} def __contains__(self, url): url = self._get_canonical_url(url) retu...
1,866
640
def initialize_states(model, data): """ Initialize states for a deep boltzmann machine given data. Double weights up to account for lack of top down input """ states = [data] for i, connection in enumerate(model.connections[:-1]): states.append(model.layers[i + 1].expectation(connection....
5,536
1,748
from .motion_controller_action_client import MotionControllerActionClient from .motion_trajectory import MotionTrajectory from .motion_waypoint import MotionWaypoint from .motion_waypoint_options import MotionWaypointOptions from .interaction_options import InteractionOptions from .interaction_publisher import Interact...
569
173
############################################################################### # Copyright (c) Lawrence Livermore National Security, LLC and other Ascent # Project developers. See top-level LICENSE AND COPYRIGHT files for dates and # other details. No copyright assignment is required to contribute to Ascent. #########...
673
172
# -*- coding: utf-8 -*- from decimal import Decimal from django.contrib.auth.models import User from django.db import models from shop.cart.modifiers_pool import cart_modifiers_pool from shop.models.productmodel import Product class Cart(models.Model): ''' This should be a rather simple list of items. Ideally ...
4,721
1,289
#!/usr/bin/env python """ CREATED AT: 2021/9/26 Des: https://leetcode.com/problems/house-robber-ii/ GITHUB: https://github.com/Jiezhi/myleetcode Difficulty: Medium Tags: DP Also See: 198. House Robber """ from typing import List class Solution: def rob(self, nums: List[int]) -> int: """ 75 / 75...
1,200
484
from pathlib import Path from typing import Dict, List import numpy as np import pandas as pd import pytest from pandas.testing import assert_frame_equal from tdda.referencetest.checkpandas import default_csv_loader from secs.tasks.extract import regroup_excels_by_sheet from secs.tasks.transform import ( transfor...
2,456
906
""" A simple list box widget with a model-view architecture. """ from __future__ import absolute_import # Major package imports. import wx # Enthought library imports. from traits.api import Event, Instance, Int # Local imports. from pyface.list_box_model import ListBoxModel from .widget import Widget class ListBo...
4,052
1,043
"""Definition of base classes for Schedules This currently contains only BaseController. It includes basic functionality for a given schedule. Cloud specific controllers are in `mist.api.schedules.controllers`. """ import logging import datetime import mongoengine as me from mist.api.scripts.models import Script from...
15,086
3,862
from numpy import * # Yup import matplotlib.pyplot as plt import ephem import sfdmap from astropy.io import ascii def add_point(RA, Dec, flipRA = 1, color = 'b', txtlabel = None, symb = '.', label = ""): assert abs(RA) <= 2.*pi assert abs(Dec) <= pi if RA <= pi: plotRA = RA else: plot...
3,870
1,745
# -*- coding: utf-8 -*- import uuid import functools from copy import deepcopy from lxml import etree from .namespaces import (XML_NS_URI, STREAM_NS_URI, CLIENT_NS_URI, SERVER_NS_URI, STANZA_ERROR_NS_URI, STREAM_ERROR_NS_URI) from .jid import Jid XML_LANG = "{%s}lang" ...
16,423
5,352
from __future__ import print_function from ...utils import print_header def play_match(game, players, verbose=True): """Plays a match between the given players""" if verbose: print(game) while not game.is_over(): cur_player = players[game.cur_player()] move = cur_player.choose_move...
1,211
394
# Generated by Django 3.0.5 on 2020-04-16 18:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('webfrontent', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='crawlerrun'...
1,028
318
from laundry.laundryclass import * from laundry.laundry_cli import *
69
26
# -*- coding: utf-8 -*- import os import sys from ironworks import serverTools def highest_position(model): highest_position = 0 items = model.query.all() for item in items: if item.position > highest_position: highest_position = item.position return highest_position + 1 clas...
1,701
464
import platform import os def creation_date(path_to_file): if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy ...
553
164
import os import asyncio from pyppeteer import launch from ..log_adapter import get_logger from ..common_utils import get_user_home_dir, add_to_osenv from ..constants import CONSTANTS def render_html(url=None, html=None, get_text=False, script=None, reload_=False, wait_time=5, timeout=10): result, content = None, ...
3,035
970
from urllib.parse import urlparse, parse_qs import flask import jwt import pytest from flask import url_for from oauthlib.common import generate_token from werkzeug.utils import redirect from flask_discord import DiscordOAuth2Session, configs, json_bool from flask_discord.configs import DISCORD_OAUTH_DEFAULT_SCOPES ...
8,678
2,830
import tkinter.filedialog import tkinter.simpledialog from tkinter import messagebox import numpy as np import matplotlib.pyplot as plt import wfdb import peakutils from scipy import signal import pandas as pd # To display any physiological signal from physionet, a dat-File needs to have a complementary hea-...
2,731
1,029
#!/usr/bin/env python3 ##################################### # # Filename : generate.py # # Projectname : diSTruct # # Author : Oskar Taubert # # Creation Date : Tue 05 Dec 2017 08:08:18 PM CET # # Last Modified : Mon 30 Jul 2018 02:36:21 PM CEST # ##################################### from distruct.tools.ffparsergmx ...
675
262
#!/usr/bin/python # # Deletes any artifacts generated from the package scripts # # Imports import shutil, os import fnmatch import distutils.dir_util import cli # # Main entry function # def main(): # Get the path to the distribution package root_path = cli.get_project_root() + '/release' if os.path.ex...
437
148
#!/usr/bin/env python # -*- coding: utf-8 -*- print "HANDLING IMPORTS..." import os import time import operator import numpy as np import matplotlib.pyplot as plt import cv2 from scipy import interpolate from sklearn.utils import shuffle from sklearn.metrics import confusion_matrix import itertools import pickle ...
28,293
10,225
import os import redis def create_redis_connection(): redis_host = os.environ['REDIS_CACHE_HOST'] redis_port = os.environ['REDIS_CACHE_PORT'] redisCache = redis.Redis(host=redis_host, port=redis_port) return redisCache
238
86
# Scrape # from urllib.request import Request, urlopen import urllib.parse from urllib.error import HTTPError from bs4 import BeautifulSoup # json # import json # errors # from .errors import * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Create scraper class # ~~~~~~~~~~~~~~~~~~~~~~~~~...
15,635
4,938
__author__ = 'mpetyx' from django.contrib import admin from .models import OpeniShop class ShopAdmin(admin.ModelAdmin): pass admin.site.register(OpeniShop, ShopAdmin)
176
62
# -*- coding: utf-8 -*- import scrapy from pattersonschwartz.items import ListingItem class HomelistdetailsSpider(scrapy.Spider): name = 'homelistdetails' allowed_domains = ['pattersonschwartz.com'] start_urls = ['http://www.pattersonschwartz.com/forsale/Harford/priceMin_250000/priceMax_650000'] def ...
1,697
541
class Solution: def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res=[] self.dfs([], 0, nums, res) return res def dfs(self, path, index, nums, res): res.append(path) for i in range(index, len(nums)): ...
369
131
#!/usr/bin/env python3 # coding:utf-8 from random import randrange class Solution: def __init__(self): """ 最小值放大顶堆 最大值放小顶堆 """ self.littleValMaxHeap = [] self.bigValMinHeap = [] self.maxHeapCount = 0 self.minHeapCount = 0 def Insert(self, num):...
3,212
1,110
import json,itertools import numpy as np import pandas as pd from statsmodels.stats.inter_rater import cohens_kappa def kappa(f1,f2,pathologists,cols_to_parse,outname,ratings): contingency_tables = {} lvsi = {} for (pathologist_one, pathologist_two) in itertools.combinations(pathologists,2): KEY = '%s-%s'%(p...
1,234
501
from abc import ABC, abstractmethod from src.utils import read_dictionary class Solver(ABC): def __init__(self, word_dict_filepath, hist_dict_filepath): self.word_dict = read_dictionary(word_dict_filepath) self.hist_dict = read_dictionary(hist_dict_filepath) def is_in_dictionary(self, word):...
755
230
import time import pytest from obd import commands, Unit # NOTE: This is purposefully tuned slightly higher than the ELM's default # message timeout of 200 milliseconds. This prevents us from # inadvertently marking the first query of an async connection as # null, since it may be the case that the ...
4,363
1,470
import matplotlib.pyplot as plt import numpy as np # made by tomita from readcsv import readcsv fig = plt.figure(figsize = (4.5,7)) ax = fig.add_subplot(111) data = "./data/mirai_rs41_20210619_2330.txt" u,v,h = [],[],[] readcsv = readcsv(data) df = readcsv.df U = readcsv["Ecomp"] V = readcsv["Ncomp"] H = readcsv["Hei...
740
296
from django.db import models from data_ocean.models import DataOceanModel from location_register.models.koatuu_models import KoatuuCategory class RatuRegion(DataOceanModel): name = models.CharField('назва', max_length=30, unique=True) koatuu = models.CharField('код КОАТУУ', max_length=10, unique=True, null=T...
2,920
972
import argparse import os import subprocess import sys import venv from pathlib import Path from typing import Union from data_as_code import __version__ def menu(args=None): args = _parse_args(args) args.func(args) def _parse_args(args: list = None): program = 'data-as-code' parser = argparse.Argu...
3,020
992
# Create your views here. from datetime import datetime from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from delivery.serializer import TaskSerializer from ...
1,788
585
# -*- coding: utf-8 -*- """ These serializers are used exclusively to import the file ``workdir/fixtures/products-meta.json``. They are not intended for general purpose and can be deleted thereafter. """ from __future__ import unicode_literals from filer.models.imagemodels import Image from rest_framework import serial...
1,485
426