text
string
size
int64
token_count
int64
# # test_server.py # # Copyright (C) 2001-2007 Oisin Mulvihill. # Email: oisin.mulvihill@gmail.com # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # versio...
2,101
714
import os import sys import angr import nose.tools test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') def test_various_loops(): p = angr.Project(os.path.join(test_location, 'x86_64', 'various_loops'), auto_load_libs=False) cfg = p.analyses.CFGFast(nor...
6,872
2,771
import serial , time , os import serial.tools.list_ports as port import logging sho_logger = logging.getLogger("shongololo_logger") def open_imets(devices): """Tries to open as many imet device serial ports as there are :return: a list of socket handles """ imet_sockets = [] for d in range(...
1,726
562
#! /usr/bin/env python # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 3915 $ # Date: $Date: 2005-10-02 03:06:42 +0200 (Sun, 02 Oct 2005) $ # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.peps. """ from __init__ import DocutilsT...
1,754
563
# Generated by Django 4.0.2 on 2022-03-15 22:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rental_property', '0010_alter_rentalunit_status'), ] operations = [ migrations.AlterModelOptions( name='rentalunit', options...
380
133
import Terminal class Axes(): def __init__(self, weak_terminal : 'Terminal.CartesianPoint'): # self._initiator_x = weak_terminal._x # self._initiator_y = weak_terminal._y self._initiator = Terminal.CartesianPoint(0.0, 0.0, "UWB", "initiator") self._weak_terminal = weak_termin...
951
328
import re from bs4 import BeautifulSoup # beautifulsoup4 import requests # requests HEADER = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } def catch_info(base,pattern,str_add=''): '''base text, pattern to search, s...
1,583
557
"""Constants for the deCONZ component.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "deconz" CONF_BRIDGE_ID = "bridgeid" CONF_GROUP_ID_BASE = "group_id_base" DEFAULT_PORT = 80 DEFAULT_ALLOW_CLIP_SENSOR = False DEFAULT_ALLOW_DECONZ_GROUPS = True DEFAULT_ALLOW_NEW_DEVICES = True CONF_ALLOW_CLIP...
1,118
492
import json from rest_framework.generics import ListAPIView, get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from course_app.api.serializers import CourseSerializer from course_app.models import Course, Enrolled f...
1,898
546
import os import json import logging import yaml from flask import Blueprint, jsonify, send_file, request, redirect from service.errors import ApiError from utils.repository import generate_repository_path, \ list_objects_in_repository from utils.list_dir import list_dir repository_controller = Blueprint('reposi...
9,005
2,673
#!/usr/bin/python3 #coding=utf-8 def cc_debug(): print(__name__)
69
30
from datetime import datetime import base64 import os import re import requests import sys import urllib.parse import xmltodict import xbmc import xbmcgui import xbmcplugin import xbmcaddon import xbmcvfs __PLUGIN_ID__ = "plugin.audio.podcasts" # see https://forum.kodi.tv/showthread.php?tid=112916 _MONTHS = ["Jan", ...
24,392
7,359
import re import time from lemoncheesecake.events import TestSessionSetupEndEvent, TestSessionTeardownEndEvent, \ TestEndEvent, SuiteSetupEndEvent, SuiteTeardownEndEvent, SuiteEndEvent, SteppedEvent from lemoncheesecake.reporting.report import ReportLocation DEFAULT_REPORT_SAVING_STRATEGY = "at_each_failed_test" ...
2,832
893
"""Genshin chronicle notes.""" import datetime import typing import pydantic from genshin.models.genshin import character from genshin.models.model import Aliased, APIModel __all__ = ["Expedition", "ExpeditionCharacter", "Notes"] def _process_timedelta(time: typing.Union[int, datetime.timedelta, datetime.datetime]...
4,676
1,424
import smart_imports smart_imports.all() class Renderer: __slots__ = ('tags', '_renderer') def __init__(self, tags): self.tags = tags self._renderer = postmarkup.create(include=[], use_pygments=False, ann...
1,222
383
# 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 u...
6,860
2,652
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
10,253
4,031
#!/usr/bin/env python import argparse from igf_data.task_tracking.igf_slack import IGF_slack from igf_data.process.data_transfer.sync_seqrun_data_on_remote import Sync_seqrun_data_from_remote parser = argparse.ArgumentParser() parser.add_argument('-r','--remote_server', required=True, help='Remote server address') par...
1,208
389
from typing import Callable, Iterable, TypeVar T = TypeVar('T') Num = TypeVar('Num', int, float) def sumBy(array: Iterable[T], iteratee: Callable[[T], Num] = None, start: Num = 0) -> Num: if iteratee is None: return sum([y for y in array], start) return sum([iteratee(y) for y in array], start)
314
110
fhand = (romeo.txt) counts = dict() for line in fhand: words = line.split() for word in words(): count word = count.get(word, 0) + 1 st = list for Key,Value in count.items(): st.append((val,key)) st.sort(reverse = true) for val,key in st[:10]: print key, val #Using Sorted Function sorted [(v,k...
344
145
newlist = lambda x<caret>, y: (x+y)/y x = 1
43
23
import grpc from consts import PORT, SERVER_CERT from grpc_generated_files import api_pb2, api_pb2_grpc def main(stub): request = api_pb2.ApiRequest( name="Shivam", message="Hey there!" ) response = stub.ApiEndpoint(request) print(response) if __name__ == "__main__": with open(S...
615
216
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-23 Last_modify: 2016-03-23 ****************************************** ''' ''' Say you have an array for which the ith el...
1,432
470
import numpy as np import copy from gips import FLOAT from gips import DOUBLE class post_processing(object): def __init__(self, fitter, x, pairs=False, prefix=None): self.fitter = fitter self.x = x self.pairs = pairs self.case = 0 score_dict = { 4 : self.parms4,...
35,087
10,998
from discord.ext import commands import discord import requests from bs4 import BeautifulSoup # work in progress! more languages welcome! class InfoCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name = 'docs', brief = 'programming language documentation', description = '...
2,560
754
def drop(i_list: list,n:int) -> list: """ Drop at multiple of n from the list :param n: Drop from the list i_list every N element :param i_list: The source list :return: The returned list """ assert(n>0) _shallow_list = [] k=1 for element in i_list: if k % n != 0: ...
451
164
# # Copyright (c) 2017 Intel Corporation # # 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...
7,929
2,141
#!/usr/bin/env python # -*- coding: utf-8 -*- from schedprof.enumerated_instance import EnumeratedInstance class Mutex(EnumeratedInstance): def __init__(self): super(Mutex, self).__init__(Mutex) self.acquired_by = None self.wait_queue = []
271
94
import pyblish.api import avalon.api from openpype.api import version_up from openpype.action import get_errored_plugins_from_data class IncrementCurrentFile(pyblish.api.InstancePlugin): """Increment the current file. Saves the current scene with an increased version number. """ label = "Increment...
1,606
449
#!/usr/bin/python3 """ Given a binary tree, we install cameras on the nodes of the tree. Each camera at a node can monitor its parent, itself, and its immediate children. Calculate the minimum number of cameras needed to monitor all nodes of the tree. Example 1: Input: [0,0,null,0,0] Output: 1 Explanation: One c...
2,586
797
from TikTokApi import TikTokApi api = TikTokApi.get_instance() count = 30 # You can find this from a tiktok getting method in another way or find songs from the discoverMusic method. sound_id = "6601861313180207878" tiktoks = api.by_sound(sound_id, count=count) for tiktok in tiktoks: print(tiktok)
308
128
from builtins import str from builtins import range from robust.simulations.simulate import filter_gamma_result_dict from SimPleAC_save import load_obj import pickle as pickle import numpy as np import matplotlib.pyplot as plt from SimPleAC_pof_simulate import pof_parameters if __name__ == "__main__": # Retrieving...
4,464
1,523
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定 import numpy as np from dataset.cifar10 import load_cifar10 from PIL import Image np.set_printoptions(threshold=100) (x_train, t_train), (x_test, t_test) = load_cifar10(flatten=False) sample_image = x_test[0:100].reshap...
588
321
from . import lights from . import schedule
44
11
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import argparse import os import numpy as np from read_files import split_imdb_files, split_yahoo_files, split_agnews_files from word_level_process import word_process, get_tokenizer ...
10,533
3,298
#!/usr/bin/env python from __future__ import absolute_import import numpy as np import os import pytest import tempfile import training_data class TestTrainingData(): def test_add(self): td = training_data.training_data() assert np.array_equal(td.get_x(), np.empty([0, 4, 4], dtype=np.int)) ...
22,970
11,339
from datetime import datetime from bee import Psd, CX, On, T from bee import Model, IntegerField, StringField, DateTimeField, Equal, W, C db_exam = Psd.open("exam") # 1) sing table count search, SELECT COUNT(*) AS COUNT FROM t_teacher with db_exam.connection() as conn: teacher_count = db_exam.Select(*CX("COUNT(*)...
2,218
820
import json from scrapy import Selector from scrapy.utils.spider import arg_to_iter from scrapely.htmlpage import parse_html, HtmlTag, HtmlDataFragment from collections import defaultdict from itertools import tee, count, groupby from operator import itemgetter from slybot.utils import (serialize_tag, add_tagids, re...
19,781
5,203
# Copyright 2014 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. DEPS = [ 'adb', 'depot_tools/bot_update', 'depot_tools/gclient', 'goma', 'recipe_engine/context', 'recipe_engine/json', 'recipe_engine/path', ...
9,840
3,346
# -*- coding:utf8 -*- import random import time from lib.navigation.PathFinding import Pathfinding from lib.control.Control import Control from lib.unit.Player import Player from lib.struct.CoordiPoint import CoordiPoint # 区域打怪 class AreaFighting(Pathfinding): # area_pos: 区域4角坐标。顺序为:左上,右上,左下,右下 def __init__(se...
3,101
1,322
import os import time import sys if(len(sys.argv) is 1): path="/home/pi/storage/" else: path=sys.argv[1] try: arr=[] for filename in os.listdir(path): if("2018-09" in filename): arr.append(filename) for f in arr: filen = os.path.splitext(f)[0] if(("%s.h264"...
722
286
petersen_spring = Graph(':I`ES@obGkqegW~') sphinx_plot(petersen_spring)
71
35
t = (19, 42, 21) print(f"The {len(t)} numbers are: {t[0]}, {t[1]}, {t[2]}")
77
49
import json import os from os.path import join from random import shuffle import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.preprocessing import MinMaxScaler, normalize from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cros...
3,002
1,076
import logging as _logging def handle_exception(e): if isinstance(e, ApiError): _logging.exception(e.message) return e.message, e.statuscode _logging.exception(repr(e)) return None, 500 class ApiError(Exception): def __init__(self, statuscode, message): self.statuscode = s...
1,569
481
#!/opt/libreoffice5.4/program/python # -*- coding: utf-8 -*- import unohelper # オートメーションには必須(必須なのはuno)。 def macro(): ctx = XSCRIPTCONTEXT.getComponentContext() # コンポーネントコンテクストの取得。 smgr = ctx.getServiceManager() # サービスマネージャーの取得。 tcu = smgr.createInstanceWithContext("pq.Tcu", ctx) # サービス名か実装名でインスタンス化。 print("\n"...
3,081
1,480
word=input() last_letter=(len(word)-1) result=word[last_letter] print(result)
77
30
import time from functools import wraps import asyncio from simple_retry.simple_retry.helpers import ( format_retry_message, has_retries_to_go, log_message ) def retry(Except, retries=5, delay=0, logger=None, level='info', multiple=1): def deco_retry(function): @wraps(function) de...
3,261
881
# application environment import settings import sys sys.path.append(settings.app_home_dir) sys.path.append(settings.app_settings["app_lib_dir"])
153
51
"""cogeo_mosaic.backend.base: base Backend class.""" import abc import itertools from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union import attr import mercantile from cachetools import TTLCache, cached from cachetools.keys import hashkey from morecantile import TileMatrixSet from rio_tiler.con...
8,618
2,869
# pylint: disable=missing-module-docstring # # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LIC...
5,190
1,330
import unittest, tempfile from pygromos.simulations.hpc_queuing.job_scheduling.schedulers import simulation_scheduler from pygromos.data.simulation_parameters_templates import template_md from pygromos.data.topology_templates import blank_topo_template from pygromos.simulations.hpc_queuing.submission_systems import D...
1,387
464
# -*- coding: utf-8 -*- """ Created on Sat Dec 30 17:03:01 2017 @author: misakawa """ from pattern_matching import Match, when, var, T, t, _, overwrite from numpy.random import randint @overwrite(var[(t == int) | (t == float)], var[(t == int) | (t == float)]) def add(a, b): return a + b @when(var[t == str], v...
1,934
830
# ---------------------------------------------------------------------- # | # | EnvironmentDiffs.py # | # | David Brownell <db@DavidBrownell.com> # | 2018-06-02 22:19:34 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2018-22. # | Distrib...
3,823
1,016
from datetime import datetime from os.path import join from tests.base import TestCase, main, assets, copy_of_directory from ocrd_utils import ( initLogging, VERSION, MIMETYPE_PAGE ) from ocrd_models import OcrdMets # pylint: disable=protected-access,deprecated-method,too-many-public-methods class TestOcr...
7,837
2,953
""" Environment for basic obstacle avoidance controlling a robotic arm from UR. In this environment the obstacle is only moving up and down in a vertical line in front of the robot. The goal is for the robot to stay within a predefined minimum distance to the moving obstacle. When feasible the robot should continue to...
7,862
2,521
from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.management.base import BaseCommand from ._private import populate_user User = get_user_model() class Command(BaseCommand): help = 'admin deployment' def add_arguments(self, parser): p...
848
240
#!/usr/bin/env python # -*- encoding: utf-8 -*- ## # Copyright 2017 FIWARE Foundation, e.V. # 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.apach...
1,789
633
"""Tests for graphmode_tensornetwork.""" import builtins import sys import pytest import numpy as np from tensornetwork import connect, contract, Node from tensornetwork.backends.base_backend import BaseBackend from tensornetwork.backends import backend_factory def clean_tensornetwork_modules(): for mod in list(sys...
12,218
4,374
#!/usr/bin/env python # -*- coding: utf-8 -*- import pyqtgraph as pg import numpy as np class CustomWidget(pg.GraphicsWindow): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') def __init__(self, parent=None, **kargs): pg.GraphicsWindow.__init__(self, **kargs) sel...
633
215
"""Tests for collapsible definition lists. When the option ``html_collapsible_definitions`` is ``True``, some HTML classes should be added to some definition lists but not all of them. """ from pathlib import Path import pytest from sphinx.application import Sphinx from .util import parse_html @pytest.mark.sphinx...
2,733
950
import numpy as np import pandas as pd import matplotlib.pyplot as plt from network import NN from evaluate import accuracy def read_data(fpath): iris = pd.read_csv(fpath) iris.loc[iris['species'] == 'virginica', 'species'] = 0 iris.loc[iris['species'] == 'versicolor', 'species'] = 1 iris.loc[iris['sp...
1,618
660
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding, rsa backend = default_backend() def generate_private_key(): key = rsa.generate_private_key( public_exponent=65537, ...
1,160
370
import unittest import unittest.mock from programy.storage.entities.nodes import NodesStore class NodesStoreTest(unittest.TestCase): def test_load(self): store = NodesStore() with self.assertRaises(NotImplementedError): collector = unittest.mock.Mock() store.load(collecto...
324
98
import numpy as np import pandas as pd from bokeh.plotting import * # Here is some code to read in some stock data from the Yahoo Finance API AAPL = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000", parse_dates=['Date']) GOOG = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=GOOG&...
1,939
699
import graphviz def convert_to_visualize(graph_ir, vgraph): for name, graph in graph_ir.items(): if name == '_training_config': continue with vgraph.subgraph(name='cluster'+name) as subgraph: subgraph.attr(color='blue') cell_node = {} ioput = {'_inpu...
1,828
541
import unittest class PrefixNotIncluded(unittest.TestCase): def test_not_included(self): pass if __name__ == '__main__': unittest.main()
155
54
''' This is the class to create a scrolling background. Because the background was so large, it was made to be a .jpg. ''' import pygame, os class Background(pygame.sprite.Sprite): # Initialize the sprite. def __init__(self,disp): pygame.sprite.Sprite.__init__(self) self.image = pygame...
885
268
import os import shutil from contextlib import contextmanager from tempfile import mkdtemp, mktemp @contextmanager def temporary_dir(): """Returns a temporary directory that gets cleaned up when the context manager exits.""" tempdir = mkdtemp() try: yield tempdir finally: shutil.rmtree(tempdir) @con...
1,705
526
import asyncio import os from parser import miniprez_markdown, build_body import logging logger = logging.getLogger("miniprez") async def file_watcher(target_file, sleep_time=0.5): """ Watchs a file. If modified, yield the filename. Yield the filename once to start. """ # Yield the file first ...
1,366
453
# -*- coding: utf-8 -*- """Linear module for dqn algorithms - Author: Kyunghwan Kim - Contact: kh.kim@medipixel.io """ import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from rl_algorithms.common.helper_functions import numpy2floattensor device = torch.device("cuda:0"...
3,943
1,249
# Advent of Code - 2015 - Day 7 # --- Day 7: Some Assembly Required --- # This year, Santa brought little Bobby Tables a set of wires and bitwise logic gates! Unfortunately, little Bobby is a little under the recommended age range, and he needs help assembling the circuit. # Each wire has an identifier (some lowerca...
10,826
3,098
# # 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...
1,346
429
from pyradioconfig.parts.ocelot.profiles.Profile_WiSUN import Profile_WiSUN_Ocelot from pyradioconfig.parts.common.profiles.bobcat_regs import build_modem_regs_bobcat from pyradioconfig.parts.common.profiles.profile_common import buildCrcOutputs, buildFecOutputs, buildFrameOutputs, \ buildWhiteOutputs class Profil...
977
315
import logging import pytest from . import auth from hydroengine_service import dgds_functions logger = logging.getLogger(__name__) class TestDGDSFunctions: @pytest.mark.parametrize('source, start_date, end_date, limit', [ ('projects/dgds-gee/bathym...
1,846
583
from math import log import numpy as np from numpy import linalg as la class LogisticProblem: """Class for the logistic regression method for classification.""" def __init__(self, feat_mtx, y): """Create a Logistic Problem with matrix `feat_mtx` n by p and vector `y` of 0s and 1s with size n. ...
2,485
868
import numpy as np # TODO : add code for referee def get_team_classifications(teamColor1, teamColor2, refColor, keeper1Color, keeper2Color, pose_estimations): for pose in pose_estimations: if len(pose[1]) < 2: pose.append('color not found') continue colorDiffs = {} ...
1,280
483
from mpi4py.futures import MPIPoolExecutor import numpy as np import pandas as pd from quasinet.qnet import Qnet, qdistance, load_qnet, qdistance_matrix from quasinet.qsampling import qsample, targeted_qsample qnet=load_qnet('../results/PTSD_cognet_test.joblib') w = 304 h = w p_all = pd.read_csv("tmp_samples_as_string...
856
354
# -*- coding: utf-8 -*- """Tests for Bio2BEL FamPlex."""
58
29
from typing import List from pysat.solvers import Solver from ..variables import VarPool from .reductions import ClauseGenerator from ..examples import BaseExamplesProvider from ..logging_utils import * from ..statistics import STATISTICS from ..structures import APTA, DFA, InconsistencyGraph class LSUS: _solve...
4,778
1,326
## -*- coding: UTF8 -*- ## manager.py ## Copyright (c) 2020 libcommon ## ## 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...
22,697
5,871
# -*- coding: utf-8 -*- """mazeexperiment.__main__: executed when mazeexperiment directory is called as script.""" from .mazeexperiment import main main()
160
55
from tweepy import StreamListener, OAuthHandler, Stream from configs import Configs import sys class StdOutListener(StreamListener): def __init__(self, kafka_producer, topic): super().__init__() self.kafka_producer = kafka_producer self.topic = topic """ A listener handles tweets tha...
1,608
513
""" Stability analysis of the D2Q4 solver for the advection equation d_t(u) + c_x d_x(u) + c_y d_y(u) = 0 """ import sympy as sp import pylbm # pylint: disable=invalid-name # symbolic variables U, X, Y = sp.symbols('U, X, Y') # symbolic parameters LA, CX, CY = sp.symbols('lambda, cx, cy', constants=True) S_...
1,717
708
from numpy import reshape def vec(x): return reshape(x, (-1,) + x.shape[2:], order="F") def unvec(x, shape): return reshape(x, shape, order="F")
157
64
# -*- coding: utf-8 -*- # ******************************************************* # Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR C...
3,386
1,091
from django.apps import AppConfig class FunolympicsConfig(AppConfig): name = 'funolympics'
97
34
"""PaccMann vanilla generator trained on polymer building blocks (catalysts/monomers).""" import logging import os from dataclasses import field from typing import ClassVar, Dict, Optional, TypeVar from ....domains.materials import SmallMolecule, validate_molecules from ....exceptions import InvalidItem from ....trai...
5,734
1,440
# -*- coding: utf-8 -*- # import wx import wx.lib.newevent from form.panel.BasePanel import BasePanel from form.parts.SizingFileSet import SizingFileSet from module.MMath import MRect, MVector3D, MVector4D, MQuaternion, MMatrix4x4 # noqa from utils import MFileUtils # noqa from utils.MLogger import MLogger # noqa log...
4,458
1,861
#!/usr/bin/env python """Androguard Gui""" import argparse import os import sys from androguard.core import androconf from androguard.gui.mainwindow import MainWindow from PyQt5 import QtWidgets, QtGui if __name__ == '__main__': parser = argparse.ArgumentParser(description="Androguard GUI") parser.add_argum...
1,261
419
"""Translate strings to and from SOAP 1.2 XML name encoding Implements rules for mapping application defined name to XML names specified by the w3 SOAP working group for SOAP version 1.2 in Appendix A of "SOAP Version 1.2 Part 2: Adjuncts", W3C Working Draft 17, December 2001, <http://www.w3.org/TR/soap12-part2/#...
2,551
1,084
from __future__ import absolute_import, division, print_function from libtbx.utils import null_out from libtbx import easy_pickle from six.moves import cStringIO as StringIO def run_validation(pdb_file, ignore_hd=True): from mmtbx.validation import restraints import mmtbx.command_line cmdline = mmtbx.command_li...
5,939
3,078
# Time: O(n) # Space: O(n) import collections class Solution(object): def findRepeatedDnaSequences(self, s): """ :type s: str :rtype: List[str] """ dict, rolling_hash, res = {}, 0, [] for i in range(len(s)): rolling_hash = ((rolling_hash << 3) & 0x3fff...
887
310
from flask import Flask, render_template, request app = Flask(__name__) @app.route("/") def hello(): return render_template("index.html", name="WORLD!") @app.route("/about") def about(): return render_template("about.html")
231
76
""" Usage: # From tensorflow/models/ # Create train data: python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=train.record # Create test data: python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record """ from __future__ import division from __future__ i...
3,695
1,256
from machine import Pin from lh_lib.sensors.sensor import AbstractSensor class Touch(AbstractSensor): """ This represents a touch sensor with integrated Logic, where there is only one output pin, which digitally represents the touched state. pin:integer can be one of all available GPIO pins: 0-19, ...
685
238
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] rls = [[1]] for i in range(2, numRows+1): row = [1] * i for j in range(1, i-1): row[j] = rls[-1][...
385
134
import os import cv2 import albumentations as A from albumentations.pytorch import ToTensorV2 from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split __all__ = ['CatDogDataset', 'fetch_dataloader'] class CatDogDataset(Dataset): def __init__(self, file_paths, ...
2,579
798
from keras.preprocessing.text import text_to_word_sequence from keras.models import Sequential from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding from keras.layers.recurrent import LSTM from keras.optimizers import Adam, RMSprop from nltk import FreqDist import numpy as np i...
4,203
1,562
"""Standard test images. """ import os from skimage.io import imread data_dir = os.path.abspath(os.path.dirname(__file__)) __all__ = ['data_dir', 'circle', 'skmuscimg'] def _load(f, as_gray=False): """Load an image file located in the data directory. Parameters ---------- f : string F...
2,830
889