text
string
size
int64
token_count
int64
from output.models.sun_data.attr_decl.ad_name.ad_name00110m.ad_name00110m7_xsd.ad_name00110m7 import Root __all__ = [ "Root", ]
133
68
def frequencies(): freqs = {} with open("frequency.txt", "r") as f: for line in f: word, freq = line.strip().split("\t") freq = int(freq) freqs[word] = freq return freqs def matches(word, letter_count): if len(word) != letter_count: return False ...
1,444
540
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. 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 # # ...
1,459
452
# Generated by Django 3.2 on 2021-04-09 14:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0004_rename_summary_text_movie_desc'), ] operations = [ migrations.AlterField( model_name='movie', name='phot...
415
141
"""Definitions for the `DiffusionCSM` class.""" from collections import OrderedDict import numpy as np from scipy.interpolate import interp1d from mosfit.constants import C_CGS, DAY_CGS, M_SUN_CGS, AU_CGS from mosfit.modules.transforms.transform import Transform # Important: Only define one ``Module`` class per fil...
3,485
1,343
""" Preprocess text """ from __future__ import absolute_import, division, print_function, unicode_literals import argparse import codecs import csv import textacy def str2bool(val): """ Helper method to convert string to bool """ if val is None: return False val = val.lower().strip() if...
5,905
1,626
from flask import Flask, render_template, request, url_for, redirect,session from datetime import timedelta from flask_sqlalchemy import SQLAlchemy import os import googlemaps import json app = Flask(__name__) seckey = os.urandom(12) app.secret_key=seckey key = os.environ["googleapikey"] app.permanent_session_lifeti...
5,013
1,602
# encoding: utf-8 """ nodename.py Created by Evelio Vila on 2016-12-01. Copyright (c) 2014-2017 Exa Networks. All rights reserved. """ from exabgp.protocol.ip import IP from exabgp.bgp.message.notification import Notify from exabgp.bgp.message.update.attribute.bgpls.linkstate import LinkState # | 1028 | I...
1,411
523
from timeit import Timer from unittest import TestCase import numpy as np from nptyping import ( Float, NDArray, Shape, ) class PerformanceTest(TestCase): def test_instance_check_performance(self): arr = np.random.randn(42, 42, 3, 5) def _check_inst(): isinstance(arr, N...
641
239
import datetime import typing from enum import ( Enum, auto, ) from dataclasses import dataclass from http import cookies class HttpType(Enum): Http = "http" Https = "https" H2 = "h2" WebSocket = "ws" WebSocketSecure = "wss" @dataclass(frozen=True) class Host: ip: str port: int...
5,185
1,593
################################################################################################### # # Copyright 2020 Otmar Nitsche # # 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 # # htt...
3,596
1,001
import argparse import boto3 import datetime import dateutil import json import logging import signal from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.engine.url import URL import sys import time from ..fetch.calculated import Calculated from ..fetch.overrides import Overrid...
6,250
1,711
#!/usr/bin/python # Copyright (C) 2015 The Android Open Source Project # # 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 req...
1,330
426
from __future__ import annotations import asyncio from abc import ABC, abstractmethod from typing import Any, List, Optional from ..job import Job, TJobId from ..machine import Machine class StateFetcher(ABC): @classmethod @abstractmethod async def create( cls, machine: WebsocketMachine,...
2,609
705
import pickle import typing from dataclasses import dataclass import numpy as np @dataclass class SimilarityMember: """ Represents a member of parliament. Contains their name and a list of the parties they have served with """ name: str parties: list[str] @dataclass class SimilarityResult: ...
6,409
1,828
from rest_framework import exceptions from rest_framework.utils.mediatypes import _MediaType from rest_framework.versioning import AcceptHeaderVersioning class AcceptHeaderVersioningRequired(AcceptHeaderVersioning): def determine_version(self, request, *args, **kwargs): media_type = _MediaType(request.ac...
607
159
# Generated by Django 2.1.7 on 2019-03-29 08:52 from django.db import migrations import django_google_maps.fields class Migration(migrations.Migration): dependencies = [ ('travelling', '0049_auto_20190327_1849'), ] operations = [ migrations.AddField( model_name='trip', ...
503
179
import logging import os import sys from lib.readCfg import ConfigReader ''' Simple Logger utility add this line to py file log = logging.getLogger(__file__) and use the log object by calling log.error("My error message") log.info("My info message") ''' class Logger: def __init__(self): readCfg = ConfigR...
1,445
387
# Author: Shao Zhang, Phil Saltzman # Last Updated: 5/2/2005 # # This tutorial shows how to detect and respond to collisions. It uses solids # create in code and the egg files, how to set up collision masks, a traverser, # and a handler, how to detect collisions, and how to dispatch function based # on the collisions....
15,789
4,666
import gensim import numpy as np from sklearn.base import BaseEstimator, TransformerMixin class WordToVecTransformer(BaseEstimator, TransformerMixin): def __init__(self, size=100): self.size = size self.word2vec = dict() def fit(self, X, y=None): model = gensim.models.Word2Vec(X, size...
626
217
import argparse import time from . import CTFModel, find_ctf def main(): default_amplitude_contrast = 0.07 parser = argparse.ArgumentParser() parser.add_argument("mrc", help="input aligned mrc file") parser.add_argument( "--pixelsize", type=float, help="pixelsize in angstroms", required=True...
1,766
623
"""pytest tests for mytoyota.models.hvac.Hvac""" from mytoyota.models.hvac import Hvac # pylint: disable=no-self-use class TestHvac: """pytest functions to test Hvac""" @staticmethod def _create_example_data(): """Create hvac with predefined data""" return Hvac( { ...
4,033
1,279
import numpy as np # EXTRACTING SOME COLUMNS OR ROWS OF THE 2D ARRAY arr1 = np.arange(36).reshape(6,6) print("THE 2D ARRAY : ",arr1) ex = np.array(arr1) print("EXTRACTION OF THE 4 ROW AND 5 ROW : ", ex[3:5]) # FINDING THE SUM OF THE COLUMNS arr2 = np.array([[1,3,5,6],[3,6,7,3],[2,3,6,6],[4,5,8,5]]) prin...
414
200
# -*- coding: utf-8 -*- import pytest from boussole.exceptions import SettingsInvalidError @pytest.mark.parametrize("paths", [ ( '/home/foo', '/home/bar', ), ( '/home', '/home/bar', '/var/lib', ), ( '/home', '/home/bar', '/home/bar.g...
1,125
383
#!/usr/bin/env python # ==================================== # Copyright (c) Microsoft Corporation. All rights reserved. # ==================================== PY_MAJOR_VERSION = 0 PY_MINOR_VERSION = 2 CONFIGPARSER_KEY = "configparser" QUEUE_KEY = "queue" import sys def install_aliases(): """ Imports the rel...
883
251
from collections import namedtuple import uuid from flask import Flask from flump import FlumpBlueprint, FlumpView, OrmIntegration, Fetcher from flump.validators import Immutable from marshmallow import fields, Schema # Our non-persistent "database" INSTANCES = [] # The "model" we will be storing in our "database" U...
1,917
632
""" Calculate the number of trailing zeroes in a factorial """ """ Solution approaches: > Consider prime factors of n! - 2's and 5's contribute to zeroes. if we count the number of 2's and 5's we can count zeroes. - If we can count the number of 5's we should be done - since number of 2's will always be more ni fac...
416
151
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code...
6,410
2,310
"""Helper class to use with `jupyterlab_code_formatter` Jupyter extension. See README for details""" import logging import black from jupyterlab_code_formatter.formatters import BaseFormatter, handle_line_ending_and_magic from globality_black.reformat_text import reformat_text class GlobalityBlackFormatter(BaseFor...
1,267
386
from app.role.models.role import Role from app.role.repositories.role_repository import RoleRepository def test_update(session): """ Test the role repository update function. """ # Arrange test_model = RoleRepository.create(Role(name='Super User')) test_model_id = test_model.id update_fiel...
2,530
811
""" Copyright (c) Facebook, Inc. and its affiliates. """ import csv import argparse import json from collections import defaultdict, Counter import re from ttad_annotate import MAX_WORDS def process_result(full_d): worker_id = full_d["WorkerId"] d = with_prefix(full_d, "Answer.root.") try: acti...
7,661
2,372
''' 重新封装的控件 ''' import os from PyQt5.QtCore import Qt, pyqtSignal, QTimer, QSize from PyQt5.QtGui import QTextDocument, QAbstractTextDocumentLayout, QPalette, QFontMetrics, QIcon from PyQt5.QtWidgets import (QApplication, QAbstractItemView, QStyle, QListView, QLineEdit, QTableView, QPushBu...
9,110
2,757
""" Membership inference attack based on https://github.com/privacytrustlab/ml_privacy_meter/blob/master/ml_privacy_meter/attack/meminf.py """ import datetime from itertools import zip_longest import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.funct...
30,355
9,755
from fastapi import Depends, HTTPException from starlette.requests import Request from starlette.responses import RedirectResponse from starlette.status import HTTP_303_SEE_OTHER, HTTP_404_NOT_FOUND from examples.models import Config from fastapi_admin.app import app from fastapi_admin.depends import get_resources fro...
1,183
351
# # Solution to Project Euler problem 15 # Copyright (c) Project Nayuki. All rights reserved. # # https://www.nayuki.io/page/project-euler-solutions # https://github.com/nayuki/Project-Euler-solutions # import eulerlib # This is a classic combinatorics problem. To get from the top left corner to the bottom right ...
670
210
# nlantau, 2022-01-01 from collections import deque def breadth_depth_print(graph, source): queue = deque([source]) while queue: curr = queue.popleft() print(curr) for neighbor in graph[curr]: queue.append(neighbor) g = { 'a' : ['b', 'c'], 'b' : ['d'], 'c' :...
435
177
from .basemodel import BaseModel from .dqncnn import DQNCNN from .evolutionary import EvolutionaryAI
100
32
#!/bin/python2.7 # # Copyright (c) 2013 University of Pennsylvania # # 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...
8,360
2,687
# Copyright (c) 2021 DataArk 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 applicable...
3,660
1,217
# # for-nested.py # Use nested for to display numbers in Python 3.7 # # Sparisoma Viridi | https://github.com/dudung # # Execute: python3.7 for.py # # 20210122 # 0933 Create this example, test it, and it works. # for i in range(1, 5): for j in range(1, 4): print(i, j)
278
129
'''Support functions for implementing keyword-only arguments. This module is designed to make it easy to support keyword-only arguments in Python 2.7 while providing the same kind of exceptions one would see with Python 3.x. Basic usage: .. code-block:: python def foo(arg1, *args, **kwargs): # Use requi...
1,463
404
import os import pytest from pathlib import Path from pyomrx.core.form_maker import FormMaker from pyomrx.core.omr_factory import OmrFactory import pandas as pd from pyomrx.utils.test_utils import * def test_attendance_register_example(request, res_folder): attendance_example_folder = Path('examples/attendance_re...
2,509
823
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with ...
13,871
4,033
from getratings.models.ratings import Ratings class NA_Poppy_Jng_Aatrox(Ratings): pass class NA_Poppy_Jng_Ahri(Ratings): pass class NA_Poppy_Jng_Akali(Ratings): pass class NA_Poppy_Jng_Alistar(Ratings): pass class NA_Poppy_Jng_Amumu(Ratings): pass class NA_Poppy_Jng_Anivia(Ratings): pass ...
6,407
3,595
"""A simple main file to showcase the template.""" '''Modulo por defecto para poner linea de comandos es argparse''' import logging.config import argparse import os import time import sys import tensorflow as tf from tensorflow.keras import datasets from tensorflow.keras import models from tensorflow.keras import laye...
5,910
1,993
# encoding="utf-8" from sqlalchemy import Integer, String from sqlalchemy import Column, create_engine, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Stri...
6,188
1,762
#!/usr/bin/env python3 class Node: def __init__(self, data): self.data = data self.next = None class Solution: def display(self, head): current = head while current: print(current.data, end=' ') current = current.next def insert(self, head, data): ...
716
212
#!/usr/bin/env python # T e x S c a n n e r . p y # # Defines a TexScanner class that can be used to extract LaTeX directives # from a .tex file. Call SetFile() to supply a reference to an already # open .tex file, then use successive calls to GetNextTexCommand() to get # all the tex directive...
19,636
5,218
import os from discord.ext import commands perceus = commands.Bot(command_prefix = '$', description = 'A demo Discord Chat Bot built using Discord.py') perceus.remove_command('help') token = '' for cog in os.listdir('./cogs'): if cog.endswith('.py') and not cog.startswith('_'): perceus.load_extension(f'co...
446
166
"""! This code is for the simulation of relays. """ import atexit class Relay(): """! This is the class for all relay devices @param pin: The RPi pin that acts as the signal pin to the relay @param name: The name of the relay. @param is_off: The current state of the relay """ pin: int ...
1,231
384
from pyshex.shex_evaluator import ShExEvaluator from pyshex.user_agent import SlurpyGraphWithAgent from pyshex.utils.sparql_query import SPARQLQuery # SPARQL Endpoint endpoint = 'http://wifo5-04.informatik.uni-mannheim.de/drugbank/sparql' # SPARQL Query sparql = """ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-synta...
1,386
513
# Copyright 2018 Databricks, Inc. VERSION = '0.5.2.dev0'
59
32
# -*- coding: utf-8 -*- from __future__ import unicode_literals import csv import pandas as pd def export_csv(head=[], datalist=[], filename='export_csv.csv', delimitator=';'): c = csv.writer(open(filename, "wb")) c.writerow(head) for data in datalist: c.writerow(data.__str__().split(delimitator)...
16,641
5,504
import codecs import os.path from setuptools import setup, find_packages def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), 'r') as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlines(): if...
795
262
from abc import ABCMeta, abstractmethod from .exceptions import EntitasException class AbstractEntityIndex(metaclass=ABCMeta): def __init__(self, comp_type, group, *fields): self.type = comp_type self._group = group self._fields = fields self._index = {} self._activate() ...
2,231
663
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import mock import pickle import re from google.appengine.ext import testbed import webapp2 import webtest from testing_utils import testing from handlers...
1,358
430
# -*- coding: utf-8 -*- import pytest from pynetworking.Device import Device ats_supported_sw_version = '3.0.0.44' ats_supported_boot_version = '1.0.1.07' ats_basic_supported_model = 'AT-8000S' ats_supported_model = [ats_basic_supported_model + '/' + '24', ats_basic_supported_model + '/' + '48'] ats_model_port_number...
35,418
13,533
#!/usr/bin/env python ''' Copyright (c) 2019, Robot Control and Pattern Recognition Group, Warsaw University of Technology 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...
2,809
957
import torch from torch.autograd import Variable from torch.autograd import Function import torch.nn as nn import torch.nn.functional as F import numpy as np from abc import ABCMeta, abstractmethod from torchvision import datasets, transforms from torch.utils.data import DataLoader from tqdm import tqdm import os from ...
4,146
1,452
# -*- coding: utf-8 -*- # Copyright (c) 2016-present, CloudZero, Inc. All rights reserved. # Licensed under the BSD-style license. See LICENSE file in the project root for full license information. from datetime import datetime from decimal import Decimal from enum import Enum import simplejson as json def markdown...
1,012
311
n = int(input()) ar = [int(ar_temp) for ar_temp in input().strip().split(' ')] for i in range(n): temp = ar[i] j = i while j > 0 and ar[j-1] > temp: ar[j] = ar[j-1] j -= 1 ar[j] = temp if i > 0: for k in ar: print (k, end=' ') print () ...
325
138
"""Test TeamCity (PyCharm) integration.""" # pylint: disable=missing-docstring,no-self-use import unittest from teamcity.unittestpy import TeamcityTestRunner from tests.features import FlexmockTestCase class TestTeamCityTeardown(FlexmockTestCase, unittest.TestCase): """Test flexmock teardown works with TeamCity...
447
141
from django.contrib.auth import authenticate from django.core.validators import RegexValidator, URLValidator from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User, PasswordResetToken from authors.apps.profiles.serializers import ProfileSerializer class ...
11,807
2,945
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: graph.py # Author: Yuxin Wu <ppwwyyxxc@gmail.com> """ Graph related callbacks""" from .base import Triggerable __all__ = ['RunOp'] class RunOp(Triggerable): """ Run an Op. """ def __init__(self, setup_func, run_before=True, run_epoch=True): """...
1,079
356
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy application = Flask(__name__) application.config.from_object('config') db = SQLAlchemy(application)
169
53
#!/usr/bin/python from datetime import datetime import os import shutil, sys from os.path import join import json i = 0 configs_dir = '/poracle-experiments/extra_configs/' for subroot, dirs, files in os.walk(configs_dir): # run('{}/cleanup'.format(root_dir)) for config_file in files: read_file = open(j...
1,152
390
import datetime from unittest.mock import patch, MagicMock import pytest from covid_world_scraper.utils import relative_year DEC_31 = datetime.datetime(2020, 12, 31, 12, 59, 1) JAN_1 = datetime.datetime(2020, 1, 1, 1, 1, 1) @pytest.mark.parametrize( 'month,day,current_day,expected', [ [12, 31, DEC...
674
284
from PySimpleGUI import PySimpleGUI as sg from sys import exit sg.theme('DarkGray14') # sg.theme_previewer() def layout(): layout = [ [sg.Text('Recomeçar:'), sg.Radio('Sim', 'recomecar', key='rSim', default=True, enable_events=True), sg.Radio('Não', 'recomecar', key='rNao', enable_events...
3,227
1,104
import pytest from common.statuses import ResponseStatus from modules.providers.exceptions import SourceFetchError from modules.podcast import tasks from modules.podcast.models import Episode, Podcast from modules.podcast.tasks import DownloadEpisodeTask from tests.api.test_base import BaseTestAPIView from tests.helpe...
13,706
4,553
from __future__ import division, print_function, absolute_import import numpy as np class EvaporatorCondenser(object): """ Object for heat exchanger based on epsilon-NTU method for a heat transfer fluid exchanging heat with refrigerant experiencing constant temperature phase change. :par...
3,928
1,190
from flask import ( abort, render_template, request, jsonify, stream_with_context, ) from .models import Inscription, db from .forms import FormPremiereEtape, FormDeuxiemeEtape from ecosante.utils.decorators import ( admin_capability_url, webhook_capability_url ) from ecosante.utils import B...
4,806
1,540
#!/usr/bin/python3 # This file is part of becalm-station # https://github.com/idatis-org/becalm-station # Copyright: Copyright (C) 2020 Enrique Melero <enrique.melero@gmail.com> # License: Apache License Version 2.0, January 2004 # The full text of the Apache License is available here # http://w...
2,455
813
from pytest import approx from easyvec import Vec2, intersect, closest, Mat2 import numpy as np from easyvec.geometry import _sortreduce, Rect, PolyLine, is_in_polygon # TODO add test for arcs def test_polyline_is_selfintersect1(): pl = PolyLine([(0,3), (10,3), (10,0), (0,0)], copy_data=True) assert not pl.i...
9,404
4,214
# -*- encoding: utf-8 -*- # Multi-scales HSD implementataion import numpy as np import networkx as nx import pygsp import multiprocessing from collections import defaultdict from tqdm import tqdm from model import HSD from tools import hierarchy class MultiHSD(HSD): def __init__(self, graph: nx.Graph, graphNam...
2,468
786
__author__ = 'Milos Prchlik' __copyright__ = 'Copyright 2010 - 2014, Milos Prchlik' __contact__ = 'happz@happz.cz' __license__ = 'http://www.php-suit.com/dpl' import collections import threading from collections import OrderedDict import hlib.api import hlib.events import hlib.input import hlib.error import games i...
10,433
3,780
from game_manager import GameManager from braindead_player import BraindeadPlayer from max.random_player import RandomPlayer from max2.training_player import TrainingPlayer import max2.model import sys import trueskill import random import itertools import math import concurrent.futures import threading from os.path im...
6,474
2,086
""" This module shows you how to perform various kinds of density calculations. """ # Does some sys.path manipulation so we can run examples in-place. # noinspection PyUnresolvedReferences import example_config from colormath.color_objects import SpectralColor from colormath.density_standards import ANSI_STA...
2,275
1,031
""" Copyright 2016 Basho Technologies, Inc. This file is provided to you 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 agre...
1,858
599
import os import requests import zipfile data_dir = os.path.dirname(__file__) source_dir = os.path.join(data_dir, 'source') if not os.path.exists(source_dir): os.mkdir(source_dir) rds_url = r'http://maps.vcgi.vermont.gov/gisdata/vcgi/packaged_zips/EmergencyE911_RDS.zip' town_boundary_url = r'http://maps.vcgi.vermo...
1,310
505
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== import os.path from environment_generator import tmp_context from environment_generator import tmp_context_name from environment_generator import generat...
976
293
""" @author Corentin Goetghebeur (github.com/CorentinGoet) """ from AST.node import Node class Block(Node): """ Class representation for the Block node. The Block node has the following syntax: Block = {Statements} """ def __init__(self, statements: list = None): """ Constr...
576
168
# # PySNMP MIB module CISCO-VOICE-IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-IF-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
9,195
4,075
import pysam import vcf from vcf.parser import _Info as VcfInfo, field_counts as vcf_field_counts import math CHR = 22 chr_to_num = lambda x: ''.join([c for c in x if c.isdigit()]) purity = 0.6 # Open files normalSample = pysam.AlignmentFile("../../data/external/HG002.hs37d5.300x.bam", "rb", ignore_truncation=True) t...
4,812
2,155
from lingua.extractors import Extractor, Message from c2c.template.config import config as configuration class GetItFixedExtractor(Extractor): # pragma: no cover """ GetItFixed extractor (settings: emails subjects and bodys) """ extensions = [".yaml"] def __call__(self, filename, options): ...
1,229
345
import os import torch def save_state(model, optim, lr_scheduler, kl_scheduler, epoch, train_dir, param_w_scheduler, epoch_i): """Save the state dict of the current training to disk Parameters ---------- train_loss : float current training loss val_loss : float curre...
1,577
507
from pfin.account import Account from moneyed import Money, EUR, USD import pytest def test_emptyaccount(): a = Account('Giro', 'EUR') assert a.name == 'Giro' assert a.currency == EUR assert a.balance == Money(0, EUR) def test_nonemptyaccount(): u = Account('my Depot', USD, 15.22) assert u.c...
489
187
import os import re import h5py import numpy as np class FeatureFile: def __init__(self, feature_file, write=False): self.feature_file = feature_file self.h5 = self.open(feature_file, write) self.features_keys = None self.labels_keys = None self.perm = None def open(...
2,306
759
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
8,162
2,796
# -*- coding:utf-8 -*- from core import UserAgent testing_data = { 'user_agent': { 'family': 'Chrome', 'major': '60', 'minor': '0', 'patch': '3112' }, 'os': { 'family': 'Windows', 'major': '10', 'minor': None, 'patch': None, 'patch_min...
856
390
""" 23 / 23 test cases passed. Runtime: 48 ms Memory Usage: 22.3 MB """ class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: store = {} for i, num in enumerate(nums): if num in store and i - store[num] <= k: return True store[num...
347
115
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
5,714
2,205
r""" **openpnm.models** ---- This module contains a selection of pore-scale models for calculating geometrical, thermophysical, and multiphysics transport properties. ---- **Using Prewritten Models from the Library** OpenPNM includes a solid library of pre-written models for most basic and standard scenarios. Th...
3,323
1,252
from __future__ import print_function import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) import keras from keras.preprocessing.image import ImageDataGenerator from keras.models import Model from keras.layers import Dense, Flatten, Conv2D, Permu...
2,247
813
#coding=utf-8 ''' infer module ''' import sys caffe_path = '../caffe/python/' #caffe_path = '/root/caffe/python/' sys.path.insert(0, caffe_path) import caffe caffe.set_device(0) caffe.set_mode_gpu() from caffe.proto import caffe_pb2 from google.protobuf import text_format import numpy as np #import cv2 ''' prepare c...
2,346
934
""" Copyright 2011 Lars Kruse <devel@sumpfralle.de> This file is part of PyCAM. PyCAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PyCA...
44,852
14,045
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Thomas Tannhaeuser <hecke@naberius.de> # This program is published under a GPLv2 license # # scapy.contrib.description = IEC-60870-5-104 APCI / APDU layer definitions # scapy.contrib.status = loads """ IEC ...
20,864
8,835
from django.contrib import admin from .models import Patient, Doctor, UserInfo,Admin_Users # Register your models here. admin.site.register(UserInfo) admin.site.register(Patient) admin.site.register(Doctor) admin.site.register(Admin_Users)
241
73
from pepper2like.type_check import type_check from pepper2like.log import Log from pepper2like.string import String from pepper2like.callable import Callable def pl_test(log, name, fn): type_check(Log, log) type_check(String, name) type_check(Callable, fn) log.part_line.info(name + " ... ") fn() ...
474
171
# from .Base_Action import * # # from .BuildAction import * # from .TestAction import * # from .LaunchAction import * # from .ProfileAction import * # from .AnalyzeAction import * # from .ArchiveAction import * # # from .BuildActionEntry import * # from .BuildableReference import * # from .BuildableProductRunnable impo...
830
211
import requests, os token = "" DMGroup_id = "" DMGroup_name = "" group = requests.patch(f'https://discord.com/api/v9/channels/{DMGroup_id}', headers={"authorization": token}, json={"name": DMGroup_name}) if group.status_code == 200: print("Successfully changed the group name!") else: print(f"Failed to cha...
367
132