text
string
size
int64
token_count
int64
import os import pytest import yaml from pocs.core import POCS from pocs.observatory import Observatory from pocs.utils import error @pytest.fixture def observatory(): observatory = Observatory(simulator=['all']) yield observatory def test_bad_state_machine_file(): with pytest.raises(error.InvalidConf...
837
287
#!/usr/bin/env python3 ############################################################## ## Jose F. Sanchez & Alba Moya ## ## Copyright (C) 2020-2021 ## ############################################################## ''' Created on 28 oct. 2020 @author: alba Mo...
7,033
2,015
import sys from distutils.core import setup import os from glob import glob import zipfile import shutil sys.path.insert(0, os.path.join('resources','library_patches')) sys.path.insert(0, os.path.join('..','..','pupy')) import pp import additional_imports import Crypto all_dependencies=set([x.split('.')[0] for x,m i...
1,729
556
import os import platform import unittest from conans.model.ref import ConanFileReference from conans.test.utils.tools import NO_SETTINGS_PACKAGE_ID, TestClient class ShortPathsTest(unittest.TestCase): @unittest.skipUnless(platform.system() == "Windows", "Requires Windows") def inconsistent_cache_test(self)...
4,742
1,539
#-*- coding: utf-8 -*- # import os # from optparse import OptionParser # from pymongo import MongoClient, bulk # import json # import collections # import sys from import_hedgehogs import * HOST = '45.55.48.43' PORT = 27017 DB = 'SEC_EDGAR' class OrderedDictWithKeyEscaping(collections.OrderedDict): def __setite...
4,086
1,289
import torch import math import time import struct import argparse import numpy as np from collections import OrderedDict if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-model', required=True, help="trained model prefix, also include dir, e.g. ../data/model-100") args =...
2,984
1,040
import typing as t from typing import TYPE_CHECKING import numpy as np import torch import pytest import imageio from detectron2 import model_zoo from detectron2.data import transforms as T from detectron2.config import get_cfg from detectron2.modeling import build_model import bentoml if TYPE_CHECKING: from det...
3,719
1,354
"""Role testing files using testinfra""" def test_config_directory(host): """Check config directory""" f = host.file("/etc/influxdb") assert f.is_directory assert f.user == "influxdb" assert f.group == "root" assert f.mode == 0o775 def test_data_directory(host): """Check data directory""...
1,867
665
#!/usr/bin/env python import cayenne.client, datetime, time, serial # import random #Delay Start #print "Time now = ", datetime.datetime.now().strftime("%H-%M-%S") #time.sleep(60) #print "Starting now = ", datetime.datetime.now().strftime("%H-%M-%S") # Cayenne authentication info. This should be obtained from the Cay...
3,847
1,353
import unittest from mox3.mox import MoxTestBase, IsA from slimta.queue.proxy import ProxyQueue from slimta.smtp.reply import Reply from slimta.relay import Relay, TransientRelayError, PermanentRelayError from slimta.envelope import Envelope class TestProxyQueue(MoxTestBase, unittest.TestCase): def setUp(self)...
1,841
691
import pytest from pypospack.potential import EamPotential symbols = ['Al'] func_pair_name = "bornmayer" func_density_name = "eam_dens_exp" func_embedding_name = "fs" expected_parameter_names_pair_potential = [] expected_parameter_names_density_function = [] expected_parameter_names_embedding_function = [] expected_...
1,912
692
from typing import Dict from main.helpers.print_helper import PrintHelper class Enricher(object): def __init__(self, enricher_type: str, header: str) -> None: self.enricher_type = enricher_type self.header = header def get_information(self, packet: Dict[str, str], information_dict) -> None: ...
417
133
import tkinter as tk import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from pandastable import Table import util.generic as utl class FormUbicacionDesigner(tk.Toplevel): def __init__(self): super().__init__() def initialize_component(self): ...
2,191
767
import coloredlogs coloredlogs.install() custom_logger = logging.getLogger(name) coloredlogs.install(level="INFO", logger=custom_logger)
138
42
import os import versioneer from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() if os.getenv('DEB_BUILD') == 'true' or os.getenv('USER') == 'root': "/usr/share/doc/linuxcnc/examples/sample-configs/sim" # list of (destination, source_file) tuples ...
4,008
1,421
from enum import Enum as _Enum class UsageType(_Enum): CONTROL_LINEAR = () CONTROL_ON_OFF = () CONTROL_MOMENTARY = () CONTROL_ONE_SHOT = () CONTROL_RE_TRIGGER = () DATA_SELECTOR = () DATA_STATIC_VALUE = () DATA_STATIC_FLAG = () DATA_DYNAMIC_VALUE = () DATA_DYNAMIC_FLAG = () ...
4,366
1,402
from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph class LegalDoc: def __init__(self, path): self.path = path styles = getSampleStyleSheet() ...
1,505
488
from datetime import datetime import uuid from sqlalchemy.exc import IntegrityError from dataservice.api.study.models import Study from dataservice.api.participant.models import Participant from dataservice.api.outcome.models import Outcome from dataservice.extensions import db from tests.utils import FlaskTestCase ...
5,627
1,779
def apply(con, target_language="E"): dict_field_desc = {} try: df = con.prepare_and_execute_query("DD03T", ["DDLANGUAGE", "FIELDNAME", "DDTEXT"], " WHERE DDLANGUAGE = '"+target_language+"'") stream = df.to_dict("records") for el in stream: dict_field_desc[el["FIELDNAME"]] = e...
384
134
import logging from werkzeug.utils import cached_property from wtforms import FormField, Form, StringField logger = logging.getLogger(__name__) def get_form_class(validators): class YearMonthDateForm(Form): year = StringField(validators=validators) month = StringField() @cached_property...
1,043
296
#AFTER PREPROCESSING AND TARGETS DEFINITION newdataset.describe() LET_IS.value_counts() LET_IS.value_counts().plot(kind='bar', color='c') Y_unica.value_counts() Y_unica.value_counts().plot(kind='bar', color='c') ZSN.value_counts().plot(kind='bar', color='c') Survive.value_counts().plot(kind='bar', color='c')
310
129
"""Confusion matrix calculation service.""" # coding=utf-8 # import relation package. from pandas_profiling import ProfileReport import pandas as pd import datetime import json # import project package. from config.config_setting import ConfigSetting class EdaService: """Confusion matrix calculation service.""" ...
1,568
459
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
1,385
410
from abc import abstractmethod, ABC from datetime import datetime, timezone from typing import Any, List, Tuple, Dict from blurr.core.base import BaseSchema from blurr.core.store_key import Key, KeyType class StoreSchema(BaseSchema): pass class Store(ABC): """ Base Store that allows for data to be persiste...
4,365
1,238
import time, copy import asyncio class TempRefManager: def __init__(self): self.refs = [] self.running = False def add_ref(self, ref, lifetime, on_shutdown): expiry_time = time.time() + lifetime self.refs.append((ref, expiry_time, on_shutdown)) def purge_all(self): ...
1,411
418
############################################################################### # Name: choicedlg.py # # Purpose: Generic Choice Dialog # # Author: Cody Precord <cprecord@editra.org> # ...
8,775
2,584
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: flower/proto/transport.proto from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection a...
29,068
11,145
version_info = (4, 0, 1) __version__ = ".".join([str(v) for v in version_info])
80
36
from random import randint import pandas as pd def random_11_digit_upc(): upc_string = ''.join(["%s" % randint(0, 9) for num in range(0, 11)]) print(upc_string) return upc_string # Class to calculate the check digit for 11 digit UPC's class CheckDigitCalculations: def __init__(self): self.i...
3,748
1,287
import yaml import forest from forest import main def test_earth_networks_loader_given_pattern(): loader = forest.Loader.from_pattern("Label", "EarthNetworks*.txt", "earth_networks") assert isinstance(loader, forest.earth_networks.Loader) def test_build_loader_given_files(): """replicate main.py as clos...
4,976
1,645
def binarySearch(inputArray, searchElement): minIndex = -1 maxIndex = len(inputArray) while minIndex < maxIndex - 1: currentIndex = (minIndex + maxIndex) // 2 currentElement = inputArray[currentIndex] if currentElement < searchElement: minIndex = currentIndex ...
481
131
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Rule(Model): """NOTE: This class is auto generated by the swagger code g...
4,309
1,317
import os import re import numpy as np # WARNING: this function overrides the mazes in sparse directory; don't run it # as the idea is that everyone test the same mazes def gen_sparses(dir_path): ''' Randomly remove points from dense instances ''' pattern = re.compile('^([0-9]+[a-zA-Z]+)') denses_fn = [x for x...
864
314
""" Analyze JJ IV curve array (core) v.2 BB, 2016 """ import numpy as np from . import jjiv2 as jjiv import sys def fit2rsj_arr(iarr, varr, **kwargs): """Fit IV array to 2 Ic RSJ model and return arrays of fit params, error. Keyword arguments: guess: array of (Ic+, Ic-, Rn, Vo) io: fixed Io. upd...
1,592
568
from leetcode_tester import Tester from typing import Optional, List class Solution: def maxProfit(self, prices: List[int]) -> int: r = 0 for i in range(1, len(prices)): if prices[i] > prices[i - 1]: r += prices[i] - prices[i - 1] return r if __name__ == '__m...
567
230
import torch import json import os from torch.utils.data import DataLoader,Dataset import torchvision.transforms as transforms from PIL import Image import numpy as np data_folder = "./dataset/images" press_times = json.load(open("./dataset/dataset.json")) image_roots = [os.path.join(data_folder,image_file) \ ...
1,406
482
import json from grafana_backup.dashboardApi import create_snapshot def main(args, settings, file_path): grafana_url = settings.get('GRAFANA_URL') http_post_headers = settings.get('HTTP_POST_HEADERS') verify_ssl = settings.get('VERIFY_SSL') client_cert = settings.get('CLIENT_CERT') debug = setting...
921
302
""" Test case for Keras """ from perceptron.zoo.ssd_300.keras_ssd300 import SSD300 from perceptron.models.detection.keras_ssd300 import KerasSSD300Model from perceptron.utils.image import load_image from perceptron.benchmarks.brightness import BrightnessMetric from perceptron.utils.criteria.detection import Targ...
1,928
669
import sys def rand7() -> int: ... class Solution: def rand10(self) -> int: index = sys.maxsize while index > 40: index = 7 * (rand7() - 1) + rand7() - 1 return index % 10 + 1
224
85
from .build import build_transforms from .pre_augmentation_transforms import Resize from .target_transforms import PanopticTargetGenerator, SemanticTargetGenerator
164
42
""" Routines for the analysis of proton radiographs. These routines can be broadly classified as either creating synthetic radiographs from prescribed fields or methods of 'inverting' experimentally created radiographs to reconstruct the original fields (under some set of assumptions). """ __all__ = [ "SyntheticPr...
46,937
13,410
# switch_start.py # Adding another switch statement # Authors : Seoyeon Hwang import string import random class Switch_Start: def __init__(self, str): self.string = str def insert_switch(self, str): #generate random variable _LENGTH = 11 string_pool = string.asci...
924
312
from numpy import array, rad2deg, pi, mgrid, argmin from matplotlib.pylab import contour import matplotlib.pyplot as plt import mplstereonet from obspy.imaging.beachball import aux_plane from focal_mech.lib.classify_mechanism import classify, translate_to_sphharm from focal_mech.io.read_hash import read_demo, read_h...
5,494
2,502
# Copyright (c) 2017 FlashX, LLC # # 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 use, copy, modify, merge, publish, distrib...
3,102
930
import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.ensemble import sklearn.metrics import sklearn import progressbar import sklearn.model_selection from plotnine import * import pdb import sys sys.path.append("smooth_rf/") import smooth_base import smooth_level # function def aver...
7,311
2,461
import numpy as np def CCC(y_true, y_pred): """ Calculate the CCC for two numpy arrays. """ x = y_true y = y_pred xMean = x.mean() yMean = y.mean() xyCov = (x * y).mean() - (xMean * yMean) # xyCov = ((x-xMean) * (y-yMean)).mean() xVar = x.var() yVar = y.var() return 2 * ...
1,147
493
# Copyright (c) 2015 Niklas Rosenstein # # 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 use, copy, modify, merge, publish, ...
11,734
3,278
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 12 13:34:49 2020 @author: lukepinkel """ import numpy as np import scipy as sp import scipy.special def poisson_logp(x, mu, logp=True): p = sp.special.xlogy(x, mu) - sp.special.gammaln(x + 1) - mu if logp==False: p = np.exp(p) ...
333
151
''' Created on Sep 29, 2021 @author: thomas ''' import ImageNetTools import sys import getopt def main(argv): try: opts, args = getopt.getopt(argv,"hd:",["dataset="]) except getopt.GetoptError: printHelp() sys.exit(2) for opt, arg in opts: if opt in...
581
193
""" $ pytest -s -v test_results_render.py """ import logging import pytest from sagas.nlu.results_render import ResultsRender def test_descriptor(): import sagas.nlu.results_render sagas.nlu.results_render.logger.setLevel(logging.DEBUG) # $ str 'Rezervasyonumu onaylamak istiyorum.' results = [{'deli...
1,775
502
import json import math from HistoricalTweetDataFetcher import getHistoricalData joelsarray = getHistoricalData(0) arrs = [] arrm = [] arrp = [] arrsTotal = 0 arrmTotal = 0 ncount = 0 ccount = 0 lcount = 0 time = joelsarray[0]["h"] for dictionary in joelsarray: arrs.append(dictionary["s"]) arrm...
5,838
2,034
from decimal import Decimal as D, ROUND_DOWN, ROUND_UP import math import datetime from django.core import exceptions from django.template.defaultfilters import slugify from django.db import models from django.utils.translation import ungettext, ugettext as _ from django.utils.importlib import import_module from djang...
43,492
12,191
#!/usr/local/bin/python # coding: latin-1 #if you use this code give me credit @tuf_unkn0wn #i do not give you permission to show / edit this script without my credit #to ask questions or report a problem message me on instagram @tuf_unkn0wn """ ██░ ██ ▄▄▄ ▄████▄ ██ ▄█▀▓█████ ▓█████▄ ▓██░ ██▒▒████▄ ▒██▀...
3,288
1,417
d_soldiers = [] class Soldier: def __init__(self, id, name, team): self.id = id self.name = name self.team = team self.x = 0 self.y = 0 self.xVelo = 0 self.yVelo = 0 self.kills = 0 self.deaths = 0 self.alive = 'true' self.driving = 'false' self.gun = 0 self.ammo = 0 self.reloading = 'fa...
2,980
1,460
from dzTrafico.BusinessEntities.Simulation import Simulation import lxml.etree as etree class DataVisualizationController(object): def __init__(self, simulation): # Initialize necessary file paths self.simulation = simulation def get_emissions_results(self): pass def get_travel_t...
785
230
#!/usr/bin/env python3 import collections import logging import os import typing import unicodedata from janome.tokenizer import Tokenizer from transformers.file_utils import cached_path from transformers.models.bert.tokenization_bert import BertTokenizer, WordpieceTokenizer, load_vocab import bunkai.constant """ T...
7,343
2,245
import unittest from datetime import datetime import os import sys from api.exchanges.exchange import ExchangeAPICallFailedException from api.exchanges.gdax_exchange import GdaxExchange from api.exchanges.kraken_exchange import KrakenExchange from api.exchanges.bitstamp_exchange import BitstampExchange from api.exchan...
10,232
3,333
from sklearn.cluster import KMeans import image_processing import numpy as np import some_analysis from sklearn.manifold import TSNE import matplotlib.pyplot as plt from autoencoder import ConvAutoencoder input_path = './bin' output_shape = (32, 48) processing_output = './processed/results_processing' data = image_pro...
1,342
519
""" Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parametro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. """ from Aula22.ex109 import moeda from Aula22.ex109.titulo import titulo preco = float(input("Preço...
572
240
from mocu.utils.toysystems import * import matplotlib.pyplot as plt import matplotlib.cm as cm def make_rhs_full_system(a,b,k,c,lam,psi,theta): def rhs_full_system(y,t): C = c(a,b,k,y[0],psi,theta) y1_dot = lam[0] * (y[0] - 1) y2_dot = lam[1] * (y[1] - C) * (y[1] - a) * (y[1] - b)...
4,787
2,339
""" Several methods for generating graphs from the stochastic block model. """ import itertools import math import random import scipy.sparse import numpy as np def _get_num_pos_edges(c1_size, c2_size, same_cluster, self_loops, directed): """ Compute the number of possible edges between two clusters. :pa...
9,053
2,544
#!/usr/bin/python3 """ | --------------------- Py include <Mauro Baladés> --------------------- | ___ _ _ _ __ _ _ ___ ____ | | |_) \ \_/ | | | |\ | / /` | | | | | | | \ | |_ | |_| |_| |_| |_| \| \_\_, |_|__ \_\_/ |_|_/ |_|__ | -----------------------------------------...
3,496
1,131
import pyensembl import sys import sqlite3 import boto3 import pickle dynamodb = boto3.resource('dynamodb') table_agfusion_gene_synonyms = dynamodb.Table('agfusion_gene_synonyms') table_agfusion_genes = dynamodb.Table('agfusion_genes') table_agfusion_sequences = dynamodb.Table('agfusion_sequences') def add_synonym(da...
7,201
2,311
# Copyright 2017 Google Inc. All Rights Reserved. # # 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 Lice...
10,118
2,866
import numpy as np import matplotlib.pyplot as plt import glob, os, time from ..lib import manageevent as me from ..lib import readECF as rd from ..lib import sort_nicely as sn from ..lib import util, logedit from . import parameters as p from . import lightcurve as lc from . import models as m from .utils import get_t...
10,830
3,229
# Copyright 2021 Sony Semiconductors Israel, Inc. 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 b...
4,724
1,273
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The next steps use just in case to recreate the already existing DB Backup and Delete the folder "migrations" Backup and Delete the file "app.db" Execute the next console commands Linux (venv) $ export FLASK_APP=microblog.py MS Windows (venv) $ set FLASK_APP=microblo...
3,022
1,072
#!/usr/bin/env python3 from .kernel import Kernel from ..functions import RBFCovariance def postprocess_rbf(dist_mat): return dist_mat.div_(-2).exp_() class RBFKernel(Kernel): r""" Computes a covariance matrix based on the RBF (squared exponential) kernel between inputs :math:`\mathbf{x_1}` and :ma...
4,328
1,313
# -*- coding: utf-8 -*- """dependenpy finder module.""" from importlib.util import find_spec from os.path import basename, exists, isdir, isfile, join, splitext class PackageSpec(object): """Holder for a package specification (given as argument to DSM).""" def __init__(self, name, path, limit_to=None): ...
5,132
1,358
import math def contfractbeta(a: float, b: float, x: float, itmax: int = 200) -> float: # https://malishoaib.wordpress.com/2014/04/15/the-beautiful-beta-functions-in-raw-python/ # evaluates the continued fraction form of the incomplete Beta function; incompbeta() # code translated from: Numerical Recipes ...
1,738
689
# Generic/Built-in import datetime import math import os import numpy as np import matplotlib.pyplot as plt import pandas as pd import pvlib from dataclasses_json import dataclass_json from typing import Optional from dataclasses import dataclass from functools import lru_cache from hisim.simulationparameters import S...
33,018
9,987
""" //////////////////////////////////////////////////////////////////////////// // // Copyright (C) NVIDIA Corporation. All rights reserved. // // NVIDIA Sample Code // // Please refer to the NVIDIA end user license agreement (EULA) associated // with this source code for terms and conditions that govern your...
1,843
472
#from http://rosettacode.org/wiki/Greatest_subsequential_sum#Python #pythran export maxsum(int list) #pythran export maxsumseq(int list) #pythran export maxsumit(int list) #runas maxsum([0, 1, 0]) #runas maxsumseq([-1, 2, -1, 3, -1]) #runas maxsumit([-1, 1, 2, -5, -6]) def maxsum(sequence): """Return maximum sum."...
1,541
561
__all__ = ["Binwalk"] import os import re import time import magic from binwalk.compat import * from binwalk.config import * from binwalk.update import * from binwalk.filter import * from binwalk.parser import * from binwalk.plugins import * from binwalk.plotter import * from binwalk.hexdiff import * from binwalk.entr...
28,280
10,059
def task_clean_junk(): """Remove junk file""" return { 'actions': ['rm -rdf $(find . | grep pycache)'], 'clean': True, }
149
52
#Uses python3 import sys def largest_number(a): #write your code here res = "" while len(a)!=0: maxa = a[0] for x in a: if int(str(x)+str(maxa))>int(str(maxa)+str(x)): maxa = x res += str(maxa) a.remove(str(maxa)) return res if __name__ == '...
442
168
import logging import subprocess class PlayingState: Inactive = 0 Active = 1 class ProfileBase: def __init__(self): raise NotImplementedError() def on_start_playing(self): raise NotImplementedError() def on_stop_playing(self): raise NotImplementedError() def on_pla...
2,403
780
# -*- coding: utf-8 -*- import os import urllib.parse from datetime import date, datetime from functools import partial from urllib.parse import quote_plus import pandas as pd import plotly.express as px import pytz from csci_utils.luigi.requires import Requirement, Requires from csci_utils.luigi.target import Target...
6,136
1,840
#!/usr/bin/env python3 def test(): cedTest = ["U²sgal²sdi ạ²dv¹ne²³li⁴sgi.", "Ụ²wo²³dị³ge⁴ɂi gi²hli a¹ke²³he³²ga na ạ²chu⁴ja.", "Ạ²ni²³tạɂ³li ạ²ni²sgạ²ya a¹ni²no²hạ²li²³do³²he, ạ²hwi du¹ni²hyọ²he.", "Sa¹gwu⁴hno ạ²sgạ²ya gạ²lo¹gwe³ ga²ne²he sọ³ɂị³hnv³ hla².", "Na³hnv³ gạ...
4,779
2,217
import pytest from django.test import TestCase, Client from django.core.urlresolvers import reverse from molo.core.tests.base import MoloTestCaseMixin from molo.core.models import Main, SiteLanguageRelation, Languages from molo.usermetadata.models import PersonaIndexPage, PersonaPage from wagtail.wagtailcore.models i...
2,585
791
import psycopg2 url = "dbname='da43n1slakcjkc' user='msqgxzgmcskvst' host='ec2-54-80-184-43.compute-1.amazonaws.com' port=5432 password='9281f925b1e2298e8d62812d9d4e430c1054db62e918c282d7039fa85b1759fa'" class database_setup(object): def __init__(self): self.conn = psycopg2.connect(url) self.curs...
1,793
585
from constants import cursor def add_message(player_name, message): cursor.execute( "INSERT INTO levelup.messages (" "SENDER, MESSAGE" ") VALUES (" "%s, %s" ")", (player_name, message) ) def reset(): cursor.execute( "DELETE FROM levelup.messages" ...
780
256
import numpy as np import shapely.geometry as geom class Bbox: def __init__(self, name, part_id, depth_image, xyz, box_size, projection): if not isinstance(xyz, np.ndarray): raise ValueError("xyz must be an np.ndarray") self.name = name self.id = part_id self.center = np...
3,248
1,277
from django.contrib import admin from .models import Tag, Article @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ('name', 'order') list_editable = ('order',) @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'author'] readonly_fields = ['...
351
111
#!/usr/bin/env python3 # Copyright (c) 2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Useful Script constants and utils.""" from test_framework.script import CScript # To prevent a "tx-size-sma...
1,326
463
#!/usr/bin/env python # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesser General ...
4,085
1,246
from __future__ import print_function, unicode_literals from binascii import unhexlify from enum import Enum import os import pwd import six from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, Enum as SQLAEnum, Numeric from sqlalchemy import event from sqlalchemy.dialects.postgresql import HSTOR...
12,418
3,850
import os import numpy as np import pytest import vtk import pyvista from pyvista import examples from pyvista.plotting import system_supports_plotting beam = pyvista.UnstructuredGrid(examples.hexbeamfile) # create structured grid x = np.arange(-10, 10, 2) y = np.arange(-10, 10, 2) z = np.arange(-10, 10, 2) x, y, z...
15,226
5,962
import asyncio import logging from collections import defaultdict from typing import Optional, List, Dict from aiohttp import web from aiohttp.web_runner import AppRunner, TCPSite from quadradiusr_server.auth import Auth from quadradiusr_server.config import ServerConfig from quadradiusr_server.cron import Cron, Setu...
5,767
1,693
def gfg(x,l = []): for i in range(x): l.append(i*i) print(l) gfg(2) gfg(3,[3,2,1]) gfg(3)
95
63
import json, pickle, sys, os from parmed.geometry import distance2 from parmed.topologyobjects import Atom import operator import parmed import math def check_same(atom, chain, res_name, res_number, atom_name): if atom.residue.name == res_name: if atom.residue.number == res_number: if atom.nam...
2,638
949
"""Module help_info.""" __author__ = 'Joan A. Pinol (japinol)' class HelpInfo: """Manages information used for help purposes.""" def print_help_keys(self): print(' F1: \t show a help screen while playing the game' ' t: \t stats on/off\n' ' L_Ctrl + R_Alt + g...
1,111
383
import warnings warnings.simplefilter('ignore') import argparse import pickle import numpy as np import pandas as pd import networkx as nx import scipy.sparse as sp from network_propagation_methods import minprop_2 from sklearn.metrics import roc_auc_score, auc import matplotlib.pyplot as plt #### Parameters ########...
3,983
1,490
n = [] i = 0 for c in range(0, 5): n1 = int(input('Digite um valor: ')) if c == 0 or n1 > n[-1]: n.append(n1) print(f'Adicionado na posição {c} da lista...') else: pos = 0 while pos < len(n): if n1 <= n[pos]: n.insert(pos, n1) print...
459
167
import cv2 import numpy as np import random import copy import dlib from keras.models import Sequential from keras.optimizers import SGD from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, F...
13,132
4,253
######################################################################################################################## # # # This file is part of kAIvy ...
3,720
997
import copy from pathlib import Path from typing import Dict, Union, List from collections import defaultdict import numpy as np from typeguard import typechecked from zsvision.zs_utils import memcache, concat_features from utils.util import memory_summary from base.base_dataset import BaseDataset class MSVD(BaseDa...
5,813
1,800
from django import forms from django.forms.models import inlineformset_factory from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailadmin.widgets import AdminPageChooser from wagtail.wagtailsearch import models class QueryForm(forms.Form): query_string = forms.CharField(label=_("Search ter...
2,381
702
""" Copyright BOOSTRY 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 agreed to in writing, software distr...
6,994
1,961
import os import sys sys.path.insert(0, "../../") import matchzoo as mz import typing import pandas as pd import matchzoo from matchzoo.preprocessors.units.tokenize import Tokenize, WordPieceTokenize from matchzoo.engine.base_preprocessor import load_preprocessor import pickle import utils os.environ["CUDA_VISIBLE_D...
2,282
868