content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""Top-level package for lsmPy."""
__author__ = """Shruti Anna Samuel"""
__email__ = 'annasam13@gmail.com'
__version__ = '0.0.1'
| """Top-level package for lsmPy."""
__author__ = 'Shruti Anna Samuel'
__email__ = 'annasam13@gmail.com'
__version__ = '0.0.1' |
with open("source.txt") as filehandle:
lines = filehandle.readlines()
with open("source.txt", 'w') as filehandle:
lines = filter(lambda x: x.strip(), lines)
filehandle.writelines(lines)
| with open('source.txt') as filehandle:
lines = filehandle.readlines()
with open('source.txt', 'w') as filehandle:
lines = filter(lambda x: x.strip(), lines)
filehandle.writelines(lines) |
""" *******************************************************************************************************************
|
| Name : __version__.py
| Module : risksense_api
| Description : Version information for risksense_api.
| Copyright : (c) RiskSense, Inc.
| License : Apache-2.0 (https://... | """ *******************************************************************************************************************
|
| Name : __version__.py
| Module : risksense_api
| Description : Version information for risksense_api.
| Copyright : (c) RiskSense, Inc.
| License : Apache-2.0 (https://... |
#break.py
for s in 'python' :
if s == 't' :
continue
print(s,end=" ")
print("over")
| for s in 'python':
if s == 't':
continue
print(s, end=' ')
print('over') |
arr = list(range(8))
def func(x):
return x*2
print(list(map(func, arr)))
print(list(map(lambda x: x**3, arr))) | arr = list(range(8))
def func(x):
return x * 2
print(list(map(func, arr)))
print(list(map(lambda x: x ** 3, arr))) |
list1=list(map(int,input().rstrip().split()))
N=list1[0]
list2=list1[2:]
res=[]
for j in list2:
if j not in res:
res.append(j)
for i in range(len(list2)):
if list2[i] in res:
res.remove(list2[i])
print(*res)
| list1 = list(map(int, input().rstrip().split()))
n = list1[0]
list2 = list1[2:]
res = []
for j in list2:
if j not in res:
res.append(j)
for i in range(len(list2)):
if list2[i] in res:
res.remove(list2[i])
print(*res) |
#!/bin/env python3
def puzzle1():
tree = {}
acceptedBags = ['shiny gold']
foundNew = True
with open('input.txt', 'r') as input:
for line in input:
if line[-1:] == "\n":
line = line[:-1]
bags = line.split(',')
partName = bags[0].split(' ')
... | def puzzle1():
tree = {}
accepted_bags = ['shiny gold']
found_new = True
with open('input.txt', 'r') as input:
for line in input:
if line[-1:] == '\n':
line = line[:-1]
bags = line.split(',')
part_name = bags[0].split(' ')
name = pa... |
# -*- coding: utf-8 -*-
"""
Parameter-related utilities.
"""
| """
Parameter-related utilities.
""" |
LinearRegression_Params = [
{"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False},
{"name": "positive", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}
]
Ridge_Params = [
{"name": "alpha", "type": "input", "values... | linear_regression__params = [{'name': 'fit_intercept', 'type': 'select', 'values': [True, False], 'dtype': 'boolean', 'accept_none': False}, {'name': 'positive', 'type': 'select', 'values': [False, True], 'dtype': 'boolean', 'accept_none': False}]
ridge__params = [{'name': 'alpha', 'type': 'input', 'values': 1.0, 'dtyp... |
class Person:
__key = None
__cipher_algorithm = None
def get_key(self):
return self.__key
def set_key(self, new_key):
self.__key = new_key
def operate_cipher(self, encrypted_text):
pass
def set_cipher_algorithm(self, cipher_algorithm):
self.__cipher_algorithm ... | class Person:
__key = None
__cipher_algorithm = None
def get_key(self):
return self.__key
def set_key(self, new_key):
self.__key = new_key
def operate_cipher(self, encrypted_text):
pass
def set_cipher_algorithm(self, cipher_algorithm):
self.__cipher_algorithm ... |
def sum_list_values(list_values):
return sum(list_values)
def symbolic_to_octal(perm_string):
perms = {"r": 4, "w": 2, "x": 1, "-": 0}
string_value = []
symb_to_octal = []
slicing_values = {"0": perm_string[:3], "1": perm_string[3:6], "2":perm_string[6:9]}
for perms_key, value in perms.items(... | def sum_list_values(list_values):
return sum(list_values)
def symbolic_to_octal(perm_string):
perms = {'r': 4, 'w': 2, 'x': 1, '-': 0}
string_value = []
symb_to_octal = []
slicing_values = {'0': perm_string[:3], '1': perm_string[3:6], '2': perm_string[6:9]}
for (perms_key, value) in perms.items... |
print(str(b'ABC'.count(b'A')))
print(str(b'ABC'.count(b'AB')))
print(str(b'ABC'.count(b'AC')))
print(str(b'AbcA'.count(b'A')))
print(str(b'AbcAbcAbc'.count(b'A', 3)))
print(str(b'AbcAbcAbc'.count(b'A', 3, 5)))
print()
print(str(bytearray(b'ABC').count(b'A')))
print(str(bytearray(b'ABC').count(b'AB')))
print(str(bytearr... | print(str(b'ABC'.count(b'A')))
print(str(b'ABC'.count(b'AB')))
print(str(b'ABC'.count(b'AC')))
print(str(b'AbcA'.count(b'A')))
print(str(b'AbcAbcAbc'.count(b'A', 3)))
print(str(b'AbcAbcAbc'.count(b'A', 3, 5)))
print()
print(str(bytearray(b'ABC').count(b'A')))
print(str(bytearray(b'ABC').count(b'AB')))
print(str(bytearr... |
"""Definition for updatesrc_diff_and_update macro."""
load("@bazel_skylib//rules:diff_test.bzl", "diff_test")
load(":updatesrc_update.bzl", "updatesrc_update")
def updatesrc_diff_and_update(
srcs,
outs,
name = None,
update_name = "update",
diff_test_prefix = "",
diff_te... | """Definition for updatesrc_diff_and_update macro."""
load('@bazel_skylib//rules:diff_test.bzl', 'diff_test')
load(':updatesrc_update.bzl', 'updatesrc_update')
def updatesrc_diff_and_update(srcs, outs, name=None, update_name='update', diff_test_prefix='', diff_test_suffix='_difftest', update_visibility=None, diff_test... |
"""Core exceptions"""
class RPGTKBaseException(Exception):
pass
class DiceException(RPGTKBaseException):
pass
| """Core exceptions"""
class Rpgtkbaseexception(Exception):
pass
class Diceexception(RPGTKBaseException):
pass |
""" philoseismos: with passion for the seismic method.
This file is needed to run pytest from a repository directory and avoid
any PYTHONPATH related import issues.
@author: Ivan Dubrovin
e-mail: dubrovin.io@icloud.com """
| """ philoseismos: with passion for the seismic method.
This file is needed to run pytest from a repository directory and avoid
any PYTHONPATH related import issues.
@author: Ivan Dubrovin
e-mail: dubrovin.io@icloud.com """ |
"""
Given a unsorted array with integers, find the median of it.
A median is the middle number of the array after it is sorted.
If there are even numbers in the array, return the N/2-th number after sorted.
Example
Given [4, 5, 1, 2, 3], return 3
Given [7, 9, 4, 5], return 5
Challenge
O(n) time.
"""
__author__ = '... | """
Given a unsorted array with integers, find the median of it.
A median is the middle number of the array after it is sorted.
If there are even numbers in the array, return the N/2-th number after sorted.
Example
Given [4, 5, 1, 2, 3], return 3
Given [7, 9, 4, 5], return 5
Challenge
O(n) time.
"""
__author__ = '... |
config ={
'CONTEXT' : 'We are in DEV context',
'Log_bucket' : 'gc://bucketname_great',
'versionNR' : 'v12.236',
'zone' : 'europe-west1-d',
} | config = {'CONTEXT': 'We are in DEV context', 'Log_bucket': 'gc://bucketname_great', 'versionNR': 'v12.236', 'zone': 'europe-west1-d'} |
def classify(number):
if number < 1:
raise ValueError("Value too small")
aliquot = 0
for i in range(number-1):
if number % (i+1) == 0:
aliquot += i+1
return "perfect" if aliquot == number else "abundant" if aliquot > number else "deficient" | def classify(number):
if number < 1:
raise value_error('Value too small')
aliquot = 0
for i in range(number - 1):
if number % (i + 1) == 0:
aliquot += i + 1
return 'perfect' if aliquot == number else 'abundant' if aliquot > number else 'deficient' |
# File: taniumrest_consts.py
# Copyright (c) 2019-2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
SESSION_URL = "/api/v2/session/login"
TANIUMREST_GET_SAVED_QUESTIONS = "/api/v2/saved_questions"
TANIUMREST_GET_QUESTIONS = "/api/v2/questions"
TANIUMREST_GET_QUESTION_RESU... | session_url = '/api/v2/session/login'
taniumrest_get_saved_questions = '/api/v2/saved_questions'
taniumrest_get_questions = '/api/v2/questions'
taniumrest_get_question_results = '/api/v2/result_data/question/{question_id}'
taniumrest_parse_question = '/api/v2/parse_question'
taniumrest_execute_action = '/api/v2/saved_a... |
class MlflowException(Exception):
"""Base exception in MLflow."""
class IllegalArtifactPathError(MlflowException):
"""The artifact_path parameter was invalid."""
class ExecutionException(MlflowException):
"""Exception thrown when executing a project fails."""
pass
| class Mlflowexception(Exception):
"""Base exception in MLflow."""
class Illegalartifactpatherror(MlflowException):
"""The artifact_path parameter was invalid."""
class Executionexception(MlflowException):
"""Exception thrown when executing a project fails."""
pass |
Text = 'text'
Audio = 'audio'
Document = 'document'
Animation = 'animation'
Game = 'game'
Photo = 'photo'
Sticker = 'sticker'
Video = 'video'
Voice = 'voice'
VideoNote = 'video_note'
Contact = 'contact'
Dice = 'dice'
Location = 'location'
Venue = 'venue'
Poll = 'poll'
NewChatMembers = 'new_chat_members'
LeftChatMember ... | text = 'text'
audio = 'audio'
document = 'document'
animation = 'animation'
game = 'game'
photo = 'photo'
sticker = 'sticker'
video = 'video'
voice = 'voice'
video_note = 'video_note'
contact = 'contact'
dice = 'dice'
location = 'location'
venue = 'venue'
poll = 'poll'
new_chat_members = 'new_chat_members'
left_chat_me... |
class A:
def met(self):
print("this is a method from class A")
class B(A):
def met(self):
print("this is a method from class B")
class C(A):
def met(self):
print("this is a method from class C")
class D(C,B):
def met(self):
print("this is a method from class D"... | class A:
def met(self):
print('this is a method from class A')
class B(A):
def met(self):
print('this is a method from class B')
class C(A):
def met(self):
print('this is a method from class C')
class D(C, B):
def met(self):
print('this is a method from class D')
a... |
# -*- coding: utf-8 -*-
class Solution:
def nthPersonGetsNthSeat(self, n):
return 1 if n == 1 else 0.5
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.nthPersonGetsNthSeat(1)
assert 0.5 == solution.nthPersonGetsNthSeat(2)
assert 0.5 == solution.nthPersonGetsNthSeat... | class Solution:
def nth_person_gets_nth_seat(self, n):
return 1 if n == 1 else 0.5
if __name__ == '__main__':
solution = solution()
assert 1 == solution.nthPersonGetsNthSeat(1)
assert 0.5 == solution.nthPersonGetsNthSeat(2)
assert 0.5 == solution.nthPersonGetsNthSeat(3) |
# Create a function that takes a number num and returns its length.
def number_length(num):
if num != None:
count = 1
val = num
while(val // 10 != 0):
count += 1
val = val // 10
return count
print(number_length(392))
| def number_length(num):
if num != None:
count = 1
val = num
while val // 10 != 0:
count += 1
val = val // 10
return count
print(number_length(392)) |
class Node:
def __init__(self, name):
self.data = name
self.nextnode = None
def remove(self, data, previous):
if self.data == data:
previous.nextnode = self.nextnode
del self.data
else:
if self.nextnode is not None:
self.nextno... | class Node:
def __init__(self, name):
self.data = name
self.nextnode = None
def remove(self, data, previous):
if self.data == data:
previous.nextnode = self.nextnode
del self.data
elif self.nextnode is not None:
self.nextnode.remove(data, sel... |
expected_output = {
'vrf':
{'VRF1':
{'address_family':
{'ipv6': {}}},
'blue':
{'address_family':
{'ipv6':
{'multicast_group':
{'ff30::/12':
{'source_address':
... | expected_output = {'vrf': {'VRF1': {'address_family': {'ipv6': {}}}, 'blue': {'address_family': {'ipv6': {'multicast_group': {'ff30::/12': {'source_address': {'*': {'flags': 'ipv6 pim6', 'incoming_interface_list': {'Null': {'rpf_nbr': '0::'}}, 'oil_count': '0', 'uptime': '10w5d'}}}}}}}, 'default': {'address_family': {'... |
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
idx1 = m - 1
idx2 = n - 1
while idx1>=0 and idx2>=0:
if nums1[idx1] > nums2[idx2]:
... | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
idx1 = m - 1
idx2 = n - 1
while idx1 >= 0 and idx2 >= 0:
if nums1[idx1] > nums2[idx2]:
... |
# The URL we will use when accessing a gulag API instance.
api_url: str = "cmyui.codes"
# When set to True it will allow us to make unverified HTTPS requests. (Good for testing.)
unsafe_request: bool = False | api_url: str = 'cmyui.codes'
unsafe_request: bool = False |
{
'target_defaults': {
'cflags': [
'-Wunused',
'-Wshadow',
'-Wextra',
],
},
'targets': [
# D-Bus code generator.
{
'target_name': 'dbus_code_generator',
'type': 'none',
'variables': {
'dbus_service_config': 'dbus_bindings/dbus-service-config.json',
... | {'target_defaults': {'cflags': ['-Wunused', '-Wshadow', '-Wextra']}, 'targets': [{'target_name': 'dbus_code_generator', 'type': 'none', 'variables': {'dbus_service_config': 'dbus_bindings/dbus-service-config.json', 'dbus_adaptors_out_dir': 'include/authpolicy'}, 'sources': ['dbus_bindings/org.chromium.AuthPolicy.xml'],... |
ENTRY_POINT = 'is_multiply_prime'
FIX = """
Fix incorrect is_prime function
Add more tests
"""
#[PROMPT]
def is_multiply_prime(a):
"""Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
i... | entry_point = 'is_multiply_prime'
fix = '\nFix incorrect is_prime function\nAdd more tests\n'
def is_multiply_prime(a):
"""Write a function that returns true if the given number is the multiplication of 3 prime numbers
and false otherwise.
Knowing that (a) is less then 100.
Example:
is_multiply_pr... |
class AbstractTransitionSystem:
def __init__(self, num_labels):
self.num_labels = num_labels
def num_actions(self):
raise NotImplementedError()
def state(self, num_tokens):
raise NotImplementedError()
def is_final(self, state):
raise NotImplementedError()
def extr... | class Abstracttransitionsystem:
def __init__(self, num_labels):
self.num_labels = num_labels
def num_actions(self):
raise not_implemented_error()
def state(self, num_tokens):
raise not_implemented_error()
def is_final(self, state):
raise not_implemented_error()
d... |
Import('defenv')
### Configuration options
cfg = Variables()
cfg.Add(
(
'NSIS_MAX_STRLEN',
'defines the maximum string length for internal variables and stack entries. 1024 should be plenty, but if you are doing crazy registry stuff, you might want to bump it up. Generally it adds about 16-32x the memory, ... | import('defenv')
cfg = variables()
cfg.Add(('NSIS_MAX_STRLEN', 'defines the maximum string length for internal variables and stack entries. 1024 should be plenty, but if you are doing crazy registry stuff, you might want to bump it up. Generally it adds about 16-32x the memory, so setting this to 4096 from 1024 will ad... |
def search(text, pat):
n = len(text)
m = len(pat)
skip = 0
right = {}
for c in text:
right[c] = -1
for j in range(0, m):
right[pat[j]] = j
i = 0
while i < n-m:
skip = 0
for j in range(m-1, 0, -1):
if pat[j] != text[i+j]:
skip ... | def search(text, pat):
n = len(text)
m = len(pat)
skip = 0
right = {}
for c in text:
right[c] = -1
for j in range(0, m):
right[pat[j]] = j
i = 0
while i < n - m:
skip = 0
for j in range(m - 1, 0, -1):
if pat[j] != text[i + j]:
s... |
class PhysicsForce :
class PhysicsGG :
pass
def W(self, Force, Distance) :
usaha = Force * Distance
return usaha
class PhysicsRotation :
def W(self, frequency) :
omega = 2 * 3.15 * frequency
return omega
Rinta = PhysicsForce()
Usaha = Rinta.W(3,2)
print(Usaha)
... | class Physicsforce:
class Physicsgg:
pass
def w(self, Force, Distance):
usaha = Force * Distance
return usaha
class Physicsrotation:
def w(self, frequency):
omega = 2 * 3.15 * frequency
return omega
rinta = physics_force()
usaha = Rinta.W(3, 2)
print(Usaha)
marsa ... |
# gmail credentials
gmail = dict(
username='username',
password='password'
)
# number of centimeters considered to be acceptable
trigger_distance = 10
# number of seconds spent below trigger distance before sending email
alert_after = 20
| gmail = dict(username='username', password='password')
trigger_distance = 10
alert_after = 20 |
def is_palindrome_permutation(string):
char_set = [0] * 26
total_letter = 0
total_odd = 0
for char in string:
if char >= 'A' and char <= 'Z':
index = ord(char) + ord('A')
elif char >= 'a' and char <= 'z':
index = ord(char)-ord('a')
if char is not ' ':
... | def is_palindrome_permutation(string):
char_set = [0] * 26
total_letter = 0
total_odd = 0
for char in string:
if char >= 'A' and char <= 'Z':
index = ord(char) + ord('A')
elif char >= 'a' and char <= 'z':
index = ord(char) - ord('a')
if char is not ' ':
... |
class StockError(Exception):
def __init__(self, message) -> None:
module_name = self.__class__.__module__
class_name = self.__class__.__name__
error_msg = f'{message} ({module_name}.{class_name})'
super().__init__(error_msg)
class InvalidHttpsReqError(StockError):
"""
This... | class Stockerror(Exception):
def __init__(self, message) -> None:
module_name = self.__class__.__module__
class_name = self.__class__.__name__
error_msg = f'{message} ({module_name}.{class_name})'
super().__init__(error_msg)
class Invalidhttpsreqerror(StockError):
"""
This ... |
a = 1
b = 2
def index():
return 'hello world'
def hello():
return 'hello 2018'
def detail():
return 'detail info'
c = 3
d = 4
| a = 1
b = 2
def index():
return 'hello world'
def hello():
return 'hello 2018'
def detail():
return 'detail info'
c = 3
d = 4 |
class TrackingMode(object):
PRINTING, LOGGING = range(0, 2)
TRACKING = True
TRACKING_MODE = TrackingMode.PRINTING
class TimyConfig(object):
DEFAULT_IDENT = 'Timy'
def __init__(self, tracking=TRACKING, tracking_mode=TRACKING_MODE):
self.tracking = tracking
self.tracking_mode = tracking_m... | class Trackingmode(object):
(printing, logging) = range(0, 2)
tracking = True
tracking_mode = TrackingMode.PRINTING
class Timyconfig(object):
default_ident = 'Timy'
def __init__(self, tracking=TRACKING, tracking_mode=TRACKING_MODE):
self.tracking = tracking
self.tracking_mode = tracking_mo... |
# two float values
val1 = 100.99
val2 = 76.15
# Adding the two given numbers
sum = float(val1) + float(val2)
# Displaying the addition result
print("The sum of given numbers is: ", sum) | val1 = 100.99
val2 = 76.15
sum = float(val1) + float(val2)
print('The sum of given numbers is: ', sum) |
with open("dane/dane.txt") as f:
lines = []
for line in f:
sline = line.strip()
lines.append(sline)
count = 0
for line in lines:
if line[0] == line[-1]:
count += 1
print(f"{count=}")
| with open('dane/dane.txt') as f:
lines = []
for line in f:
sline = line.strip()
lines.append(sline)
count = 0
for line in lines:
if line[0] == line[-1]:
count += 1
print(f'count={count!r}') |
def decode_orientation(n_classes, train_data, train_labels, test_data, test_labels):
""" Initialize, train, and test deep network to decode binned orientation from neural responses
Args:
n_classes (scalar): number of classes in which to bin orientation
train_data (torch.Tensor): n_train x n_neurons tensor... | def decode_orientation(n_classes, train_data, train_labels, test_data, test_labels):
""" Initialize, train, and test deep network to decode binned orientation from neural responses
Args:
n_classes (scalar): number of classes in which to bin orientation
train_data (torch.Tensor): n_train x n_neurons tenso... |
class Customer:
def __init__(self, client):
self.client = client
self.logger = client.logger
self.endpoint_base = '/data/v2/projects/{}/customers'.format(client.project_token)
def get_customer(self, ids):
path = '{}/export-one'.format(self.endpoint_base)
payload = {'cust... | class Customer:
def __init__(self, client):
self.client = client
self.logger = client.logger
self.endpoint_base = '/data/v2/projects/{}/customers'.format(client.project_token)
def get_customer(self, ids):
path = '{}/export-one'.format(self.endpoint_base)
payload = {'cus... |
__author__ = 'wektor'
class GenericBackend(object):
def set(self, key, value):
raise NotImplemented
def get(self, key):
raise NotImplemented
def delete(self, key):
raise NotImplemented | __author__ = 'wektor'
class Genericbackend(object):
def set(self, key, value):
raise NotImplemented
def get(self, key):
raise NotImplemented
def delete(self, key):
raise NotImplemented |
#!/usr/bin/env python
""" generated source for module MetaGamingException """
# package: org.ggp.base.player.gamer.exception
@SuppressWarnings("serial")
class MetaGamingException(Exception):
""" generated source for class MetaGamingException """
def __init__(self, cause):
""" generated source for method... | """ generated source for module MetaGamingException """
@suppress_warnings('serial')
class Metagamingexception(Exception):
""" generated source for class MetaGamingException """
def __init__(self, cause):
""" generated source for method __init__ """
super(MetaGamingException, self).__init__(ca... |
#
# PySNMP MIB module H3C-UNICAST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-UNICAST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:24:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
'''
nums: [2, 3, -2, 4]
max: [2, 6, -2, 4]
min: [2, 3, -12, -48]
max: [2, 6, 6, 6]
''' | """
nums: [2, 3, -2, 4]
max: [2, 6, -2, 4]
min: [2, 3, -12, -48]
max: [2, 6, 6, 6]
""" |
def gmt2json(pathx,hasDescColumn=True,isFuzzy=False):
wordsAll = []
# secondColumn = []
with open(pathx,'r') as gf:
for line in gf:
line = line.strip('\r\n\t')
# if not a empty line
if line:
words = []
i = 0
for item in line.split('\t'):
if i==0:
words.append(item)
els... | def gmt2json(pathx, hasDescColumn=True, isFuzzy=False):
words_all = []
with open(pathx, 'r') as gf:
for line in gf:
line = line.strip('\r\n\t')
if line:
words = []
i = 0
for item in line.split('\t'):
if i == 0:
... |
class Coordinates:
"""
Geo location coordinates.
Reference: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects#coordinates
"""
def __init__(self, data: dict = {}):
if not data:
return None
self.coordinates = data.get('coordinates')
... | class Coordinates:
"""
Geo location coordinates.
Reference: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects#coordinates
"""
def __init__(self, data: dict={}):
if not data:
return None
self.coordinates = data.get('coordinates')
se... |
OCM_SIZE = 2 ** 8
READ_MODE = 0
WRITE_MODE = 1
DATA_BITWIDTH = 32
WORD_SIZE = DATA_BITWIDTH / 8
instream = CoramInStream(0, datawidth=DATA_BITWIDTH, size=64)
outstream = CoramOutStream(0, datawidth=DATA_BITWIDTH, size=64)
channel = CoramChannel(idx=0, datawidth=32)
DOWN_LEFT = 0
DOWN_PARENT = 1
DOWN_RIGHT = 2
UP_PARE... | ocm_size = 2 ** 8
read_mode = 0
write_mode = 1
data_bitwidth = 32
word_size = DATA_BITWIDTH / 8
instream = coram_in_stream(0, datawidth=DATA_BITWIDTH, size=64)
outstream = coram_out_stream(0, datawidth=DATA_BITWIDTH, size=64)
channel = coram_channel(idx=0, datawidth=32)
down_left = 0
down_parent = 1
down_right = 2
up_p... |
'''
Endpoints are collected from the Market Data Endpoints api section under the official binance api docs:
https://binance-docs.github.io/apidocs/spot/en/#market-data-endpoints
'''
# Test Connectivity:
class test_ping:
params = None
method = 'GET'
endpoint = '/api/v3/ping'
security_type = 'None'
# C... | """
Endpoints are collected from the Market Data Endpoints api section under the official binance api docs:
https://binance-docs.github.io/apidocs/spot/en/#market-data-endpoints
"""
class Test_Ping:
params = None
method = 'GET'
endpoint = '/api/v3/ping'
security_type = 'None'
class Get_Servertime:
... |
## Oscillating Lambda Man
##
## Directions:
### 0: top
### 1: right
### 2: bottom
### 3: left
def main(world, _ghosts):
return (strategy_state(), step)
def step(state, world):
return (update_state(state), deduce_direction(state, world))
# Oscilation strategy state
def strategy_state():
#returns (frequency, co... | def main(world, _ghosts):
return (strategy_state(), step)
def step(state, world):
return (update_state(state), deduce_direction(state, world))
def strategy_state():
return (4, 0)
def update_state(state):
return (state[0], state[1:] + 1)
def deduce_direction(state, _world):
if state[0] > modulo(s... |
url= 'http://ww.sougou.com/s?'
def sougou(nets):
count = 1
for net in nets:
rest1 = 'res%d.txt' %count
with open(rest1,'w',encoding='utf8') as f:
f.write(net)
print(net)
count +=1
if __name__ == '__main__':
nets = ('one','two','pr')
sougou(nets) | url = 'http://ww.sougou.com/s?'
def sougou(nets):
count = 1
for net in nets:
rest1 = 'res%d.txt' % count
with open(rest1, 'w', encoding='utf8') as f:
f.write(net)
print(net)
count += 1
if __name__ == '__main__':
nets = ('one', 'two', 'pr')
sougou(nets) |
class Task:
def name():
raise NotImplementedError
def description():
raise NotImplementedError
def inputs():
raise NotImplementedError
def run(inputs):
raise NotImplementedError
| class Task:
def name():
raise NotImplementedError
def description():
raise NotImplementedError
def inputs():
raise NotImplementedError
def run(inputs):
raise NotImplementedError |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_cl... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
#Updating menu to include a save option
students= []
def displayMenu():
print("what would you like to do?")
print("\t(a) Add new student")
print("\t(v) View students")
print("\t(s) Save students")
print("\t(q) Quit")
choice = input("type one letter (a/v/s/q):").strip()
return choice
def do... | students = []
def display_menu():
print('what would you like to do?')
print('\t(a) Add new student')
print('\t(v) View students')
print('\t(s) Save students')
print('\t(q) Quit')
choice = input('type one letter (a/v/s/q):').strip()
return choice
def do_add():
print('in adding')
def do... |
# You need the Elemental codex 1+ to cast "Haste"
# You need unique hero to perform resetCooldown action
# You need the Emperor's gloves to cast "Chain Lightning"
hero.cast("haste", hero)
hero.moveDown()
hero.moveRight()
hero.moveDown(0.5)
enemy = hero.findNearestEnemy()
hero.cast("chain-lightning", enemy)
hero.resetC... | hero.cast('haste', hero)
hero.moveDown()
hero.moveRight()
hero.moveDown(0.5)
enemy = hero.findNearestEnemy()
hero.cast('chain-lightning', enemy)
hero.resetCooldown('chain-lightning')
hero.cast('chain-lightning', enemy) |
"""
Module: 'flashbdev' on esp32 3.0.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='3.0.0', version='v3.0.0 on 2020-01-29', machine='ESP32 module with ESP32')
# Stubber: 1.3.2
class Partition:
''
BOOT = 0
RUNNING = 1
TYPE_APP = 0
TYPE_DATA = 1
def find():
pass
def get_ne... | """
Module: 'flashbdev' on esp32 3.0.0
"""
class Partition:
""""""
boot = 0
running = 1
type_app = 0
type_data = 1
def find():
pass
def get_next_update():
pass
def info():
pass
def ioctl():
pass
def readblocks():
pass
def set_boo... |
'''
Title : String Formatting
Subdomain : Strings
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
def print_formatted(number):
# your code goes here
width = len("{0:b}".format(n))
for i in range(1,n+1):
print( "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".f... | """
Title : String Formatting
Subdomain : Strings
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
"""
def print_formatted(number):
width = len('{0:b}'.format(n))
for i in range(1, n + 1):
print('{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}'.format(i, width=width))
... |
class FiniteAutomata:
def __init__(self):
Q = [] # finite set of states
E = [] # finite alphabet
D = {} # transition function
q0 = '' # initial state
F = [] # set of final states
self.clear_values()
def clear_values(self):
self.Q =... | class Finiteautomata:
def __init__(self):
q = []
e = []
d = {}
q0 = ''
f = []
self.clear_values()
def clear_values(self):
self.Q = []
self.E = []
self.D = {}
self.q0 = ''
self.F = []
def read(self, file_name):
... |
class Solution:
"""
@param n: an integer
@return: the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n
"""
def nextGreaterElement(self, n):
digits = [i for i in str(n)]
digits.sort()
res = self.dfs(digits, [], ... | class Solution:
"""
@param n: an integer
@return: the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n
"""
def next_greater_element(self, n):
digits = [i for i in str(n)]
digits.sort()
res = self.dfs(digits, [... |
tup=tuple(input("Enter the tuple").split(","))
st=tuple(input("Enter the another tuple").split(","))
tup1=tup+st
print(tup1)
| tup = tuple(input('Enter the tuple').split(','))
st = tuple(input('Enter the another tuple').split(','))
tup1 = tup + st
print(tup1) |
# -*- coding: utf-8 -*-
# DATA STRUCTURES
cats = [
{"name": "tom", "age": 1, "size": "small"},
{"name": "ash", "age": 2, "size": "medium"},
{"name": "hurley", "age": 5, "size": "large"},
]
print(cats)
| cats = [{'name': 'tom', 'age': 1, 'size': 'small'}, {'name': 'ash', 'age': 2, 'size': 'medium'}, {'name': 'hurley', 'age': 5, 'size': 'large'}]
print(cats) |
# coding=utf-8
class JavaHeap:
def __init__(self):
pass
| class Javaheap:
def __init__(self):
pass |
# Generated by h2py from /usr/include/netinet/in.h
# Included from net/nh.h
# Included from sys/machine.h
LITTLE_ENDIAN = 1234
BIG_ENDIAN = 4321
PDP_ENDIAN = 3412
BYTE_ORDER = BIG_ENDIAN
DEFAULT_GPR = 0xDEADBEEF
MSR_EE = 0x8000
MSR_PR = 0x4000
MSR_FP = 0x2000
MSR_ME = 0x1000
MSR_FE = 0x0800
MSR_FE0 = 0x0800
MSR_SE = ... | little_endian = 1234
big_endian = 4321
pdp_endian = 3412
byte_order = BIG_ENDIAN
default_gpr = 3735928559
msr_ee = 32768
msr_pr = 16384
msr_fp = 8192
msr_me = 4096
msr_fe = 2048
msr_fe0 = 2048
msr_se = 1024
msr_be = 512
msr_ie = 256
msr_fe1 = 256
msr_al = 128
msr_ip = 64
msr_ir = 32
msr_dr = 16
msr_pm = 4
default_msr =... |
#Inputing Age
age = int(input("Enter Age : "))
# condition to check if the person is an adult or a teenager or a kid
if age>=18:
status="Not a teenager. You are an adult"
elif age>=13:
status="Teenager"
elif age<=12:
status="You are a kid"
print("You are ",status,)# Printing the r... | age = int(input('Enter Age : '))
if age >= 18:
status = 'Not a teenager. You are an adult'
elif age >= 13:
status = 'Teenager'
elif age <= 12:
status = 'You are a kid'
print('You are ', status) |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 09 19:07:20 2018
@author: techietrader
""" | """
Created on Fri Nov 09 19:07:20 2018
@author: techietrader
""" |
__author__ = 'chira'
# "def" as defining mathematical functions
# 18-Unpacking_args gives an alternate way to pass arguments
def f(x): # function name is "f". It has ONE argument
y = 2*x + 3
print("f(%d) = %d" %(x,y))
def g(x): # function name is "g". It has ONE argument
y = pow(x,2)
... | __author__ = 'chira'
def f(x):
y = 2 * x + 3
print('f(%d) = %d' % (x, y))
def g(x):
y = pow(x, 2)
print('g(%d) = %d' % (x, y))
def h(x, y):
z = pow(x, 2) + 3 * y
print('h(%d,%d) = %d' % (x, y, z))
f(1)
f(3)
g(5)
h(2, 3) |
def list_reverse(list1):
new_list = []
for i in range(len(list1)-1, -1, -1):
new_list.append(list1[i])
return new_list
test = [1, 2, 3, 4, 5, 6]
print(test)
print(list_reverse(test))
| def list_reverse(list1):
new_list = []
for i in range(len(list1) - 1, -1, -1):
new_list.append(list1[i])
return new_list
test = [1, 2, 3, 4, 5, 6]
print(test)
print(list_reverse(test)) |
"""This problem was asked by Samsung.
A group of houses is connected to the main water plant by means of a set of pipes.
A house can either be connected by a set of pipes extending directly to the plant,
or indirectly by a pipe to a nearby house which is otherwise connected.
For example, here is a possible configur... | """This problem was asked by Samsung.
A group of houses is connected to the main water plant by means of a set of pipes.
A house can either be connected by a set of pipes extending directly to the plant,
or indirectly by a pipe to a nearby house which is otherwise connected.
For example, here is a possible configur... |
"""
This module contains all the exceptions that ZipTaxClient can throw
See http://docs.zip-tax.com/en/latest/api_response.html#response-codes
"""
class ZipTaxFailure(Exception):
pass
class ZipTaxInvalidKey(ZipTaxFailure):
pass
class ZipTaxInvalidFormat(ZipTaxFailure):
pass
class ZipTaxInvalidData(ZipTa... | """
This module contains all the exceptions that ZipTaxClient can throw
See http://docs.zip-tax.com/en/latest/api_response.html#response-codes
"""
class Ziptaxfailure(Exception):
pass
class Ziptaxinvalidkey(ZipTaxFailure):
pass
class Ziptaxinvalidformat(ZipTaxFailure):
pass
class Ziptaxinvaliddata(ZipTa... |
#
# @lc app=leetcode id=205 lang=python3
#
# [205] Isomorphic Strings
#
# https://leetcode.com/problems/isomorphic-strings/description/
#
# algorithms
# Easy (40.89%)
# Likes: 2445
# Dislikes: 520
# Total Accepted: 402.9K
# Total Submissions: 974.8K
# Testcase Example: '"egg"\n"add"'
#
# Given two strings s and ... | class Solution:
def is_isomorphic(self, s: str, t: str) -> bool:
if not s or not t or len(s) == 0 or (len(t) == 0) or (len(s) != len(t)):
return False
(s2t, t2s) = ({}, {})
n = len(s)
for i in range(n):
if s[i] not in s2t:
if t[i] in t2s and t... |
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
... | class Solution:
def max_area_of_island(self, grid: List[List[int]]) -> int:
grid = [[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0,... |
# event manager permissions are set to expire this many days after event ends
CBAC_VALID_AFTER_EVENT_DAYS = 180
# when a superuser overrides permissions, this is how many minutes the temporary permissions last
CBAC_SUDO_VALID_MINUTES = 20
# these claims are used, if present, when sudoing. Note that sudo cannot give y... | cbac_valid_after_event_days = 180
cbac_sudo_valid_minutes = 20
cbac_sudo_claims = ['organization', 'event', 'app'] |
"""This module contains the filter and regressor managers used by
task to apply the filters and regressors. Both those classes use a
side operation manager that implement the generic functions. This
allow to apply the filters and regressors as early as possible during
the triplet generation to optimise the performances... | """This module contains the filter and regressor managers used by
task to apply the filters and regressors. Both those classes use a
side operation manager that implement the generic functions. This
allow to apply the filters and regressors as early as possible during
the triplet generation to optimise the performances... |
def is_isogram(string):
found = []
for letter in string.lower():
if letter in found:
return False
if letter.isalpha():
found.append(letter)
return True
| def is_isogram(string):
found = []
for letter in string.lower():
if letter in found:
return False
if letter.isalpha():
found.append(letter)
return True |
class speedadjustclass():
def __init__(self):
self.speedadjust = 1.0
return
def speedincrease(self):
self.speedadjust = round(min(3.0, self.speedadjust + 0.05), 2)
print("In speedincrease",self.speedadjust)
def speeddecrease(self):
self.speedadjust = round(max(0.5, ... | class Speedadjustclass:
def __init__(self):
self.speedadjust = 1.0
return
def speedincrease(self):
self.speedadjust = round(min(3.0, self.speedadjust + 0.05), 2)
print('In speedincrease', self.speedadjust)
def speeddecrease(self):
self.speedadjust = round(max(0.5, ... |
# getting input from user and pars it to the integer
your_weight = input("Enter your Weight in kg: ")
print(type(your_weight))
# to parse value of variable, we have to put it in seperate line or put it equal new variable
int_weight_parser = int(your_weight)
print(type(int_weight_parser))
# formatted String
first_... | your_weight = input('Enter your Weight in kg: ')
print(type(your_weight))
int_weight_parser = int(your_weight)
print(type(int_weight_parser))
first_name = 'pooya'
last_name = 'panahandeh'
message = f'mr. {first_name} {last_name}, welcome to the python world.'
print(message)
print(len(message))
print(message.find('p'))
... |
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first = second = third = -math.inf
for num in nums:
if num > first:
first, second, third = num, first, second
elif num != first and num > second... | class Solution:
def third_max(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first = second = third = -math.inf
for num in nums:
if num > first:
(first, second, third) = (num, first, second)
elif num != first and num > ... |
"""
This is a collection of default transaction data used to test various components.
"""
UNIT = 100000000
"""This structure is used throughout the test suite to populate transactions with standardized and tested data."""
#removed pubkey hash, may need to be re-added.
DEFAULT_PARAMS = {
'addresses': [
['U... | """
This is a collection of default transaction data used to test various components.
"""
unit = 100000000
'This structure is used throughout the test suite to populate transactions with standardized and tested data.'
default_params = {'addresses': [['Ukn3L4dgG13R3dSdxLvAAJizeiaW7cyUFz', 'cUuSAEXmiYMpu2Eu8QR52NzpsYB5Ma... |
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True") | a = 200
b = 33
c = 500
if a > b and c > a:
print('Both conditions are True') |
# MetaPrint.py
# Copyright (c) 2008-2017 Chris Gonnerman
# 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 source code must retain the above copyright
# notice, this list... | """
MetaPrint.py defines a class and utility functions for use by programs
which also use MSWinPrint.py for output. MetaPrint exposes a document
class which replicates the functionality of MSWinPrint, but rather than
actually printing, a document object collects the output generated so
that it can be replayed, either... |
# Copyright 2014 Google Inc. 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 applicable law or ag... | """Default value constants exposed by core utilities."""
default_registry = 'gcr.io'
regional_registries = ['us.gcr.io', 'eu.gcr.io', 'asia.gcr.io']
bucket_registries = ['b.gcr.io', 'bucket.gcr.io']
appengine_registry = 'appengine.gcr.io'
specialty_registries = BUCKET_REGISTRIES + [APPENGINE_REGISTRY]
all_supported_reg... |
#print is function when we want to print something on output
print("My name is Dhruv")
#You will notice something strange if you try to print any directory
#print("C:\Users\dhruv\Desktop\dhruv.github.io")
#Yes unicodeescape error
# Remember i told about escape character on previous tutorial
# yes it causing prob... | print('My name is Dhruv')
print('C:\\Users\\dhruv\\Desktop\\dhruv.github.io')
myname = 'Dhruv '
myname + 'Patel'
myname * 5 |
SECRET_KEY = '-dummy-key-'
INSTALLED_APPS = [
'pgcomments',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
},
}
| secret_key = '-dummy-key-'
installed_apps = ['pgcomments']
databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2'}} |
names = ["libquadmath0", "libssl1.0.0"]
status = {"libquadmath0":
{"Name": "libquadmath0",
"Dependencies": ["gcc-5-base", "libc6"],
"Description": "GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float1... | names = ['libquadmath0', 'libssl1.0.0']
status = {'libquadmath0': {'Name': 'libquadmath0', 'Dependencies': ['gcc-5-base', 'libc6'], 'Description': 'GCC Quad-Precision Math Library<br/> A library, which provides quad-precision mathematical functions on targets<br/> supporting the __float128 datatype. The library is used... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# dfs search
... | class Solution(object):
def max_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
'\n ### simple bfs\n\n stck=[root]\n depth=0\n # bfs search\n while stck:\n tmp=[]\n ... |
"""Exceptions"""
class LibvirtConnectionError(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass
class DomainNotFoundError(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass
| """Exceptions"""
class Libvirtconnectionerror(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass
class Domainnotfounderror(Exception):
"""Error to indicate something went wrong with the LibvirtConnection class"""
pass |
S = input()
scale_list = ["Do", "", "Re", "", "Mi", "Fa", "", "So", "", "La", "", "Si"]
order = "WBWBWWBWBWBW" * 3
print(scale_list[order.find(S)])
| s = input()
scale_list = ['Do', '', 'Re', '', 'Mi', 'Fa', '', 'So', '', 'La', '', 'Si']
order = 'WBWBWWBWBWBW' * 3
print(scale_list[order.find(S)]) |
class Solution:
def solve(self, nums):
uniques = set()
j = 0
ans = 0
for i in range(len(nums)):
while j < len(nums) and nums[j] not in uniques:
uniques.add(nums[j])
j += 1
ans = max(ans, len(uniques))
... | class Solution:
def solve(self, nums):
uniques = set()
j = 0
ans = 0
for i in range(len(nums)):
while j < len(nums) and nums[j] not in uniques:
uniques.add(nums[j])
j += 1
ans = max(ans, len(uniques))
uniques.re... |
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0: return 0
min_price, max_profit = prices[0], 0
for i in prices[1:]:
min_price = min(min_price, i)
profit = i - min_price
... | class Solution:
def max_profit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
(min_price, max_profit) = (prices[0], 0)
for i in prices[1:]:
min_price = min(min_price, i)
profit = i ... |
"""
patterns - Package of different software patterns.
Provided patterns:
* `abstractf` - abstract factory
* `threetier` - 3-tier software architecture
Use:
Each submodule is self-contained. If you don't want the whole package, you can
take the files you need. Usage examples are in the examples directory.
"""
__autho... | """
patterns - Package of different software patterns.
Provided patterns:
* `abstractf` - abstract factory
* `threetier` - 3-tier software architecture
Use:
Each submodule is self-contained. If you don't want the whole package, you can
take the files you need. Usage examples are in the examples directory.
"""
__autho... |
#!/usr/bin/python3
def append_after(filename="", search_string="", new_string=""):
"""appends after search string instances in file
"""
with open(filename, 'r', encoding='utf-8') as myFile:
lines = myFile.readlines()
for i, line in enumerate(lines):
if search_string in line:
... | def append_after(filename='', search_string='', new_string=''):
"""appends after search string instances in file
"""
with open(filename, 'r', encoding='utf-8') as my_file:
lines = myFile.readlines()
for (i, line) in enumerate(lines):
if search_string in line:
lines.insert(i +... |
MUSHISHI_ID = 457
FULLMETAL_ID = 25
GINKO_ID = 425
KANA_HANAZAWA_ID = 185
YEAR = 2018
SEASON = "winter"
DAY = "monday"
TYPE = "anime"
SUBTYPE = "tv"
GENRE = 1
PRODUCER = 37
MAGAZINE = 83
USERNAME = "Nekomata1037"
CLUB_ID = 379
| mushishi_id = 457
fullmetal_id = 25
ginko_id = 425
kana_hanazawa_id = 185
year = 2018
season = 'winter'
day = 'monday'
type = 'anime'
subtype = 'tv'
genre = 1
producer = 37
magazine = 83
username = 'Nekomata1037'
club_id = 379 |
"""
A Mapping module
"""
class DataMapping:
"""DataMapping"""
def __init__(self, data: dict, keys_map: dict):
"""__init__
:param data:
:type data: dict
:param keys_map:
:type keys_map: dict
data = {'username': 'John', 'email': 'john@example.com'}
keys_... | """
A Mapping module
"""
class Datamapping:
"""DataMapping"""
def __init__(self, data: dict, keys_map: dict):
"""__init__
:param data:
:type data: dict
:param keys_map:
:type keys_map: dict
data = {'username': 'John', 'email': 'john@example.com'}
keys_... |
def setup():
size(500,500)
smooth()
background(50)
strokeWeight(5)
stroke(250)
noLoop()
cx=250
cy=250
cR=200
i=0
def draw():
global cx,cy, cR, i
while i < 2*PI:
i +=PI/6
x1 = cos(i)*cR+cx
y1 = sin(i)*cR+cy
line(x1,y1,x1,y1)
... | def setup():
size(500, 500)
smooth()
background(50)
stroke_weight(5)
stroke(250)
no_loop()
cx = 250
cy = 250
c_r = 200
i = 0
def draw():
global cx, cy, cR, i
while i < 2 * PI:
i += PI / 6
x1 = cos(i) * cR + cx
y1 = sin(i) * cR + cy
line(x1, y1, x1, y1)
... |
# Here is the code from the generators2.py file
# From the demo
# Can you refactor any or all of it to use comprehensions?
# More chaining
# Courtesy of my friend Jim Prior
def gen_fibonacci():
a, b = 0, 1
while True:
a, b = b, a + b
yield b
def gen_even(gen):
return (number for number in ... | def gen_fibonacci():
(a, b) = (0, 1)
while True:
(a, b) = (b, a + b)
yield b
def gen_even(gen):
return (number for number in gen if number % 2 == 0)
def error():
raise StopIteration
def gen_lte(gen, max):
return (error() if number > max else number for number in gen)
for num in ge... |
#from models import HVAC
class HvacBuildingTracker():
""" Creates a tracker that will manage the data that the hvac building generates
"""
def __init__(self):
"""Creates an instance of the hvac building tracker
"""
self.__HouseTempArr = []
self.__OutsideTempArr = []
self.__AvgPowerPerSecArr = []
def ... | class Hvacbuildingtracker:
""" Creates a tracker that will manage the data that the hvac building generates
"""
def __init__(self):
"""Creates an instance of the hvac building tracker
"""
self.__HouseTempArr = []
self.__OutsideTempArr = []
self.__AvgPowerPerSecArr = []
d... |
def main():
value = 1
if value == 0:
print("False")
elif value == 1:
print("True")
else:
print("Undefined")
if __name__ == "__main__":
main()
| def main():
value = 1
if value == 0:
print('False')
elif value == 1:
print('True')
else:
print('Undefined')
if __name__ == '__main__':
main() |
# -*- coding: UTF-8 -*-
logger.info("Loading 16 objects to table ledger_matchrule...")
# fields: id, account, journal
loader.save(create_ledger_matchrule(1,2,1))
loader.save(create_ledger_matchrule(2,2,2))
loader.save(create_ledger_matchrule(3,4,3))
loader.save(create_ledger_matchrule(4,2,4))
loader.save(create_ledger_... | logger.info('Loading 16 objects to table ledger_matchrule...')
loader.save(create_ledger_matchrule(1, 2, 1))
loader.save(create_ledger_matchrule(2, 2, 2))
loader.save(create_ledger_matchrule(3, 4, 3))
loader.save(create_ledger_matchrule(4, 2, 4))
loader.save(create_ledger_matchrule(5, 4, 4))
loader.save(create_ledger_m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.