text
string
size
int64
token_count
int64
import os import pickle import numpy as np import re from string import ascii_letters from datetime import datetime import argparse import gzip def collect_datasets_is(folder = [], model = [], ndata = [], nsubsample = []): # Load in param...
6,840
2,339
from datetime import date from django.contrib.auth import get_user_model from django.test import Client from oauth2_provider.models import get_application_model, get_access_token_model from apps.accounts.models import UserProfile from .base import BaseTestCase User = get_user_model() Application = get_application_mode...
9,239
2,718
class VanishingDateMixIn(): """The VanishingMixIn is used to register Signals for deletion events, so all registered VanishingDateTime will be deleted. Inherit it in every class/Model where VanishingDateTime is used. Otherwise the VanishingDateTime-Instances are not registered and therefore not de...
478
123
from urllib.parse import urlencode from flask import ( Blueprint, make_response, current_app, url_for, request, redirect, render_template, session) import requests import globus_sdk # This is mostly copy-and-paste from # https://globus-sdk-python.readthedocs.io/en/stable/examples/three_legged_oauth/ bluepr...
5,094
1,566
import os import numpy as np import matplotlib.pyplot as plt import xarray from hparams import Hparams hparams = Hparams() parser = hparams.parser hp = parser.parse_args() dic = [ [f'{hp.observe_dataset_dir}/meta-data/sst.mnmean.nc', f'{hp.observe_dataset_dir}/interp-data/sst.nc', 'sst', 'lat'], [f'{hp.observ...
5,208
2,732
# All Rights Reserved 2020 # # 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 t...
8,283
2,671
from auth.pwdLine import PwdLine from auth.userLine import UserLine from auth.enabler import Enabler from tkinter import Tk class Auth: ul: UserLine pl: PwdLine en: Enabler def __init__(self, tk: Tk, row: int, col: int, w: int): self.ul = UserLine("disabled", tk, row+1, col, w) self.p...
600
213
from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f: readme = f.read() setup( name="w3cpull", version="1.1.1", author="Mikalai Lisitsa", author_email="Mikalai.Lisitsa@ibm.com", url="https://github.com/soulless-viewer/w3cpull", description="w3cpull is a...
782
291
# Copyright 2016 Google 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 agreed to in writing, ...
2,341
689
# print copyright restrictions: 0 = not restricted, 1 = in copyright # that said, several pieces (particularly in Contemporary Art collection) # do have copyright notices on them even if copyright restrictions == 0 # sorting by "rights_type": "name" might be more clarifying, but the number of # But I'd argue this use ...
567
162
from nltk import Tree from parseq.grammar import tree_to_lisp_tokens def reorder_tree(x:Tree, orderless=None, typestr="arg:~type"): """ Reorders given tree 'x' such that if a parent label is in 'orderless', the order of the children is always as follows: - arg:~type goes first - other children are or...
1,243
398
"""This program will open a connection to a server you choose from a list, or specify a name not on the list. Build a text file named servers.txt and save it in the same directory this program is ran from. Please make sure not to have any extra spaces before or at the end of the name of the servers. One name per li...
3,887
1,220
# coding: utf-8 import collections import random import time import urllib import urlparse from urlencoding import escape, parse_qs, compose_qs OAUTH_VERSION = '1.0' TIMESTAMP_THRESHOLD = 300 NONCE_LENGTH = 10 class OAuthError(RuntimeError): """ Generic OAuthError for all error cases. """ pass clas...
10,069
2,753
#!/usr/bin/env python # coding: utf-8 # In[1]: from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense,Flatten, Dropout,BatchNormalization, GlobalAveragePooling2D, ZeroPadding2D from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array fr...
5,244
2,192
# Copyright (c) 2011 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. from master.chromium_git_poller_bb8 import ChromiumGitPoller def Update(config, active_master, c): syzygy_poller = ChromiumGitPoller( repourl='...
448
160
"""Tests for `salt_user` package.""" def test_content(): """Bogus test.""" assert True is False
107
38
# Generated by Django 3.2.3 on 2021-11-11 22:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('admin_panel', '0004_stripesubscription'), ('grocers_panel', '0001_initial'), ] operations = [ migra...
557
194
from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("MinTemperatures") sc = SparkContext(conf = conf) def parseLine(line): fields = line.split(',') stationID = fields[0] entryType = fields[2] temperature = float(fields[3]) * 0.1 * (9.0 / 5.0) + 32.0 return ...
861
314
#! /usr/bin/env python3 import irc.bot import irc.strings from irc.client import ip_numstr_to_quad, ip_quad_to_numstr import paho.mqtt.client as mqtt class ListenerBot(irc.bot.SingleServerIRCBot): def __init__(self, irc_channel, irc_nickname, irc_server, irc_port): irc.bot.SingleServerIRCBot.__init__(sel...
2,062
755
""" isort:skip_file """ from concurrent.futures import ThreadPoolExecutor from requests_futures.sessions import FuturesSession from polyswarmd.monkey import patch_all patch_all() import datetime import functools import logging from flask import Flask, g, request from flask_caching import Cache from polyswarmd.c...
6,122
2,002
#!/bin/env python ''' PURPOSE: THIS SCRIPT IMPORTS ALL THE OPERATING SYSTEMS INFORMATION FROM AWS EC2 API, PRINTS THE OUTPUT TO A CSV AND THEN IMPORTS THE CSV INTO FIREPOWER MANAGEMENT CENTER USING THE HOST INPUT API OF FMC. DEPENDENCIES / REQUIREMENTS: 1- PYTHON 3.6 2- PERL 5 3- ACCOUNT ON AWS CLOUD AN API KEY G...
9,702
3,194
import operator from functools import partial from utilitiespackage.yunobuiltin import ( get, gensym, isa, interleave, is_even, is_iterable, new_list, new_iter, new_tuple, juxt, flatten, is_str_or_bytes, identity, is_map, is_seq, append...
7,703
3,694
#!/usr/bin/env python """ 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");...
2,394
836
# 2017数据补齐 # 根据SPE文件和RPT文件生成导入SQL import os import time def parse_spe(filename): f = open(filename) line = f.readline() while line: if line.startswith('$DATE_MEA:'): begin_time_line = f.readline() begin_time = time.strptime(begin_time_line.strip(), '%m/%d/%Y %H:%M:%S') ...
2,364
877
from django.shortcuts import render from . models import Location, Image, categories def get_images(request): images = Image.get_all_images() locations = Location.objects.all() context = { "images":images, "locations":locations } return render(request, 'images.html', context) def get_loc...
1,200
336
#something new var="BOB was here!!!!" #have to change something else print("\n\nDave what are you doing????\n\n\n") #New branch master added
142
49
""" Unit tests for mpc """ import logging import os import unittest import astropy.units as u import numpy from astropy.coordinates import SkyCoord from rascil.data_models.parameters import rascil_path, rascil_data_path from rascil.data_models.polarisation import PolarisationFrame from rascil.processing_components i...
9,103
2,733
load("@//tools:build_rules/go.bzl", "go_library") standard_proto_path = "third_party/proto/src/" def go_package_name(go_prefix, label): return "%s%s/%s" % (go_prefix.go_prefix, label.package, label.name) def _genproto_impl(ctx): proto_src_deps = [src.proto_src for src in ctx.attr.deps] inputs, outputs, argumen...
6,822
2,399
#! /usr/bin/env python ################################### # Test NchooseK on a two-region # # map-coloring problem # # # # By Scott Pakin <pakin@lanl.gov> # ################################### import nchoosek # Define a type for "exactly one color". env = nchoosek.Enviro...
1,128
392
import copy from typing import Dict, List, Optional, Set, Union from unittest.mock import Mock from uuid import uuid4 class File: """ Mock File class representing a GoogleDrive File with basic information file_id, name, parents (list of parent ids), mimeType """ def __init__( self, ...
7,902
2,404
"""Definitions related to the `Entry` class for catalog entries.""" import codecs import gzip as gz import hashlib import json import logging import os import sys from collections import OrderedDict from copy import deepcopy from decimal import Decimal from astrocats.catalog.catdict import CatDict, CatDictError from a...
43,854
12,535
import socket size = 8192 try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for i in range(0,51): msg = bytes(str(i), encoding="utf-8") sock.sendto(msg, ('127.0.0.1', 9876)) print(str(sock.recv(size),encoding='utf-8')) sock.close() except: print("cannot reach the server")
309
139
"""[General Configuration Params] """ from os import environ, path from dotenv import load_dotenv basedir = path.abspath(path.dirname(__file__)) load_dotenv(path.join(basedir, '.env'))
186
62
''' get-google-calendars.py This script will obtain the `token.json` required for getting your google calendar appointments on the info display. It will also give you the ID's of your calendars, which you can choose to include in your config.ini Run this on your local desktop! Install the following pa...
3,096
875
from bcrypt import gensalt, hashpw from flask_login import UserMixin from sqlalchemy import Binary, Column, Integer, String, Float from app import db, login_manager class Pharmacy(db.Model): __table__name = 'Pharmacy' id = Column(Integer, primary_key=True) title = Column(String) dosage = Column(Strin...
3,910
1,141
import os import pathlib curr_path = pathlib.Path(__file__).parent.absolute() def boot(dashjl, filename): fp = os.path.join(curr_path, "jl_update_title", filename) dashjl.start_server(fp) dashjl.wait_for_text_to_equal( "#hello-div", "Hello world!" ) def get_update_title_state(dashjl...
855
325
from .neobaseextractor import NeoBaseRecordingExtractor, NeoBaseSortingExtractor from pathlib import Path from typing import Union, Optional try: import neo HAVE_NEO = True except ImportError: HAVE_NEO = False PathType = Union[str, Path] class BlackrockRecordingExtractor(NeoBaseRecordingExtractor): ...
1,667
502
from infi.unittest import TestCase from infi.instruct.buffer.reference import (Context, GetAttrReference, FuncCallReference, ObjectReference, CyclicReferenceError) class NumberHolder: def __init__(self, n): self.n = n self.k = 10 class ReferenceTestCas...
2,220
721
import numpy as np import sys import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser( description="terminal view a numpy file or image as np array") parser.add_argument("data", help=".npy file to be viewed or im.") parser.add_argument("--img", action='store_true', help="if an image.") arg...
619
193
"""Initialize app.""" from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import Config import logging # Database variable db = SQLAlchemy() def create_app(): # Construct the core application app = Flask(__name__, instance_relative_config=False) # Apply the configuration app.c...
1,042
295
import jsonpickle as jsonpickle import pytest from fixture.application import Application import json import os.path import importlib import ftputil fixture=None target=None def load_config(file): global target if target is None: config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), f...
3,002
950
""" A coroutine implementation in Python. Convert functions to iterator generators by replacing return <expression> with yield <expression> and function calls: f(*args, **kw) with for loops: for i in f(*args, **kw): pass # the function value is in i now. Unfortunately, you have to know which routine has been ...
7,160
2,236
from mlaut.shared.static_variables import GRIDSEARCH_NUM_CV_FOLDS, GRIDSEARCH_CV_NUM_PARALLEL_JOBS from mlaut.shared.static_variables import VERBOSE from tensorflow.python.keras.models import Sequential, load_model, model_from_json from tensorflow.python.keras.layers import Dense, Activation, Dropout from tensorflow.p...
5,667
1,800
#!/usr/bin/env python import io import re import logging import pathlib # Own modules from rtfparse import re_patterns from rtfparse import entities from rtfparse import utils # Typing from typing import Optional from typing import Union from rtfparse import config_loader # Setup logging logger = logging.getLogger(...
3,130
908
import FWCore.ParameterSet.Config as cms process = cms.Process("MyAnalyzer") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( "file:/home/jonas/PhD/022E2036-A2D9-E711-9A8C-0CC47A13D2A4.root" ) ) process.analyzer = cms.EDAnalyzer('MyAnalyzer') process.p = cms.Path(process....
330
149
#!/usr/bin/env python # -*- coding: utf-8 -*- from textblob.classifiers import NaiveBayesClassifier with open('data/train.csv', 'r') as fp: cl = NaiveBayesClassifier(fp, format="json")
190
73
# Methods for dealing with Matrices. Don't use these. Just use the numpy functions. def get_random_matrix(size = [5, 5], value_range = [-10, 10], type_of_value = int): """ A function which can generate many different types of random matrixes of whatever dimension is desired. """ if len(size)>1: ...
4,513
1,499
import stepper import sys if (len(sys.argv) != 2): print("missing parameter: 0|1"); sys.exit(); value = int(sys.argv[1]) stepper.setLock(0) stepper.setPower(value) if (value > 0): print("power on") else: print("power off")
233
99
import pytest from v1.views.results import RESULTS_URL @pytest.fixture def results_requests_mock(requests_mock, resource_factory): resource = resource_factory("results.html") requests_mock.post(RESULTS_URL, text=resource.read())
240
78
from mkdocs.structure.files import get_files def test_urls_no_use_directory_urls(config_base, config_plugin): config_base["use_directory_urls"] = False files = get_files(config_base) # config_plugin["use_directory_urls"] = False i18n_plugin = config_plugin["plugins"]["i18n"] # i18n_plugin....
1,549
536
import enum from dataclasses import dataclass from datetime import datetime from logging import getLogger from typing import Tuple from ..protocol import ( AUTH_VERSION, Command, MismatchError, NONCE_LENGTH, PROTOCOL_VERSION, Packet, TLV, check_result, create_bonding_key, decode...
10,880
3,433
# Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
1,023
349
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Description : The base class of Unit test @Time :2020/08/27 15:35:05 @Author :sam.qi @Version :1.0 ''' import unittest class BaseTest(unittest.TestCase): pass
246
97
# -*- coding: utf-8 -*- # This file is part of the OpenSYMORO project. Please see # https://github.com/symoro/symoro/blob/master/LICENCE for the licence. """ This module of SYMORO package contains function to compute the base inertial parameters. """ import sympy from sympy import Matrix from pysymoro.geometry i...
8,742
3,707
from cython.cimports.strstr import strstr def main(): data: cython.p_char = "hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh" pos = strstr(needle='akd', haystack=data) print(pos is not cython.NULL)
204
88
# Copyright (C) 2021, Pyronear contributors. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. """ The following file is dedicated to the "Risk Score" view of the dashboard. Following a first section dedic...
7,543
2,014
from fastapi import APIRouter, Depends from lws_backend.api.dependencies.authorization import check_user_auth router = APIRouter() @router.get("/user-access") async def user_access(user_auth=Depends(check_user_auth)): exception = user_auth[1] if exception: raise exception return user_auth[0]
318
99
import logging import flask import bhamon_orchestra_website.helpers as helpers import bhamon_orchestra_website.service_client as service_client logger = logging.getLogger("JobController") def show_collection(project_identifier): item_total = service_client.get("/project/{project_identifier}/job_count".format(**l...
3,219
989
# -*- coding: utf-8 -*- import sys import boto3 from botocore.exceptions import ClientError import json from datetime import datetime CUSTOMER_FILE_NAME = "customer_assessment.yandeh.config.json" SERVICES_FILE_NAME = "services.config.json" def get_customer_config(): customer_file = open(CUSTOMER_FILE...
10,751
3,508
''' Marker definition used to generate markers in bokeh using matplotlib notation ''' _mrk_fncs = { # '.' m00 point '.': ('dot', ['color'], {'size': 2}, {}), # ',' m01 pixel ',': ('dot', ['color'], {'size': 3}, {}), # 'o' m02 circle 'o': ('circle', ['color', 'size'], {}, {'size': -3}), # 'v...
4,678
1,925
from datetime import datetime, timedelta import os from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator) from helpers import SqlQueries # AWS_KEY = ...
3,351
1,164
# coding: utf8 from __future__ import unicode_literals, print_function, division from clldutils.dsv import UnicodeReader from clldutils.misc import slug from pylexibank.util import xls2csv from pylexibank.lingpy_util import iter_alignments, segmentize from pylexibank.dataset import CldfDataset def download(dataset)...
3,468
1,012
# Utility macros for Twister2 core files def twister2_core_files(): return twister2_core_conf_files() + twister2_core_lib_files() def twister2_core_conf_files(): return [ "//twister2/config/src/yaml:config-system-yaml", ] def twister2_core_lib_files(): return twister2_core_lib_resource_schedu...
2,891
1,062
import asyncio from aiochannels import Channel, aenumerate async def simple_pinger(ch): sender = await ch.new_sender() while sender.is_attached: # sender can be detached from Channel with `sender.detach` await sender.send('ping') async def simple_ponger(ch): sender = await ch.new_sender(...
3,051
959
from django.urls import path from itembase.core.views.item_views import UOMCreateView, UOMDeleteView, UOMDetailView, \ UOMListView, UOMUpdateView, VendorItemCreateView, VendorItemDeleteView, VendorItemDetailView, \ VendorItemListView, VendorItemUpdateView app_name = "vendor-items" urlpatterns = [ path("uo...
1,004
369
# coding: utf-8 """ BombBomb We make it easy to build relationships using simple videos. # noqa: E501 OpenAPI spec version: 2.0.831 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from bombbomb.models.curriculum_user_prog...
8,853
2,858
#!/usr/bin/env python3 """ Runs the test suite and prints the results to standard output. It uses the given separator in the following way: <Separator> #Tests <Separator> #Succeeded Tests <Separator> First Error <Separator> First Failure <Separator> """ import sys import traceback import unittest def main(): sep...
1,472
460
# code to visualize from dqn import DQN from torch import load from run import collect_trajectories import argparse import gym def main(): parser = argparse.ArgumentParser(description="to visualize trained model") parser.add_argument("model_name", help="path to model to visualize", type=str) # parser.add...
721
239
from __future__ import unicode_literals from django.conf.urls import include, patterns, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^$', 'base.views.index', name='index'), url(r'^i18n/', ...
1,135
392
from ansible_host import AnsibleHost import pytest import ptf.testutils as testutils import time import itertools import logging import pprint DEFAULT_FDB_ETHERNET_TYPE = 0x1234 DUMMY_MAC_PREFIX = "02:11:22:33" DUMMY_MAC_COUNT = 10 FDB_POPULATE_SLEEP_TIMEOUT = 2 logger = logging.getLogger(__name__) def send_eth(p...
5,433
1,894
import subprocess command='python ‪G:\Pycharm_Project\PyTest\guest\manage.py runserver' subprocess.Popen(command,shell=True)
125
47
from flask import request from rpc.gen.system.backup.services import TSystemBackupService from rpc.gen.user.user.types.ttypes import TUserRole from rpc.gen.system.backup.structs.ttypes import TBackupFile import db from models import models class TSystemBackupServiceHandler(TSystemBackupService.Iface): def __init...
1,677
556
# adso_odata_to_neo4j.py # from francois.belleau@saaq.gouv.qc.ca # create ADSO nodes in NEO4J using a CDS VIEW exposed as OData service from neo4j import GraphDatabase #pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org neo4j driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j",...
4,916
1,905
import re def clean_uri(uri): """ This method removes the url part of the URI in order to obtain just the property or class :param uri: An uri to be cleaned :return: The name of the property or the class """ if uri.find('#') != -1: special_char = '#' else: special_char =...
3,372
905
class MLClusterBase(object): def __init__(self): pass def create_cluster(self, spec, cluster_management, namespace_name, volume_claim_name, **kwargs): pass def get_cluster_info(self,cluster_name,cluster_management,user_id): pass def delete_cluster(self,payload): ...
330
106
"""homelabmgr URL Configuration """ from django.contrib import admin from django.urls import path from resources import views urlpatterns = [ path('admin/', admin.site.urls), path('terraform/', views.terraform, name='terraform'), ]
241
72
import time from pyglet.gl import * from pyglet import image from pyglet.window import key import globals import helpers class TextScreen(object): def __init__(self, txt): self.text = txt self.state = 0 self.startTime = 0.0 def draw(self, ww): label = pyglet.text.HTMLLabel(se...
1,008
303
#!/usr/bin/env python """ Example of using the hierarchical classifier to classify (a subset of) the digits data set. Demonstrated some of the capabilities, e.g using a Pipeline as the base estimator, defining a non-trivial class hierarchy, etc. """ from sklearn import svm from sklearn.decomposition import TruncatedS...
2,490
811
EMAIL_RECIPIENTS = { # "Ema": "ema_pra@hotmail.com", "Matías": "cardenasmatias.1990@gmail.com", # "David": "k1.dave@gmail.com", # "Fede": "fede_pra@hotmail.com", # "Fede": "fpradomacat@gmail.com", # "David": "departamentosvillasuiza@gmail.com" } # GMAIL SMTP_SERVER = "smtp.gmail.com" GMAIL_SE...
389
187
"""Resource module for resultat view.""" import logging from aiohttp import web import aiohttp_jinja2 from sprint_webserver.services import ( InnstillingerService, KjoreplanService, KlasserService, ) class Kjoreplan(web.View): """Class representing the kjoreplan / heatliste resource.""" async d...
2,336
707
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
823
190
import asyncio import discord import os import json import time from datetime import datetime from config import get_configuration departements = json.loads(open("departements.json").read()) regions = json.loads(open("regions.json").read()) async def log(self, guild, message) : config = get_configuration(guild....
19,768
6,097
import smbus import time bus = smbus.SMBus(1) # instantiate bus slaveAddress = 0x04 # assign a slave address def writeNumber(value): # function to write value bus.write_byte(slaveAddress, value) def readNumber(): # function to read value number = bus.read_byte(slaveAddress) return number while True: # c...
682
211
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="mtna-rds", version="0.2.16", author="Metadata Technology North America Inc.", author_email="mtna@mtna.us", description="A library to query the Rich Data Services API framework developed by...
1,062
344
import re from collections import Counter def pair_sum_to_value(seq, value): """"test if any pair in sequence sum to value""" for i in xrange(len(seq)): for j in xrange(i+1, len(seq)): if seq[i]+seq[j] == value: return True return False def is_mirror_number(i): tm...
1,186
481
#-*- coding: utf-8 -*- #Vstream https://github.com/Kodi-vStream/venom-xbmc-addons from resources.lib.gui.gui import cGui from resources.lib.handler.requestHandler import cRequestHandler from resources.lib.comaddon import addon, dialog, VSlog class cJDownloaderHandler: ADDON = addon() DIALOG = dialog() d...
2,829
886
from poop.hfdp.factory.pizzafm.chicago_pizza_store import ChicagoPizzaStore from poop.hfdp.factory.pizzafm.ny_pizza_store import NYPizzaStore from poop.hfdp.factory.pizzafm.pizza import Pizza def main() -> None: ny_store: NYPizzaStore = NYPizzaStore() chicago_store: ChicagoPizzaStore = ChicagoPizzaStore() ...
1,086
421
#! /usr/bin/python # coding:utf-8 __val_dict = {} def filter_new(key, bean_list): old_bean_id = [old_bean.uid for old_bean in __val_dict.get(key, {})] return [bean.uid for bean in bean_list if bean.uid not in old_bean_id] def add(key, bean_list): __val_dict[key] = bean_list
292
120
from nally.port_scanner.scanning_strategies.scanning_strategy import ScanningStrategy class SynScanningStrategy(ScanningStrategy): def scan_port(self, host: str, port: int) -> bool: return False @staticmethod def get_strategy_name() -> str: return ScanningStrategy.SYN_STRATEGY
310
98
# See End Of File For Licensing from inspect import signature from functools import wraps from typing import Union, Callable, Optional from contextlib import contextmanager from weakref import WeakValueDictionary from spectate.core import Watchable, watched, Immutable, MethodSpectator from .utils import members __a...
13,575
3,723
import datetime from enum import Enum from typing import List from flask_resql.resql import Serializer from flask_resql.resql.utils import transform_serializer_field def object_type(cls): schema = cls.schema() obj_type = transform_serializer_field( f"/{cls.__name__}", cls.__name__, schema, model_sche...
1,073
358
import warnings from pathlib import Path from typing import Any, List def identical(val: Any) -> Any: return val def to_string(val: Any) -> str: warnings.warn("to_string has deprecated.use str to instead.", DeprecationWarning) return str(val) def to_integer(val: Any) -> int: warnings.warn("to_inte...
970
301
import numpy as np import statistics import time from astropy.coordinates import SkyCoord from astropy import units as u def crossmatch(cat1, cat2, max_dist): matches = [] nomatches = [] start = time.perf_counter() skycat1 = SkyCoord(cat1*u.degree, frame='icrs') skycat2 = SkyCoord(cat2*u.degree, frame='ic...
1,803
701
from PyQt5.QtWidgets import ( QTabWidget, ) class TabWidget(QTabWidget): tab_ids = 0 def addTab(self, widget, label, silent=False): tab_id = self.tab_ids self.tab_ids += 1 i = super().addTab(widget, label) if not silent: super().setCurrentIndex(i) wid...
997
315
from typing import Set from code_generator.line_buffer import LineBuffer, IndentedBlock from code_generator.type_generators.cpp_array_alias import CppArrayAlias from code_generator.type_generators.cpp_enum import CppEnum from code_generator.type_generators.cpp_extended_variant_utils.from_json_generator import FromJson...
5,753
1,693
from django import forms from .models import * class NewPostForm(forms.ModelForm): class Meta: model = Post exclude = ['user'] class UserForm(forms.ModelForm): class Meta: model = Profile fields = ('name','user_name','bio') class CreateHoodForm(forms.ModelForm): class Me...
635
180
import numpy as np import os from .file_loader import ( CatsvsdogsFileLoader, FashionMnistFileLoader, ImdbSentimentFileLoader, StackoverflowFileLoader, ) from .model_input import ModelInputGenerator from .output_decoder import OutputDecoder from .pipeline import Pipeline from .preprocessing import pipe...
5,959
1,809
import os from typing import Set from . import MarkovDecisionProcedure class Sokoban(MarkovDecisionProcedure): def __init__(self, state_initial: Set[str], state_static: Set[str]): # No discounting for Sokoban discount_rate = 1.0 file_name = 'sokoban.lp' super().__init__(state_i...
2,206
740
import sqlite3 conn = sqlite3.connect('elements.db') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS elements') cur.execute('CREATE TABLE elements (number INTEGER, atomic_weight FLOAT, element TEXT, symbol TEXT, mp FLOAT, bp FLOAT, density FLOAT, earth_crust FLOAT, discovered INTEGER, egroup INTEGER, ionization...
1,014
378
import open3d as o3d from open3d import * import numpy as np import sys, os import matplotlib.pyplot as plt import cv2 import torch import glob import copy import mathutils from PIL import Image from pytorch3d.loss import chamfer_distance from tk3dv.nocstools.aligning import estimateSimilarityUmeyama import math from ...
12,454
4,956