content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import pytest
import numpy as np
from mcalf.models import ModelBase as DummyModel, FitResult, FitResults
fitted_parameters = [1, 2, 1000.2, 1001.8, 5]
fit_info = {'chi2': 1.4, 'classification': 2, 'profile': 'abc',
'success': True, 'index': [123, 456, 789]}
def test_fitresult_passthrough():
fit = Fi... | nilq/baby-python | python |
# Generated by Django 4.0.1 on 2022-03-09 12:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('BruteScan', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='bruteresult',
name='result_flag',
... | nilq/baby-python | python |
import backend
import imagery
import config_reader
import os
import shutil
import geolocation
import numpy as np
import json
from detectors.Detector import Detector
from Mask_RCNN_Detect import Mask_RCNN_Detect
from PIL import Image
from flask import Flask, render_template, request, flash, redirect, url_for, send_from_... | nilq/baby-python | python |
# I am a comment, python interpreter will ignore every line that starts with '#'
"""
I am a multiline comment and surrounded by 3 \" or 3 \'
"""
| nilq/baby-python | python |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | nilq/baby-python | python |
import numpy as np
import sys
import matplotlib.ticker as mticker
def file2stats(filename):
#f=open(filename)
f=open('results/'+filename)
print('WARNING: Results read have not been regenerated')
lines = f.readlines()
f.close()
A = []
for line in lines:
A.append(float(line[:-1]))
... | nilq/baby-python | python |
import os
import numpy as np
from OpenGL.GL import *
import lib.basic_shapes as bs
import lib.easy_shaders as es
import lib.transformations as tr
import lib.object_handler as oh
class Charmander():
def __init__(self): self.GPU = es.toGPUShape(oh.readOBJ(os.path.join('mod','tex','charmander.obj'), (241/255, 95/266... | nilq/baby-python | python |
from setuptools import setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(name='elektrum',
version='0.1',
url='https://github.com/zxpower/elektrum',
author='Reinholds Zviedris (zxpower)',
author_email='reinholds@zviedris.lv',
description="Utility to a... | nilq/baby-python | python |
import json
try:
import simplejson as json
except ImportError:
import json
import requests
import os.path
def autodetect_proxy():
proxies = {}
proxy_https = os.getenv('HTTPS_PROXY', os.getenv('https_proxy', None))
proxy_http = os.getenv('HTTP_PROXY', os.getenv('http_proxy', None))
if proxy_h... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.keras.callbacks import Callback
from scipy.optimize import linear_sum_assignment
def unsupervised_labels(y, yp, n_classes, n_clusters):
"""Linear assignment algorithm
... | nilq/baby-python | python |
from fuzzer import Ascii, Utf8, Num
from grammar import Cfg, Syms
IdChar = Utf8.exclude("?", ":", "}").with_sym_name("IdChar")
IdStartChar = IdChar.exclude("=").with_sym_name("IdStartChar")
RawChar = Utf8.exclude("{", "\\").with_sym_name("RawChar")
ExprLitChar = RawChar.exclude(":", "}").with_sym_name("ExprLitChar")
A... | nilq/baby-python | python |
class Fila:
def __init__(self):
self.data = []
def is_empty(self):
return self.data == []
def get_size(self):
return len(self.data)
def peek(self):
if self.is_empty():
raise IndexError
else:
return self.data[0]
def enqueue(self, ite... | nilq/baby-python | python |
"""
Test cases to validate centos7 base image configurations
"""
import subprocess
import pytest
import testinfra
DOCKER_IMAGE_NAME = 'python:latest'
# scope='session' uses the same container for all the tests;
# scope='function' uses a new container per test function.
@pytest.fixture(scope='session')
def host():
... | nilq/baby-python | python |
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from PyKEP import epoch, DAY2SEC, planet_ss, AU, MU_SUN, lambert_problem
from PyKEP.orbit_plots import plot_planet, plot_lambert
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
a... | nilq/baby-python | python |
import os, sys
from threading import Thread, active_count
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import QIcon
from logic import get_cheaters
from layout import Ui_CheatChecker
# If layout shows an import error, generate it using:
# pyuic5 checker.ui -o layout.py
class Chea... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pandas as pd
import os
def read_csv_data_in_directory(directory_path, variables_to_keep = []):
"""
Read a directory of .csv files and merges them into a single data frame
Parameters
----------
directory_path : str
absolute path to directory containing cs... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
import time
with open('letters_source.txt', 'r', encoding = 'utf-8') as f:
source_data = f.read()
with open('letters_target.txt', 'r', encoding = 'utf-8') as f:
target_data = f.read()
def extrtact_character_vocab(data):
#construct mapping table
special_... | nilq/baby-python | python |
from functools import partial
import numpy as np
import gym
import gym_rock_paper_scissors
import gym_connect4
from regym.environments import generate_task, EnvType
from regym.environments.wrappers import FrameStack
from regym.environments.tasks import RegymAsyncVectorEnv
def test_can_stack_frames_singleagent_env(... | nilq/baby-python | python |
import numpy as np
import sympy
import itertools
import math
import mpmath
import warnings
from qubricks.operator import Operator
DEBUG = False
def debug(*messages):
if DEBUG:
for message in messages:
print messages,
print
class Perturb(object):
'''
`Perturb` is a class that allows one to perform degenera... | nilq/baby-python | python |
"""
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 use this ... | nilq/baby-python | python |
# nuScenes dev-kit.
# Code written by Freddy Boulton, Eric Wolff, 2020.
import json
import os
from typing import List, Dict, Any
from nuscenes.eval.prediction.metrics import Metric, deserialize_metric
from nuscenes.prediction import PredictHelper
class PredictionConfig:
def __init__(self,
metri... | nilq/baby-python | python |
"""
This is a file which will contain basic functions to call the GIOŚ API
"""
import requests
import errors
def get_all_measuring_stations():
"""
Returns a list of all measuring stations with their details.
Examplary response
------------------
[{
"id": 14,
"stationName": "Dział... | nilq/baby-python | python |
import ldap3.core
import ldap3.abstract
import ldap3.operation
import ldap3.protocol
import ldap3.protocol.sasl
import ldap3.protocol.schemas
import ldap3.protocol.formatters
import ldap3.strategy
import ldap3.utils
import ldap3.extend
import ldap3.extend.novell
import ldap3.extend.microsoft
import ldap3.extend.standar... | nilq/baby-python | python |
import PyPluMA
CODING_TABLE = dict()
CODING_TABLE["TTT"] = 'F'
CODING_TABLE["TTC"] = 'F'
CODING_TABLE["TTA"] = 'L'
CODING_TABLE["TTG"] = 'L'
CODING_TABLE["TCT"] = 'S'
CODING_TABLE["TCC"] = 'S'
CODING_TABLE["TCA"] = 'S'
CODING_TABLE["TCG"] = 'S'
CODING_TABLE["TAT"] = 'Y'
CODING_TABLE["TAC"] = 'Y'
CODING_TABLE["TAA"] ... | nilq/baby-python | python |
import base64
code="aW1wb3J0IHB5bW9uZ28KaW1wb3J0IHVybGxpYjIKaW1wb3J0IHVybGxpYgppbXBvcnQgY29va2llbGliCmltcG9ydCByYW5kb20KaW1wb3J0IHJlCmltcG9ydCBzdHJpbmcKaW1wb3J0IHN5cwppbXBvcnQgZ2V0b3B0CgojIGluaXQgdGhlIGdsb2JhbCBjb29raWUgamFyCmNqID0gY29va2llbGliLkNvb2tpZUphcigpCiMgZGVjbGFyZSB0aGUgdmFyaWFibGVzIHRvIGNvbm5lY3QgdG8gZGIKY29u... | nilq/baby-python | python |
#!/usr/bin/env python
import sys;print(sys.argv);print(__file__)
| nilq/baby-python | python |
import torch
from neural_clbf.systems import ControlAffineSystem
def normalize(
dynamics_model: ControlAffineSystem, x: torch.Tensor, k: float = 1.0
) -> torch.Tensor:
"""Normalize the state input to [-k, k]
args:
dynamics_model: the dynamics model matching the provided states
x: bs x se... | nilq/baby-python | python |
from enum import Enum
import datetime
import dbaccess
class Action(Enum):
PAUSE, FINISH, ARCHIVE, WORK, CREATE, DELETE = range(6)
class Log(object):
def __init__(self, action, problem_id, name, category_id, dt=None):
self.action = action
self.problem_id = problem_id
self.name = name... | nilq/baby-python | python |
import argparse
import collections
import torch
import numpy as np
import data_loader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch
from parse_config import ConfigParser
from trainer import Trainer
from utils import prepare_device
"... | nilq/baby-python | python |
from django.conf.urls import include, url
from categories import views
class SingleCategoryPatterns():
urlpatterns = [
url(r'^$', views.category, name='category'),
url(r'^new/$', views.new_category, name='new_category'),
url(r'^delete/$', views.delete_category, name='delete_category'),
... | nilq/baby-python | python |
#!/usr/bin/env python
print("SUB_TASK, Hello, Am sub_task");
import os;
import hashlib;
import time;
import multiprocessing;
def __getMd5(localFile):
md5Value = "";
md5tool = hashlib.md5();
print("__CheckFile, localFile:" + localFile);
try:
if (os.path.exists(localFile) == False):
... | nilq/baby-python | python |
def primeFactors(n):
facts, by_two = {}, 0
start = n
while n % 2 == 0:
n //= 2
by_two += 1
for t in range(by_two):
facts[2] = by_two
for i in range(3, int(n**0.5)+1, 2):
while n % i == 0:
n = n / i
if i in facts:
facts[i] += 1... | nilq/baby-python | python |
# Project: hardInfo
# Author: George Keith Watson
# Date Started: March 18, 2022
# Copyright: (c) Copyright 2022 George Keith Watson
# Module: model/LsCpu.py
# Date Started: March 20, 2022
# Purpose: Run Linux commands and collect output into usable Python objects.
#... | nilq/baby-python | python |
import json
from .AccessControlEntry import AccessControlEntry
class AccessControlList(object):
"""OCS access control list definition"""
def __init__(self, role_trustee_access_control_entries: list[AccessControlEntry] = None):
self.RoleTrusteeAccessControlEntries = role_trustee_access_control_entrie... | nilq/baby-python | python |
"""Tests for zaim_row.py."""
from datetime import datetime
from typing import Type
import pytest
from tests.testlibraries.instance_resource import InstanceResource
from tests.testlibraries.row_data import ZaimRowData
from zaimcsvconverter import CONFIG
from zaimcsvconverter.inputcsvformats import InputRow, InputRowDa... | nilq/baby-python | python |
"""
Script with modules to connect with the database to prepare sources
"""
import logging
import os
import uuid
import pandas as pd
import utils.data_connection.constant_variables_db as cons
from utils.data_connection.source_manager import Connector
from pypika import Query, Tables, Table, JoinType
logger = logging... | nilq/baby-python | python |
#!/share/pyenv/bin/python3
'''
###########################################################
# Code name: VASP Electronic Structure Tool(VEST) #
# #
########### script to extract data from PROCAR ############
# Input file : PROCAR, ... | nilq/baby-python | python |
class MultiSigDeprecationWitness:
def __init__(self, next_state_state_update, signatures, inclusion_witness):
self.next_state_state_update = next_state_state_update
self.signatures = signatures
self.inclusion_witness = inclusion_witness
class MultiSigPredicate:
dispute_duration = 10
... | nilq/baby-python | python |
import json
import os
import logging
import random
from collections import OrderedDict, defaultdict
import numpy as np
import torch
from coref_bucket_batch_sampler import BucketBatchSampler
from metrics import CorefEvaluator, MentionEvaluator
from utils.utils import extract_clusters, extract_mentions_to_predicted_clust... | nilq/baby-python | python |
#!/usr/bin/python3
"""
kimcsv2fasttext.py: convert kim's balanced data format to fasttext format
usage: ./kimcsv2fasttext.py < BalancedDataSet.csv
20180504 erikt(at)xs4all.nl
"""
import csv
import html
import nltk
import re
import sys
import time
from io import BytesIO
from urllib.request import urlopen
... | nilq/baby-python | python |
# This file is part of the PySide project.
#
# Copyright (C) 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
# Copyright (C) 2009 Riverbank Computing Limited.
# Copyright (C) 2009 Torsten Marek
#
# Contact: PySide team <pyside@openbossa.org>
#
# This program is free software; you can redistribute it and/or
# m... | nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2019 Red Hat, Inc.
#
# 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... | nilq/baby-python | python |
from enum import Enum, unique
from Tables import door_pair_offset_table
def create_rooms(world, player):
world.rooms += [
Room(player, 0x01, 0x51168).door(Position.WestN2, DoorKind.Warp).door(Position.EastN2, DoorKind.Warp),
Room(player, 0x02, 0x50b97).door(Position.South2, DoorKind.TrapTriggerabl... | nilq/baby-python | python |
# ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / info@conceptive.be
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condition... | nilq/baby-python | python |
#!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, March 2017
import pylab
from datasets.nir_tecator impor... | nilq/baby-python | python |
# Copyright (c) 2019-2022 ThatRedKite and contributors
from turtle import right
import discord
from discord.ext import commands
import time
import re
from datetime import datetime
from operator import itemgetter
import aioredis
import discord
from discord.ext import commands
async def update_count(redis: aioredi... | nilq/baby-python | python |
from pysit.Tomo.tomo import *
| nilq/baby-python | python |
import pandas as pd
def rail_station():
data = pd.read_csv('data/GTFS_stations.txt',sep = ',', header = None)
data = data.rename(columns = {0:'ID',2:'Name'})
use_col = ['ID','Name']
data = data.loc[:,use_col]
link_info = pd.read_csv('data/link_info.csv')
station1 = link_info.loc[:,['link_start... | nilq/baby-python | python |
# coding=utf-8
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
class SiameseLSTMw2v(object):
"""
A LSTM based deep Siamese network for text similarity.
Uses an word embedding layer (looks up in pre-trained w2v), followed by a biLSTM and Energy Loss layer.
"""
def... | nilq/baby-python | python |
from keras.applications import VGG16
from keras import models
from keras import layers
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
image_width = 768
image_heig... | nilq/baby-python | python |
Import("env")
import os
dataFolder = 'data'
if not dataFolder in os.listdir(os.getcwd()):
os.mkdir(dataFolder)
print("Empty \"data\" folder for empty filesystem creation ready")
print("Replace MKSPIFFSTOOL with mklittlefs.exe")
env.Replace (MKSPIFFSTOOL = "mklittlefs.exe") | nilq/baby-python | python |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libproxy(CMakePackage):
"""libproxy is a library that provides automatic proxy configurati... | nilq/baby-python | python |
import torch
import torch.nn as nn
import numpy as np
from operations import *
from torch.autograd import Variable
from genotypes import PRIMITIVES
from genotypes import Genotype
class MixedOp (nn.Module):
def __init__(self, C, stride):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
... | nilq/baby-python | python |
import pytest
from django.contrib.auth import get_user_model
from django.test import Client
def test_user_guest():
c = Client()
resp = c.get("/require-user")
assert resp.status_code == 403
assert resp.json() == {"message": "You have to log in"}
def test_async_user_guest():
c = Client()
resp ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from mock import patch
from sentry.tasks.fetch_source import (
UrlResult, expand_javascript_source, discover_sourcemap,
fetch_sourcemap, fetch_url, generate_module, BAD_SOURCE, trim_line)
from sentry.utils.sourcemaps import (SourceMap, SourceMapI... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import thermalstd
import dataclima
import solarpower
db_cable = 'DB_cables.xlsx'
csvfile = r'D:\Analise_Dados_Solares\UFV Rio do Peixe\Séries de longo prazo (Helio-Clim3)\SAO_JOAO_DO_RIO_DO_PEIXE_HC3-METEO_hour_lat-6.725_lon-38.454_2004-02-01_2019-01-30_hz1.csv'
# dictstudy_AC... | nilq/baby-python | python |
# Copyright (c) 2003-2020 Xsens Technologies B.V. or subsidiaries worldwide.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above c... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete= models.CASCADE)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__... | nilq/baby-python | python |
#!/usr/bin/env python
import glob
import json
import logging
import math
import mimetypes
import os
import platform
import re
import shutil
import socket
import subprocess
import sys
import tempfile
from multiprocessing import Process
from random import uniform
from socket import gaierror
from time import sleep
from im... | nilq/baby-python | python |
import os
import sys
import getpass
import logging
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import SessionNotCreatedException
import colorama
from .databa... | nilq/baby-python | python |
from armstrong.core.arm_sections import utils
from armstrong.core.arm_sections.models import Section
from ._utils import ArmSectionsTestCase, override_settings
from .support.models import SimpleCommon
def rel_field_names(rels):
return [rel.field.name for rel in rels]
class get_configured_item_modelTestCase(Arm... | nilq/baby-python | python |
import boto3, ipaddress, os, socket, time
from codeguru_profiler_agent import with_lambda_profiler
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from aws_lambda_powertools import Logger, Tracer
# AWS Lambda Powertools
logger = Logge... | nilq/baby-python | python |
from aicademeCV.skinCV import skinseperator
| nilq/baby-python | python |
import os
from get_data import read_params, get_data
import argparse
def load_and_save(config_path):
config = read_params(config_path)
df = get_data(config_path)
df['fixed acidity'].fillna(int(df['fixed acidity'].median()), inplace=True)
df['volatile acidity'].fillna(int(df['volatile acidity'].mean())... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
import unittest
from exactitude import countries
class CountriesTest(unittest.TestCase):
def test_country_codes(self):
self.assertEqual(countries.clean('DE'), 'de')
self.assertTrue(countries.validate('DE'))
self.assertFalse(countries.validate('DEU'))
self.assertFalse(countries.va... | nilq/baby-python | python |
import numpy as np
import pandas as pd
from gaitcalibrate.extract.walk import extract_step
from gaitcalibrate.util.adjust_acceleration import tilt_adjustment
def estimate_walk_speed(
acc,
model,
g2acc=True,
n_skip_edge_step=3,
thd_n_step_each_walk=10,
apply_tilt_adjust=True
):
"""Estima... | nilq/baby-python | python |
#!/usr/bin/env python
"""User API for controlling Map job execution."""
from google.appengine.ext import db
from mapreduce import util
# pylint: disable=g-bad-name
# pylint: disable=protected-access
def start(job_config=None,
in_xg_transaction=False):
"""Start a new map job.
Args:
job_config: an... | nilq/baby-python | python |
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
from sklearn.model_selection import train_test_split
from IPython.display import display
import eli5
from eli5.sklearn import PermutationImportance
RANDOM_STATE = 0
# Get Iris data
iris = datasets.load_iris()
X = iris.data
y = iris.targ... | nilq/baby-python | python |
from mock import patch
import pytest
from s3parq import publish_redshift
from s3parq.testing_helper import setup_custom_redshift_columns_and_dataframe
class MockScopeObj():
def execute(self, schema_string: str):
pass
def scope_execute_mock(mock_session_helper):
pass
class Test():
# Make sur... | nilq/baby-python | python |
import argparse
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils import data
from torchvision import datasets, transforms
import torchvision.utils as vutils
from classes import Generator, Discriminator
import conf
import utils as ut
# Command line arguments
parser = argparse.Ar... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
import xml.etree.ElementTree as ET
class Parser:
"""
this class parse style xml files.
xml -> dict in list
* all arguments and text is string. not int. you need to convert it yourself.
like this xml
<?xml version="1.0"?>
<style>
<width>635</widt... | nilq/baby-python | python |
from .bases import EndpointBase
from aioconsul.api import consul, extract_meta
from aioconsul.exceptions import NotFound
from aioconsul.util import extract_attr
class SessionEndpoint(EndpointBase):
"""Create, destroy, and query sessions
.. note:: All of the read session endpoints support blocking queries and... | nilq/baby-python | python |
import os
import json
from common.models import Contact, ContactType
from facilities.models import (
Facility, FacilityContact, Officer, OfficerContact
)
from users.models import MflUser
from django.core.management import BaseCommand
from django.conf import settings
system_user = MflUser.objects.get(email='syste... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import nnabla as nn
import numpy as np
import common.rawdata as rdat
from tex_util import Texture
""" from nnc_proj.($$project_name_of_nnc) import network """
from nnc_proj.model import network
nn.clear_parameters()
nn.parameter.load_parameters('./nnc_proj/model.nnp')
ratios = rdat.ratios
mve... | nilq/baby-python | python |
# Copyright 2021 Sean Robertson
#
# 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... | nilq/baby-python | python |
"""
def main():
print('main')
TestCase1:
a = [1, 2, 3, 4]
b = [5, 6, 7]
# c = [1, 8, 0, 1]
TEst case2:
a = [1, 2, 3, 4]
b = [5, 6, 7,9]
#c =[6,9,1,3]
Test case3:
a = [2, 3, 4]
b = [5, 6, 7,9]
#c = [5,9,1,3]
"""
a = [2, 3, 4]
b = [5, 6, 7, 9]
sum = new_su... | nilq/baby-python | python |
#!/bin/env python
import os
import json
import subprocess
import sys
import shutil
class Debug:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def info(self, msg):
p... | nilq/baby-python | python |
''' Class to construct circular parts of the eyepiece
'''
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import NumericProperty
Builder.load_string('''
<Ring>:
canvas:
Color:
rgba: self.color
rgba: self.grey, self.grey, self.grey, 1 - app.tra... | nilq/baby-python | python |
import mock
import pytest
@pytest.fixture
def contentful():
with mock.patch(
'contentful_proxy.handlers.items.DetailProxyHandler.contentful',
new_callable=mock.PropertyMock
) as mock_types:
yield mock_types
def test_get_item_by_id(app, contentful):
contentful.return_value... | nilq/baby-python | python |
# Practice python script for remote jobs
import time
import os
print('starting')
time.sleep(30)
if os.path.exists('62979.pdf'):
os.remove('62979.pdf')
else:
print('The file does not exist')
print('done') | nilq/baby-python | python |
from django.db import models
from django.utils.translation import gettext_lazy as _
from itertools import chain
from operator import attrgetter
# A model which represents a projects to be displayed on the projects page of the website.
class Project(models.Model):
# Define the possible statuses of a project, each ... | nilq/baby-python | python |
import asyncio
import asyncpg
from aiohttp import web
loop = asyncio.get_event_loop()
loop.create_server(["127.0.0.1", "localhost"], port=1234)
async def handle(request):
"""Handle incoming requests."""
pool = request.app["pool"]
power = int(request.match_info.get("power", 10))
# Take a connection ... | nilq/baby-python | python |
"""Utilities for converting notebooks to and from different formats."""
from .exporters import *
from . import filters
from . import transformers
from . import post_processors
from . import writers
| nilq/baby-python | python |
import unittest
import suite_all_tests_chrome
import suite_all_tests_firefox
if __name__ == '__main__':
runner = unittest.TextTestRunner(verbosity=2)
suite = unittest.TestSuite()
suite_chrome = suite_all_tests_chrome.suite()
suite_firefox= suite_all_tests_firefox.suite()
suite.addTests(suite_chrome... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
''' pyrad_proc.py - Process and pipeline management for Python Radiance scripts
2016 - Georg Mischler
Use as:
from pyradlib.pyrad_proc import PIPE, Error, ProcMixin
For a single-file installation, include the contents of this file
at the same place (minus the __future__ import below).
'''
fro... | nilq/baby-python | python |
import requests
import pandas as pd
import json
rply = []
regions = [172]
for region in regions:
url = "https://api.bilibili.com/x/web-interface/ranking/region?rid=" + str(region) + "&day=7&original=0&jsonp=jsonp"
response = requests.get(url=url)
text = response.text
ob = json.loads(text)
... | nilq/baby-python | python |
# Agent.py
from Tools import *
from agTools import *
import commonVar as common
class Agent(SuperAgent):
def __init__(self, number, myWorldState,
xPos, yPos, lX=0, rX=0, bY=0, tY=0, agType=""):
# 0 definitions to be replaced (useful only if the
# dimensions are o... | nilq/baby-python | python |
# -*- coding: iso-8859-15 -*-
#
# Copyright 2017 Mycroft AI Inc.
#
# 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 appli... | nilq/baby-python | python |
#!/usr/bin/env python
import Pyro.naming
import Pyro.core
import connvalidator
class testobject(Pyro.core.ObjBase):
def __init__(self):
Pyro.core.ObjBase.__init__(self)
def method(self,arg):
caller = self.getLocalStorage().caller # TCPConnection of the caller
login = caller.authenticated # set by the co... | nilq/baby-python | python |
from ThirdParty.CookiesPool.cookiespool.scheduler import Scheduler
def main():
s = Scheduler()
s.run()
if __name__ == '__main__':
main() | nilq/baby-python | python |
from typing import List, Sequence, Optional, Union
import pandas as pd
import pyexlatex as pl
from datacode.sem.constants import STANDARD_SCALE_MESSAGE, ROBUST_SCALE_MESSAGE
def summary_latex_table(fit_df: pd.DataFrame, structural_dfs: Sequence[pd.DataFrame],
latent_dfs: Sequence[pd.DataFram... | nilq/baby-python | python |
from devito.ir.ietxdsl.operations import * # noqa
from devito.ir.ietxdsl.cgeneration import * # noqa
| nilq/baby-python | python |
def find_ocurrences(collection, item):
result = []
for i, word in enumerate(collection):
if word == item:
result.append(i + 1)
return result
words_count, lookup_count = map(int, raw_input().split())
collection_items = []
for i in enumerate(xrange(words_count)):
current_item = raw... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | nilq/baby-python | python |
ll = eval(open("day_17_2.out", "r").readline())
def lookup(sl, i, j):
for (l, v) in sl:
if l == (i, j):
return v
for sl in ll:
for j in range(-3, 4):
for i in range(-3, 4):
print(lookup(sl, i, j), end='')
print()
print()
| nilq/baby-python | python |
import sqlite3
from string import Template
# import threading #MultiThreading
# 1: successful
# 2: in_progress
# 3: failed
class SQL_Lite_Logger:
def __init__(self, filename):
self.connection = sqlite3.connect(filename)
self.connection.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate... | nilq/baby-python | python |
# Link: https://leetcode.com/problems/validate-stack-sequences/
# Time: O(N)
# Space: O(N)
# def validate_stack_sequences(pushed, popped):
# stack, i = [], 0
# while stack or popped:
# if i < len(pushed):
# stack.append(pushed[i])
# elif stack[-1] != popped[0]:
# return... | nilq/baby-python | python |
# A singular message for an error. An error is made up of multiple error messages
# A error message defines the formatting of an error.
class _ErrorMessage:
def __init__(self, message:str = None,
content:str = None,
object = None,
tokens:[] = None... | nilq/baby-python | python |
from pyqum import create_app
app = create_app()
app.run(host='127.0.0.1', port=5777, debug=True)
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.