text
string
size
int64
token_count
int64
#!/usr/bin/env python3 from pwn import * binary = context.binary = ELF('./chall_05') if not args.REMOTE: p = process(binary.path) else: p = remote('chal.2020.sunshinectf.org', 30005) p.sendlineafter('Race, life\'s greatest.\n','foobar') p.recvuntil('Yes I\'m going to win: ') _ = p.recvline().strip() main = int(_...
521
221
from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.admin.edit_handlers import EditHandler class FormSubmissionsPanel(EditHandler): template = "wagtailforms/edit_handlers/form_responses_panel.html" ...
1,047
301
from aws_cdk import ( core as cdk, aws_elasticache as elasticache, aws_ec2 as ec2, ) from aws_cdk.core import Tags from config import config_util as config def get_vpc(scope: cdk.Construct) -> ec2.Vpc: """ Look up and return the none default vpc. Args: scope: the cdk construct. ...
2,189
728
# -*- coding: utf-8 -*- """ Extension that adjust project file tree to include a namespace package. This extension adds a **namespace** option to :obj:`~pyscaffold.api.create_project` and provides correct values for the options **root_pkg** and **namespace_pkg** to the following functions in the action list. """ impo...
5,101
1,325
# encoding: utf-8 from mock import call, patch from django.template import Template, Context from django.test import TestCase from core.models import MockModel @patch("haystack.templatetags.more_like_this.SearchQuerySet") class MoreLikeThisTagTestCase(TestCase): def render(self, template, context): # Wh...
2,324
745
from django_mako_plus.converter import ParameterConverter from django_mako_plus import view_function from django.http import HttpRequest class RecordingConverter(ParameterConverter): '''Converter that also records the converted variables for inspecting during testing''' def convert_parameters(self, *args, **k...
669
177
from notebook.utils import url_path_join from jupyterlab_bigquery.list_items_handler import handlers from jupyterlab_bigquery.details_handler import DatasetDetailsHandler, TablePreviewHandler, TableDetailsHandler from jupyterlab_bigquery.version import VERSION from jupyterlab_bigquery.pagedAPI_handler import PagedQuer...
1,953
614
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django_fields.fields class Migration(migrations.Migration): dependencies = [ ('ios_notifications', '0003_notification_loc_payload'), ] operations = [ migrations.AlterField( ...
581
176
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import editdistance import os impo...
9,232
2,681
# -*- coding: utf-8 -*- # SenseNets is pleased to support the open source community by making caffe-int8-convert-tool available. # # Copyright (C) 2018 SenseNets Technology Ltd. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except # in compliance with the L...
20,440
6,196
""" All your views aka. your template endpoints go here. There are two ways to create a view. 1. Create a new Subclass inheriting from one of the flask_template_master views 2. Use the view-factory function flask_template_master.views.create_template_endpoint Each view requires an 1 (and 2 optional) things: 1. An envi...
2,404
633
class PerceptronError(Exception): pass
44
15
#!/usr/bin/env python3 import unittest import os from pytorch_translate import data from pytorch_translate import dictionary from pytorch_translate.test import utils as test_utils class TestInMemoryNumpyDataset(unittest.TestCase): def setUp(self): self.src_txt, self.trg_txt = test_utils.create_test_text...
5,534
1,915
import numpy as np import sys import json import glob import os.path as osp import cv2 def compute_whdr(reflectance, judgements, delta=0.1): points = judgements['intrinsic_points'] comparisons = judgements['intrinsic_comparisons'] id_to_points = {p['id']: p for p in points} rows, cols = reflectance.sha...
2,877
1,077
__title__ = 'The Onion Box' __description__ = 'Dashboard to monitor Tor node operations.' __version__ = '20.2' __stamp__ = '20200119|095654'
141
61
import re from sublime import Region import sublime_plugin REPLACEMENTS = { '\u00a0': ' ', # no-break space '\u200b': '', # zero-width space } class UnicodeTrapsListener(sublime_plugin.EventListener): @staticmethod def on_pre_save(view): view.run_command('unicode_traps') class UnicodeTrap...
649
223
import glob import pandas as pd from configparser import ConfigParser import os from simba.drop_bp_cords import * def multiplyFreeHand(inifile, currVid): _, CurrVidName, ext = get_fn_ext(currVid) config = ConfigParser() configFile = str(inifile) config.read(configFile) projectPath = conf...
2,743
886
from logging import getLogger import traceback from .get_public_exchange import get_public_exchange logger = getLogger("__main__").getChild(__name__) def fetch_order_book(exchange_name, pair): logger.debug("start") logger.debug(exchange_name) logger.debug(pair) exchange = get_public_exchange(exchange...
689
203
# Copyright 2018 The Fuego Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
20,080
5,618
import math import numpy as np import torch import torch.nn.functional as F from torch import nn class SimpleMLP(nn.Module): """Simple MLP function approximator for Q-Learning.""" def __init__(self, in_dim, out_dim, hidden_units=256, num_hidden_layers=1): super().__init__() self.input_layer...
8,165
2,615
"""Auto-generated file, do not edit by hand. AC metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AC = PhoneMetadata(id='AC', country_code=247, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[2-467]\\d{3}', possible_number_pattern=...
1,705
542
# Generated by Django 2.2.20 on 2021-12-17 19:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0155_improved_health_check'), ] operations = [ migrations.AlterField( model_name='inst...
1,574
438
import torch from torch import nn from torch.nn import functional as F class BicubicDownSample(nn.Module): def bicubic_kernel(self, x, a=-0.50): """ This equation is exactly copied from the website below: https://clouard.users.greyc.fr/Pantheon/experiments/rescaling/index-en.html#bicubic ...
2,981
1,160
import logging from flask import Flask from . import utils, home, member, society, signup, jobs, admin from .flask_seasurf import SeaSurf from flask_talisman import Talisman app = Flask(__name__, template_folder="../templates", static_folder="../static") app.config['CSRF_CHECK_REFERER'] = F...
655
228
import arche.rules.duplicates as duplicates from arche.rules.result import Level, Outcome from conftest import create_result import numpy as np import pandas as pd import pytest unique_inputs = [ ({}, {}, {Level.INFO: [(Outcome.SKIPPED,)]}), ( {"id": ["0", "0", "1"]}, {"unique": ["id"]}, ...
3,569
1,155
# This is the word list from where the answers for the hangman game will come from. word_list = [ 2015, "Fred Swaniker", "Rwanda and Mauritius", 2, "Dr, Gaidi Faraj", "Sila Ogidi", "Madagascar", 94, 8, "Mauritius" ] # Here we are defining the variables 'Right'(for ...
2,602
1,008
import json import os import pycspr # A known casper test-net node address. _NODE_ADDRESS = os.getenv("CASPER_NODE_ADDRESS", "3.136.227.9") # A known block hash. _BLOCK_HASH: bytes = bytes.fromhex("c7148e1e2e115d8fba357e04be2073d721847c982dc70d5c36b5f6d3cf66331c") # A known block height. _BLOCK_HEIGHT: int = 2065...
1,416
473
import nose2.tools from typing import Union from app.util import has_attributes class SampleClass: pass class TestUtil: @nose2.tools.params( ('SET_VALUE', True), (None, False), ('NO_ATTRIBUTE', False), (False, True), ('', True), (0, True), ) def test...
582
191
# Copyright 2022 by Autodesk, Inc. # Permission to use, copy, modify, and distribute this software in object code form # for any purpose and without fee is hereby granted, provided that the above copyright # notice appears in all copies and that both that copyright notice and the limited # warranty and restricted ...
4,427
1,537
""" This process creates the two kafka topics to be used. The input-topic with ten partitions and the output-topic with one partition. Also preloads the kafka cluster with test data (if flag is set to true). """ import os import time import json import logging from confluent_kafka.admin import AdminClient, NewTopic fro...
5,044
1,472
OS_MA_NFVO_IP = '192.168.1.197' OS_USER_DOMAIN_NAME = 'Default' OS_USERNAME = 'admin' OS_PASSWORD = '0000' OS_PROJECT_DOMAIN_NAME = 'Default' OS_PROJECT_NAME = 'admin'
167
84
"""Extract body part annotations.""" import re import spacy from traiter.const import COMMA from traiter.patterns.matcher_patterns import MatcherPatterns from anoplura.pylib.const import COMMON_PATTERNS from anoplura.pylib.const import CONJ from anoplura.pylib.const import MISSING from anoplura.pylib.const import REP...
1,591
640
#!/usr/bin/python3 import os import time import sys os.system("clear") print('''\033[91m CREATED BY Hironotori ''') def slowprint(s): for c in s + '\n' : sys.stdout.write(c) sys.stdout.flush() slowprint(''' \033[93m [1] apt-pkg pip-pip3 [2] apt-pkg python [3] apt-pkg python2 [4] ...
17,478
5,960
from RFEM.initModel import Model, clearAtributes, ConvertToDlString from RFEM.enums import SolidSetLoadType, SolidSetLoadDistribution, SolidSetLoadDirection class SolidSetLoad(): def __init__(self, no: int =1, load_case_no: int = 1, solid_sets_no: str= '1', ...
10,255
3,114
# 2D example tensile test import numpy as np import matplotlib.pyplot as plt import PyFEMP import PyFEMP.elements.Elmt_BaMo_2D as ELEMENT FEM = PyFEMP.FEM_Simulation(ELEMENT) n = 4 XI, Elem = PyFEMP.msh_rec([0.0, 0.0], [10.0, 10.0], [n, n], type='Q1') FEM.Add_Mesh(XI, Elem) FEM.Add_Material([2100, 0.3], "All") FEM.A...
838
429
#!/usr/bin/env python import asyncio import websockets import os port = int(os.environ.get('PORT', '8765')) async def hello(): print("Starting client on :%s" % port) async with websockets.connect('ws://localhost:%s' % port) as websocket: msg = 'Client msg #1' await websocket.send(msg) ...
547
183
from django import forms from flags.forms import FlagStateForm as DjangoFlagsFlagStateForm from flags.models import FlagState from flags.sources import get_flags class NewFlagForm(forms.ModelForm): name = forms.CharField(label="Name", required=True) def clean_name(self): name = self.cleaned_data["na...
1,073
295
# -*- coding:utf8 -*- """ 一些其他工具 当需要细化或者函数太多时,应该把其中一些独立出去 """ import uuid from enum import Enum, unique from utils.log import get_logger logger = get_logger(__name__) @unique class PipeTaskStatus(Enum): # 还不够需要写状态机,先用这个凑活一下 """ name is Status value is Next """ # TODO 多线程时应该增加STOPPING, WAITIN...
830
458
# This is just for GitHub, and is used to clean up leftover files after # automatic testing has completed, and generate developer reports about # anything left undocumented! # run: "sudo python ./extras/scripts/finish_ci.py" import os import sys os.system("sudo python ./extras/scripts/generate_doxygen_report.py") os...
693
227
import pygame import random pygame.init() pygame.font.init() class Card(object): """ The Card Class """ def __init__(self, left, top, width, height, back_color, front_color, solved_color, display, font_color, text_font, value=None): self._rect = pyg...
9,549
3,060
import os class config: host = 'zhangxuanyang.zhangxuanyang.ws2.hh-c.brainpp.cn' username = 'admin' port = 5672 exp_name = os.path.dirname(os.path.abspath(__file__)) exp_name = '-'.join(i for i in exp_name.split(os.path.sep) if i); test_send_pipe = exp_name + '-test-send_pipe' test_recv_p...
1,889
967
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Projection(_BaseLayoutHierarchyType): # class properties # -------------------- _parent_path_str = "layout.geo" _path_str = "layout.geo.projection" _valid_props = {"parallels", "rotatio...
6,801
1,853
from btypes.big_endian import * cstring_sjis = CString('shift-jis') class Header(Struct): string_count = uint16 __padding__ = Padding(2) class Entry(Struct): string_hash = uint16 string_offset = uint16 def unsigned_to_signed_byte(b): return b - 0x100 if b & 0x80 else b def calculate_hash(s...
1,286
432
#!/usr/bin/env python3.5 from time import sleep, time from datetime import datetime, timedelta from pid.decorator import pidfile #from subprocess import call from RPi import GPIO import requests import json #import config import logging import signal import sys #13: grün #16: braun #19: orange #20: grün #21: braun #2...
4,549
1,549
from flask import Blueprint, request, render_template, flash, redirect, url_for from flask_login import login_user, login_required, current_user, logout_user from models import User from werkzeug.security import generate_password_hash, check_password_hash from app import db, login_manager admin = Blueprint('admin', __...
1,757
484
import datetime import types from nose.tools import eq_ from nose.tools import ok_ from inferno.lib.map import keyset_map from inferno.lib.rule import InfernoRule class TestKeysetMap(object): def setUp(self): self.data = { 'city': 'toronto', 'country': 'canada', 'pop...
4,321
1,348
# Copyright 2016 The Bazel 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 la...
1,882
640
import copy import os class Project(object): def __init__(self, folder, *jobtypes): self.jobtypes = jobtypes self.folder = folder self.params = [] self.version = 1 def is_v2(self): self.version = 2 return copy.deepcopy(self) def is_v1(self): self....
928
287
''' Purpose: Server responsible for routing Author: Md. Tanvir Islam Command to execute: python app.py ''' from flask import Flask from flask import render_template from flask import json from flask import request import random import sys app = Flask(__name__) print("Server is live...", file = s...
2,337
926
from .base import Base from .admin import Admin from .dashboard import Dashboard from .datasource import Datasource from .folder import Folder from .organisation import Organisation, Organisations from .search import Search from .user import User, Users
254
62
from shop.forms import UserForm from django.views import generic from django.urls import reverse_lazy from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import auth from .models import Product, Contact, Categ...
9,176
2,719
import FWCore.ParameterSet.Config as cms from SimMuon.GEMDigitizer.muonGEMDigis_cfi import * from SimMuon.GEMDigitizer.muonGEMPadDigis_cfi import * from SimMuon.GEMDigitizer.muonGEMPadDigiClusters_cfi import * muonGEMDigiTask = cms.Task(simMuonGEMDigis, simMuonGEMPadDigis, simMuonGEMPadDigiClusters) muonGEMDigi = cms...
347
157
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
8,843
2,691
import sys from PyQt5 import QtCore, QtGui, QtWidgets, uic import database_receita import pyqt5_aux qt_tela_inicial = "telas/tela_cadastro_loja_embala.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_tela_inicial) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): switch_tela_gerenciar_loja_embala = QtCor...
7,094
2,651
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) import logging import numpy as np import torch from parallel_wavegan.layers import Conv1d from parallel_wavegan.layers import Conv1d1x1 from parallel_wavegan.layers import Conv2d from ...
2,253
817
import os import re import logging from django.conf import settings from django.contrib.gis.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.formats import date_format from easy_thumbnails.alias import aliases from easy_thumbnails.exceptions import InvalidImageFormatError fro...
22,417
6,848
# -*- coding: utf-8 -*- from signed_requests.signed_request_auth import SignedRequest __author__ = 'alpaloma' from flask import Blueprint, current_app, request from helpers import Helpers import requests from json import dumps, loads from DetailedHTTPException import error_handler from flask_restful import Resource, A...
6,313
1,940
def is_bored(S): """ You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For example: >>> is_bored("Hello world") 0 >>> is_bored("The sky is blue. The s...
1,075
369
# Copyright 2020 The Tilt Brush Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
23,882
8,580
''' ''' ''' ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all c...
33,150
11,565
from multiprocessing import Pool from multiprocessing.pool import ThreadPool from queue import Queue from .chunks import chunks __all__ = 'map_parallel', 'map_multicore', 'map_multithread' def _pool_map_stream(pool_type, pipe, fn, workers): assert callable(fn), fn assert isinstance(workers, int), workers ...
2,458
731
from apps.bot.classes.messages.attachments.Attachment import Attachment class AudioAttachment(Attachment): TYPE = "audio" def __init__(self): super().__init__(self.TYPE) self.duration = None def parse_vk_audio(self, event_audio): from petrovich.settings import VK_URL self...
492
155
""" SQLAlchemy database models. """ from datetime import datetime from depot.fields.sqlalchemy import UploadedFileField from app import db from app.util.data import many_to_many, foreign_key from app.config import TOKEN_LEN class User(db.Model): """ User model class. """ id = db.Column(db.Integer(), primary_k...
4,384
1,442
import logging ## Logging Configuration ## logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() # console handler ch.setLevel(logging.INFO) fh = logging.FileHandler('logfile.txt') fh.setLevel(logging.INFO) fmtr = logging.Formatter('%(asctime)s | [%(levelname)s] | (%(name)s...
623
198
#!/bin/python3 import os def getTotalX(a, b): c = 0 for i in range(max(a), min(b) + 1): if all([i % d == 0 for d in a]) and all([d % i == 0 for d in b]): c += 1 return c if __name__ == "__main__": f = open(os.environ["OUTPUT_PATH"], "w") nm = input().spl...
552
251
import h5py import numpy as np import os, pdb import tensorflow as tf from rllab.envs.base import EnvSpec from rllab.envs.normalized_env import normalize as normalize_env import rllab.misc.logger as logger from sandbox.rocky.tf.algos.trpo import TRPO from sandbox.rocky.tf.policies.gaussian_mlp_policy import Gaussian...
17,628
5,919
import argparse import ast import configparser import io import os.path from typing import Any from typing import Dict from typing import Optional from typing import Sequence METADATA_KEYS = frozenset(( 'name', 'version', 'url', 'download_url', 'project_urls', 'author', 'author_email', 'maintainer', 'maintaine...
8,429
2,623
from .user import User, MultiUserUpload from .problem import Problem, TestData from .submit import Submit
106
27
# pytest tests import numpy as np from Advent2019_10 import Day10 class TestDay10(): def test_instantiate(self): test = Day10('../tests/test_Advent2019_10a.txt') grid = ['.#..#', '.....', '#####', '....#', '...##'] grid = [li...
726
246
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: if len(nums) < 1: raise Exception("Invalid Array") n = len(nums) res = [] s = set() for x in nums: s.add(x) for i in range(1, n + 1): if i not in s: ...
370
122
import pytest from tests.test_application import app @pytest.fixture def client(): client = app.test_client() yield client def test_hello_resource(client): """ Test if it is possible to access to /hello resource :param client: Test client object :return: """ response = client.get('/h...
691
209
''' 03 - Multiple arguments In the previous exercise, the square brackets around imag in the documentation showed us that the imag argument is optional. But Python also uses a different way to tell users about arguments being optional. Have a look at the documentation of sorted() by typing help(sorted) in the IPython...
1,614
439
""" Entradas: 3 Valores flotantes que son el valor de diferentes monedas Chelines autriacos --> float --> x Dramas griegos --> float --> z Pesetas --> float --> w Salidas 4 valores flotantes que es la conversión de las anteriores monedas Pesetas --> float --> x Francos franceses --> float --> z Dolares --> float...
790
337
import argparse import os from glob import glob import imageio from tqdm import tqdm from csbdeep.utils import normalize from stardist.models import StarDist3D def get_image_files(root, image_folder, ext): # get the image and label mask paths and validate them image_pattern = os.path.join(root, image_folder...
2,844
877
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from estacionamientos.models import Estacionamiento, Reserva, Pago class EstacionamientosForm(forms.ModelForm): nombre_duenio = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Nombre del Dueño'})...
4,049
1,295
""" Y. Saad, M. Schultz, GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems, SIAM J. Sci. and Stat. Comput., 7(3), 856–869, 1986, <https://doi.org/10.1137/0907058>. Other implementations: <https://petsc.org/release/docs/manualpages/KSP/KSPGMRES.html> """ from __future__ import anno...
6,095
2,354
# Copyright 2020 Northern.tech AS # # 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 a...
7,321
2,598
import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import json import logging import yaml import requests import time from actions.migrate_job_action import MigrateJobAction from actions.send_alert_action import SendAlertAction from actions.reboot_node_action import RebootNodeAction from action...
8,985
2,800
# Copyright 2019 Nokia # # 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, softwa...
2,735
807
from django.core.cache import cache from datetime import datetime from museum_site.models.detail import Detail from museum_site.models.file import File from museum_site.constants import TERMS_DATE from museum_site.common import ( DEBUG, EMAIL_ADDRESS, BOOT_TS, CSS_INCLUDES, UPLOAD_CAP, env_from_host, qs_sans ...
2,344
808
from django.contrib.auth import get_user_model from django.contrib.staticfiles.templatetags.staticfiles import static from django.shortcuts import redirect from misago.conf import settings UserModel = get_user_model() def user_avatar(request, pk, size): size = int(size) try: user = UserModel.objec...
671
221
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter from keras.layers import Input, Conv2D, Conv3D, Activation, Lambda from keras.models import Model from keras.layers.merge import Add, Concatenate import tensorflow as tf from keras i...
14,501
4,892
parameters = {} genome = {} genome_stats = {} genome_test_stats = [] brain = {} cortical_list = [] cortical_map = {} intercortical_mapping = [] block_dic = {} upstream_neurons = {} memory_list = {} activity_stats = {} temp_neuron_list = [] original_genome_id = [] fire_list = [] termination_flag = False variation_counte...
1,602
609
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from geonamescache import GeonamesCache gc = GeonamesCache() toposrc = '../data/states-provinces.json' for iso2, country in gc.get_countries().items(): iso3 = country['iso3'] topojson = 'mapshaper -i {0} -filter \'"{1}" == adm0_a3\' -filter-fiel...
494
192
""" This module contains all information for pushing a NordicEvent object into the database. Functions and Classes --------------------- """ import psycopg2 import os import re import datetime from nordb.core import usernameUtilities from nordb.database import creationInfo INSERT_COMMANDS = { 1:...
10,768
3,033
"""This module contains class definitions for storing media files""" import webbrowser class Movie(): """Movie class defines movies. Attributes: movie_title (str): Title of the movie movie_storyline (str): Sort description of the movie poster_image (str): Url of the poster image ...
973
259
# workserver.py - simple HTTP server with a do_work / stop_work API # GET /do_work activates a worker thread which uses CPU # GET /stop_work signals worker thread to stop import math import socket import threading import time from bottle import route, run hostname = socket.gethostname() hostport = 9000 keepworking = ...
1,700
520
from maxdb import DB def runtime_on_any_exception(func): def decorate(*args, **kwargs): try: func(*args, **kwargs) except: raise RuntimeError return decorate class CLIUtils(object): DEFAULT_PATH = 'storage.json' def __init__(self): self._db = None ...
7,521
2,237
import easygui as g # judge=1 # def judge_null(tmp): # if tmp.isspace()or len(tmp)==0: # return judge==0 # # while 1: # user_info=g.multenterbox(title='账号中心', # msg='【*用户名】为必填项\t【*真实姓名】为必填项\t【*手机号码】为必填项\t【*E-mail】为必填项', # fields=['*用户名','*真实姓名','固定电话','*手...
1,348
667
from cognibench.models import CNBModel from cognibench.capabilities import ContinuousAction, ContinuousObservation from cognibench.continuous import ContinuousSpace from cognibench.models.wrappers import MatlabWrapperMixin class PsPMModel(MatlabWrapperMixin, CNBModel, ContinuousAction, ContinuousObservation): nam...
962
301
from layout import Layout class PixelList(Layout): """ A simple generic layout, just a list of pixels """ def __init__(self, pixels): """ pixels is a list of pixel objects """ self.pixels = pixels
254
67
import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.clients.restful.config import RestConfiguration from programy.clients.events.console.config import ConsoleConfiguration class RestConfigurationTests(unittest.TestCase): def test_init(self): yaml = YamlConfigura...
2,328
723
# Write a recursive function to count the number of nodes in a Tree. (first do your self then see code) def count_nodes(self): count = 1 left_count = 0 right_count = 0 if self.left: left_count = self.left.count_nodes() if self.right: right_count = self.right.count_nodes() return count + left_count + rig...
1,211
396
#! /usr/bin/env python3 # from datetime import datetime # from random import choices # from string import ascii_lowercase from flask import Flask, request, render_template, Response, send_file from flaskext.markdown import Markdown from D47crunch import D47data, pretty_table, make_csv, smart_type from D47crunch import...
28,020
17,037
r"""Train a neural network to predict feedback for a program string.""" from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import sys import random import numpy as np from tqdm import tqdm import torch import torch.optim as optim import torch.utils....
6,505
2,216
# -------------- # Code starts here class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio'] class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) del new_class[5] print(new_class) # Code...
1,232
499
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' NAME: checklog.py DESCRIPTION: This script checks the tail of the log file and lists the disk space CREATED: Sun Mar 15 22:53:54 2015 VERSION: 1.0 AUTHOR: Mark Tibbett AUTHOR_EMAIL: mtibbett67@gmail.com URL: N/A DOWNLOAD_URL: N/A INSTALL_REQUIRES: [] PACKAGES:...
1,629
690
n = int(input().strip()) items = [ int(A_temp) for A_temp in input().strip().split(' ') ] items_map = {} result = None for i, item in enumerate(items): if item not in items_map: items_map[item] = [i] else: items_map[item].append(i) for _, item_indexes in items_map.items(): it...
726
236
""" Sparse Poisson Recovery (SPoRe) module for solving Multiple Measurement Vector problem with Poisson signals (MMVP) by batch stochastic gradient ascent and Monte Carlo integration Authors: Pavan Kota, Daniel LeJeune Reference: [1] P. K. Kota, D. LeJeune, R. A. Drezek, and R. G. Baraniuk, "Extreme Compressed Se...
15,518
4,562
"""Use translation table to translate coding sequence to protein.""" from Bio.Data import CodonTable # type: ignore from Bio.Seq import Seq # type: ignore def translate_cds(cds: str, translation_table: str) -> str: """Translate coding sequence to protein. :param cds: str: DNA coding sequence (CDS...
734
239