text
string
size
int64
token_count
int64
import mysql.connector as mydb conn = mydb.connect( host='mysql_container', port='3306', user='docker', password='docker', database='my_db' ) conn.is_connected()
184
66
from django.db import models class Exam(models.Model): """Exam Model""" class Meta(object): verbose_name = 'Іспит' verbose_name_plural = 'Іспити' title = models.CharField( max_length=256, blank=False, verbose_name='Назва предмету') datetime = models.DateTimeF...
752
253
from __future__ import unicode_literals import frappe from frappe import _ from datetime import datetime, timedelta, date, time from frappe.utils import getdate, get_time, flt, now_datetime from frappe.utils import escape_html from frappe import throw, msgprint, _ @frappe.whitelist() def get_schedule(): time_sched...
2,201
724
''' goalboost.model package The goalboost model package consists of MongoEngine models along with Marshmallow schemas. MongoEngine is our database ORM to MongoDB, and Marshmallow is a serialization library that helps us validate, consume, and expose these Orm objects for clients that need it at the API layer. For Mon...
647
191
# Copyright 2018 Huawei Technologies Co.,Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
3,290
1,041
import boto3 from zipfile import ZipFile import argparse import json import os import shutil class LambdaMaker(object): def __init__(self, config_file, working_dir): # const vars self.creator='TomLambdaCreator_v1.0.0' os.chdir(working_dir) self.process_config_file(config_file) ...
6,270
1,879
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. 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 ...
6,260
1,949
"""Initialize the index package""" # flake8: noqa from __future__ import absolute_import from .base import * from .typ import *
129
41
# -*- coding: utf-8 -*- class Saucer(object): """ Representa un plato de comida. """ def __init__(self, cadNombre, realPrecio, cadDescription=None, cadImagen=None, boolVegetariano=False, entCoccion=1): self.nombre = cadNombre self.precio = realPrecio self.des...
885
296
import torch import torch.nn.functional as F from torch import nn from resnext.resnext101_regular import ResNeXt101 class _AttentionModule(nn.Module): def __init__(self): super(_AttentionModule, self).__init__() self.block1 = nn.Sequential( nn.Conv2d(64, 64, 1, bias=False), nn.BatchNo...
9,768
4,500
'Classes and functions for creating fonts and text buttons' #IMPORTS import pygame from pathlib import Path from .core import clip_surface, load_image from .colour import palette_swap #IMPORTS #VARIALBES __all__ = ['create_font', 'TextButton'] path = Path(__file__).resolve().parent #VARIABLES #CREATE_FON...
7,413
2,958
""" This modules contain helper function to deal with PIL / Pillow Images. .. note:: Please note that the ``[PIL]`` (pillow) extra dependency must be installed to allow functions from this module to work. """ from . import guetzli def _to_pil_rgb_image(image): """Returns an PIL Image converted to the R...
1,814
598
# # @lc app=leetcode id=201 lang=python # # [201] Bitwise AND of Numbers Range # # https://leetcode.com/problems/bitwise-and-of-numbers-range/description/ # # algorithms # Medium (35.44%) # Total Accepted: 77.3K # Total Submissions: 217.7K # Testcase Example: '5\n7' # # Given a range [m, n] where 0 <= m <= n <= 214...
1,034
409
''' dip @author Bardia Mojra - 1000766739 @brief ee-5323 - project - @date 10/31/21 code based on below YouTube tutorial and Pymotw.com documentation for socket mod. @link https://www.youtube.com/watch?v=3QiPPX-KeSc @link https://pymotw.com/2/socket/tcp.html python socket module documentation @link ht...
12,053
5,044
""" A Command parser to parse over each jinja template for a given cmake command """ import os from apigen.Logger import Logger from jinja2 import Environment, PackageLoader, FileSystemLoader class CommandParser(object): def __init__(self, cmdfile: str, env: Environment, outdir: str): super().__init__() ...
1,128
334
#!/usr/bin/env python import sys print("Please tell me your favorite color: ") color = sys.stdin.readline() animal = raw_input("Please tell me your favorite animal: ") print(animal) sys.stdout.write("Your favorite color is: " + color + " favorite animal is: " + animal + "\n") print("*" * 10)
299
99
# Comet VOEvent Broker. # Event handlers. from comet.handler.relay import * from comet.handler.spawn import *
111
39
from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase from measure_mate.models import Template from measure_mate.tests.factories import TemplateFactory class TemplateAPITestCases(APITestCase): def test_list_template(self): """ Lis...
954
255
# Generated by Django 4.0 on 2021-12-29 11:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop_management', '0002_alter_shop_type_alter_shoptype_name'), ] operations = [ migrations.AddField( model_name='shop', ...
658
228
import torch import torch.nn as nn from lib.util import normal_log_density class ModelActor(nn.Module): def __init__(self, obs_size, act_size, active='tanh', hidden_size=128, lstd=-0.0): super(ModelActor, self).__init__() if active == 'tanh': self.active = torch.tanh else: ...
4,085
1,506
import importlib import unittest solution = importlib.import_module('2020_04_2') class Test2020Day4Part1(unittest.TestCase): def test_example1(self): input = ( 'eyr:1972 cid:100\n' 'hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926\n' '\n' 'iyr:2019\n' 'hcl:#602927...
1,129
674
# Copyright 2018 DeepMind Technologies Limited. 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 by ...
1,649
553
from __future__ import print_function from cineapp import app, db, lm from flask_login import login_required from flask import jsonify, session, g, url_for, request from pywebpush import webpush, WebPushException from cineapp.models import PushNotification import json, traceback, sys, datetime, time from cineapp.auth i...
2,578
849
# generated by datamodel-codegen: # filename: openapi.yaml # timestamp: 2021-12-31T02:50:50+00:00 from __future__ import annotations from datetime import datetime from enum import Enum from typing import Annotated, Any, List, Optional from pydantic import BaseModel, Extra, Field class ResourceNotFoundExceptio...
37,380
10,987
# -*- coding: utf-8 -*- """ Created on Sun Jan 25 15:48:52 2015 @author: Sofia """ import csv import json import os sourceEncoding = "iso-8859-1" targetEncoding = "utf-8" # encode files to utf8 (source: http://stackoverflow.com/questions/191359/how-to-convert-a-file-to-utf-8-in-python) csvfile = open('..\Data\AMFI....
4,577
1,496
import datetime import os import unittest from io import StringIO from tempfile import mkdtemp from unittest.mock import patch from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command as real_call_command from django.core.management.base i...
3,751
1,139
from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import urlparse, parse_qs from cowpy import cow import json import sys class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): parsed_path = urlparse(self.path) parsed_qs = parse_qs(parsed_path.query) ...
2,977
912
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 30 00:58:34 2018 @author: jeff """ '''************************************* #1. Import libraries and key varable values ''' import os import quandl import pandas as pd import numpy as np import keras from PIL import Image #folder path folder_path =...
7,033
2,860
# -*- coding: utf-8 -*- from lichee import plugin from .field_parser_base import BaseFieldParser import os from PIL import Image from torchvision import transforms import torch from lichee.utils import storage @plugin.register_plugin(plugin.PluginType.FIELD_PARSER, "image_local_path") class ImgDataFieldParser(BaseFie...
2,589
767
import torch from torch import nn import torch.nn.functional as F import torchvision from torchvision.models.inception import BasicConv2d, InceptionAux import pretrainedmodels from common import num_class class InceptionV3(nn.Module): def __init__(self, pre=True): super().__init__() self.encoder ...
2,054
816
name = "Saeed" cordinates = (10.0, 20.0) names = ["Saeed", "Bob", "Mousa"]
74
40
#!/usr/bin/python ############################################## ###Python template ###Author: Elizabeth Lee ###Date: 9/2/14 ###Function: mean peak-based retro zOR metric vs. total attack rate ###Import data: SQL_export/OR_allweeks_outpatient.csv, SQL_export/OR_allweeks.csv ###Command Line: python Supp_zOR_totalAR....
2,622
1,063
"""This is the solution to Problem 1 of Project Euler.""" """Copyright 2021 Dimitris Mantas""" import time def compute_all_multiples(of_number, below_number): """Compute all natural numbers, which are multiples of a natural number below a predefined number.""" # Register the list of said multiple...
1,238
396
#!/usr/bin/env python # coding: utf-8 # # Colecciones - Listas # In[1]: l = [22, True, "una lista", [1, 2]] mi_var = l[0] # mi_var vale 22 mi_var1 = l[3] # mi_var1 vale [1, 2] print (mi_var) print (mi_var1) # In[50]: # Si queremos acceder a un elemento de una lista incluida dentro de otra lista tendremos que #...
3,731
1,395
import pytest from itertools import product import torch from torch import nn from torch.nn.utils import parameters_to_vector from torch.utils.data import DataLoader, TensorDataset from torchvision.models import wide_resnet50_2 from laplace import Laplace, SubnetLaplace, FullSubnetLaplace, DiagSubnetLaplace from lapl...
28,045
8,858
""" rylog Logging happening in a 3-dimensional Cartesian product of: 1. The logging level: [debug, info, warn, error] 2. The logging category: e.g. software event, action, output 3. The detected function/method: e.g. my_class.class_method or foo """ from .misc import * from .server import * from .clie...
332
105
class ConstraintSyntaxError(SyntaxError): """A generic error indicating an improperly defined constraint.""" pass class ConstraintValueError(ValueError): """A generic error indicating a value violates a constraint.""" pass
243
63
#!/usr/bin/python # -*- coding: UTF-8 -*- import timeit import numpy as np import sys import random as rand class Queue_array: """ 顺序队列 """ def __init__(self,capacity): self._items = [None]*(capacity+1) #最后一个位置 空置 self._capacity = capacity self._head = 0 self._tail...
3,701
1,390
import numpy as np from matplotlib import pyplot as plt import math MAX_SPEED = 2 ACCELERATION = 0.5 DRAG = 0.3 TURN_SPEED=5 IMAGE = np.array([ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,1,1,1,1,1,0], [0,0,1,1,1,0,0], [0,0,0,1,0,0,0]]) def main(): position=(42 ,42) speed=0 bear...
1,703
798
# coding: utf-8 # 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。 # 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。 # 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/container-with-most-water class Solution(object): # 递归做法 def maxArea1(self, height): """ ...
1,868
810
# Generated by Django 2.1.3 on 2018-12-06 10:42 from django.db import migrations, models import system.models.system_settings class Migration(migrations.Migration): dependencies = [ ('system', '0002_systemsettings_contract_vot_manager_address'), ] operations = [ migrations.AlterField( ...
561
179
from __future__ import division, print_function from .trajgroup import TrajectoryGroup from .hypath import HyPath from .hygroup import HyGroup def print_clusterprocedure(): """Print clustering guide.""" print(""" In ``PySPLIT`` 1. Create ``TrajectoryGroup`` with desired set of trajectorie...
4,338
1,199
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import os import re import requests import sys sys.path.append(os.path.join(sys.path[0], "../", "lib")) import lkft_squad_client # noqa: E402 def get_branch_from_make_kernelversion(make_kernelversion): """ IN: "4.4.118" OUT: "4.4" ...
2,424
817
from math import ceil, sqrt def part_one(input): circle_index = get_circle_index(input) circle_zero = get_circle_zero(circle_index) cardinal_points = get_cardinal_points(circle_index, circle_zero) distance_to_closest_cardinal_point = compute_distance_to_closest_cardinal_point(input, cardinal_points) ...
1,507
581
#022: Crie um programa que leia o nome completo de uma pessoa e mostre: # - O nome com todas as letras maiúsculas e minúsculas. # - Quantas letras ao tdo (sem considerar espaços). # - Quantas letras tem o primeiro nome. nome = input("Qual é o seu nome? ") print(">>",nome.upper()) print(">>",nome.lower()) jnome = nome....
423
156
from typing import Optional from pysqldump.domain.formatters import ( CSVFormatter, DictFormatter, JsonFormatter, ConsoleFormatter, ) from pysqldump.settings.base import get_config config = get_config() class File: def __init__(self, filename): self.filename = filename def get_exten...
2,395
684
"""**Mortgage Calculator** - Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan.""" months = int(input("Enter mortgage term (in months): ")) rate = float(input("Enter interest rate (in %): ...
605
218
import numpy as np def div(a, b): if b == 0: print("denominator iz zero!!!") return np.inf else: return a/b def add(a,b): return (a+b)
172
66
import cv2 class StereoSGBMConfig: min_disparity = 0 num_disparities = 16*10 sad_window_size = 3 uniqueness_ratio = 5 p1 = 16*sad_window_size*sad_window_size p2 = 96*sad_window_size*sad_window_size pre_filter_cap = 63 speckle_window_size = 0 speckle_range = 0 disp_max_diff = 1 ...
956
435
from brnolm.runtime.tensor_reorganization import TensorReorganizer import torch from torch.autograd import Variable from .common import TestCase class Dummy_lstm(): def __init__(self, nb_hidden): self._nb_hidden = nb_hidden def init_hidden(self, batch_size): return ( torch.FloatT...
5,460
2,359
jobname="BachelorThesis"
25
11
from eventsourcing.infrastructure.event_sourced_repo import EventSourcedRepository from quantdsl.domain.model.contract_specification import ContractSpecification, ContractSpecificationRepository class ContractSpecificationRepo(ContractSpecificationRepository, EventSourcedRepository): domain_class = ContractSpeci...
331
85
from requests_html import HTMLSession import os import sys writeFileName = "courseLinks.out" writeFileStream = open(writeFileName,'w',encoding='utf-8') session = HTMLSession() url = 'https://www.ji.sjtu.edu.cn/academics/courses/courses-by-number/' r = session.get(url) for i in range(2,100): sel = '...
660
247
import logging import discord from datetime import datetime from discord.ext import tasks, commands from discord.ext.commands import Cog from cogs.utils.utils import json_io_dump, json_io_load log = logging.getLogger(__name__) STATUS = 'status' TIME_STARTED = 'time_started' NAME = 'name' GAMES = 'games' NONE = 'none'...
7,655
2,313
import numpy as np from .converter import TransformConverter from .. import linear class PyqtgraphTransformConverter(TransformConverter): name = 'pyqtgraph' def __init__(self): try: import pyqtgraph self._import_error = None except ImportError as exc: s...
2,578
842
from pyqt.utils import time
28
9
class BadIngredient(Exception): """ Something is wrong with an ingredient """ class BadRecipe(Exception): """ Something is wrong with a recipe """ class InvalidColumnError(Exception): def __init__(self, *args, **kwargs): self.column_name = kwargs.pop("column_name", None) if not args: ...
491
136
import os def readAnn(textfolder="../data/SemEval2017Task10/"): ''' Read .ann files and look up corresponding spans in .txt files Args: textfolder: ''' flist = os.listdir(textfolder) for f in flist: if not f.endswith(".ann"): continue f_anno = open(os...
1,373
429
from collections import namedtuple import os import sympy import numpy as np from means.core.model import Model _Reaction = namedtuple('_REACTION', ['id', 'reactants', 'products', 'propensity', 'parameters']) def _sbml_like_piecewise(*args): if len(args) % 2 == 1: # Add a final True element you can skip ...
5,018
1,507
import pytest import clrenv @pytest.fixture(autouse=True) def clear_overlay_path(monkeypatch): monkeypatch.setenv("CLRENV_OVERLAY_PATH", "") def test_custom_base(tmp_path, monkeypatch): custom_path = tmp_path / "custom/path" custom_path.parent.mkdir() custom_path.write_text("data") monkeypatch....
1,123
428
import random import pandas as pd import numpy as np import json from tqdm import * def split(full_list, shuffle=False, ratio=0.2): n_total = len(full_list) offset = int(n_total * ratio) if n_total == 0 or offset < 1: return [], full_list if shuffle: random.shuffle(full_list) subli...
2,583
867
''' pip install Scrapy pip install selenium In a folder: scrapy startproject imgt when running: scrapy crawl new_imgt -o out.json when using scrapy shell: scrapy shell 'url' in Ipython, you can use response.xpath or response.css to try out object: 1. selectorlist if css('a') and there are ...
3,237
1,094
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
1,667
529
#!/usr/bin/python3 # (c) Robert Muth - see LICENSE for more info from typing import List, Dict import enum from Util import cgen # maximum number of operands in an instruction MAX_OPERANDS = 5 # maximum number of function parameters (or results) MAX_PARAMETERS = 64 #################################################...
38,786
15,211
# Generated by Django 3.2.7 on 2021-10-27 09:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("connector_airflow", "0012_remove_airflow_run_message"), ] operations = [ migrations.AlterModelOptions( name="dagrun", ...
784
225
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: LAMARCK_ML/data_util/TypeShape.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf impo...
3,447
1,387
from flask import Flask, render_template, request, session, redirect, url_for import pymysql.cursors import datetime from pyecharts import options as opts from pyecharts.charts import Pie,Bar from appdef import * #Get the airline the staff member works for def getStaffAirline(): username = session['username'] ...
31,149
8,791
from fastapi import FastAPI try: from routes import analytics,templates,auth except: from .routes import analytics,templates,auth app = FastAPI() app.include_router(analytics.router) app.include_router(templates.router) app.include_router(auth.authr)
261
80
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import str from future import standard_library standard_library.install_aliases() import query_releases import unittest class TestQueryReleases(unittest....
873
277
# simplePendulum.py # Model of a simple pendulum import math def simplePendulum(length = 1, angle = math.pi/4, angular_velocity = 0, DT = 0.0001, simLength = 12): numIterations = int(simLength/DT) + 1 g = 9.81 angle_change = angular_velocity angular_acceleration = -g...
1,211
373
from setuptools import setup setup( name='dropboxbackup', version='0.1', py_modules=['dropboxbackup'], install_requires=[ 'click', 'dropbox', 'simple-crypt' ], entry_points=''' [console_scripts] dropboxbackup=dropboxbackup:cli ''', )
303
104
from os import path from shutil import copyfile import tvm from tvm import relay from tvm.driver import tvmc from tvm.driver.tvmc.model import TVMCModel from tvm.relay.transform import InferType, ToMixedPrecision """Copy pasted mostly from: https://github.com/AndrewZhaoLuo/TVM-Sandbox/blob/bb209e8845440ed9f40af1b258...
6,896
2,628
# -*- coding: utf-8 -*- """ XJB Generate Images Module (/doodle) Created on Sun Sep 1 16:03:16 2019 @author: user """ import os import asyncio import uuid import tg_connection gen_path = "D:/AndroidProjects/ScarletKindom/flandre-generator/wgan/sample.png" inp_base = "D:/AndroidProjects/ScarletKindom/flandre-genera...
1,547
587
from rest_framework import viewsets, permissions from leads.serializers import LeadSerializer from leads.models import Lead class LeadViewSet(viewsets.ModelViewSet): """Manage CRUD operations for Leads in the database""" queryset = Lead.objects.all() permission_classes = [ permissions.AllowAny ...
362
100
from flask import render_template from . import main @main.app_errorhandler(404) def fo_O_fo(error): """ Function to render the 404 error page """ return render_template('fo_O_fo.html'), 404
207
73
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): followers = models.ManyToManyField('self',symmetrical=False,related_name='following') class Post(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE,related_name='posts') content = mode...
408
124
import PIL.Image as Img import numpy as np from tqdm.notebook import tqdm from PIL import ImageFilter import tables import time import gc """ all the insert/append function for collage generator _canvas_append takes the inserting operation, the rest are finding add_point logic """ class _insertion(): def _canvas_a...
18,476
4,902
# coding: utf-8 """ OpenShift API (with Kubernetes) OpenShift provides builds, application lifecycle, image content management, and administrative policy on top of Kubernetes. The API allows consistent management of those objects. All API operations are authenticated via an Authorization bearer token that is...
190,066
45,999
import socket import sys IP_ADDR = "192.168.1.19" TCP_PORT = 10000 if __name__ == "__main__": # Create TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Associate the socket with the server address server_address = (IP_ADDR, TCP_PORT) print("Start TCP server at address {} on p...
722
238
import pandas as pd countryInformation = pd.read_csv('resource/countryInformation.csv') #looping row #for index,row in countryInformation.iterrows(): #print(index, row['country_name']) print(countryInformation.loc[countryInformation['country_name'] == 'india'])
269
77
""" List Comprehensions Examples """ my_list = [] # my_list.append() # my_list.extend() """ When to use ListComps """ phones = [ { 'number': '111-111-1111', 'label': 'phone', 'extension': '1234', }, { 'number': '222-222-2222', 'label': 'mobile', 'extension...
2,011
833
import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras import models as KM from tensorflow.keras import layers as KL class DenoisingNetwork(object): def __new__(cls, mode: str) \ -> KM.Model: assert mode in ['base', 'skip', 'bn'] inputs = KL.Input(sha...
2,549
829
import time class Timer(object): def __init__(self, Log, *args, **kwargs): self.Log = Log return super().__init__(*args, **kwargs) @property def time(self): return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) def mktime(self, timex): return time.mktime(time.strptime(timex, '%Y-%m-%d...
884
336
""" Select only a part of the instances .. todo: group instance selectors """ import random import logging from collections import defaultdict from pySPACE.missions.nodes.base_node import BaseNode from pySPACE.tools.memoize_generator import MemoizeGenerator class InstanceSelectionNode(BaseNode): """Retain only...
17,464
4,321
# -*- coding: utf-8 -*- """ """ from __future__ import absolute_import from contextlib import contextmanager import imp import posixpath from zipfile import ZipFile from click.testing import CliRunner import pkginfo import pytest from six import PY3 def test_pyfile_compiled(packages, tmpdir): packages.require_e...
4,050
1,411
import logging from abc import ABC, abstractmethod logger = logging.getLogger(__name__) class ActionsMasterListBase(ABC): """ Base class meant to hold the entire Set of IAM resource actions. It is up to a concrete class to implement a source document parser (parse_actions_source) """ def __init_...
1,649
446
import pybullet as p from gym import spaces import pybullet_planning as pbp import numpy as np from diy_gym.addons.addon import Addon class JointTrace(Addon): """ JointTrace Trace the follows a joints movements """ def __init__(self, parent, config): super().__init__(parent, config) ...
1,401
464
def solution(S): rs = "" for i in S: if i != " ": rs += i else: rs += "%20" return rs S = "Mr John Smith" print(solution(S))
181
67
from __future__ import print_function import ngraph.transformers as ngt from ngraph.flex.names import flex_gpu_transformer_name import argparse class FlexNgraphArgparser(): """ Flex specific command line args """ @staticmethod def setup_flex_args(argParser): """ Add flex specific ...
1,612
433
""" Simple reduced order solver. More of a no-op, in that it doesn't actually perform a flux solution """ import numpy from hydep.internal.features import FeatureCollection from hydep.internal import TransportResult from .lib import ReducedOrderSolver class SimpleROSolver(ReducedOrderSolver): """The simplest r...
969
270
import FWCore.ParameterSet.Config as cms # # produce ttGenEvent with all necessary ingredients # from TopQuarkAnalysis.TopEventProducers.producers.TopInitSubset_cfi import * from TopQuarkAnalysis.TopEventProducers.producers.TopDecaySubset_cfi import * from TopQuarkAnalysis.TopEventProducers.producers.TtGenEvtProducer_...
449
160
import os from os.path import join as pjoin import time import numpy as np import torch from torch import nn import torch.nn.functional as F from torch.optim.lr_scheduler import CosineAnnealingLR try: from .radam import RAdam except (ImportError, ModuleNotFoundError) as err: from radam import RAdam try: ...
8,442
2,773
import os import sys import unittest from nose.importer import Importer class TestImporter(unittest.TestCase): def setUp(self): self.dir = os.path.normpath(os.path.join(os.path.dirname(__file__), 'support')) self.imp = Importer() self._mods...
6,043
2,214
from sklearn.base import clone import pandas as pd from abc import ABCMeta from time import time from datetime import datetime import numpy as np from sklearn.model_selection import ParameterGrid from sklearn.base import BaseEstimator, MetaEstimatorMixin from mvmm.utils import get_seeds from mvmm.multi_view.utils impo...
16,278
4,774
"""Delegate provider traversal tests.""" from dependency_injector import providers def test_traversal_provider(): another_provider = providers.Provider() provider = providers.Delegate(another_provider) all_providers = list(provider.traverse()) assert len(all_providers) == 1 assert another_provi...
812
237
# -*- coding: utf-8 -*- """Top-level package for RHG Compute Tools.""" __author__ = """Michael Delgado""" __email__ = 'mdelgado@rhg.com' __version__ = '0.2.1'
161
72
# Generated by Django 3.2.3 on 2021-12-19 17:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('grocers_panel', '0004_shop_grocer'), ] operations = [ migrations.AlterField( model_name='shop',...
481
174
class Colabore(): def getContext(self): return self.__contextColabore(self) def __contextColabore(self): context = { "grupo": "geral", "grupo_link": "saiba_mais", "titulo": "Observatório UFJ Covid-19 - Colabore" } return context
271
106
import datetime from sqlalchemy.orm import sessionmaker from database import db from database.order_history import OrderHistory from stock_analysis.logic import order_history from stock_analysis.logic.order_history import Order from stock_analysis.logic.order_history import OrderHistoryLogic from stock_analysis.logic....
6,339
2,209
import os import tensorflow as tf from densenet_3d_model import DenseNet3D def model_fn(features, labels, mode, params): # Define the model model = DenseNet3D( video_clips=features['video_clips'], labels=labels, **params) # Get the prediction result if mode == tf.estimator.ModeKeys.PRED...
3,380
1,058