content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# A few convenient math functions for the bicorr project
import matplotlib
#matplotlib.use('agg') # for flux
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks')
import sys
import os
import os.path
import scipy.io as sio
from scipy.optimize import curve_fit
import time
import numpy as np
np.s... | nilq/baby-python | python |
import sys
import os
project = u'Pelikan'
description = u"Unified cache backend. http://go/pelikan"
copyright = u'Twitter'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.ifconfig',
]
exclude_patterns = ['_build']
html_static_path = ['_static']
source_suffix = '.rst'
master_do... | nilq/baby-python | python |
from random import (randrange, shuffle)
from copy import deepcopy
from forest_calculations import (get_forest_dimensions, get_tree_counts)
from forest_transpormations import (flatten_forest, deflatten_forest)
from forest_constants import (LEAFY, CONIFEROUS)
def get_random_position(rows, cols):
return randrange(ro... | nilq/baby-python | python |
from img_utils import img_utils as _lib
from .utils import u8
def darken_pixels(src_path: str, dst_path: str, amount: int, cutoff: int):
""" Darken Pixels
Darkens all pixels in the image by percentage, specified by `amount`. Any pixel
that doesn't have a subpixel below than the `cutoff` will be ignored.... | nilq/baby-python | python |
import asyncio
import logging
import os
import socket
import uuid
import pika
import pika.adapters.asyncio_connection
from .subscription import QueueSubscriptionObject, ExchangeSubscriptionObject
from ..broker import Broker
#
L = logging.getLogger(__name__)
#
class AMQPBroker(Broker):
'''
The broker that uses ... | nilq/baby-python | python |
from urllib import urlencode
from django import forms
from django.conf import settings
from django.contrib import admin
from django.core import validators
from django.core.urlresolvers import resolve
from django.utils.html import format_html
from django.utils.translation import ugettext
from olympia import amo
from o... | nilq/baby-python | python |
def ext_gcd(p, q):
if p == 0:
return q, 0, 1
else:
# gcd, s_i, t_i
gcd, u, v = ext_gcd(q % p, p)
return gcd, v - (q // p) * u, u
p = 240
q = 46
gcd, u, v = ext_gcd(p, q)
print("[+] GCD: {}".format(gcd))
print("[+] u,v: {},{}".format(u,v))
print(f"\n[*] FLAG: crypto{{{u},{v}... | nilq/baby-python | python |
# Generated by Django 2.2.6 on 2019-11-21 17:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('selections', '0009_auto_20190529_0937'),
]
operations = [
migrations.AlterField(
model_name='selection',
name='is_no... | nilq/baby-python | python |
import urllib
import time
def main(request, response):
index = request.request_path.index("?")
args = request.request_path[index+1:].split("&")
headersSent = 0
for arg in args:
if arg.startswith("ignored"):
continue
elif arg.endswith("ms"):
time.sleep(float(arg[0... | nilq/baby-python | python |
import dotenv
from pathlib import Path
from .exceptions import EnvKeyNotFoundError, EnvNotFoundError
BASE_PATH = Path(__file__).resolve().parent.parent
if not (ENV := dotenv.dotenv_values(BASE_PATH / '.env')):
raise EnvNotFoundError()
if not (BOT_CLIENT_TOKEN := ENV.get((key := 'BOT_CLIENT_TOKEN'))):
raise EnvKe... | nilq/baby-python | python |
from django.db import models
class Customer(models.Model):
id = models.AutoField(primary_key=True, null=False)
name = models.CharField(max_length=200, null=False)
keyAPI = models.CharField(max_length=200, null=False)
pathTrainingDataSet = models.CharField(max_length=1000, null=True)
status = models... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import configparser
import nbformat
from .static_text import Common, EvasionAttack
# Type of printing.
OK = 'ok' # [*]
NOTE = 'note' # [+]
FAIL = 'fail' # [-]
WARNING = 'warn' # [!]
NONE = 'none' # No label.
# Create report.
class IpynbRepor... | nilq/baby-python | python |
"""
pygments.lexers.email
~~~~~~~~~~~~~~~~~~~~~
Lexer for the raw E-mail.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups
from pygments.lexers.mime import MIM... | nilq/baby-python | python |
# import dota_utils as util
import os
# import cv2
import json
# from PIL import Image
import xmltodict
import xml.etree.ElementTree as ET
# from ShipRSImageNet_devkit import ShipRSImageNet_utils as util
# from collections import OrderedDict
wordname_50 = ['Other Ship', 'Other Warship', 'Submarine', 'Other Aircraft Ca... | nilq/baby-python | python |
from draw2d import Viewer, Text, Line, Rectangle, Frame, Point, Circle
import math, time, random
viewer = Viewer(600,600)
W = 1.0
F = viewer.frame(0., W, 0., W)
F.add(Text("North", anchor_x="center", anchor_y="top", color=(0.2,0.2,1.0)).move_to(0.5,0.9))
F.add(Text("South", anchor_x="center", anchor_y="bottom", col... | nilq/baby-python | python |
class Student():
# 类变量
# name = ''
sum = 0
age = 0
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
self.__score = 0
# print(name) # xiaoming
# print(age) # 18
print(Student.age)
print(self.__class__... | nilq/baby-python | python |
import os
import pytest
from ci_framework import FlopyTestSetup, base_test_dir
import flopy
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
pthtest = os.path.join("..", "examples", "data", "swtv4_test")
swtv4_exe = "swtv4"
isswtv4 = flopy.which(swtv4_exe)
runmodel = False
verbose = False
swtdir ... | nilq/baby-python | python |
from ursina import *
from model.pion import PionBlanc, PionNoir
class VuePion(Entity):
def __init__(self, position, qubic, *args, **kwargs):
self.qubic = qubic
super().__init__(
position=position,
*args, **kwargs
)
class VuePionFactory:
def __init__(self, qubic, pion='Classic'):
"""
Args:
pion... | nilq/baby-python | python |
import db_handler
ZONE_MAPPING = {
27721: 3,
27767: 9,
-2: 7,
45041: 8,
27723: 3,
-6: 5,
27724: 5,
115_092: 5,
33130: 5,
27770: 2,
27726: 5,
61204: 4,
117_928: 4,
30754: 9,
35673: 8,
27774: 8,
27775: 8,
110_924: 8,
130_226: 12,
27779: 12,
... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation.
#
# 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 wri... | nilq/baby-python | python |
# -*- test-case-name: mimic.test.test_cinder -*-
"""
Defines a mock for Cinder
"""
import json
from uuid import uuid4
from six import text_type
from zope.interface import implementer
from twisted.plugin import IPlugin
from mimic.rest.mimicapp import MimicApp
from mimic.catalog import Entry
from mimic.catalog import En... | nilq/baby-python | python |
from sklearn.metrics import classification_report
import pandas as pd
import tests.test_utils as t
import unittest
from nlu import *
class SentimentTrainingTests(unittest.TestCase):
def test_sentiment_training(self):
#sentiment datase
df_train = self.load_sentiment_dl_dataset()#'/home/loan/Docum... | nilq/baby-python | python |
import ntpath
import os
import sys
import tempfile
import unittest
from itertools import count
try:
from unittest.mock import Mock, patch, call, mock_open
except ImportError:
from mock import Mock, patch, call, mock_open
from flask import Flask, render_template_string, Blueprint
import six
import flask_s3
from... | nilq/baby-python | python |
# Copyright (c) 2018, Ioannis Tziakos
# All rights reserved.
#
# Plugin hooks are inspired by the current implementations found in
# the tox.venv module and adapted to support edm.
import subprocess
import os
import re
import sys
from tox import hookimpl, exception
from tox.venv import VirtualEnv
COMMAND_FAILED = (
... | nilq/baby-python | python |
# Generated by Django 2.1.1 on 2018-09-23 18:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0002_song'),
]
operations = [
migrations.AlterModelOptions(
name='song',
options={'ordering': ['position'... | nilq/baby-python | python |
#!/usr/bin/env python
import dfl.dynamic_system
import dfl.dynamic_model as dm
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
m = 1.0
k11 = 0.2
k13 = 2.0
b1 = 3.0
class Plant1(dfl.dynamic_system.DFLDynamicPlant):
def __init__(self):
self.n_x = 2
self.n... | nilq/baby-python | python |
# RUN this file for an example adventure.
# THEN go to 02_my_adventure.py to make your own!
from random import randint
def startGame():
print("This is an adventure game.")
input("Press enter to continue the text.")
print("When you see this you will need to respond. Here type 'ok'. Then press ent... | nilq/baby-python | python |
from src.preprocessing.data_filter import DataFilter
from src.preprocessing.dataset import Article, Sentence, Token
class ThreeSentenceDataFilter(DataFilter):
def __init__(self, total_sentence_limit=None, *args, **kwargs):
self.article = None
self.sentence = None
self.last_entity = None
... | nilq/baby-python | python |
import pytest
from pyvipr.examples_models.lopez_embedded import model
from pyvipr.pysb_viz.static_viz import PysbStaticViz
@pytest.fixture
def viz_model():
viz = PysbStaticViz(model)
return viz
def test_viz_exists(viz_model):
assert viz_model
def test_graphs(viz_model):
g_sp = viz_model.species_gr... | nilq/baby-python | python |
# Generated by Django 2.1.5 on 2019-01-31 18:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ipam', '0023_change_logging'),
]
operations = [
migrations.AlterField(
model_name='vrf',
name='rd',
fiel... | nilq/baby-python | python |
from itertools import product
with open("day-04.txt") as f:
numbers_str, *boards_str = f.read().rstrip().split("\n\n")
numbers = [int(n) for n in numbers_str.split(",")]
boards = {}
for b, board_str in enumerate(boards_str):
boards[b] = {}
for r, row in enumerate(board_str.splitlines()):
for c, n... | nilq/baby-python | python |
import gffutils
import pyfaidx
def select_annotation_type(db, fasta, selectionAnnotationType):
"""
list of gff3 features as fasta record of selected gff3 type (e.g. mRNA)
"""
countFeature = db.count_features_of_type(selectionAnnotationType)
featureList = [None] * countFeature
i = 0
for feat... | nilq/baby-python | python |
import socket
import win32.lib.win32serviceutil as win32serviceutil
import win32.servicemanager as servicemanager
import win32.win32event as win32event
import win32.win32service as win32service
class SMWinServiceBase(win32serviceutil.ServiceFramework):
_svc_name_ = "SampleleService"
_svc_display_name_ = "Sam... | nilq/baby-python | python |
import os
import re
import subprocess
import shlex
from ConfigParser import SafeConfigParser
CONFIG_FILE = os.path.join(os.getcwd(), '.forrest')
def get_config():
config = SafeConfigParser()
config.read(CONFIG_FILE)
return config
def save_config(config):
config.write(open(CONFIG_FILE, 'w'))
def get_inpu... | nilq/baby-python | python |
from http import HTTPStatus
from django.urls import reverse
from mock import patch
from barriers.models import Company
from core.tests import MarketAccessTestCase
class EditCompaniesTestCase(MarketAccessTestCase):
company_id = "0692683e-5197-4853-a0fe-e43e35b8e7c5"
company_name = "Test Company"
company_... | nilq/baby-python | python |
#!/usr/bin/env python3
# Reading and Writing files
# Creates a new file object and assigning it to a variable called file
file = open ("spider.txt")
# readline method reads a single line of a file
print(file.readline())
# readline method reads the second line of a file - each time the readline method isi called the... | nilq/baby-python | python |
import math
def length_norm(score):
length_tgt = len(score)
return sum(score) / length_tgt
def word_reward(score, reward):
length_tgt = len(score)
return sum(score) - reward * length_tgt
def bounded_word_reward(score, reward, bound):
"""
bound = L_predict
L_predict could be:
... | nilq/baby-python | python |
import pandas as pd
while(1):
menu = {1:"Driver Login",
2:"Customer Login",
3:"ZULA Administarator",
4:"Exit"}
intial_cab_drivers = {"id":[1,2,3,4],
"Name":["aaa","bbb","ccc","ddd"],
"Pass":[111,222,333,444],
... | nilq/baby-python | python |
# =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... | nilq/baby-python | python |
"""
link: https://leetcode.com/problems/word-ladder
problem: 给起始单词,结尾单词,与单词列表,问能否每次转换一个字母,使用列表中的单词由起始变换到结尾
solution: 无权最短路图,即BFS。难点在于如何构造图,一个很巧妙的思路,增加虚拟节点。将 hit 的相邻节点记为 hi*, h*t, *it,
将 hot 的相邻节点记为 ho*, h*t, *ot,这样两个节点就存在了相连路径。构造图后做BFS即可。
"""
class Solution:
def ladderLength(self, beginWord: str, end... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
df_train = pd.read_csv('train.csv')
train=pd.DataFrame(df_train)
train = pd.crosstab(index=train["Type"],columns="count")
type = [[1,"Dog"], [2,"Cat"]]
pet = pd.DataFrame(type, columns = ['Type','Animal... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import CompressedImage,Image # @UnresolvedImport
from duckietown_msgs.msg import AntiInstagramHealth, BoolStamped, AntiInstagramTransform # @UnresolvedImport
from anti_instagram.AntiInstagram import *
from duckietown_utils.jpg import image_cv_... | nilq/baby-python | python |
# coding: utf-8
import types
import pymssql
from itertools import chain
from .abstract import DatabaseAdapter
class MSSQLAdapter(DatabaseAdapter):
last_table = None
def get_connection(self):
if hasattr(self, 'connection') and self.connection:
return self.connection
params = {
... | nilq/baby-python | python |
class Camera:
def __init__(self, game):
self.game = game
self.dx = 0
self.dy = 0
self.ny = 240
self.is_start = True
def start_camera(self):
self.dx = -2100
self.dy = -2100
def apply(self, obj):
obj.rect.x += self.dx
obj.rect.y += self... | nilq/baby-python | python |
import libres
import threading
from cached_property import cached_property
from contextlib import contextmanager
from libres.modules import errors
missing = object()
required = object()
class StoppableService(object):
""" Services inheriting from this class have their stop_service method
called when the se... | nilq/baby-python | python |
"""
COMMAND: SELECT
Select objects by id or name for further
command processes.
"""
import command
import cache
from util import logger
from api import APIRequests
class Select(command.Command):
@staticmethod
def get_invoke():
return 'SELECT'
@staticmethod
def get_args():
retur... | nilq/baby-python | python |
from testcases import TestCaseWithFixture as TestCase
from django.http import HttpRequest
from django.contrib.auth.models import User, Permission
from core.models import Note
from tastypie.authorization import Authorization, ReadOnlyAuthorization, DjangoAuthorization
from tastypie import fields
from tastypie.resources ... | nilq/baby-python | python |
from django.core.exceptions import ValidationError
from pulpo_forms.fieldtypes.Field import Field
from pulpo_forms.statistics.ListStatistics import ListStatistics
class ListField(Field):
"""
List field validator, render and analize methods
"""
def get_methods(self, **kwargs):
base = super(Li... | nilq/baby-python | python |
from sqlalchemy import Column, Integer, Float, String, Date, Time
from shared.core.db import Base
class HourlyMainData(Base):
__tablename__ = 'HourlyMain'
Id = Column(Integer, primary_key=True, nullable=False)
StationId = Column(Integer, nullable=False)
Date = Column(Date, nullable=False)
Hour =... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import sys
from forcebalance.molecule import *
# Script to generate virtual sites and rename atoms in .gro file.
M = Molecule(sys.argv[1])
if 'M' in M.elem:
print(... | nilq/baby-python | python |
from django.utils import timezone
from django.conf import settings
import datetime
from rest_framework_jwt.settings import api_settings
expires_delta = (api_settings.JWT_REFRESH_EXPIRATION_DELTA) - datetime.timedelta(seconds=200)
def jwt_response_handler(token, user=None, request=None):
return {
'token':... | nilq/baby-python | python |
import zeit.cms.testing
import zeit.content.article.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'edit.landing.txt',
'edit.txt',
'edit.form.txt',
package='zeit.content.article.edit.browser',
layer=zeit.content.article.testing.WSGI_LAYER)
| nilq/baby-python | python |
"""Auxiliar functions that may be used in most modules"""
from typing import List
import numpy as np
def compute_permutation_distance(
distance_matrix: np.ndarray, permutation: List[int]
) -> float:
"""Compute the total route distance of a given permutation
Parameters
----------
distance_matrix
... | nilq/baby-python | python |
'''
test_var = False
if(test_var == True):
print("okay")
else:
print("this is not true")
number_a = 500.6
number_b = 100.4
if(number_a > number_b):
print(number_a,"is bigger than",number_b)
else:
print(number_b,"is bigger than",number_a)
# name = input("what's your name? ")
# print("your name is",n... | nilq/baby-python | python |
#!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils impor... | nilq/baby-python | python |
class Card:
def __init__(self, card_type):
"""
card_type 0 is a skipbo card
card_type 1-12 are the normal value cards
actual value indicates the value a skipbo card takes on after it is played
"""
self.card_type = card_type
self.actual_value = card_type if car... | nilq/baby-python | python |
import numpy as np
from lagom.envs.spaces import Box
from lagom.envs.wrappers import ObservationWrapper
class PartialFlattenDict(ObservationWrapper):
"""
Returns flattened observation from a dictionary space with partial keys into a Box space.
"""
def __init__(self, env, keys):
super().__ini... | nilq/baby-python | python |
#
# Copyright 2022 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
import environ
ROOT_DIR = environ.Path(__file__) - 3
ENVIRONMENT = environ.Env()
if ENVIRONMENT.bool("DJANGO_READ_DOT_ENV_FILE", default=False):
# Operating System Environment variables have precedence over variables
# defined in the .e... | nilq/baby-python | python |
# coding: utf-8
# # Performance of various Machine Learning Algorithms on Electrical Impedance Tomography Images
#
# ## Copyright (c) 2018, Faststream Technologies
#
# ## Author: Sudhanva Narayana
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from sklearn.neighbors imp... | nilq/baby-python | python |
import os
import numpy as np
import torch
import nibabel as nib
from glob import glob
import scipy.io
import random
from PIL import Image
import elastic_transform as elt
from torch.utils.data import Dataset
import torchvision.transforms.functional as F
def load_nifty(full_file_name):
img = nib.load(full_file_name... | nilq/baby-python | python |
import functools
from typing import Type, Generic, TypeVar, Dict, Any, Optional
from drf_yasg.utils import swagger_auto_schema
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
from thairod.utils.decorators im... | nilq/baby-python | python |
"""A config store holds the configuration data for running system-of-systems models with smif:
- model runs
- system-of-systems models
- model definitions
- strategies
- scenarios and scenario variants
- narratives
"""
from abc import ABCMeta, abstractmethod
class ConfigStore(metaclass=ABCMeta):
"""A ConfigStore ... | nilq/baby-python | python |
# Copyright (C) 2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import os
path_prefix = os.path.join('cvat', 'apps', 'annotation')
BUILTIN_FORMATS = (
os.path.join(path_prefix, 'cvat.py'),
os.path.join(path_prefix, 'pascal_voc.py'),
os.path.join(path_prefix, 'yolo.py'),
os.path.join(path_prefi... | nilq/baby-python | python |
dataFile = open("Day10_Data.txt")
asteroidCoordinates =[]
for corY,line in enumerate(dataFile):
for corX,c in enumerate(line):
if(c=="#"):
asteroidCoordinates.append([corX,corY])
curMax=0
astBaseX = astBaseY =0
for astBase in range( len(asteroidCoordinates)):
seenDivisionsR = ... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2006-2011 André Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... | nilq/baby-python | python |
'''OpenGL extension ARB.transform_feedback3
This module customises the behaviour of the
OpenGL.raw.GL.ARB.transform_feedback3 to provide a more
Python-friendly API
Overview (from the spec)
This extension further extends the transform feedback capabilities
provided by the EXT_transform_feedback, NV_tran... | nilq/baby-python | python |
"""
Meshing: Make and plot a 3D prism mesh
"""
from fatiando import mesher
from fatiando.vis import myv
mesh = mesher.PrismMesh(bounds=(-2, 2, -3, 3, 0, 1), shape=(4,4,4))
myv.figure()
plot = myv.prisms(mesh)
axes = myv.axes(plot)
myv.show()
| nilq/baby-python | python |
import click
@click.command()
def main():
print("This is the CLI!")
if __name__ == '__main__':
main()
| nilq/baby-python | python |
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('h_dim', default=32,
help='Hidden dim in various models.')
flags.DEFINE_integer('rnn_dim', default=256,
help='RNN hidden dim.')
flags.DEFINE_integer('rnn_n_layers', default=2,
help='Number ... | nilq/baby-python | python |
"""
Compared with model_baseline, do not use correlation output for skip link
Compared to model_baseline_fixed, added return values to test whether nsample is set reasonably.
"""
import tensorflow as tf
import numpy as np
import math
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sy... | nilq/baby-python | python |
"""
TODO module docstring
"""
from re import fullmatch
from typing import Optional
from datetime import timedelta, datetime
from jose import JWTError, jwt
from passlib.hash import bcrypt
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, s... | nilq/baby-python | python |
from webapp import db, login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin # is_authenticated is_loggedin usw...
@login_manager.user_loader # if user is authenticated, then....
def load_user(user_id):
return Us... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | nilq/baby-python | python |
var1 = 'Geeks'
print("Original String :-", var1)
print("Updated String :- ", var1[:5] + 'for' + 'Geeks') # statement 1
| nilq/baby-python | python |
import scapy.all as scapy
import time
from iemlav import logger
class SynFlood(object):
"""SynFlood Class."""
def __init__(self, debug=False):
"""
Initialize SynFlood.
Args:
debug (bool): Log on terminal or not
Raises:
None
Returns:
... | nilq/baby-python | python |
# -*- coding: utf8 -*-
# test encoding: à-é-è-ô-ï-€
# Copyright 2021 Adrien Crovato
#
# 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
#
# Unl... | nilq/baby-python | python |
# name: person_builder.py
# version: 0.0.1
# date: 20211225
# author: Leam Hall
# desc: Build a person.
from person import Person
class PersonBuilder:
def set_data(self, person, data = {}):
person.idx = data.get('idx', -1)
person.gender = data.get('gender', '')
pe... | nilq/baby-python | python |
import rasterio
from sklearn.cluster import AgglomerativeClustering
from shapely.geometry import Polygon
from shapely.ops import nearest_points
from math import sqrt
from gisele import initialization
from shapely import geometry
from gisele.functions import *
from math import *
#from gisele import LV_routing_new_strate... | nilq/baby-python | python |
from typing import Any, Dict, Optional, Union
import httpx
from ...client import AuthenticatedClient
from ...models.osidb_api_v1_schema_retrieve_format import OsidbApiV1SchemaRetrieveFormat
from ...models.osidb_api_v1_schema_retrieve_lang import OsidbApiV1SchemaRetrieveLang
from ...models.osidb_api_v1_schema_retrieve... | nilq/baby-python | python |
def work_well():
print("ok")
return "ok"
def say_hello():
print("hello")
return "hello"
| nilq/baby-python | python |
# uses minimax to look ahead
import sys
from functools import partial
from game import *
import interactive_game
def compute_score(board, res=TURN_OK):
score = board[0]**5 \
+ board[1]**4 + board[4]**4 \
+ board[2]**2 + board[5]**2 + board[8]**2 \
+ board[3] + board[6] + board[... | nilq/baby-python | python |
"""Module with function to regularize a 2D curve (with uniform resolution)."""
import math
import numpy
def _get_perimeter(x, y):
"""Return the perimeter of the geometry.
Parameters
----------
x : numpy.ndarray
x-coordinate of the points along the curve.
y : numpy.ndarray
y-coord... | nilq/baby-python | python |
from bstools import bsSsh
from bstools import bsPrint
from bstools import bsTime
name = "bstools"
__version__ = "0.1.9" | nilq/baby-python | python |
"""
libmonster.py - mixed support library
# TODO: consider replacing pauthor in keyid with _bibtex.names
# TODO: enusure \emph is dropped from titles in keyid calculation
"""
import re
from heapq import nsmallest
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from cs... | nilq/baby-python | python |
## Code taken from https://github.com/vqdang/hover_net/blob/master/metrics/stats_utils.py
import warnings
import numpy as np
import scipy
from scipy.optimize import linear_sum_assignment
# --------------------------Optimised for Speed
def get_fast_aji(true, pred):
"""AJI version distributed by MoNuSeg, has no p... | nilq/baby-python | python |
from ivy import ivy_module as im
from ivy.ivy_compiler import ivy_from_string
from ivy.tk_ui import new_ui
from ivy import ivy_utils as iu
from ivy import ivy_check as ick
from ivy import ivy_logic as il
prog = """#lang ivy1.5
type t
type p
relation sent(X:p,Y:t)
function pid(X:t):p
axiom X:t = X
axiom X:t < Y & Y... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Ambry Bundle Library File
# Use this file for code that may be imported into other bundles
| nilq/baby-python | python |
import kydb
from portfolio_management.common.base_item import BaseItem, Factory
from portfolio_management.common.account_container_mixin import AccountContainerMixin
from portfolio_management.common.position_mixin import PositionMixin
from portfolio_management.portfolio.event import Event, EventType
from portfolio_mana... | nilq/baby-python | python |
uctable = [ [ 48 ],
[ 49 ],
[ 50 ],
[ 51 ],
[ 52 ],
[ 53 ],
[ 54 ],
[ 55 ],
[ 56 ],
[ 57 ],
[ 194, 178 ],
[ 194, 179 ],
[ 194, 185 ],
[ 194, 188 ],
[ 194, 189 ],
[ 194, 190 ],
[ 217, 160 ],
[ 217, 161 ],
[ 217, 162 ],
[ 217, 163 ],
[ 217, 164 ],
[ 217, 165 ],
[ 217, 166 ],
... | nilq/baby-python | python |
import functools
import time
import argparse
import sys
import asyncio
import cocrawler.burner as burner
import cocrawler.config as config
def burn(dt, data):
t0 = time.clock()
end = t0 + dt
while time.clock() < end:
pass
return 1,
async def work():
while True:
dt, data = await... | nilq/baby-python | python |
## Script (Python) "updateProductionStage"
##parameters=sci
# Copy the object in development to review and production.
object = sci.object
st = object.portal_staging
st.updateStages(object, 'dev', ['review', 'prod'],
sci.kwargs.get('comment', ''))
| nilq/baby-python | python |
"""
Benchmark Sorted Dictionary Datatypes
"""
import warnings
from .benchmark import *
# Tests.
@register_test
def contains(func, size):
for val in lists[size][::100]:
assert func(val)
@register_test
def getitem(func, size):
for val in lists[size][::100]:
assert func(val) == -val
@register_... | nilq/baby-python | python |
import sys
import salt.client.ssh
import salt.utils.parsers
class SaltSSH(salt.utils.parsers.SaltSSHOptionParser):
"""
Used to Execute the salt ssh routine
"""
def run(self):
if "-H" in sys.argv or "--hosts" in sys.argv:
sys.argv += ["x", "x"] # Hack: pass a mandatory two option... | nilq/baby-python | python |
import os
import importlib
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
# from matplotlib.finance import volume_overlay
import matplotlib.ticker as ticker
from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.excha... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Atmosphere container base class definitions
Created on Wed Nov 16 16:37:03 2016
@author: maxwell
"""
from collections import MutableMapping
import numpy as np
from . import constants
from .readprof import readprof, readprof_ozone
class Atmosphere(MutableMapping):... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
#autor -> manoel vilela
#gerando graficos em relação a eficiencia dos algoritmos de ordenação bubble, merge and personal
import pylab
def extract_data(file_name):
data = open(file_name, "r").read().split()
data = [element.split() for element in data.split("=")]
vector, values = ... | nilq/baby-python | python |
import graphene
from django.db.models import F, Q
from tabletop.models import DurationType, Game
from tabletop.schema import GameNode
from tabletop.utils.graphene import optimize_queryset
class Query(object):
games = graphene.List(
GameNode,
id=graphene.UUID(),
query=graphene.String(),
... | nilq/baby-python | python |
#General imports====================================
from html.parser import HTMLParser
from urllib import parse
#Finds all anchor <a> tags in a website============
class LinkFinder(HTMLParser):
def __init__(self, base_url, page_url):
super().__init__()
self.base_url = base_url
self.page_... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2017 Ganggao Zhu- Grupo de Sistemas Inteligentes
# gzhu[at]dit.upm.es
# DIT, UPM
#
# 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... | nilq/baby-python | python |
"""
MIT License
Copyright (c) 2020-2021 Hyeonki Hong <hhk7734@gmail.com>
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,... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.