content stringlengths 7 1.05M |
|---|
# dataset settings
dataset_type = 'CUB'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=510),
dict(type='RandomCrop', size=384),
dict(type='RandomFlip', flip_prob=0.5, direction... |
# -*- coding: utf-8 -*-
class Config:
class MongoDB:
database = "crawlib2_test"
|
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
n = int(input("Enter month Number: "))
if (n > 0 and n < 13):
mE = (3 * n)
mA = mE - 3
print(months[mA:mE])
else:
print("falsche Zahl")
|
"""
>>> getg()
5
>>> setg(42)
>>> getg()
42
"""
g = 5
def setg(a):
global g
g = a
def getg():
return g
class Test(object):
"""
>>> global_in_class
9
>>> Test.global_in_class
Traceback (most recent call last):
AttributeError: type object 'Test' has no attrib... |
#!python
with open('pessoas.csv') as arquivo:
with open('pessoas.txt', 'w') as saida:
for registro in arquivo:
pessoa = registro.strip().split(',')
print('Nome:{}, Idade:{}'.format(*pessoa), file=saida)
if saida.closed:
print('Saida OK')
if arquivo.closed:
print('saida ok'... |
class ConfigError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class MercuryUnsupportedService(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class MercuryConnectException(Exception):
def __init__(s... |
#######################################
graph={}
graph["start"]["a"]=6
graph["start"]["b"]=2
graph["a"]={}
graph["a"]["fin"]=1
graph["b"]={}
graph["b"]["a"]=3
graph["b"]["fin"]=5
graph["fin"]={}
#######################################
infinity = float("inf")
costs={}
costs["a"]=6
costs["b"]=2
costs["fin"]=infinity... |
# Calcula o IMC.
print(' ====== Exercicio 43 ====== ')
peso = float(input('Digite seu peso em quilos: '))
altura = float(input('digite sua altura em metros: '))
# Calculo do IMC.
imc = peso / (altura ** 2)
# verificando o IMC e exibindo o indice do usuário.
print('\nSeu IMC: {:.1f}'.format(imc))
print('Voce está em ... |
## using the return statement in python
## execute fct and give the respond back
def cube(num): ## expectin one num
return num*num*num ## allows to return value to the caller
print(cube(3)) ## return none
result = cube(4)
print(result)
|
def flatten(x):
"""Flatten a two-dimensional list into one-dimension.
Todo:
* Support flattening n-dimension list into one-dimension.
Args:
x (list of list of any): A two-dimension list.
Returns:
list of any: An one-dimension list.
"""
return [a for i in x for a in i... |
# Used when we want to process an array of requests through a chain of handlers. Respective handler processes the request depending on the value, and send the request to the successor handler if not handled at that handler.
class Handler:
def __init__(self, successor):
self.successor = successor
def ... |
def brac_balance(expr):
stack = []
for char in expr:
if char in ["(", "{", "["]:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ")":
return False
if current_char == '{':
if char != "}":
return False
if curre... |
# Stack implementation
'''
Stack using python list. Use append to push an item
onto the stack and pop to remove an item
'''
my_stack = list()
my_stack.append(4)
my_stack.append(7)
my_stack.append(12)
my_stack.append(19)
print(my_stack)
print(my_stack.pop()) # 19
print(my_stack.pop()) # 12
print(my_stack) # [4,7]
|
class LED_80_64:
keySize = 64
T0 = [0x00BB00DD00AA0055, 0x00BA00D100AE0057, 0x00BC00DF00A5005B, 0x00B500D900A7005A, 0x00B100DC00A40052,
0x00B000D000A00050, 0x00B700D200AF005E, 0x00B900D600A20051, 0x00B600DE00AB005C, 0x00BF00D800A9005D,
0x00BD00D300A10059, 0x00B300D700AC0056, 0x00B800DA00... |
"""Package metadata"""
TITLE = "aiosfstream"
DESCRIPTION = "Salesforce Streaming API client for asyncio"
KEYWORDS = "salesforce asyncio aiohttp comet cometd bayeux push streaming"
URL = "https://github.com/robertmrk/aiosfstream"
PROJECT_URLS = {
"CI": "https://travis-ci.org/robertmrk/aiosfstream",
"Coverage": "... |
#!python
class BinaryMinHeap(object):
"""BinaryMinHeap: a partially ordered collection with efficient methods to
insert new items in partial order and to access and remove its minimum item.
Items are stored in a dynamic array that implicitly represents a complete
binary tree with root node at index 0 ... |
def moveZeroes(nums):
"""
Move all zeros to the end of the given array (nums) with keeping the order of other elements.
Do not return anything, modify nums in-place instead.
"""
# counter = 0
# for i in range(len(nums) - 1):
# if nums[counter] == 0:
# nums.pop(counter)
#... |
# https://leetcode.com/problems/jump-game/
class Solution:
def canJump(self, nums: list[int]) -> bool:
last = 0
for index in range(len(nums)):
if index > last:
return False
last = max(last, index + nums[index])
if last >= len(nums) - 1:
... |
def calculate(mass):
if mass < 6:
return 0
return int(mass/3-2) + calculate(int(mass/3-2))
with open("1.txt", "r") as infile:
print("First part solution: ", sum([int(int(x)/3)-2 for x in infile.readlines()]))
print("Second part solution: ", sum([calculate(int(x)) for x in infile.readlines()]))
|
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Type2Enum(object):
"""Implementation of the 'Type2' enum.
Type of the L7 Rule. Must be 'application', 'applicationCategory', 'host',
'port' or 'ip... |
class Dimension:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
@property
def width(self):
return self.x2 - self.x1
@property
def height(self):
return self.y2 - self.y1
@property
def aspect_ratio(self... |
with open("../documentation/resource-doc.txt", "r") as DOC_FILE:
__doc__ = DOC_FILE.read()
def repositionItemInList(__index, __item, __list):
__list.remove(__item)
__list.insert(__index, __item)
return __list
def removeItems(__item_list, __list):
for item in __item_list:
try:
... |
# SPDX-License-Identifier: Apache-2.0
"""
Constants used with this package.
For more details about this api, please refer to the documentation at
https://github.com/G-Two/subarulink
"""
COUNTRY_USA = "USA"
COUNTRY_CAN = "CAN"
MOBILE_API_SERVER = {
COUNTRY_USA: "mobileapi.prod.subarucs.com",
COUNTRY_CAN: "mo... |
# An example with subplots, so an array of axes is returned.
axes = df.plot.line(subplots=True)
type(axes)
# <class 'numpy.ndarray'>
|
class problem(object):
"""docstring for problem"""
def __init__(self, arg):
super(problem, self).__init__()
self.arg = arg
|
class Statistics():
def __init__(self):
self.time_cfg_constr = 0 #ok
self.time_verify = 0 #ok
self.time_smt = 0 #ok
self.time_smt_pure = 0
self.time_interp = 0 #ok
self.time_interp_pure = 0 #ok
self.time_to_lia = 0 #ok
self.time_from_lia = 0 #ok
... |
class Knapsack01:
def rebot(self, w, v, index, c):
if c <= 0:
return 0
if index == len(w) - 1:
return v[index] if c >= w[index] else 0
if c >= w[index]:
return max(self.rebot(w, v, index+1, c-w[index])+v[index], self.rebot(w, v, index+1, c))
r... |
class Gen:
def __init__(self, type, sequence, data_object):
self.type = type
self.sequence = sequence
self.data_object = data_object
class GenType:
CDNA = 'cdna'
DNA = 'dna'
CDS = 'cds'
class DnaType:
dna = '.dna.'
dna_sm = '.dna_sm.'
dna_rm = '.dna_rm.'
|
def for_G():
"""printing capital 'G' using for loop"""
for row in range(6):
for col in range(5):
if col==0 and row not in(0,5) or row==0 and col in(1,2,3) or row==5 and col not in(0,4) or row==3 and col!=1 or col==4 and row in(1,4):
print("*",end=" ")
else:
... |
_css_basic = """
.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
"""
_css_cloze = """
.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
.cloze {
font-weight: bold;
color: blue;
}
.nightMode .c... |
# Insert line numbers
in_file = open('Resources/02. Line Numbers/Input.txt', 'r').read().split('\n')
result = [str(number + 1) + '. ' + item for number, item in enumerate(in_file)][:-1]
print(*result, sep = '\n')
out_str = '\n'.join(result)
open('output/02.txt', 'w').write(out_str)
|
class Pessoa: # criar seus types personalizados
olhos = 2 # atributo default ou de classe
def __init__(self, *filhos, nome = None, idade = 35): # atributos de dados
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá, meu ... |
# divisão por dois números
numero1 = int(input('Entre com o primeiro número: '))
numero2 = int(input('Entre com o segundo número: '))
resultado = numero1 / numero2
print('O resultado é: ',resultado)
input('Pressione ENTER para sair...')
|
fib = lambda n: n if n <= 2 else fib(n - 1) + fib(n - 2)
'''
print(fib(10)) #89
'''
|
# https://leetcode.com/problems/rotate-array/
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def reverse(s, e):
while s < e:
nums[s]... |
"""
Operadores logicos - aula 4
and, or not
in e not in
"""
# (verdadeiro e False) = Falso
#comparação1 and comparação
#verdadeiro OU Verdadeiro
#comp1 or comp2
#Not inverter uma expressão
#Comando in muito utilllll
nome = 'Pedro'
if 'Ped' in nome: #todo: Muito util
print('Existe o texto.')
else:
print('N... |
"""
PASSENGERS
"""
numPassengers = 3191
passenger_arriving = (
(5, 8, 7, 5, 1, 0, 3, 5, 8, 3, 0, 0), # 0
(2, 8, 13, 5, 0, 0, 12, 10, 6, 1, 0, 0), # 1
(1, 10, 5, 4, 2, 0, 13, 13, 5, 2, 3, 0), # 2
(5, 11, 16, 2, 3, 0, 8, 0, 6, 3, 4, 0), # 3
(5, 8, 6, 2, 1, 0, 7, 10, 6, 5, 1, 0), # 4
(1, 10, 8, 5, 1, 0, 3, 1... |
"""
Copyright 2020 Skyscanner Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software dis... |
"""
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two
characters may map to the same character but a character ... |
# Searvice Check Config
#### Global
DOMAIN = 'TEAM'
### HTTP
HTTP_PAGES = [
{ 'url':'', 'expected':'index.html', 'tolerance': 0.05 },
]
### HTTPS
HTTPS_PAGES = [
{ 'url':'', 'expected':'index.html', 'tolerance': 0.05 },
]
### DNS
DNS_QUERIES = [
{ 'type':'A', 'query':'team.local', 'expected':'216.239.32... |
class FakeTwilioMessage(object):
status = 'sent'
def __init__(self, price, num_segments=1):
self.price = price
self.num_segments = str(num_segments)
def fetch(self):
return self
class FakeMessageFactory(object):
backend_message_id_to_num_segments = {}
backend_message_id_t... |
class ValueNotRequired(Exception):
pass
class RaggedListError(Exception):
pass
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"AttStats": "att_stats.ipynb",
"Attribute": "attribute.ipynb",
"Data": "data.ipynb",
"DataScrambler": "data_scrambler.ipynb",
"configuration": "data_scrambler.ipynb",
... |
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = xiongliff
__mtime__ = '2019/7/20'
""" |
# fixing the issue in food.py
# this is kind of a bug, thats not what we wanted
# this can be done by making the class variable an instance variable
class Food:
def __init__(self, name):
self.name = name # instance variable (attr)
self.fav_food = [] # class variable fix by making inst var
... |
'''
People module for the Derrida project.
It provides basic personography, VIAF lookup, and admin functionality to edit
people associated with Derrida's library.
'''
default_app_config = 'derrida.people.apps.PeopleConfig'
|
"""
===============
=== Purpose ===
===============
Encodes the hierarchy of US political divisions.
This file, together with populations.py, replaces the static data portion of
state_info.py.
The location names used in this file match FluView names as specified in
fluview_locations.py of delphi-epidata.
=========... |
def calc_size(digest_size, seed_size, num_rounds, lowmc_k, lowmc_r, lowmc_m, is_unruh):
lowmc_n = lowmc_k
# bytes required to store one input share
input_size = (lowmc_k + 7) >> 3;
# bytes required to store one output share
output_size = (lowmc_n + 7) >> 3;
# number of bits per view per LowMC ... |
# -*- coding: utf-8 -*-
class dllink:
"""doubly linked node (that may also be a "head" a list)
A Doubly-linked List class. This class simply contains a link of
node's. By adding a "head" node (sentinel), deleting a node is
extremely fast (see "Introduction to Algorithm"). This class does
not keep... |
"""Internal API endpoint constant library.
_______ __ _______ __ __ __
| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.
|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|
|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|
|: 1 | ... |
def visit_rate_ate(df, test_set=False):
if test_set:
treatment_visit_rate = df[df.Treatment == 1].Outcome.mean() * 100
control_visit_rate = df[df.Treatment == 0].Outcome.mean() * 100
average_treatment_effect = treatment_visit_rate - control_visit_rate
print("Test set visit rate uplif... |
__all__ = [
'provider',
'songObj',
'spotifyClient',
'utils'
]
#! You should be able to do all you want with just theese three lines
#! from spotdl.search.spotifyClient import initialize
#! from spotdl.search.songObj import songObj
#! from spotdl.search.utils import * |
class Registry:
def __init__(self, name):
self._name = name
self._registry_dict = dict()
def register(self, name=None, obj=None):
if obj is not None:
if name is None:
name = obj.__name__
return self._register(obj, name)
return self._decora... |
#!/usr/bin/env python3
"""RZFeeser | Alta3 Research
learning about for logic"""
# create list of dictionaries for farms
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": ... |
def findRoot(x, power, epsilon):
"""Assumes x and epsilon an int or float, power an int, epsilon > 0
& power >= 1
Returns float y such that y**power is within epsilon of x.
If such float does not exist, it returns None"""
if x < 0 and power%2 ==0:
return None #since negative numbers have no ... |
def dobro(n):
return n * 2
def metade(n):
return n / 2
def aumentar(n):
return n + (10 / 100 * n)
def diminuir(n):
return n - (13 / 100 * n)
|
g = [ (['p'],[('cat','wff')]),
(['q'],[('cat','wff')]),
(['r'],[('cat','wff')]),
(['s'],[('cat','wff')]),
(['t'],[('cat','wff')]),
(['not'],[('sel','wff'),('cat','wff')]),
(['and'],[('sel','wff'),('sel','wff'),('cat','wff')]),
(['or'],[('sel','wff'),('sel'... |
def f(n, c=1):
print(c)
if c == n:
return c
f(n, c+1)
f(12) |
MD_HEADER = """\
# Changelog
"""
MD_ENTRY = """\
## {version}
[PR #{pr_number}]({pr_url}): {summary} (thanks [{committer}]({committer_url}))
"""
RST_HEADER = """\
Changelog
=========
"""
RST_ENTRY = """\
{version}
-------------------------------------------------
`PR #{pr_number} <{pr_url}>`__: {summary} (thanks `{c... |
nop = b'\x00\x00'
brk = b'\x00\xA0'
lde = b'\x63\x07' # Load 0x07 (character 'a') into register V3
skp = b'\xE3\xA1' # Skip next instruction if user is NOT pressing character held in V3
with open("sknpvxtest.bin", 'wb') as f:
f.write(lde) # 0x0200 <-- Load the byte 0x07 into register V3
f.write(brk) # 0x02... |
load("@bazel_skylib//rules:run_binary.bzl", "run_binary")
load("@rules_cc//cc:defs.bzl", "cc_library")
def rust_cxx_bridge(name, src, deps = []):
native.alias(
name = "%s/header" % name,
actual = src + ".h",
)
native.alias(
name = "%s/source" % name,
actual = src + ".cc",
... |
# Miho Damage Skin
success = sm.addDamageSkin(2436044)
if success:
sm.chat("The Miho Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem(2436044)
|
#!/usr/bin/python3
def lie_bracket(f, g, q):
"""Take the Lie bracket of two vector fields.
[f, g] = (d/dq)f * g - (d/dq)g * f
Args:
f (sympy.matrix): an N x 1 symbolic vector
g (sympy.matrix): an N x 1 symbolic
q (sympy.matrix or List): a length N array like object of coordinates... |
"""
873. Length of Longest Fibonacci Subsequence
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, retu... |
DOCKER_IMAGES = {
"cpu": {
"tensorflow": "ritazh/azk8sml-tensorflow:latest",
},
"gpu": {
"tensorflow": "ritazh/azk8sml-tensorflow:latest-gpu",
}
}
DEFAULT_DOCKER_IMAGE = "ritazh/azk8sml-tensorflow:latest"
DEFAULT_ARCH = "cpu"
|
# 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... |
# This file has automatically been generated
# biogeme 2.6a [Mon May 14 17:32:05 EDT 2018]
# <a href='http://people.epfl.ch/michel.bierlaire'>Michel Bierlaire</a>, <a href='http://transp-or.epfl.ch'>Transport and Mobility Laboratory</a>, <a href='http://www.epfl.ch'>Ecole Polytechnique Fédérale de Lausann... |
def longest_palindromic_substring_DP(s):
S = [[False for i in range(len(s))] for j in range(len(s))]
max_palindrome = ""
for i in range(len(s))[::-1]:
for j in range(i, len(s)):
S[i][j] = s[i] == s[j] and (j - i < 3 or S[i+1][j-1])
if S[i][j] and j - i + 1 > len(max_palind... |
class Solution:
def nthUglyNumber(self, n):
ugly = [1]
i2 = i3 = i5 = 0
while len(ugly) < n:
while ugly[i2] * 2 <= ugly[-1]: i2 += 1
while ugly[i3] * 3 <= ugly[-1]: i3 += 1
while ugly[i5] * 5 <= ugly[-1]: i5 += 1
ugly.append(min(ugly[i2] * 2, u... |
def dividableNumberGenerator(limit, number):
dividableNumbers = []
for i in range(0, limit, number):
dividableNumbers.append(i)
return dividableNumbers
def sumDividableNumbers(dividableNumbers):
sum = 0
for i in range(0, len(dividableNumbers)):
sum += dividableNumbers[i]
return sum
print(sumDivida... |
(
((1,), (), ()),
((2,), (), ()),
((1, 2), (), ()),
((), (0,), ()),
((), (0,), (0,)),
((), (), ()),
((), (), ()),
((), (), ()),
((), (), ()),
((), (0,), (0,)),
)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 19:43:28 2020
@author: Ravi
"""
def minimumDistance(arr,n):
a = set(arr)
if len(a) == len(arr):
return -1
li = {}
for i in range(n):
for j in range(n):
if arr[i]==arr[j]:
if i!=j:
... |
class Solution:
def __init__(self, w: List[int]):
self.total = sum(w)
for i in range(1, len(w)):
w[i] += w[i-1]
self.w = w
def pickIndex(self) -> int:
ans = 0
stop = randrange(self.total)
l,r = 0, len(self.w)-1
... |
select_atom ={
1: "H",
3: "Li",
6: "C",
7: "N",
8: "O",
9: "F",
}
select_weight ={
1: 1.00794,
6: 12,
7: 15,
8: 16,
9: 18.998403,
}
|
config = dict({
"LunarLander-v2": {
"DQN": {
"eff_batch_size" : 128,
"eps_decay" : 0.99,
"gamma" : 0.99,
"tau" : 0.005,
"lr" : 0.0005
},
"EnsembleDQN": {
"eff_batch_size" : 64,
"eps_decay" : 0.99,
"gamma" : 0.99,
"tau" : 0.005,
"lr" : 0... |
season = str(input())
gender = str(input())
people = int(input())
time = int(input())
winter = False
spring = False
summer = False
girls = False
boys = False
mixed = False
tax = 0
sport = str()
total_price = 0
discount = 0
if season == "Winter":
winter = True
elif season == "Spring":
spring = True
elif season... |
work_hours = [('Abby',100),('Billy',400),('Cassie',800)]
def employee_check(work_hours):
current_max = 0
# Set some empty value before the loop
employee_of_month = ''
for employee,hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month... |
def row_sum_odd_numbers(n):
row_first_odd = int(0.5*(n-1)*n)
odd_list = range(1, (row_first_odd+n)*2, 2)
odd_row = odd_list[row_first_odd:]
return sum(odd_row)
# Example:
# 1
# 3 5
# 7 9 11
# 13 15 17 19
# 21 23 25 27 29
# row_sum_odd_num... |
"""
Tuples. Immutable lists i.e. contents cannot be changed. These are ordered so indexes and duplicates are allowed.
tuples vs lists
fixed length vs variable length
tuples ()
lists []
tuples - immutable
tuples - mutable
"""
my_tuple = ()
print(f"Type is : {type(my_tuple)}")
# Single element in a tuple needs a trick;... |
# -*- coding: utf-8 -*-
# Scrapy settings for Downloader project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'CNSpider'
SPIDER_MODULES = ['CNSpider.spiders']... |
#
# Copyright (c) 2019 MagicStack Inc.
# All rights reserved.
#
# See LICENSE for details.
##
GET_USER = """
SELECT User {
id,
name,
image,
latest_reviews := (
WITH UserReviews := User.<author[IS Review]
SELECT UserReviews {
id,
... |
sequence = [1]
n = 0
while n < 40:
sequence.append(sequence[n] + sequence[n-1])
n += 1
print('The Fibonacci sequence, up to the 30th term, is \n' + str(sequence) + '.')
pisano = input("Please pick a number. ")
psequence = []
for item in sequence:
psequence.append(item % pisano)
print(psequence)
# for ... |
class OperationHolderMixin:
def __and__(self, other):
return OperandHolder(AND, self, other)
def __or__(self, other):
return OperandHolder(OR, self, other)
def __rand__(self, other):
return OperandHolder(AND, other, self)
def __ror__(self, other):
return OperandHolder(... |
class InvalidBackend(Exception):
pass
class NodeDoesNotExist(Exception):
pass
class PersistenceError(Exception):
pass
|
# -*- coding: utf-8 -*-
class WebsocketError:
CodeInvalidSession = 9001
CodeConnCloseErr = 9005
class AuthenticationFailedError(RuntimeError):
def __init__(self, msg):
self.msgs = msg
def __str__(self):
return self.msgs
class NotFoundError(RuntimeError):
def __init__(self, msg... |
# Problem: https://www.hackerrank.com/challenges/repeated-string/problem
# Score: 20
def repeated_string(s, n):
return n // len(s) * s.count('a') + s[0: n % len(s)].count('a')
s = input()
n = int(input())
print(repeated_string(s, n))
|
num1 = int(input())
num2 = int(input())
if num1>=num2:
print(num1)
else:
print(num2)
|
class EnergyAnalysisSurface(Element, IDisposable):
"""
Analytical surface.
The collection of analytic openings belonging to this analytical parent surface
"""
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAdjacentAnalyticalSpace(self):
"... |
__doc__ = """An object oriented solution to the problem."""
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
class FamilyMember(Person):
def __init__(self, name):
self.name = name
def... |
# -- Project information -----------------------------------------------------
project = 'LUNA'
copyright = '2020 Great Scott Gadgets'
author = 'Katherine J. Temkin'
# -- General configuration ---------------------------------------------------
master_doc = 'index'
extensions = [
'sphinx.ext.autodoc',
'sph... |
def sample_single_dim(action_space_list_each, is_act_continuous):
each = []
if is_act_continuous:
each = action_space_list_each.sample()
else:
if action_space_list_each.__class__.__name__ == "Discrete":
each = [0] * action_space_list_each.n
idx = action_space_list_ea... |
class Solution(object):
def match_note_to_magazine(self, ransom_note, magazine):
if ransom_note is None or magazine is None:
raise TypeError('ransom_note or magazine cannot be None')
seen_chars = {}
for char in magazine:
if char in seen_chars:
seen_ch... |
def on_message_deleted(msg, server):
return "Deleted: {}".format(msg["previous_message"]["text"])
def on_message_changed(msg, server):
text = msg.get("message", {"text": ""}).get("text", "")
if text.startswith("!echo"):
return "Changed: {}".format(text)
def on_message(msg, server):
if msg["tex... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/hunter/github_projects/ROS/catkin_ws/src/my_package/msg/Num.msg"
services_str = "/home/hunter/github_projects/ROS/catkin_ws/src/my_package/srv/AddTwoInts.srv"
pkg_name = "my_package"
dependencies_str = "std_msgs"
langs = "gencpp;geneus;genlisp;g... |
class FunctionDifferentialRegistry(dict):
def __setitem__(self, k, v):
if not callable(k):
raise ValueError("key must be callable")
if not callable(v):
raise ValueError("value must be callable")
super().__setitem__(k, v)
global_registry = FunctionDifferentialRegis... |
"""
The dependencies for running the gen_rust_project binary.
"""
load("//util/import/raze:crates.bzl", "rules_rust_util_import_fetch_remote_crates")
def import_deps():
rules_rust_util_import_fetch_remote_crates()
# For legacy support
gen_rust_project_dependencies = import_deps
|
version = "1.0"
def sayhi():
print("Hi,this is mymodule speaking.")
def judge_1():
a = int(input("input a"))
c = int(input("input c"))
if a > c:
print("椭圆")
if a == c:
print("抛物线")
if a < c:
print("双曲线")
|
def timeconverter(days):
years = days // 365
days = days % 365
months = days // 30
days = days % 30
print(f"{years} years, {months} months and {days} days")
days = input("Enter number of days: ")
days = int(days)
timeconverter(days) |
print("hello world")
print("my name is mark zed bruyg")
print("555")
karachi_city = ["gulshan", "johar", "malir", "defence", "liyari"]
print(karachi_city[2])
names_of_student = ["maaz", "musab", "usman", "shuraim", "sudais", "ausaf"]
print(names_of_student)
age = 12
amount_to_increment = 3
a... |
# (raw name, table column)
COLS=[
('cxid', 'cxid'),
('dts', 'dts'),
('Existing Meter Number', 'old_meter_number'),
('Existing Meter Reading', 'old_meter_reading'),
('New Meter Number', 'new_meter_number'),
('New Meter Reading', 'new_meter_reading'),
('Geo Tag', 'geo_tag'),
('GPS', 'gps'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.