text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _, throw, msgprint from frappe.utils import nowdate from frappe.model.document import Documen...
3,752
1,418
# Generated by Django 2.1.5 on 2019-05-04 07:55 import blog.formatChecker from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0040_auto_20190504_0840'), ] operations = [ migrations.AlterField( model_name='videos', ...
481
172
import numpy as np import numpy.testing as npt import tardis import os from astropy import units as u from tardis.io.config_reader import Configuration from tardis.model import Radial1DModel import pytest DATA_PATH = os.path.join(tardis.__path__[0],'model','tests','data') @pytest.fixture(scope="module", params=['conf...
1,850
587
from typing import List import os import json from os.path import join as _join from os.path import exists as _exists import math from osgeo import gdal, osr import numpy as np from scipy.ndimage import label from subprocess import Popen, PIPE from pprint import pprint from wepppy.all_your_base.geo import read_tif...
34,911
11,115
""" Set of functions used by the PyRSM class to compute detection maps and optimize the parameters of the RSM algorithm and PSF-subtraction techniques via the auto-RSM and auto-S/N frameworks """ __author__ = 'Carl-Henrik Dahlqvist' from scipy.interpolate import Rbf import pandas as pd import numpy.linalg as la from v...
47,930
16,438
from torch.utils.data import Dataset from tqdm import tqdm import torch import pickle import json class CustomDataset(Dataset): def __init__(self, args, tokenizer, data_type): assert data_type in ["train", "valid", "test"] print(f"Loading {data_type} data...") with open(f"{args.t...
4,618
1,545
# -*- coding: future_fstrings -*- import codecs import pdb import string # NOTE https://stackoverflow.com/questions/38777818/how-do-i-properly-create-custom-text-codecs # prepare map from numbers to letters _encode_table = {str(number): bytes(letter) for number, letter in enumerate(string.ascii_lowercase)} # prepar...
1,588
513
import lkml from time import time_ns from rich import print FILE_PATH = "/Users/ladvien/rusty_looker/src/resources/test.lkml" with open(FILE_PATH, "r") as f: lookml = f.read() startTime = time_ns() // 1_000_000 result = lkml.load(lookml) print(result) executionTime = (time_ns() // 1_000_000) - startTime print('...
370
147
from keras.models import Sequential, load_model from keras.layers import Dense import csv import numpy as np import os LOAD_MODEL = False with open("Linear_Regression/Normalized_Attributes.csv", "r", newline='') as fp: reader = csv.reader(fp) headings = next(reader) dataset = np.array(list(read...
1,595
627
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 2 19:33:02 2021 @author: bressler """ import SBCcode as sbc import numpy as np import pulse_integrator as pi import gc def check_multibub_scintillation(run, event, at0, PMTgain, PMTwindow): tstart = PMTwindow[0] t_end= PMTwindow[1] sc...
3,141
1,095
from django.db import models from django.db.models.signals import pre_save, post_save from core.utils.constants import Constants from core.utils.data_convertion import DataConversion class ExcelFile(models.Model): file_name = models.FileField(upload_to='uploads') date_created = models.DateTimeField(auto_now_...
4,038
1,331
"""Interface to the `SLURM job scheduler <https://slurm.schedmd.com/documentation.html>`_ .. autofunction:: create_slurm_script """ from pathlib import Path from typing import Any, Dict, List from ..utils import Options def create_slurm_script(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata: List[Options]...
1,533
485
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com import re from urllib import quote class Url(object): unsafe_o...
5,290
1,726
import random from Virus import Virus class Person: ''' The simulation will contain people who will make up a population.''' def __init__(self, is_vaccinated, infection=None): ''' We start out with is_alive = True All other values will be set by the simulation through the parameters when ...
1,084
294
class Programa: def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @property def likes(self): return self._likes def dar_like(self): self._likes += 1 @property def nome(self): return self._nome @nome.set...
1,741
650
import constants as c from deck import Deck from player import Human, RandomAI class Game: def __init__(self): self.deck = None self.players = None self.scores = None self.rounds_left = None self.game_over = False def new(self): self.game_over = F...
3,275
983
from numba import unittest_support as unittest import gc from os.path import dirname, join import multiprocessing import sys import time import warnings from unittest.suite import TestSuite from numba.testing import load_testsuite from numba.testing import ddt # for backward compatibility try: import faulthandl...
1,084
332
""" Clustar module for fitting-related methods. This module is designed for the 'ClustarData' object. All listed methods take an input parameter of a 'ClustarData' object and return a 'ClustarData' object after processing the method. As a result, all changes are localized within the 'ClustarData' object. Visit <https...
5,377
1,715
from django.conf.urls import url from .forms import ( CookieContactWizard, Page1, Page2, Page3, Page4, SessionContactWizard, ) def get_named_session_wizard(): return SessionContactWizard.as_view( [('form1', Page1), ('form2', Page2), ('form3', Page3), ('form4', Page4)], url_name='nwiz_session'...
970
375
import pathlib from setuptools import setup CURRENT_PATH = pathlib.Path(__file__).parent README = (CURRENT_PATH/"README.md").read_text() setup( name="derive_event_pm4py", version="1.0.1", description="It derives new events based on rules provided as inputs.", long_description=README, long_descrip...
907
309
import unittest from datetime import datetime, timezone from typing import List from chillow.service.ai.not_killing_itself_ai import NotKillingItselfAI from chillow.model.action import Action from chillow.model.cell import Cell from chillow.model.direction import Direction from chillow.model.game import Game from chil...
16,334
5,295
#! /usr/bin/env python # coding: utf-8 # __author__ = 'meisanggou' try: from setuptools import setup except ImportError: from distutils.core import setup import sys if sys.version_info <= (2, 7): sys.stderr.write("ERROR: ldap-user requires Python Version 2.7 or above.\n") sys.stderr.write("Your Pyt...
1,123
408
import json import pytest @pytest.mark.usefixtures('client', 'headers') class TestInfection: def test_infection_region_tc01(self, client, headers): # db has data BETWEEN 2020-03-22 2020-03-24 region = 'China' payload = { 'region': region, 'start_date': '2020-03-22...
4,387
1,444
"""Module grouping tests for the pydov.util.owsutil module.""" import copy import re import pytest from numpy.compat import unicode from owslib.etree import etree from owslib.fes import ( PropertyIsEqualTo, FilterRequest, ) from owslib.iso import MD_Metadata from owslib.util import nspath_eval from pydov.util...
19,442
6,357
# -*- coding: utf-8 -*- """ manage ~~~~~~ Flask-Script Manager """ import os from flask.ext.script import Manager from flask.ext.migrate import MigrateCommand from fbone import create_app from fbone.extensions import db from fbone.utils import PROJECT_PATH, MALE from fbone.modules.user import User, ADMI...
1,430
474
import os sql_files = [x for x in os.listdir(".") if x.endswith("sql")] sql_files = list(sorted(sql_files, key = lambda x : int(x.split('.')[0]))) result = "" for i, f in enumerate(sql_files): i = i + 1 i = f.replace(".sql", "") with open(f) as sql: result += f"--- Query {i}\n" result += s...
444
166
""" MDCrane demo ============= .. seealso:: `Material Design spec, Crane <https://material.io/design/material-studies/crane.html#>` Crane is a travel app that helps users find and book travel, lodging, and restaurant options that match their input preferences. """ import os import sys from pathlib i...
2,882
1,026
# -*- coding: utf-8 -*- from nltk.parse import DependencyGraph from collections import defaultdict import random import sys import copy from json import dumps from pprint import pprint try: from .lg_graph import LgGraph except: sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil") from .lg_graph import...
8,368
2,556
# !/usr/bin/env python # coding=UTF-8 """ @Author: WEN Hao @LastEditors: WEN Hao @Description: @Date: 2021-09-24 @LastEditTime: 2022-04-17 源自OpenAttack的DCESSubstitute """ import random from typing import NoReturn, List, Any, Optional import numpy as np from utils.transformations.base import CharSubstitute from uti...
5,517
1,998
import optparse from abc import ABCMeta, abstractmethod from contextlib import contextmanager from typing import Iterator, Optional, Set from pip._internal.index.package_finder import PackageFinder from pip._internal.models.index import PyPI from pip._internal.network.session import PipSession from pip._internal.req i...
2,588
671
# Copyright 2020 Google LLC. 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/LICENSE-2.0 # # Unless required by applicable law or a...
11,371
3,113
# # Copyright 2020 Spotify AB # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
6,220
2,268
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/billing/budgets_v1beta1/proto/budget_model.proto import sys _b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1")) from google.protobuf import descriptor as _descriptor from google.proto...
28,079
9,633
# Copyright 2020 Google Research # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # ''' Imported from: https://github.com/google-research/sam ''' import torch class SAM(torch.optim.Optimizer): def __init__(self, params, base_optimizer, rho...
4,010
1,182
""" The MIT License Copyright 2020 Adewale Azeez <azeezadewale98@gmail.com>. """ import os.path from .konfiger_util import type_of, is_string, is_char, is_bool, escape_string, un_escape_string def file_stream(file_path, delimiter = '=', separator = '\n', err_tolerance = False): return KonfigerStream(file...
11,958
3,083
import math import numpy as np import collections import scipy.stats as sst import matplotlib.pyplot as plt def plot(*args, **kwargs): plt.plot(*args, **kwargs) plt.show() def linregshow(x, y, col: str="r"): linregresult = sst.linregress(list(zip(x, y))) plot(x, y, col, x, [(val * linregresult.slope) ...
2,674
874
import os from pathlib import Path import requests import shutil import sys from distutils.version import LooseVersion import time from tqdm import tqdm from docly.parser import parser as py_parser from docly.tokenizers import tokenize_code_string from docly import __version__ # from c2nl.objects import Code UPDATE_...
5,362
1,720
SE_VERSION = "4.2.1"
21
13
import pandas as pd import utils def check_msms_model_name(converter): def wrapper(*args, **kwargs): if kwargs['style'] not in ["pdeep", "prosit"]: raise Exception("MSMS model must be 'pdeep' or 'prosit'") converter(*args, **kwargs) return wrapper @check_msms_model_name...
2,978
1,027
#importing necessary modules from sklearn.linear_model import Perceptron from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score import numpy as np # Data and labels Xtrain = [[182, 80, 34], [176, 70, 33], [161, 60, 28], [154, 55, 27], [166, 63, 30], [189, 90, 36], [175, 63, 28], ...
1,497
724
import numpy as np class SGD: def __init__(self, lr=0.01, momentum=0.0, decay=0.0, nesterov=False, maximum=None, minimum=None): self.lr = lr self.momentum = momentum self.decay = decay self.nesterov = nesterov self.idx = None self.maximum = maximum ...
909
295
# Copyright 2022 Xanadu Quantum Technologies 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 # # Unless required by applicable law or a...
122,809
39,528
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright...
1,693
561
import itertools import unittest data = """Faerun to Norrath = 129 Faerun to Tristram = 58 Faerun to AlphaCentauri = 13 Faerun to Arbre = 24 Faerun to Snowdin = 60 Faerun to Tambi = 71 Faerun to Straylight = 67 Norrath to Tristram = 142 Norrath to AlphaCentauri = 15 Norrath to Arbre = 135 Norrath to Snowdin = 75 Norra...
2,469
934
#Exercício Python 39: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. imp...
1,000
353
#!/usr/bin/env python # -*- coding: utf-8 -*- from fish_core.utils.common_utils import format_dict_to_str, get_current_date, list_to_str, str_to_list from fish_dashboard.scrapyd.model import ScrapydStatusVO, JobListDO, JobStatus, JobPriority, ProjectListVO, SpiderListVO from fish_dashboard.scrapyd.scrapyd_db import Sql...
10,903
3,188
import os from tempfile import mkstemp from django.conf import settings from django.core.files import locks from django.core.files.move import file_move_safe from django.core.files.storage import FileSystemStorage from django.utils.text import get_valid_filename class OverwritingStorage(FileSystemStorage): """ ...
1,750
508
#!/usr/bin/env python2 import os import hashlib import datetime import sqlite3 from sqlite3 import Error def sha256(fname): """Return sha256 hash from input file (fname). :param fname: :return: Sha256 hash digest in hexadecimal""" hash_sha256 = hashlib.sha256() with open(fname, "rb") as f: for chunk in iter(lam...
3,783
1,428
def factorial(n): fact = 1 for i in range(2,n+1): fact*= i return fact def main(): n = int(input("Enter a number: ")) if n >= 0: print(f"Factorial: {factorial(n)}") else: print(f"Choose another number") if __name__ == "__main__": main()
309
120
###################################### # Import and initialize the librarys # ##################################### from code.pygame_objects import * from code.algorithm.bubblesort import bubblesort from code.algorithm.insertionsort import insertionsort from code.algorithm.bogosort import bogosort from code.algorithm.m...
5,919
1,851
#!/usr/bin/env python import rospy from std_msgs.msg import Int64 counter = 0 pub = None def callback_number(msg): global counter counter += msg.data new_msg = Int64() new_msg.data = counter pub.publish(new_msg) rospy.loginfo(counter) if __name__ == '__main__': rospy.init_node('...
489
187
#!/usr/bin/env python import codecs from os import path from setuptools import setup pwd = path.abspath(path.dirname(__file__)) with codecs.open(path.join(pwd, 'README.md'), 'r', encoding='utf8') as input: long_description = input.read() version='1.7' setup( name='Perdy', version=version, license='MIT', ...
806
343
from tabulate import tabulate from slack.errors import SlackApiError import sys import logging import slack class Slackalert: """To send cost report on slack.""" def __init__(self, channel=None, slack_token=None): self.channel = channel self.slack_token = slack_token logging.basicConfi...
2,658
742
import logging from abc import ABC, abstractmethod from pony.orm import db_session, commit log = logging.getLogger(__name__) class Importer(ABC): def __init__(self, TargetEntity): self.TargetEntity = TargetEntity @db_session def truncate(self): log.info('Truncating target tables...') ...
526
154
# Generated by Django 3.2.7 on 2021-10-09 18:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pybo', '0005_auto_20211010_0320'), ] operations = [ migrations.AddField( model_name='issue', name='agree_representor...
982
317
import json import os def get_file_index(filesProcessed): new_dict = {} for f in filesProcessed: new_dict[f]={"framerate": 30.0, "selected": {"0": 1, "9000": 0}} return new_dict ref = json.load(open("/home/lijun/downloads/kf1_meta/references/kf1_all.json","r")) files = ref["filesProcessed"] print...
852
360
from enum import Enum, auto import funcy as fn import numpy as np from monotone_bipartition import rectangles as mdtr from monotone_bipartition import refine EPS = 1e-4 class SearchResultType(Enum): TRIVIALLY_FALSE = auto() TRIVIALLY_TRUE = auto() NON_TRIVIAL = auto() def diagonal_convex_comb(r): ...
2,561
895
from flask import url_for from flaskcbv.view import View from flaskcbv.conf import settings from misc.mixins import HelperMixin from misc.views import JSONView class authView(JSONView): def helper(self): return """Authorizaion handler Use "login" and "passwd" arguments by GET or POST to get ses...
1,562
473
from pykitml.testing import pktest_graph, pktest_nograph @pktest_graph def test_heart_forest(): import os.path import numpy as np import pykitml as pk from pykitml.datasets import heartdisease # Download the dataset if(not os.path.exists('heartdisease.pkl')): heartdisease.get() # Lo...
2,069
769
from globals import Globals import os import subprocess import datetime as dt from urllib import \ request as request # urlopen from io import \ StringIO, BytesIO import string import requests import re import csv import threading import utils as utils import time import datetime as datetime import multiproces...
25,682
7,840
import morepath from webtest import TestApp as Client def test_implicit_function(): class app(morepath.App): @morepath.dispatch_method() def one(self): return "Default one" @morepath.dispatch_method() def two(self): return "Default two" @app.path(path=...
2,114
686
# # This source file is part of the EdgeDB open source project. # # Copyright 2015-present MagicStack Inc. and the EdgeDB 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...
14,020
4,558
from typing import List from mathy_core import ExpressionParser, MathExpression parser = ExpressionParser() expression: MathExpression = parser.parse("4 + 2x") nodes: List[MathExpression] = expression.to_list() # len([4,+,2,*,x]) assert len(nodes) == 5
255
79
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np convolve_grayscale_padding = __import__( '2-convolve_grayscale_padding').convolve_grayscale_padding if __name__ == '__main__': dataset = np.load('../../supervised_learning/data/MNIST.npz') images = dataset['X_train'] print(ima...
603
231
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file data=pd.read_csv(path) data.rename(columns={'Total':'Total_Medals'},inplace =True) data.head(10) #Code starts here # -------------- try: data['Better_Event'] = np.where(...
2,950
1,207
import bpy import math import numpy as np #=== add scripts dir to path import sys import os #=== define path of scripts dir libDir=bpy.path.abspath("//../../scripts/") # version1: relative to current file #libDir="/where/you/placed/blenderCadCam/scripts/" #version 2: usa an absolute path if not libDir in sys.path: ...
7,096
2,729
# Generated by Django 2.2.4 on 2019-08-14 09:13 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("order", "0071_order_gift_cards")] operations = [ migrations.RenameField( model_name="order", old...
1,715
506
import numpy as np from sklearn.preprocessing import FunctionTransformer from sklearn.pipeline import Pipeline from sklearn.pipeline import FeatureUnion from sklearn.preprocessing import StandardScaler from ..models.profile import Profile from ..interfaces.helper import Helper from ..interfaces.glove import GloVe fro...
9,382
2,350
# Copyright (c) 2015 Mitch Garnaat # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
1,383
459
import urllib.request import urllib.parse import json def http_request(url, query=None, method=None, headers={}, data=None): """Perform an HTTP request and return the associated response.""" parts = vars(urllib.parse.urlparse(url)) if query: parts['query'] = urllib.parse.urlencode(query) url ...
1,267
397
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
3,678
1,102
# Copyright (C) 2014 Deutsche Telekom AG # 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/LICENSE-2.0 # # Unless r...
899
260
import config import misc def heartbeat(): """ Processes data from Bittrex into a simpler dictionary, calls the save function on it, deletes the oldest saved dictionary(if it's out of lookback range), and finally creates a list of the best coins to be used in tkinter listboxes. :return: A list...
2,195
707
""" created by nikos at 4/26/21 """ import datetime from ..base import MLBStatsAPIEndpointModel from mlb_statsapi.utils.stats_api_object import configure_api YMDTHMS = '%Y-%m-%dT%H:%M:%SZ' YYYYMMDD_HHMMSS = '%Y%m%d_%H%M%S' MMDDYYYY_HHMMSS = '%m%d%Y_%H%M%S' class GameModel(MLBStatsAPIEndpointModel): date_forma...
2,325
813
#!/usr/bin/env python3 import os import sys import textwrap self_path = os.path.dirname(os.path.realpath(__file__)); f = open(self_path + "/unicode/CaseFolding.txt", "r") status_list = [ "C", "F" ] folding_list = [ dict(), dict(), dict() ] # Filter the foldings for "full" folding. for line in f: comment_off =...
4,351
1,446
users = [] class UserModel(object): """Class user models.""" def __init__(self): self.db = users def add_user(self, fname, lname, email, phone, password, confirm_password, city): """ Method for saving user to the dictionary """ payload = { "userId": len(self.db)+1, ...
1,038
285
from controller import Robot from controller import Motor from controller import PositionSensor from controller import Robot, DistanceSensor, GPS, Camera, Receiver, Emitter import cv2 import numpy as np import math import time robot = Robot() timeStep = 32 tile_size = 0.12 speed = 6.28 media_baldoza = 0.06 estado = 1 ...
6,644
2,584
# Generated by Django 3.0.7 on 2020-11-25 13:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drip', '0001_initial'), ] operations = [ migrations.AddField( model_name='querysetrule', name='rule_type', ...
433
150
# cligj # Shared arguments and options. import click from .features import normalize_feature_inputs # Arguments. # Multiple input files. files_in_arg = click.argument( 'files', nargs=-1, type=click.Path(resolve_path=True), required=True, metavar="INPUTS...") # Multiple files, last of which is...
3,393
1,088
from pkg_resources import parse_version from configparser import ConfigParser import setuptools assert parse_version(setuptools.__version__)>=parse_version('36.2') # note: all settings are in settings.ini; edit there, not here config = ConfigParser(delimiters=['=']) config.read('settings.ini') config = config['DEFAULT...
2,031
661
from __future__ import absolute_import, division, print_function, unicode_literals from amaasutils.random_utils import random_string, random_decimal import random from amaascore.core.reference import Reference from amaascore.parties.asset_manager import AssetManager from amaascore.parties.broker import Broker from am...
3,730
1,120
# -*- coding: utf-8 -*- """User functions to streamline working with selected pymer4 LMER fit attributes from lme4::lmer and lmerTest for ``fitgrid.lmer`` grids. """ import functools import re import warnings import numpy as np import pandas as pd import matplotlib as mpl from matplotlib import pyplot as plt import f...
9,291
2,983
import os import json from hashlib import md5 from tornado import web from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler __all__ = ['load_jupyter_server_extension'] STATIC_DIR = os.path.join(os.path.dirname(__file__), 'nbextension', 'static'); CONFIG = os.path.expanduser('~/.py...
2,055
656
# -*-: coding utf-8 -*- """ Skeleton Snips skill. """ import re import json import os import datetime from text2num import text2num from collections import defaultdict FORMAT = '%Y.%m.%dT%H:%M:%S' class PingPongSkill(object): """ Skeleton Snips skill. """ def __init__(self): pass def handle_lo...
3,552
1,135
import numpy as np import xarray as xr import pandas as pd import sys import json import os import datetime from xarray.core.utils import ( decode_numpy_dict_values, either_dict_or_kwargs, ensure_us_time_resolution, ) from numpy.compat import ( asbytes, asstr, asunicode, bytes, basestring, os_fspath,...
13,006
4,296
# Copyright (c) 2019 Graphcore 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/LICENSE-2.0 # # Unless required by applicable l...
14,222
3,984
import json import numpy as np import pdb import torch from ray_utils import get_rays, get_ray_directions, get_ndc_rays BOX_OFFSETS = torch.tensor([[[i,j,k] for i in [0, 1] for j in [0, 1] for k in [0, 1]]], device='cuda') SQR_OFFSETS = torch.tensor([[[i,j] for i in [0, 1] for j in [0,...
9,921
4,322
import os import cv2 import time import json import random import inspect import argparse import numpy as np from tqdm import tqdm from dataloaders import make_data_loader from models.sync_batchnorm.replicate import patch_replication_callback from models.vs_net import * from utils.loss import loss_dict from utils.lr_s...
15,755
4,798
import numpy as np import gzip import pickle import os import urllib.request class MNIST: host = 'http://yann.lecun.com/exdb/mnist/' filenames = { 'train': ('train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz'), 'test': ('t10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz'), } dataset_filen...
2,692
925
#Задачи на циклы и оператор условия------ #---------------------------------------- ''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' for i in range(1, 6): print(i, '0000000000000000000000000000000000000000000') ''' Задача 2 Пользователь в цикле вводит 1...
2,279
979
import os import numpy as np import time import multiprocessing as mp import csv import socket import datetime import math import glob from pypushexp import PushSim # # input - [recorded item] # [weight] : 48 # [height] : 160 # [crouch_angle] (deg) # [step_length_ratio] # [halfcycle_duration_rati...
11,368
4,219
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.conf.urls import include from django.views.generic import TemplateView, RedirectView urlpatterns = [ # Administration path('admin/', admin.site.urls),...
776
245
from django.contrib import admin from .models import Room, Topic, Message, User admin.site.register(Room) admin.site.register(Topic) admin.site.register(Message) admin.site.register(User)
189
60
# Copyright (c) Open-MMLab. All rights reserved. import os import json import tempfile import warnings from typing import Optional from argparse import Namespace from addict import Dict from ..utils import check_file BASE_KEY = "_base_" RESERVED_KEYS = ["filename", "text"] class ConfigDict(Dict): r"""ConfigDic...
10,744
3,213
from Kaspa.modules.abstract_modules.abstractSubmodule import AbstractSubmodule from Kaspa.modules.exceptions.impossibleActionError import ImpossibleActionError from Kaspa.config import Config class SpotifyModuleEn(AbstractSubmodule): module_name = "Spotify" language = "en" key_regexes = dict() def ...
2,643
755
import os import sys import pathlib from utilities import get_random_hash from flask import Flask, flash, request, redirect, url_for, send_from_directory, jsonify, Response UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER') if os.environ.get('UPLOAD_FOLDER') else '/tmp' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', '...
2,768
816
# Generated by Django 3.2 on 2022-01-31 14:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notifications', '0001_initial'), ] operations = [ migrations.AlterField( model_name='notification', name='emails', ...
517
156
import copy import subprocess import sys import unicodedata def disable_colored_func(text, *args, **kwargs): return text try: from termcolor import colored as colored_func except ImportError: print 'You should run "pip install termcolor" to fully utilize these utilities.' colored_func = disable_colore...
2,800
857
import numpy as np import pygsti.baseobjs.basisconstructors as bc from ..util import BaseCase class BasisConstructorsTester(BaseCase): def test_GellMann(self): id2x2 = np.array([[1, 0], [0, 1]]) sigmax = np.array([[0, 1], [1, 0]]) sigmay = np.array([[0, -1.0j], [1.0j, 0]]) sigmaz ...
4,308
1,695
# Copyright 2016 The TensorFlow Authors. 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/LICENSE-2.0 # # Unless required by applica...
7,913
3,034