text
string
size
int64
token_count
int64
# This file is part of Pynguin. # # Pynguin 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 the License, or # (at your option) any later version. # # Pynguin is distributed in the ho...
5,434
1,564
"Test history entries for migrated, obsolete fields" from datetime import ( time, timedelta, ) from decimal import Decimal from typing import ( Any, Dict, ) from django.contrib.auth.models import User from django.db import models from wicked_historian.usersmuggler import usersmuggler from wicked_histo...
7,778
2,428
from UdonPie import UnityEngine from UdonPie.Undefined import * class HideFlags: def __new__(cls, arg1=None): ''' :returns: HideFlags :rtype: UnityEngine.HideFlags ''' pass
219
71
# Generated by Django 2.2.5 on 2019-11-01 06:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('solicitudes', '0005_auto_20191101_0115'), ] operations = [ migrations.RemoveField( model_name='solicitud', name='tip...
536
190
""" #################################################################################################### # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : tp_head.py # Abstract : Text Perceptron head structure, mainly including losses for s...
12,639
4,206
import wx, wx.lib.newevent import wx.lib.ogl as ogl from myhdl import Signal, always, intbv from MyHDLSim.sequential import ClkDriver # OGL object to draw a signal class SignalOGLShape(ogl.CompositeShape): """ This shape is used exclusively to contruct the SIGNAL main shape. The shape is initially based wi...
5,757
1,740
import json import sys from frankenbot.bot import Bot from frankenbot.console_chat_interface import ConsoleChatInterface from frankenbot.persistence.json.json_unserializer import JSONUnserializer bot_def = "bot_def/restaurantsearch.json" unserializer = JSONUnserializer() #simpleResponseGenerator object bot = unseriali...
1,403
460
#!/usr/bin/env python # # # 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, soft...
6,801
2,183
from typing import TYPE_CHECKING, Optional from ModularChess.movements.Movement import Movement, MovementData if TYPE_CHECKING: from ModularChess.pieces.Piece import Piece from ModularChess.utils.Position import Position class EnPassant(Movement): def __init__(self, piece: "Piece", new_position: "Positi...
1,383
422
# -*- coding: utf-8 -*- """ julabo.py Contains Julabo temperature control see documentation http://www.julabo.com/sites/default/files/downloads/manuals/french/19524837-V2.pdf at section 10.2. :copyright: (c) 2015 by Maxime DAUPHIN :license: MIT, see LICENSE for details """ import serial import time from .pytempera...
2,387
978
""" Some basic matrix-related functionality. """ def cumulative2d(grid): """ >>> cumulative2d([[2, 5, 4], [3, 8, 1]]) [[0, 0, 0, 0], [0, 2, 7, 11], [0, 5, 18, 23]] """ rows = [] for row in grid: rrr = [0] last = 0 for col in row: last += col rrr.a...
1,143
492
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from lxml import etree import json class DouyuSpider: def __init__(self): """ 初始化 """ start_u...
5,361
1,959
#!/usr/bin/env python from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() # Read version in...
960
314
# ___ ___ ___ ___ ___ ___ # /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ # /::\ \ /::\ \ \:\ \ /::\ \ /::\ \ /::\ \ # /:/\:\ \ /:/\:\ \ \:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ # /:/ \:\ \ /:/ \...
29,850
10,122
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2019, Linear Labs Technology 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 ...
4,053
1,281
import os from project import app, db class BaseConfig: """Base configuration""" TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False print('Running through config') class DevelopmentConfig(BaseConfig): """Development configuration""" SQLALCHEMY_DATABASE_URI = os.environ.get('POSTGRES_URL')...
790
278
from sqlalchemy import Column,Integer,String, Float from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from config.envvar import * Base = declarative_base() class Steps(Base): __tablename__ = "steps" id = Column(Integer, primary_key=True, autoincrement=True) recip...
625
210
class ChoiceGenerator: ''' Generates (nonrecursively) all of the combinations of a choose b, where a, b are nonnegative integers and a >= b. The values of a and b are given in the constructor, and the sequence of choices is obtained by repeatedly calling the next() method. When the sequence is fin...
2,184
617
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 11:17:21 2020 @author: eilxaix """ import pandas as pd import re def remove_hashtag(t): t=re.sub('-',' ', t) t=' '.join(t.split()) return t def read_csv_data(df): title = [remove_hashtag(i) for i in df['Document Title']] abstract = [remove_hashta...
1,259
450
# Generated from Scicopia.g4 by ANTLR 4.9.2 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7...
17,705
6,291
from pathlib import Path import sys sys.path.append(str(Path(__file__).resolve().parents[1])) from werewolf import create_app from werewolf.database import db app = create_app('db') with app.app_context(): db.drop_all() db.create_all()
259
95
import numpy as np import pytest from sklego.common import flatten from sklego.linear_model import ProbWeightRegression from tests.conftest import nonmeta_checks, regressor_checks, general_checks @pytest.mark.parametrize("test_fn", flatten([ nonmeta_checks, general_checks, regressor_checks ])) def test_e...
936
349
# -*- coding: utf-8 -*- """ Created on Sat Jun 29 19:44:28 2019 @author: Administrator """ class Solution: def canWin(self, s: str) -> bool: ans = self.generatePossibleNextMoves(s) print(ans) count = 0 for state in ans: # print(state) for k in range(len(state...
854
306
"""The CSDMS Web Modeling Tool (WMT) execution server.""" __version__ = '0.3'
79
30
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd save_results = False def plot_stored_GEM_reults(interval_x=None, interval_y=None): if interval_x is None: #interval_list_x = [0.499, 0.506] # 1 interval_list_x = [0, 1] #interval_list_x = [0.299, 0.30...
8,284
3,730
# # Copyright 2020 Antoine Sanner # 2020 Lars Pastewka # # ### MIT license # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
3,725
1,261
import os import glob from ast import literal_eval import numpy as np import sympy from sympy import pi, sin, cos, var from sympy.printing import ccode from compmech.conecyl.sympytools import mprint_as_sparse, pow2mult var('x1t, x1r, x2t, x2r') var('y1t, y1r, y2t, y2r') var('xi1, xi2') var('c0, c1') subs = { ...
4,687
1,688
import time import numpy as np from sparsecoding import sparse_encode_omp from sparsecoding import sparse_encode_nnmp from distributedpowermethod import distri_powermethod def cloud_ksvd(X, AtomN, dict_init, s, NodeN, networkGraph, vec_init, max_iter, powerIterations, consensusIterations): sigdim = ...
6,277
2,034
# Simple Game # Demonstrates importing modules import games, random print("Welcome to the world's simplest game!\n") again = None while again != "n": players = [] num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5) for i in range(num): na...
677
214
import engine class Player: def talk(self, message: str) -> None: engine_version = engine.get_version() engine.print_log(message=f"Engine version = {engine_version}")
189
56
import argparse import yomikatawa as yomi def create_parser(): parser = argparse.ArgumentParser(description="A command line interface for https://yomikatawa.com.") parser.add_argument("-c", "--category", type=str, default="kanji", help="print possible choices on error") parser.add_argument("-r", "--romaji"...
964
311
""" A module hosting all algorithms devised by Izzo """ import time import numpy as np from numpy import cross, pi from numpy.linalg import norm from scipy.special import hyp2f1 def izzo2015( mu, r1, r2, tof, M=0, prograde=True, low_path=True, maxiter=35, a...
10,873
4,352
''' Test deleting SG with 2 attached NICs. @author: Youyk ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.zstack_test.zstack_test_security_group as test_sg_header import zstackwoodpecker....
2,688
1,128
# Figure 5 in https://arxiv.org/pdf/1909.13404.pdf (towards modular and programmable architecture search) import sane_tikz.core as stz import sane_tikz.formatting as fmt frame_height = 9.5 frame_width = 10.0 frame_spacing = 0.2 frame_roundness = 0.6 frame_line_width = 4.5 * fmt.standard_line_width module_height = 1.6...
15,365
6,307
import time import json from basetestcase import BaseTestCase from couchbase_helper.documentgenerator import doc_generator from couchbase_helper.durability_helper import DurabilityHelper, \ DurableExceptions from couchbase_helper.tuq_generators import JsonGenerator from ...
25,801
7,836
import matplotlib.pyplot as plt import yaml import os workspace = "/workspace/mnt/storage/guangcongzheng/zju_zgc/guided-diffusion" num_samples = 192 log = os.path.join(workspace, 'log/imagenet1000_classifier256x256_channel128_upperbound/predict/model500000_imagenet1000_stepsddim25_sample{}_selectedClass'.format(num_...
1,025
386
from bs4 import BeautifulSoup import requests import urllib.request from datetime import datetime import time from PIL import Image, ImageDraw, ImageFont import ctypes import os import shutil import socket import sys def is_connected(hostname): try: # see if we can resolve the host name -- tells us if the...
2,882
846
# coding=utf-8 # @Author : zhzhx2008 # @Time : 18-10-9 import os import warnings import jieba import numpy as np from keras import Input from keras import Model from keras import backend as K from keras import initializers, regularizers, constraints from keras.callbacks import EarlyStopping, ModelCheckpoint from...
9,401
3,351
# coding: utf8 vpc_cidr = "192.168.0.0/16" http_cidr = "192.168.1.0/24"
73
53
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from fastfold.model.fastnn.kernel import scale_mask_softmax, scale_mask_bias_softmax from fastfold.model.fastnn.kernel import LayerNorm from .initializer import glorot_uniform_af from fastfold.model.fastnn.kernel ...
6,731
2,518
# -*- coding:utf-8 -*- """ __init__.py ~~~~~~~~ 数据收集插件 input :author: Fufu, 2021/6/7 """ from abc import abstractmethod from asyncio import create_task, sleep from typing import Any from loguru import logger from ..libs.plugin import BasePlugin class InputPlugin(BasePlugin): """数据采集插件基类""" ...
1,093
426
import yaml import re from .SummonableBot import SummonableBot class Librarian(SummonableBot): def __init__(self, bot_name, event): self.help_command = 'help' self.help_preamble = "Here are my available responses" self.event = event with open('./responses.yml') as file: ...
1,933
598
import pprint import statistics from contextlib import suppress from dataclasses import dataclass from enum import Enum from typing import Optional @dataclass class ValidCharacter: definite_locations: set[int] definite_not_locations: set[int] class CharacterStatus(Enum): GRAY = "gray" GREEN = "green...
8,201
2,195
# coding=utf-8 # # @lc app=leetcode id=876 lang=python # # [876] Middle of the Linked List # # https://leetcode.com/problems/middle-of-the-linked-list/description/ # # algorithms # Easy (64.97%) # Likes: 593 # Dislikes: 42 # Total Accepted: 76.4K # Total Submissions: 117.5K # Testcase Example: '[1,2,3,4,5]' # # ...
2,249
847
# New BSD License # # Copyright (c) 2007-2019 The scikit-learn developers. # All rights reserved. # # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # a. Redistributions of source code must retain the above copyright...
3,442
1,141
import pytest import sys sys.path.append('.') from turingmachine import Transition, Direction, State def test_create_transition(): q0 = State() q1 = State() #In q0 upon reading a move to q1, output b, and move the tape 1 right q0.create_transition('a', q1, 'b', Direction.RIGHT) assert q0.transiti...
1,757
646
class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ # constant space # [1, len(nums) + 1] n = len(nums) for i, num in enumerate(nums): if num < 0 or num > n: nums[i] = 0 n ...
558
180
import os def returnText(): cwd = os.getcwd().replace(os.environ['HOME'],'~') lstCwd = str.split(cwd, '/') if len(lstCwd) > 3: lstCwd.reverse() lstCwd = lstCwd[0:3] lstCwd.append('+') lstCwd.reverse() strCwd = '/'.join(lstCwd) return strCwd
294
120
from unittest import mock from django.contrib.auth import get_user_model from django.core import mail from django.template import TemplateDoesNotExist from django.test import TestCase from django.urls import reverse from ..accounts.adapter import EmailAdapter from .utils import TestOrganizationMixin User = get_user_...
1,850
555
from setuptools import setup setup( name='vuln_toolkit', version='0.1', description='Transfer Learning Toolkit', url='https://para.cs.umd.edu/purtilo/vulnerability-detection-tool-set/tree/master', author='Ashton Webster', author_email='ashton.webster@gmail.com', license='MIT', packages=...
382
141
# # Copyright (c) European Synchrotron Radiation Facility (ESRF) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy,...
13,255
3,303
import numpy as np from tqdm import * from utils import DataLoaderX from dataset import collate from math import * def prediction(data, model, batch_size, cuda): data_loader = DataLoaderX(data, batch_size=batch_size, collate_fn=collate, num_workers=0) model.training = False iterator = tqdm(data_loader) ...
1,556
586
import torch from torch import nn from tqdm import tqdm from entmax import entmax_bisect import torch.nn.functional as F # helper function def eval_decorator(fn): def inner(model, *args, **kwargs): was_training = model.training model.eval() out = fn(model, *args, **kwargs) model.tr...
3,318
1,243
# 1478. Allocate Mailboxes # User Accepted:342 # User Tried:594 # Total Accepted:364 # Total Submissions:1061 # Difficulty:Hard # Given the array houses and an integer k. where houses[i] is the location of the ith house along a street, your task is to allocate k mailboxes in the street. # Return the minimum total dista...
1,686
661
""" Operadores lógicos Para agrupar operações com lógica booleana, utilizaremos operadores lógicos. Python suporta três operadores básicos: not (não), and (e), or (ou). Esses operadores podem ser traduzidos como não (¬ negação), e (Λ conjunção) e ou (V disjunção). """ # Operador not """ >>> not True False >>> not Fa...
990
353
# # Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from nfv_common.alarm import * # noqa: F401,F403 from nfv_vim.alarm._general import clear_general_alarm # noqa: F401 from nfv_vim.alarm._general import raise_general_alarm # noqa: F401 from nfv_vim.alarm._host import host...
944
402
"""~#SHORTDESCRIPTION#~""" __version__ = "1.0.0" __release__ = "1" __program_name__ = "~#PROJECT#~"
101
51
from typing import Optional from torch import nn from rl_multi_agent.experiments.furnmove_grid_marginal_nocl_base_config import ( FurnMoveExperimentConfig, ) from rl_multi_agent.models import A3CLSTMNStepComCoordinatedActionsEgoGridsEmbedCNN class FurnMoveGridExperimentConfig(FurnMoveExperimentConfig): # In...
2,225
643
""" Request controllers for the external links service. These may be used handle requests originating from the :mod:`.routes.api` and/or the :mod:`.routes.ui`. If the behavior of these controllers diverges along the UI/API lines, then we can split this into ``controllers/api.py`` and ``controllers/ui.py``. """ from ...
728
212
from __future__ import division from __future__ import unicode_literals import re from django.http import HttpResponse from django.shortcuts import redirect from django.template import RequestContext from django.template import loader from models import * from apps.core.views import get_bg_color def list_students(...
3,101
896
from __future__ import unicode_literals from subprocess import call from re import search from random import sample, choice from csv import reader from os import popen from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter ''' The strings, input and output of this program is in lowercase...
6,635
2,171
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=wrong-import-position # pylint: disable=protected-access import concurrent.futures import io import os import sys import tempfile import threading sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from ratarmountcore i...
4,775
1,911
import datetime import json import os import requests import smtplib import ssl def check_status(config): new_state = get_current_state() last_known_state = get_last_known_state() activated = get_activated(new_state, last_known_state) deactivated = get_deactivated(new_state, last_known_state) save...
3,029
972
# Settings Manager # guidanoli DEFAULT_STGS = { "commas": "true", "comments": "true", "tknlistpath": "tknlist.tk", "tokenpath": "token.tk" } SETTINGS_PATH = "fibonacci.cfg" TYPE_STR = type("") TYPE_LIST = type([]) def _validateFilename( filename , extension = "" ): from re import match return...
5,340
1,627
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright SquirrelNetwork from core import decorators from telegram.utils.helpers import mention_markdown @decorators.public.init @decorators.delete.init def init(update,context): bot = context.bot administrators = update.effective_chat.get_administrators() ...
632
204
from ..utils import Object class Users(Object): """ Represents a list of users Attributes: ID (:obj:`str`): ``Users`` Args: total_count (:obj:`int`): Approximate total count of users found user_ids (List of :obj:`int`): A list of user identifiers ...
762
249
# -*- coding: utf-8 -*- ####################################################### ''' input 路徑 圖片數量 MOD值 嵌密率 處理內容 輸入一張圖片的資料,包含: 1.資料夾名稱 2.檔案名稱(圖片),單純用來記錄在xlsx檔案中 3.輸出路徑-xlsx 4.嵌密mod值 5.嵌密率 output 產生輸入圖片的xlsx檔(依序將所有圖片的資料寫入xlsx檔中) 包含執行時間 ''' ####...
2,937
1,156
from collections import OrderedDict my_dict = OrderedDict() def populate(data: dict): my_dict.update(data) return True if __name__ == "__main__": print(populate({}))
183
63
# -*- coding: utf-8 -*- # Copyright (c) 2021 Brian Scholer (@briantist) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import pytest from ansible_collections.community.hashi...
2,592
1,038
def crescente_e_decrescente(): while True: n1, n2 = entrada() if n1 > n2: print('Decrescente') elif n1 < n2: print('Crescente') else: break def entrada(): numeros = list(map(int, input().split(' '))) numero1 = numeros[0] numero2 = num...
384
134
from kivy.lang import Builder import array import scipy import os import syft as sy import tensorflow as tf import numpy import time import scipy import sys from dataset import get_dataset from cluster import get_cluster from PIL import Image import leargist from skimage import transform from imageio import imsave f...
2,695
969
from network.network import Network import tensorflow as tf import numpy as np class VGG16(Network): def __init__(self, input_shape, class_number, x, y, train=False, learning_rate=0.001): super().__init__() self.loss = None self.accuracy = None self._build_network(input_shape, cla...
5,910
2,270
from google.protobuf import descriptor from google.protobuf import message from google.protobuf import reflection from google.protobuf import descriptor_pb2 DESCRIPTOR = descriptor.FileDescriptor(name='ResourceKey.proto', package='EA.Sims4.Network', serialized_pb='\n\x11ResourceKey.proto\x12\x10EA.Sims4.Network"<\n\x0b...
2,840
1,014
import math import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Polygon # from matplotlib.ticker import MaxNLocator # Rafael Redondo (c) Eurecat 2020 colors = np.array([ [[247, 197, 188],[242, 151, 136],[242, 120, 99],[237, 85, 59]], [[255, 242, 196], [247, 232, 176], [250, 225, 135], [...
5,787
4,217
import yaml import os import sys import yaml import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from utils import load_poses, load_calib, load_files, load_vertex from preprocessing.utils import * from example.laserscan import * from PC_cluster.ScanLineRun_cluster.build import ScanLineRun_Cluster ...
4,299
1,435
class Solution: def nextGreatestLetter(self, letters, target): """ :type letters: List[str] :type target: str :rtype: str """ for l in letters: if l > target: return l return letters[0] if __name__ == '__main__': solution = S...
529
182
from math import sqrt def factorial(n): """Computes factorial of n.""" if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result def estimate_pi(): factor = (sqrt(2) * 2) / 9801 k = 0 total = 0 while True: nu...
592
247
# WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 import enum import winsdk _ns_module = winsdk._import_ns_module("Windows.Graphics.Printing.PrintTicket") try: import winsdk.windows.data.xml.dom except Exception: pass try: import winsdk.windows.foundation except Exc...
1,202
387
import threading import sys class ReturnValueThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.result = None def run(self): if self._target is None: return # could alternatively raise an exception, depends on the use cas...
638
183
class Other: def __init__(self, name21): self.name21 = name21 def get_name21(self): return self.name21 @staticmethod def decode(data): f_name21 = data["name21"] if not isinstance(f_name21, unicode): raise Exception("not a string") return Other(f_name21) def encode(self): dat...
540
203
import asyncio class EchoClient(asyncio.Protocol): def __init__(self, message, loop): self.mesage = message self.loop = loop def connection_made(self, transport): transport.write(self.mesage.encode("utf-8")) self.transport = transport def data_received(self, data): ...
623
217
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals class ResultMeta(object): def __init__(self, meta): self._meta = meta @property def width(self): return int(self._meta['Image-Width']) @property def height(self): ret...
482
146
# -*- coding: UTF-8 -*- from spider import * def main_view(): print '-------------------------------------------------------' print 'l.列出项目\ts.查找项目\tc.更新项目\tq.退出' print '|---0.顺序 \t|---0.关键字' print '|---1.收藏↑\t|---1.收藏>=' print '|---2.收藏↓\t|---2.收藏<' print '|---3.评论↑\t|---3.评论>=' print '|-...
855
403
import pandas as pd from matplotlib import pyplot as plt import numpy as np import math from matplotlib import pyplot as plt from sklearn.preprocessing import LabelEncoder feature_dict = {i:label for i,label in zip( range(4), ('sepal length in cm', 'sepal width in c...
5,653
2,175
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-07-09 23:15 from __future__ import unicode_literals from django.db import migrations, models import js_color_picker.fields class Migration(migrations.Migration): dependencies = [ ('js_services', '0012_auto_20190430_0804'), ] operatio...
1,509
484
""" gentex.texmeas package """ import numpy as np class Texmeas: """Class texmeas for generating texture measures from co-occurrence matrix Parameters ---------- comat: ndarray Non-normalized co-occurrence matrix - chi-squared conditional distribution comparisons require the actua...
29,968
8,946
#!/usr/bin/env python # encoding: utf-8 """ @author: zk @contact: kun.zhang@nuance.com @file: dataio.py @time: 8/27/2019 4:31 PM @desc: """ import os def load_txt_data(path, mode='utf-8-sig', origin=False): """ This func is used to reading txt file :param origin: :param path: path where file stored ...
3,373
1,147
from constants import * import pygame as pg from time import sleep from metronome import * import math import numpy as np from copy import deepcopy from audio import * from instructions_panel import * from loop import * class MusicMaker: def __init__(self, screen): self.pitch = 0 self.screen = scr...
20,511
6,771
import aiohttp import struct import json import re class eGame: heartbeat = b'\x00\x00\x00\x12\x00\x12\x00\x01\x00\x07\x00\x00\x00\x01\x00\x00\x00\x00' heartbeatInterval = 60 @staticmethod async def get_ws_info(url): rid = url.split('/')[-1] page_id = aid = rid headers = { ...
10,084
3,503
from django.views.generic import DetailView, TemplateView from star_ratings.models import Rating from .models import Beer, Snack class BeerRateView(TemplateView): model = Beer template_name = 'minimal_rating_system/article_ratings.html' def get_context_data(self, **kwargs): kwargs['article_class...
832
265
# Generated by Django 3.2.5 on 2021-07-20 15:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('AwardsApp', '0004_alter_userprofile_bio'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='bio', ...
335
117
# Imports from flask import Flask, render_template, session, redirect, request, flash, url_for, abort from flask_session import Session from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_password_hash from cs50 import S...
8,530
2,677
from pycipher import Rot13 import unittest class TestRot13(unittest.TestCase): def test_decipher(self): text = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' declist = ['nopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm'] dec = Rot13().decipher(text) self.assertEqual(dec...
621
257
from typing import Any from hypothesis import given from lz.functional import identity from tests import strategies @given(strategies.scalars) def test_basic(object_: Any) -> None: result = identity(object_) assert result is object_
246
72
from datetime import datetime, timedelta from discord import Embed from discord.ext.commands import Cog from discord.ext.commands import command import logging class Reactionpolls(Cog): NUMBERS = [ "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] def __init__(self, bot): ...
3,703
1,193
""" Copyright (C) 2020 ETH Zurich. All rights reserved. Author: Sergei Vostrikov, ETH Zurich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LI...
5,975
1,867
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
4,725
2,087
# Copyright (c) 2021 Red Hat, Inc. # # 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 requi...
4,651
1,308
import tensorflow as tf import pathlib import matplotlib.pyplot as plt import pandas as pd import numpy as np #print(np.version.version) #np.set_printoptions(precision=4) dataset=tf.data.Dataset.from_tensor_slices([8,3,0,8,2,1]) num=np.arange(5) numT=tf.convert_to_tensor(num) numF=tf.cast(numT,dtype=tf.float32) print(...
512
218
#LeetCode problem 378: Kth Smallest Element in a Sorted Matrix class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: res=[] for i in range(len(matrix)): for j in range(len(matrix[0])): res.append(matrix[i][j]) return(sorted(res)[k-1])
315
105