text
string
size
int64
token_count
int64
import pint as Q class Quantity: """ Enables the use of measurement units in our statements """ ur = Q.UnitRegistry() @classmethod def parse(self, s): q = self.ur.Quantity(s) my_q = Quantity(0,"mL") my_q._quant = q return my_q def __init__(self, value, unit): ...
637
207
from itertools import chain from django.db import models from random import choices class Node(object): def neighbors(self): raise NotImplementedError def graph(self, depth=1): if not depth: return {self: set()} elif depth == 1: return {self: set(self.neighbors...
4,752
1,553
#!/usr/bin/env ipy import clr clr.AddReference("MyMediaLite.dll") clr.AddReference("MyMediaLiteExperimental.dll") from MyMediaLite import * train_file = "trainIdx1.firstLines.txt" validation_file = "validationIdx1.firstLines.txt" test_file = "testIdx1.firstLines.txt" # load the data training_data = IO.K...
1,076
412
"""KB mapping resource.""" from __future__ import absolute_import, division, print_function, unicode_literals from ..base import BaseResource class Mapping(BaseResource): """Knowledge base Mapping resource.""" endpoint = 'kb.mapping.admin' query_endpoint = 'kb.mapping.search' query_method = 'POST' ...
754
248
"""Scans a given path (folder) for .wav files recursively and plots them all into files.""" from pathlib import Path, PurePath import matplotlib.pyplot as plt import numpy as np from numpy import fft as fft import click import scipy.io.wavfile from wavlength import get_files, plot_wav def analyze_and_plot(wavfile, ou...
1,293
421
#!/usr/bin/env python3 """ OCR with the Tesseract engine from Google this is a wrapper around pytesser (http://code.google.com/p/pytesser/) """ import config as cfg from lib.process import get_simple_cmd_output def image_file_to_string(fname): """Convert an image file to text using OCR.""" cmd = "{tesseract...
456
159
#!/usr/bin/env python3 import gimpbbio.gpio as gpio import serial import re import http.client import urllib import threading import queue import sys import datetime import time import socket import logging import logging.handlers import argparse import Adafruit_BMP.BMP085 as BMP085 class MyLogger(object): def __ini...
4,848
1,843
"""empty message Revision ID: 0e26a2d71475 Revises: Create Date: 2021-03-19 00:13:23.019330 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0e26a2d71475' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
852
316
# Functions print("************* Function ***********") # Simple function without any arguments/parameters def say_welocme(): return print('Welocme') # Simple function with arguments/parameters def say_helo(name, age): print('Helo', name, age) # this function returns None say_helo('Nayeem', 18) #...
9,510
2,648
screen_resX=1920 screen_resY=1080 img_id=['1.JPG_HIGH_', '2.JPG_HIGH_', '7.JPG_HIGH_', '12.JPG_HIGH_', '13.JPG_HIGH_', '15.JPG_HIGH_', '19.JPG_HIGH_', '25.JPG_HIGH_', '27.JPG_HIGH_', '29.JPG_HIGH_', '41.JPG_HIGH_', '42.JPG_HIGH_',...
3,763
1,694
from django.contrib.auth import authenticate, login, logout as django_logout from django.contrib.auth import get_user_model from django.http import HttpResponseRedirect from django.conf import settings from django.core.urlresolvers import reverse from twython import Twython from profiles.models import Profile def log...
3,219
925
import helper from helper import greeting def main(): #print("called hello") helper.greeting("hello") if __name__ == '__main__': main()
140
48
def create_matrix(rows_count): matrix = [] for _ in range(rows_count): matrix.append([int(x) for x in input().split(', ')]) return matrix def get_square_sum(row, col, matrix): square_sum = 0 for r in range(row, row + 2): for c in range(col, col + 2): square_sum += matri...
989
354
''' Find the largest element and place that element at the bottom of the list. Repeat for each sub-array. O(n^2) time complexity. ''' from string import ascii_letters arrays = ( [12, 3, 7, 22, -12, 100, 1], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], [4, 1, 3, 9, 7], [0, -1.5, 1.5, 1.3, -1.3, -1.01, 1.01], list(revers...
756
389
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext_lazy as _ from djangocms_html_tags.forms import HTMLTextInputForm, HTMLFormForm, HTMLTextareaForm from djangocms_html_tags.models import HTMLTag, HTMLText from djangocms_html_tags.utils impor...
2,535
832
# команда меню "права пользователей" from aiogram.types import Message, CallbackQuery, ReplyKeyboardRemove from filters import IsAdmin from loader import dp, db, bot from keyboards.inline.callback_data import change_button_data from keyboards.inline.callback_data import set_status_data from keyboards.inline.callback_...
4,659
1,666
import helpers import exceptions import datetime as dt ''' This is the sessions module: ''' ''' Base class with the basic structure of all frontend sessions. ''' class Session: # username is None when no one logged in. def __init__(self, username = None): self.username = username # return with t...
12,878
3,370
#!/usr/bin/env python3 # Diodes "1N4148" "1N5817G" "BAT43" # Zener "1N457" # bc junction of many transistors can also be used as dioded, i.e. 2SC1815, 2SA9012, etc. with very small leakage current (~1pA at -4V).
215
111
from pageobject import PageObject from homepage import HomePage from locatormap import LocatorMap from robot.api import logger class LoginPage(): PAGE_TITLE = "Login - PageObjectLibrary Demo" PAGE_URL = "/login.html" # these are accessible via dot notaton with self.locator # (eg: self.locator.usernam...
1,574
478
'''Maps buttons for the Reefbot control.''' import roslib; roslib.load_manifest('reefbot-controller') import rospy class JoystickButtons: DPAD_LR = 4 DPAD_UD = 5 ALOG_LEFT_UD = 1 ALOG_LEFT_LR = 0 ALOG_RIGHT_UD = 3 ALOG_RIGHT_LR = 2 BUTTON_1 = 0 BUTTON_2 = 1 BUTTON_3 = 2 BUTTON_4 = 3 BUTTON_...
2,569
971
import os os.environ.setdefault("MONGO_URI", "mongodb+srv://root:Thisisarandompassword@myfirstcluster-qpzww.mongodb.net/theRecipe?retryWrites=true&w=majority")
159
60
# coding: utf-8 # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from __future__ import absolute_import import sys import unittest im...
1,482
487
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional from parlai.core.params import ParlaiParser from parlai.core.opt import Opt import os impo...
1,803
567
# Listing_7-1.py # Copyright Warren & Carter Sande, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # Using comparison operators num1 = float(raw_input("Enter the first number: ")) num2 = float(raw_input("Enter the second ...
614
217
""" Convolutional Neural Network for facial landmarks detection. """ import argparse import cv2 import numpy as np import tensorflow as tf from model import LandmarkModel # Add arguments parser to accept user specified arguments. parser = argparse.ArgumentParser() parser.add_argument('--train_record', default='train...
6,658
2,044
import skimage.io # bug. need to import this before tensorflow import skimage.transform # bug. need to import this before tensorflow from resnet_train import train from resnet import inference import tensorflow as tf import time import os import sys import re import numpy as np from image_processing import image_pre...
2,593
880
import os from datetime import datetime from PIL import Image, ImageDraw, ImageFont from pySmartDL import SmartDL from telethon.tl import functions from uniborg.util import admin_cmd import asyncio import shutil import random, re FONT_FILE_TO_USE = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" #Add telegraph ...
2,305
860
import os, sys class Preprocesser(): def __init__(self): self.data = { "X": [], "Y": [] } def process(self, input): if not os.path.isfile(input): print(input + " is not exists.") sys.exit(-1) with open(input) as in_file: ...
514
158
# import discord # import asyncio # import json # from discord.ext import commands # from discord.utils import get # # from cogs.personalPoint import PersonalPoint # from main import client # from discord_ui import UI,Button # from functions.userClass import User,experiences,levelNames # from cogs.rank import getSorted...
34,938
9,548
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class WirelessHotStandbyGridRemote(RemoteModel): """ | ``id:`` none | ``attribute type:`` string | ``WlsHotSbTimestamp:`` none | ``attribute type:`` string | ``MonitoredIPD...
1,680
567
from pyrr.geometric_tests import ray_intersect_sphere try: import unittest2 as unittest except: import unittest import numpy as np from pyrr import geometric_tests as gt from pyrr import line, plane, ray, sphere class test_geometric_tests(unittest.TestCase): def test_import(self): import pyrr ...
11,717
4,905
# 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,462
1,923
# Copyright 2021 EnICS Labs, Bar-Ilan University. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import sys, os sys.path.append(os.path.abspath('..')) from salamandra import * def main(): test(is_metatest=False) def test(is_metatest): inv = ...
1,807
815
''' update rule for the DQN model is defined ''' ''' Preprocessing : give only hsv value or masked end efforctor image Downsample pixel and convert RGB to grayscale Use nn.functional where there is no trainable parameter like relu or maxpool Try pooling vs not pooling In Atari they consider multiple frames to find dir...
4,109
1,352
from .protocol import Resp from flask import make_response import pandas as pd class Utils: @staticmethod def build_resp(error_no: int, msg: str, data: dict): return make_response(Resp(error_no, msg, data).to_json()) @staticmethod def treat_bar(data: pd.DataFrame) -> dict: # data = da...
923
294
from rest_framework import viewsets, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated import redis import os import json from core.models import Tag, Ingredient from recipe import serializers # Connect to our Redis instance redis_instance = r...
2,626
744
import random import numpy as np import torch from torch import nn from torchbenchmark.tasks import OTHER from ...util.model import BenchmarkModel torch.manual_seed(1337) random.seed(1337) np.random.seed(1337) # pretend we are using MLP to predict CIFAR images class MLP(nn.Module): def __init__(self): ...
2,468
864
clientId = 'CLIENT_ID' clientSecret = 'CLIENT_SECRET' geniusToken = 'GENIUS_TOKEN' bitrate = '320'
99
46
import os import sys sys.path.append(os.getcwd()) import utils.runners as urun # # Dropout is `keep_prob` probability not `dropout rate` (as in TF2.x) # if __name__ == "__main__": exp_folder = "experiments_2" exp = "bs3_exp11" exp_rev = "2" runner = urun.get_runner(sys.argv[1]) run = 0 for h...
654
267
""" AQ6315E DATA EXTRACTOR Extracts all visible traces from Ando AQ-6315E Optical Spectrum Analyser Usage: ./aq6315.py [filename] If specified, extracted data is saved to CSV called "filename" Relevant list of commands available at http://support.us.yokogawa.com/downloads/TMI/COMM/AQ6317B/AQ6317B%20R0101.pdf ...
2,003
723
from src.uint8 import uint8 def test_constructor1(): assert int(uint8(20)) == 20 def test_constructor2(): assert uint8(256) == uint8(0) assert uint8(260) == uint8(4) assert uint8(-1) == uint8(255) assert uint8(-5) == uint8(251) assert uint8(-5) != uint8(252) def test_add_other(): asser...
1,707
823
#!/usr/bin/env python def test_ldc(): import numpy as np import os from read_single_field_binary import read_single_field_binary data_ref = np.loadtxt("data_ldc_re1000.txt") if "data_x" in os.getcwd(): data,xp,yp,zp,xu,yv,zw = read_single_field_binary("vey_fld_0001500.bin",np.array([1,1,1]))...
1,042
481
""" icons index """ import zoom class MyView(zoom.View): """Index View""" def index(self): """Index page""" zoom.requires('fontawesome4') content = zoom.tools.load('icons.html') subtitle = 'Icons available as part of FontAwesome 4<br><br>' return zoom.page(content,...
638
204
''' This script takes one 'npy' file that contains market data of multiple markets and produces 3 files "train.npy", "test.npy", "val.npy". The script calculates the mean image of the dataset and substracts it from each image. ''' import numpy as np def save_file(dir, data): np.save(dir, data) print(f"save...
1,096
410
#! /usr/bin/env python import rospy import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from tf.transformations import quaternion_from_euler from std_msgs.msg import UInt8 from enum import Enum #region ################## TODOLIST ######################## # DONE 1. Add Task class and make othe...
8,352
2,539
# import the function that will return an instance of a connection from mysqlconnection import connectToMySQL # model the class after the friend table from our database class User: def __init__( self , data ): self.id = data['id'] self.first_name = data['first_name'] self.last_name = data['l...
1,426
389
import os import asyncio from typing import List import traceback import pyppeteer from pyppeteer.page import Page from tqdm import tqdm import pdb import time from tiktokpy.client import Client from tiktokpy.utils.client import catch_response_and_store, catch_response_info, get_dt_str, trans_char from t...
21,488
6,810
import json import time import sys from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_con...
2,927
849
import os import plugin import pluginconf util = plugin.get("util") FILE_COUNTER = "~/.vpn_counter" FILE_VPN_SH = "~/.vpn_sh" EXPECT_SCRIPT = """#!/usr/bin/expect spawn {cmd} expect -exact "Enter Auth Username:" send -- "{user}\\n" expect -exact "Enter Auth Password:" send -- "{password}\\n" interact """ class V...
1,656
575
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) from abc import ABCMeta, abstractmethod from Crypto import Random from jasypt4py.exceptions import ArgumentError class PBEParameterGenerator(object): __metaclass__ = ABCMeta @staticmethod def adjust(a, a_o...
7,321
2,463
""" Binary Ninja plugin for recovering kernel build configuration settings using BNIL """ import argparse import logging from binaryninja import (BinaryViewType, BinaryView, PluginCommand, SaveFileNameField, get_form_input, BackgroundTaskThread) class RecoverKConfigBackground(BackgroundTaskTh...
2,862
811
from openapi_core.schema.exceptions import OpenAPIMappingError class OpenAPIOperationError(OpenAPIMappingError): pass class InvalidOperation(OpenAPIOperationError): pass
182
49
import numpy as np from gym import spaces from gym import Env #from rlkit.envs.mujoco.half_cheetah import HalfCheetahEnv from rlkit.envs import register_env @register_env('cheetah-vel') class HalfCheetahVelEnv(Env): def __init__(self, task={}, n_tasks=2, randomize_tasks=True, max_episode_steps=200): ...
1,811
650
# -*- coding: utf-8 -*- from openprocurement.api.validation import ( validate_json_data, validate_data, validate_accreditation_level, validate_accreditation_level_mode, ) from openprocurement.api.utils import update_logging_context, error_handler, upload_objects_documents from openprocurement.planning.a...
6,812
2,055
# Importando librerías from numpy import array # Listas y arreglos a = array(['h', 101, 'l', 'l', 'o']) x = ['h', 101, 'l', 'l', 'o'] print(a) print(x) print("Tamaño: ", len(x)) # Condicionales if isinstance(x[1], int): x[1] = chr(x[1]) elif isinstance(x[1], str): pass else: raise TypeError("Tipo no sop...
1,176
536
import math SCREEN_WIDTH = 1400 SCREEN_HEIGHT = 800 TEXT = (5, 5) FPS = 60 BASE_SIZE = 10 EYE_SIZE = 4 PUPIL_SIZE = EYE_SIZE - 2 BASE_SPEED = 2 MIN_DISTANCE = 1 MAX_DISTANCE = MIN_DISTANCE + 3 SIZE_INC = 15 EYE_INC = SIZE_INC * 4 PUPIL_INC = SIZE_INC * 8 GROWTH_INC = SIZE_INC * 20 BOOST_MIN = 10 BOOST_FACTOR = 2 BOO...
3,751
1,481
from fastapi import APIRouter, Depends, status from fastapi.security import OAuth2PasswordRequestForm from sqlalchemy.orm import Session from app.controllers.authControllers import login_user, register_user from app.schemas.users import UserCreate from app.schemas.tokens import Token from app.config.database import get...
831
267
import chainer import chainer.functions as F import chainer.links as L class VGGNet(chainer.Chain): """ VGGNet - It takes (224, 224, 3) sized image as imput """ def __init__(self, n_class=1000): super(VGGNet, self).__init__() with self.init_scope(): self.conv1_1 = L.C...
2,222
1,075
import sqlite3 import requests from bs4 import BeautifulSoup from login import keys import config ARTICLE_SEARCH_URL = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key={key}' SUNLIGHT_CONGRESS_URL = 'http://congress.api.sunlightfoundation.com/{method}?{query}&apikey={key}' def get_json(url): ret...
2,147
703
# load modules from dataclasses import dataclass from typing import Union from ...beatsaver.entity import UserDetail # definition class @dataclass(frozen=True) class MapTestplay: createdAt: str feedback: str feedbackAt: str user: Union[UserDetail.UserDetail, None] video: str # definition funct...
850
238
#! /usr/bin/env python # -*- coding: utf-8 -*- """docstring""" from __future__ import print_function, unicode_literals import argparse import sys from .settingsdiff import dump_settings, diff_settings def main(): parser = argparse.ArgumentParser() parser.add_argument( "settings_path_1", nar...
1,425
448
import os import types import typing import numpy as np import constants import environment import policy import update class EvaluateEnv: def __init__(self, show_details: bool = True): self.env_obj = environment.Easy21Env() self.show_details = show_details def reset(self): self.env_...
5,283
1,729
import unittest from axelrod import Action, MockPlayer, Player C, D = Action.C, Action.D class TestMockPlayer(unittest.TestCase): def test_strategy(self): for action in [C, D]: m = MockPlayer(actions=[action]) p2 = Player() self.assertEqual(action, m.strategy(p2)) ...
502
161
import os import datetime import numpy as np from jinja2 import Template from scipy.stats import hypergeom import matplotlib.pyplot as plt import covidtracker as ct from covidtracker.dataloader import DataLoader from covidtracker.models import update_samples from covidtracker.plotter import plot_interval def plot_grad...
10,870
4,176
''' Created on Jun 15, 2016 @author: eze ''' class NotFoundException(Exception): ''' classdocs ''' def __init__(self, element): ''' Constructor ''' self.elementNotFound = element def __str__(self, *args, **kwargs): return "NotFoundException(%s)" %...
359
107
# Solution to the practise problem # https://automatetheboringstuff.com/chapter6/ # Table Printer def printTable(tableList): """Prints the list of list of strings with each column right justified""" colWidth = 0 for row in tableList: colWidth = max(colWidth, max([len(x) for x in row])) col...
782
253
import torch import torch.nn as nn from ..utils.torch import pack_forward from .pooling import GatherLastLayer class CharEncoder(nn.Module): FORWARD_BACKWARD_AGGREGATION_METHODS = ["cat", "linear_sum"] def __init__( self, char_embedding_dim, hidden_size, char_fw_bw_agg_method...
4,727
1,634
import json import uuid from dataclasses import dataclass from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar from serflag import SerFlag from handlers.graphql.graphql_handler import ContextProtocol from handlers.graphql.utils.string import camelcase from xenadapter.task import ge...
7,458
2,045
import os import shutil import subprocess from distutils.dir_util import copy_tree from shutil import copyfile from typing import List, Optional import click import git from omegaconf import DictConfig def copy_objects(target_dir: os.PathLike, objects_to_copy: List[os.PathLike]): for src_path in objects_to_copy:...
3,383
1,132
from django import template from django.utils import timezone register = template.Library() @register.filter def sold(oil, delta_months='12'): total = 0 curTime = timezone.localtime(timezone.now()) from_time = curTime - timezone.timedelta(days=int(delta_months)*30) for t in oil.trades.filter(dateTime...
2,011
658
from datetime import datetime import py42.util as util def test_convert_timestamp_to_str_returns_expected_str(): assert util.convert_timestamp_to_str(235123656) == "1977-06-14T08:07:36.000Z" def test_convert_datetime_to_timestamp_str_returns_expected_str(): d = datetime(2020, 4, 19, 13, 3, 2, 3) assert...
393
183
#!/usr/bin/env python """Script for fetching my min and max heart rate over the past 15 minutes.""" import time from config import * from gather_keys_oauth2 import OAuth2Server if __name__ == '__main__': server = OAuth2Server(client_id, client_secret) server.browser_authorize() fb = server.fitbit det...
849
283
import argparse import collections import os import cv2 import numpy as np import pandas as pd import pretrainedmodels import torch import torch.optim as optim import torchsummary from torch.optim import lr_scheduler from torch.utils.data import DataLoader from torchvision import datasets, models, transforms from tqdm...
11,891
3,991
# MIT License # Copyright (c) 2017 GiveMeAllYourCats # 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, mer...
47,312
13,975
import functools import numpy as np def dft2(f, alpha, npix=None, shift=(0, 0), offset=(0, 0), unitary=True, out=None): """Compute the 2-dimensional discrete Fourier Transform. This function allows independent control over input shape, output shape, and output sampling by implementing the matrix triple p...
8,392
2,767
from setuptools import setup, find_packages setup( name = 'Flask-Digest', version = '0.2.1', author = 'Victor Andrade de Almeida', author_email = 'vct.a.almeida@gmail.com', url = 'https://github.com/vctandrade/flask-digest', description = 'A RESTful authentication service for Flask applicatio...
999
301
class Contact: def __init__(self, first_name = None, last_name = None, mobile_phone = None): self.first_name = first_name self.last_name = last_name self.mobile_phone = mobile_phone
210
64
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import math import random import numpy as np import matplotlib.pyplot as plt from scipy.constants import N_A from numba import jit import copy __author__ = "Ronald Kam, Evan Spotte-Smith, Xiaowei Xie" __email_...
42,143
12,309
from __future__ import division import sys import numpy from numpy.core import * import vtk from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk import vtkbone import traceback import unittest class TestLinearOrthotropicMaterial (unittest.TestCase): def test_isotropic (self): material = vtkbone...
7,816
2,938
#!/usr/bin/env python import os import argparse import tensorflow as tf import numpy as np from PIL import Image def _int64_feature(values): if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) def _bytes_feature(values): ...
3,376
1,076
""" notebook imports """ from __future__ import absolute_import import warnings import ipywidgets import IPython from .notebooktools import * from .ontologysearch import OntologySearch from .parameterslider import ParameterSlider from .speciessearch import SearchBySpeciesForm # except ImportError: # warnings.war...
391
105
''' Created on 2018-12-21 Copyright (c) 2018 Bradford Dillman Generate code from a model and a jinja2 template. ''' import logging from pathlib import Path from jinja2 import FileSystemLoader, Environment from jinja2.exceptions import TemplateNotFound from munch import munchify from fashion.mirror import Mirror ...
2,297
665
class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ pl = [] ret = [0] * len(S) for i in range(0, len(S)): if S[i] == C: pl.append(i) for i in range(...
622
238
# Optional solution with tidy data representation (providing x and y) monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt( id_vars="datetime", var_name="victim_type", value_name="count" ) sns.relplot( data=monthly_victim_counts_melt, x="datetime", y="count", hue="victim_type", ...
386
149
def findSmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): newarr = [] for i in range(len(arr)): smallest...
488
191
from ....utils.byte_io_mdl import ByteIO from ....shared.base import Base
73
22
{ 'Hello World':'Salve Mondo', 'Welcome to web2py':'Ciao da wek2py', }
71
32
domain='https://monbot.hopto.org' apm_id='admin' apm_pw='New1234!' apm_url='https://monbot.hopto.org:3000' db_host='monbot.hopto.org' db_user='izyrtm' db_pw='new1234!' db_datadbase='monbot'
190
101
import sys if len(sys.argv) < 2: print('Need the dataset name!') exit(0) for split in ['train', 'valid', 'test']: with open('data/'+sys.argv[1]+'/'+split+'.txt', 'r') as f1, open( 'data/'+sys.argv[1]+'_pos_only/'+split+'.txt', 'r') as f2, open( 'data/'+sys.argv[1]+'_pos/'+split...
721
261
def norm(x, ord=None, axis=None): # TODO(beam2d): Implement it raise NotImplementedError def cond(x, p=None): # TODO(beam2d): Implement it raise NotImplementedError def det(a): # TODO(beam2d): Implement it raise NotImplementedError def matrix_rank(M, tol=None): # TODO(beam2d): Implemen...
1,307
433
import numpy from shadow4.sources.source_geometrical.source_geometrical import SourceGeometrical from shadow4.beamline.optical_elements.refractors.s4_conic_interface import S4ConicInterface, S4ConicInterfaceElement from shadow4.tools.graphics import plotxy from shadow4.syned.element_coordinates import ElementCoord...
2,771
1,039
import subprocess from setuptools import setup, find_packages, Extension setup( name='transabyss', version='1.54', author='transabyss', license='Free Software License', packages=['transabyss'], scripts=['scripts/transabyss', 'scripts/transabyss-merge'], )
281
87
from .classes import Entry, EntryJso from .spec_version import SPEC_VERSION from .version import version as __version__ # noqa: F401 from .version import version_tuple as __version_info__ # noqa: F401 __all__ = ["Entry", "EntryJso", "SPEC_VERSION"]
252
86
# /////////////////////////////////////////////////////////////// # # BY: WANDERSON M.PIMENTA # PROJECT MADE WITH: Qt Designer and PySide6 # V: 1.0.0 # # This project can be used freely for all uses, as long as they maintain the # respective credits only in the Python scripts, any information in the visual # interface ...
1,816
533
from multiprocessing.dummy import Value from agents.Base_Agent import Base_Agent import copy import numpy as np import torch import torch.nn.functional as F from torch.optim import Adam class RunningMeanStd(object): # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm def _...
9,939
3,021
#!/usr/bin/env python # -*- coding: UTF-8 -*- import pandas as pd from pandas import DataFrame from spacy.lang.en import English from tabulate import tabulate from base import BaseObject class PerformPosParse(BaseObject): """ Perform POS (Part-of-Speech) Parse with spaCy Sample Input: Amoebozoa is...
6,079
1,836
from causal_world.intervention_actors.base_actor import \ BaseInterventionActorPolicy import numpy as np class VisualInterventionActorPolicy(BaseInterventionActorPolicy): def __init__(self, **kwargs): """ This intervention actor intervenes on all visual components of the robot, (i.e: ...
2,229
557
import csv import time from datetime import datetime from prettytable import PrettyTable from .api import countries, country, totals, us_states def to_csv(data): fieldnames = set() for event in data: fieldnames |= event.keys() with open("%s.csv" % int(time.time()), "w", newline="") as c: ...
3,259
947
from collections import OrderedDict, defaultdict from contextlib import contextmanager from datetime import datetime import torch.cuda from ..viz.plot import plot_timeline def time(name=None, sync=False): return Task(name=name, sync=sync, log=True) class Task: __slots__ = ('name', 'start_time', 'end_time', 'met...
2,879
1,006
import os from conans.errors import ConanException from conans.util.files import save, load, normalize from conans.model.settings import Settings from conans.client.conf import ConanClientConfigParser, default_client_conf, default_settings_yml from conans.model.values import Values from conans.client.detect import det...
6,731
1,942