content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def powerLevelForCell(x, y, gridSerialNumber):
rackID = x + 11
powerLevel = rackID * (y + 1)
powerLevel += gridSerialNumber
powerLevel *= rackID
powerLevel //= 100
toSubtract = powerLevel // 10 * 10
powerLevel -= toSubtract
powerLevel -= 5
return powerLevel
"""
print(powerLevelForCell(2, 4, 8))
pri... | def power_level_for_cell(x, y, gridSerialNumber):
rack_id = x + 11
power_level = rackID * (y + 1)
power_level += gridSerialNumber
power_level *= rackID
power_level //= 100
to_subtract = powerLevel // 10 * 10
power_level -= toSubtract
power_level -= 5
return powerLevel
'\t\nprint(powe... |
# Input: Two strings, Pattern and Genome
# Output: A list containing all starting positions where Pattern appears as a substring of Genome
def PatternMatching(pattern, genome):
positions = [] # output variable
# your code here
for i in range(len(genome)-len(pattern)+1):
if genome[i:i+len(patt... | def pattern_matching(pattern, genome):
positions = []
for i in range(len(genome) - len(pattern) + 1):
if genome[i:i + len(pattern)] == pattern:
positions.append(i)
return positions
def approximate_pattern_matching(pattern, genome, d):
positions = []
for i in range(len(genome) - ... |
def encodenum(num):
num = str(num)
line =""
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ""
for c in line:
num += str(ord(c)-ord('a'))
return num | def encodenum(num):
num = str(num)
line = ''
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ''
for c in line:
num += str(ord(c) - ord('a'))
return num |
class exemplo():
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode)
| class Exemplo:
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode) |
class Foo():
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = Foo()
g = Foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop)
| class Foo:
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = foo()
g = foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop) |
#author: Lynijah
# date: 07-01-2021
def blank():
return print(" ")
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that pri... | def blank():
return print(' ')
print('Addition Section')
print(2006 + 2000)
print(2000 + 9000 + 4)
print(-4 + -7)
blank()
print('Subtraction Section')
print(2006 - 2000)
print(2000 - 10 - 90)
print(-4 - -7)
blank()
print('Multiplication And True Division Section')
print(6 * 2000)
print(2000 / 9)
print(5 * 8 / 2)
bl... |
class RemoteError(Exception):
"""A base class for all remote's custom exception"""
class RemoteConnectionError(RemoteError):
"""Remote wasn't able to connect to remote host"""
class RemoteExecutionError(RemoteError):
"""A command executed remotely exited with non-zero status"""
class ConfigurationErro... | class Remoteerror(Exception):
"""A base class for all remote's custom exception"""
class Remoteconnectionerror(RemoteError):
"""Remote wasn't able to connect to remote host"""
class Remoteexecutionerror(RemoteError):
"""A command executed remotely exited with non-zero status"""
class Configurationerror(R... |
#
# PySNMP MIB module CISCO-ENTITY-REDUNDANCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-REDUNDANCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, value_size_constraint, single_value_constraint) ... |
message = "This is a message!"
print(message)
message = "This is a new message!"
print(message) | message = 'This is a message!'
print(message)
message = 'This is a new message!'
print(message) |
# author: Roy Kid
# contact: lijichen365@126.com
# date: 2021-09-20
# version: 0.0.1
def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
lenValue = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.ap... | def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
len_value = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.append({})
for (k, v) in kwargs.items():
for (i, vv) in enumerate(v):
... |
# Feel free to add new properties and methods to the class.
"""
class MinMaxStack:
def __init__(self):
self.stack = []
self.min = float('inf')
self.max = float('-inf')
def _update_min(self, num, drop=False):
if drop and num == self.min:
self.min = min(self.stack or [... | """
class MinMaxStack:
def __init__(self):
self.stack = []
self.min = float('inf')
self.max = float('-inf')
def _update_min(self, num, drop=False):
if drop and num == self.min:
self.min = min(self.stack or [float('inf')])
elif not drop and num < self.min:
... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331001120
# Hideout :: Training Room 2
KINESIS = 1531000
JAY = 1531001
if "1" not in sm.getQuestEx(22700, "E2"):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
... | kinesis = 1531000
jay = 1531001
if '1' not in sm.getQuestEx(22700, 'E2'):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
sm.setNpcOverrideBoxChat(JAY)
sm.sendSay('#face9#Fine, whatever! Just ignore the test plan I ... |
def do_something(x):
sq_x=x**2
return (sq_x) # this will make it much easier in future problems to see that something is actually happening
| def do_something(x):
sq_x = x ** 2
return sq_x |
"""1143. Longest Common Subsequence"""
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i, a... | """1143. Longest Common Subsequence"""
class Solution(object):
def longest_common_subsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
m = len(text1)
n = len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
... |
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in (s[1:] + s[:-1])
if __name__ == '__main__':
solution = Solution()
print(solution.repeatedSubstringPattern("abab"))
print(solution.repeatedSubstringPatter... | class Solution:
def repeated_substring_pattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in s[1:] + s[:-1]
if __name__ == '__main__':
solution = solution()
print(solution.repeatedSubstringPattern('abab'))
print(solution.repeatedSubstringPattern('aaaa')... |
"""Exercise 2: Step Over, Step Into, Step Out"""
def calculate_sum(list_of_nums):
"""Calculates the sum of a list of numbers."""
total = 0
for num in list_of_nums:
total += num
return total
def calculate_average(list_of_nums):
"""Calculates the average of a list of numbers."""
average... | """Exercise 2: Step Over, Step Into, Step Out"""
def calculate_sum(list_of_nums):
"""Calculates the sum of a list of numbers."""
total = 0
for num in list_of_nums:
total += num
return total
def calculate_average(list_of_nums):
"""Calculates the average of a list of numbers."""
average ... |
class SetUp:
base = "http://localhost:8890/"
URL = "http://localhost:8890/notebooks/test/testing.ipynb"
kernel_link = "#kernellink"
start_kernel = "link=Restart & Run All"
start_confirm = "(.//*[normalize-space(text()) and normalize-space(.)='Continue Running'])[1]/following::button[1]"
title = ... | class Setup:
base = 'http://localhost:8890/'
url = 'http://localhost:8890/notebooks/test/testing.ipynb'
kernel_link = '#kernellink'
start_kernel = 'link=Restart & Run All'
start_confirm = "(.//*[normalize-space(text()) and normalize-space(.)='Continue Running'])[1]/following::button[1]"
title = ... |
# int object is immutable
age = 30
print(id(age)) # id is used to get a object reference id
age = 40
print(id(age))
# list is mutable
series1 = [1, 2, 3]
series2 = series1
print(id(series1))
print(id(series1))
series1[1] = 10
print(series1)
print(series2)
print(id(series1))
print(id(series1))
# i... | age = 30
print(id(age))
age = 40
print(id(age))
series1 = [1, 2, 3]
series2 = series1
print(id(series1))
print(id(series1))
series1[1] = 10
print(series1)
print(series2)
print(id(series1))
print(id(series1))
series1 = [1, 2, 3]
series2 = [1, 2, 3]
print(series1 is series2)
print(series1 == series2) |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast = head
slow = head
while slow != None and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False... | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast = head
slow = head
while slow != None and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
... |
__author__ = 'rene_esteves'
def factorial(input):
if input < 1: # base case
return 1
else:
return input * factorial(input - 1) # recursive call
def sum(input):
if input == 1: # base_case
return 1
else:
return input + sum(input - 1) # recursive call
def fibonacci... | __author__ = 'rene_esteves'
def factorial(input):
if input < 1:
return 1
else:
return input * factorial(input - 1)
def sum(input):
if input == 1:
return 1
else:
return input + sum(input - 1)
def fibonacci(input):
if input == 1 or input == 0:
print('PAROU')
... |
""""
2 shelves
5 books
5 nooks
5 books in each shelve MAX VALUE = 5
1 book comes out,
4 books at any shelf
1 space is there
1 user 10 0 clock
another user 12 0 clock returned
another user 01 clock returned
10 -> out
12 -> out
1 -> in
2 -> out
3 -> out
5 -> in
5 operations
a stack of 10... | """"
2 shelves
5 books
5 nooks
5 books in each shelve MAX VALUE = 5
1 book comes out,
4 books at any shelf
1 space is there
1 user 10 0 clock
another user 12 0 clock returned
another user 01 clock returned
10 -> out
12 -> out
1 -> in
2 -> out
3 -> out
5 -> in
5 operations
a stack of 10... |
class MySQL:
def __init__(self, db):
self.__db = db
def pre_load(self):
# do nothing
return
def load(self, check_id, results):
for result in results:
responsetime = result.get('responsetime', None)
self.__db.query(
'REPLACE INTO pingd... | class Mysql:
def __init__(self, db):
self.__db = db
def pre_load(self):
return
def load(self, check_id, results):
for result in results:
responsetime = result.get('responsetime', None)
self.__db.query('REPLACE INTO pingdom_check_result (`check_id`, `at`, `p... |
#
# PySNMP MIB module OPT-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPT-IF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:26:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
"""Spotify response stated codes.
Reference:
https://developer.spotify.com/documentation/web-api/#response-status-codes
"""
RESPONSE_OK = 200
RESPONSE_CREATED = 201
RESPONSE_ACCEPTED = 202
RESPONSE_NO_CONTENT = 204
RESPONSE_NOT_MODIFIED = 304
RESPONSE_BAD_REQUEST = 400
RESPONSE_UNAUTHORIZED = 401
RESPONSE_FORBI... | """Spotify response stated codes.
Reference:
https://developer.spotify.com/documentation/web-api/#response-status-codes
"""
response_ok = 200
response_created = 201
response_accepted = 202
response_no_content = 204
response_not_modified = 304
response_bad_request = 400
response_unauthorized = 401
response_forbidde... |
'''
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area ... | """
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area ... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k %= length
self.reverse(0, length - 1, nums)
self.reverse(0, k - 1, nums)
self.reverse(k, leng... | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k %= length
self.reverse(0, length - 1, nums)
self.reverse(0, k - 1, nums)
self.reverse(k, length - 1, ... |
'''
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not b... | """
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not b... |
def checkrootpos(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d > 0
def checkrootneg(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d < 0
def fbinsearch(l, r, eps, check, params):
while l + eps < r:
m = (l + r) / 2
... | def checkrootpos(root, params):
(a, b, c, d) = params
return a * root ** 3 + b * root ** 2 + c * root + d > 0
def checkrootneg(root, params):
(a, b, c, d) = params
return a * root ** 3 + b * root ** 2 + c * root + d < 0
def fbinsearch(l, r, eps, check, params):
while l + eps < r:
m = (l + ... |
LOWER_BOUND = -2147483648
UPPER_BOUND = 2147483647
def solve(i: int) -> int:
base = 10
digit_arr = []
mult = 1 if i > 0 else -1
num = abs(i)
while num:
digit_arr.append(num % base)
num //= base
reverse_num = 0
for digit in digit_arr[::-1]:
reverse_num += mult * dig... | lower_bound = -2147483648
upper_bound = 2147483647
def solve(i: int) -> int:
base = 10
digit_arr = []
mult = 1 if i > 0 else -1
num = abs(i)
while num:
digit_arr.append(num % base)
num //= base
reverse_num = 0
for digit in digit_arr[::-1]:
reverse_num += mult * digit... |
class MultiSerializerMixin:
def get_serializer_class(self):
return self.serializer_classes[self.action]
| class Multiserializermixin:
def get_serializer_class(self):
return self.serializer_classes[self.action] |
# While loops practice
# PART A
ages = [5, 6, 24, 32, 21, 70]
counter = 0
while ages[counter] < 30:
print("Part A - The ages is : " +str(ages[counter]))
counter+=1
print("Part A - The value that caused the loop to stop : " +str(ages[counter]))
print("\n")
# PART B
counter = 0
while ages[counter] < 30:
... | ages = [5, 6, 24, 32, 21, 70]
counter = 0
while ages[counter] < 30:
print('Part A - The ages is : ' + str(ages[counter]))
counter += 1
print('Part A - The value that caused the loop to stop : ' + str(ages[counter]))
print('\n')
counter = 0
while ages[counter] < 30:
if ages[counter] > 20:
print('Part... |
def out_red(text):
return "\033[31m {}" .format(text)
def out_yellow(text):
return "\033[33m {}" .format(text)
def out_green(text):
return "\033[32m {}" .format(text)
| def out_red(text):
return '\x1b[31m {}'.format(text)
def out_yellow(text):
return '\x1b[33m {}'.format(text)
def out_green(text):
return '\x1b[32m {}'.format(text) |
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
| vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels) |
# set the path-to-files
TRAIN_FILE = "/home/luban/work_jupyter/point_rec_data/train.csv"
TEST_FILE = "/home/luban/work_jupyter/point_rec_data/test.csv"
SUB_DIR = "./output"
NUM_SPLITS = 3
RANDOM_SEED = 2017
# types of columns of the dataset dataframe
CATEGORICAL_COLS = [
'common.os',
'common.loc_provider',... | train_file = '/home/luban/work_jupyter/point_rec_data/train.csv'
test_file = '/home/luban/work_jupyter/point_rec_data/test.csv'
sub_dir = './output'
num_splits = 3
random_seed = 2017
categorical_cols = ['common.os', 'common.loc_provider', 'time.time', 'time.week']
numeric_cols = ['personal.cur_rectangle', 'common.loc_a... |
# Copyright 2019 Xilinx Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | class Statitem:
def __init__(self, name, timeunit='ms'):
self.name = name
self.runs = 0
self.min_t = float('inf')
self.max_t = 0.0
self.ave_t = 0.0
self.total_t = 0.0
self.timeunit = timeunit
def add(self, time):
self.runs += 1
self.total... |
HIVE_CONFIG = {
"host": '127.0.0.1',
"port": 10000,
"username": 'username',
"password": 'password'
}
MYSQL_CONFIG = {
'test':
{
"host": "127.0.0.1",
"port": 3306,
"user": "username",
"password": "password",
"database": "default"},
... | hive_config = {'host': '127.0.0.1', 'port': 10000, 'username': 'username', 'password': 'password'}
mysql_config = {'test': {'host': '127.0.0.1', 'port': 3306, 'user': 'username', 'password': 'password', 'database': 'default'}, 'prod': {'host': '127.0.0.1', 'port': 3306, 'user': 'username', 'password': 'password', 'data... |
def test_stats_filter(api, b2b_raw_config, utils):
"""
configure two flows f1 and f2
- Send 1000 packets from f1 of size 74B
- Send 2000 packets from f2 of size 1500B
Validation:
1) Get port statistics based on port name & column names and assert
each port & column has returned the values a... | def test_stats_filter(api, b2b_raw_config, utils):
"""
configure two flows f1 and f2
- Send 1000 packets from f1 of size 74B
- Send 2000 packets from f2 of size 1500B
Validation:
1) Get port statistics based on port name & column names and assert
each port & column has returned the values a... |
# Readable: can read during runtime/compile time
# Writeable: can write during runtime and compile time
"""
============
| Tuple |
============
Readable
Not writeable:
- cannot modify value, add or remove an element during the runtime.
"""
fooTuple = ("fooTupleItem", True, 123);
another... | """
============
| Tuple |
============
Readable
Not writeable:
- cannot modify value, add or remove an element during the runtime.
"""
foo_tuple = ('fooTupleItem', True, 123)
another_tuple = tuple(('anotherTupleItem', False, 456))
print(fooTuple)
print(anotherTuple)
print('===============================... |
"""
Common constants.
"""
ALPH = list('abcdefghijklmnopqrstuvwxyz')
| """
Common constants.
"""
alph = list('abcdefghijklmnopqrstuvwxyz') |
# mock.py
# Metadata
NAME = 'mock'
ENABLE = True
PATTERN = r'^!mock (?P<phrase>.*)'
USAGE = '''Usage: !mock <phrase>
Given a phrase, this translates the phrase into a mocking spongebob phrase.
Example:
> !mock it should work on slack and irc
iT ShOuLd wOrK On sLaCk aNd iRc
'''
# Command
async def mock... | name = 'mock'
enable = True
pattern = '^!mock (?P<phrase>.*)'
usage = 'Usage: !mock <phrase>\nGiven a phrase, this translates the phrase into a mocking spongebob phrase.\nExample:\n > !mock it should work on slack and irc\n iT ShOuLd wOrK On sLaCk aNd iRc\n'
async def mock(bot, message, phrase):
phrase = phr... |
"""
To sum in a sorted array
Given:
l: a list of sorted arrays
s: integer
find unique pair of items in the list l where sum is 's'
Problems:
1. Not working when there is a duplicate item is the list - [2, 3, 5, 4, 2, 1, 0]
"""
def two_sum_sorted_array(l, sum):
l.sort()
print(l)
a = 0
z = len(l)-1
... | """
To sum in a sorted array
Given:
l: a list of sorted arrays
s: integer
find unique pair of items in the list l where sum is 's'
Problems:
1. Not working when there is a duplicate item is the list - [2, 3, 5, 4, 2, 1, 0]
"""
def two_sum_sorted_array(l, sum):
l.sort()
print(l)
a = 0
z = len(... |
# Check For Vowel in a sentence....
s = input("Enter String: ")
s = s.lower()
f = 0
for i in range(0, len(s)):
if(s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print("Yes, Present")
else:
print("No, Not Present")
| s = input('Enter String: ')
s = s.lower()
f = 0
for i in range(0, len(s)):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print('Yes, Present')
else:
print('No, Not Present') |
"""Provides python helper functions."""
load("@pydeps//:requirements.bzl", _requirement = "requirement")
def filter_deps(deps = None):
if deps == None:
deps = []
return [dep for dep in deps if dep]
def py_library(deps = None, **kwargs):
return native.py_library(deps = filter_deps(deps), **kwargs)... | """Provides python helper functions."""
load('@pydeps//:requirements.bzl', _requirement='requirement')
def filter_deps(deps=None):
if deps == None:
deps = []
return [dep for dep in deps if dep]
def py_library(deps=None, **kwargs):
return native.py_library(deps=filter_deps(deps), **kwargs)
def py_... |
class Crawler:
"""
This class handles the calling of the scraper.
"""
def __init__(self) -> None:
pass | class Crawler:
"""
This class handles the calling of the scraper.
"""
def __init__(self) -> None:
pass |
"""
Generators Expression
WE studied:
- List Comprehension
- Dictionary Comprehension
- Set Comprehension
Not use:
- Tuple Comprehension => because call Generators
# List Comprehension
names = ['Carlos', 'Camila', 'Carla', 'Cassino', 'Cristina', 'Vanessa']
print(any([name[0] == 'C' for name in names]... | """
Generators Expression
WE studied:
- List Comprehension
- Dictionary Comprehension
- Set Comprehension
Not use:
- Tuple Comprehension => because call Generators
# List Comprehension
names = ['Carlos', 'Camila', 'Carla', 'Cassino', 'Cristina', 'Vanessa']
print(any([name[0] == 'C' for name in names]... |
# Given a 2D grid, each cell is either a wall 'W',
# an enemy 'E' or empty '0' (the number zero),
# return the maximum enemies you can kill using one bomb.
# The bomb kills all the enemies in the same row and column from
# the planted point until it hits the wall since the wall is too strong
# to be destroyed.
# Note t... | def max_killed_enemies(grid):
if not grid:
return 0
(m, n) = (len(grid), len(grid[0]))
max_killed = 0
(row_e, col_e) = (0, [0] * n)
for i in range(m):
for j in range(n):
if j == 0 or grid[i][j - 1] == 'W':
row_e = row_kills(grid, i, j)
if i == ... |
def insertion_sort(arr):
isSorted = None
while not isSorted:
isSorted = True
for x,val in enumerate(arr):
try:
if val>arr[x+1]:
temp = arr[x]
arr[x] = arr[x+1]
arr[x+1] = temp
isSorted = False
except IndexError:
x-=1
return arr
print(insertion_sort([5,3,1,2,10... | def insertion_sort(arr):
is_sorted = None
while not isSorted:
is_sorted = True
for (x, val) in enumerate(arr):
try:
if val > arr[x + 1]:
temp = arr[x]
arr[x] = arr[x + 1]
arr[x + 1] = temp
... |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
a -= 1
b -= 1
n = 100
grid = [['.'] * n for _ in range(n // 2)]
for _ in range(n // 2):
grid.append(['#'] * n)
print(n, n)
for i in range(0, n // 2, 2):
for j in range(0, n, 2):
... | def main():
(a, b) = map(int, input().split())
a -= 1
b -= 1
n = 100
grid = [['.'] * n for _ in range(n // 2)]
for _ in range(n // 2):
grid.append(['#'] * n)
print(n, n)
for i in range(0, n // 2, 2):
for j in range(0, n, 2):
if b > 0:
grid[i][j... |
# Constant values
IS_COLD_START = True
WARM_ACTION_INDENTIFIER = 'warm_up'
DEFAULT_WARM_METHOD = 'sleep'
| is_cold_start = True
warm_action_indentifier = 'warm_up'
default_warm_method = 'sleep' |
def test_endpoint_with_var2(client):
response = client.get("/items2/2")
assert response.status_code == 200
assert response.json() == {"item_id": 2}
| def test_endpoint_with_var2(client):
response = client.get('/items2/2')
assert response.status_code == 200
assert response.json() == {'item_id': 2} |
class SampleClass:
@staticmethod
def sample_method(a, b):
return a + b
| class Sampleclass:
@staticmethod
def sample_method(a, b):
return a + b |
name = "S - Density Squares"
description = "Trigger randomly placed squares"
knob1 = "Square Size"
knob2 = "Density"
knob3 = "Line Width"
knob4 = "Color"
released = "March 21 2017"
| name = 'S - Density Squares'
description = 'Trigger randomly placed squares'
knob1 = 'Square Size'
knob2 = 'Density'
knob3 = 'Line Width'
knob4 = 'Color'
released = 'March 21 2017' |
'''
Interface Genie Ops Object Outputs for IOSXR.
'''
class InterfaceOutput(object):
ShowInterfacesDetail = {
'GigabitEthernet0/0/0/0': {
'auto_negotiate': True,
'bandwidth': 768,
'counters': {'carrier_transitions': 0,
'drops': 0,
... | """
Interface Genie Ops Object Outputs for IOSXR.
"""
class Interfaceoutput(object):
show_interfaces_detail = {'GigabitEthernet0/0/0/0': {'auto_negotiate': True, 'bandwidth': 768, 'counters': {'carrier_transitions': 0, 'drops': 0, 'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_discards': 0, 'in_er... |
# Least Recently Used Cache
#
# The LRU caching scheme remove the least recently used data when the cache is full and a new page is referenced which is not there in cache.
#
# We use two data structures to implement an LRU Cache:
# - Double Linked List: The maximum size of the queue will be equal to the total number of... | class Node:
"""Double Linked List node implemetation for handling LRU Cache data"""
def __init__(self, key, value):
self.value = value
self.key = key
self.prev = None
self.next = None
def __repr__(self):
return f'Node({self.key}, {self.value})'
def __str__(self... |
# Tuenti Challenge Edition 8 Level 10
PROBLEM_SIZE = "submit"
# -- jam input/output ------------------------------------------------------- #
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
i = 0
res = []
while i < len(lines):
P, G = map(int, lines[i].split(... | problem_size = 'submit'
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
i = 0
res = []
while i < len(lines):
(p, g) = map(int, lines[i].split())
grudges = [tuple(map(int, lines[i + n + 1].split())) for n in range(G)]
i += G +... |
#python 3.5.2
'''
With the Remained Methods first you count the number of elements you what to store. So the length of the
array will eaual the number of elements you want so each element will have place to be stored. When you
do the divide by array length the remainer will always to equal or less than the numbe... | """
With the Remained Methods first you count the number of elements you what to store. So the length of the
array will eaual the number of elements you want so each element will have place to be stored. When you
do the divide by array length the remainer will always to equal or less than the number of element in the
... |
class Solution:
def minWindow(self, s: str, t: str) -> str:
"""
s = "ADOBECODEBANC", t = "ABC" t count = 3
^
^
010
s count = 0
Time O(N+M)
Space O(M)
"""
... | class Solution:
def min_window(self, s: str, t: str) -> str:
"""
s = "ADOBECODEBANC", t = "ABC" t count = 3
^
^
010
s count = 0
Time O(N+M)
Space O(M)
"""
... |
"""color methods"""
def color(r, g, b):
assert 256 > r > -1, "expected integer in range 0-255"
assert 256 > g > -1, "expected integer in range 0-255"
assert 256 > b > -1, "expected integer in range 0-255"
return '#%02x%02x%02x' % (r, g, b)
def color_to_rgb(html_color):
if len(html_color) == 7 and html_color[0]... | """color methods"""
def color(r, g, b):
assert 256 > r > -1, 'expected integer in range 0-255'
assert 256 > g > -1, 'expected integer in range 0-255'
assert 256 > b > -1, 'expected integer in range 0-255'
return '#%02x%02x%02x' % (r, g, b)
def color_to_rgb(html_color):
if len(html_color) == 7 and ... |
def secti(a, b):
return a + b
if __name__ == '__main__':
print(secti(1, 2))
# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
| def secti(a, b):
return a + b
if __name__ == '__main__':
print(secti(1, 2)) |
weights_path = './weights'
#pre trained model
name_model = 'model_unet'
#directory where read noisy sound to denoise
audio_dir_prediction = './mypredictions/input/'
#directory to save the denoise sound
dir_save_prediction = './mypredictions/output/'
#Name noisy sound file to denoise
#audio_input_prediction = args.a... | weights_path = './weights'
name_model = 'model_unet'
audio_dir_prediction = './mypredictions/input/'
dir_save_prediction = './mypredictions/output/'
sample_rate = 8000
min_duration = 1.0
frame_length = 8064
hop_length_frame = 8064
n_fft = 255
hop_length_fft = 63 |
BOT_NAME = 'books_images'
SPIDER_MODULES = ['books_images.spiders']
NEWSPIDER_MODULE = 'books_images.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'books_images.pipelines.BooksImagesPipeline': 1
}
FILES_STORE = r'downloaded'
# Change this to your path
DOWNLOAD_DELAY = 2
# Change to 0 for fastest crawl
| bot_name = 'books_images'
spider_modules = ['books_images.spiders']
newspider_module = 'books_images.spiders'
robotstxt_obey = True
item_pipelines = {'books_images.pipelines.BooksImagesPipeline': 1}
files_store = 'downloaded'
download_delay = 2 |
#punto1
def triangulo(a,b):
area = (b * a)/2
print(area)
triangulo(30,50)
| def triangulo(a, b):
area = b * a / 2
print(area)
triangulo(30, 50) |
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums)<3:
return False
found = []
n = len(nums)
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
... | def three_sum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3:
return False
found = []
n = len(nums)
for i in range(0, n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if nums[i] + nums[j... |
area = float(input())
kgInM = float(input())
badGrape = float(input())
allGrape = area * kgInM
restGrape = allGrape - badGrape
rakia = restGrape * 45 / 100
sell = restGrape * 55 / 100
lRakia = (rakia / 7.5) * 9.80
lSell = sell * 1.5
print('%.2f' % lRakia)
print('%.2f' % lSell) | area = float(input())
kg_in_m = float(input())
bad_grape = float(input())
all_grape = area * kgInM
rest_grape = allGrape - badGrape
rakia = restGrape * 45 / 100
sell = restGrape * 55 / 100
l_rakia = rakia / 7.5 * 9.8
l_sell = sell * 1.5
print('%.2f' % lRakia)
print('%.2f' % lSell) |
inputFile = open("input/day7.txt", "r")
inputLines = inputFile.readlines()
listBagsWithoutShinyGold = []
listBagsWithShinyGold = []
listUncertain = []
def goldMiner():
for line in inputLines:
splittedLine = line.split()
bagColor = splittedLine[0] + splittedLine[1]
childrenBags = []
... | input_file = open('input/day7.txt', 'r')
input_lines = inputFile.readlines()
list_bags_without_shiny_gold = []
list_bags_with_shiny_gold = []
list_uncertain = []
def gold_miner():
for line in inputLines:
splitted_line = line.split()
bag_color = splittedLine[0] + splittedLine[1]
children_bag... |
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution, try codin... | class Solution:
def max_sub_array(self, nums):
total_sum = max_sum = nums[0]
for i in nums[1:]:
total_sum = max(i, total_sum + i)
max_sum = max(max_sum, total_sum)
return max_sum
if __name__ == '__main__':
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(solution... |
def sum2(nums):
if len(nums) >= 2 :
return (nums[0] + nums[1])
elif len(nums) == 1 :
return nums[0]
else :
return 0 | def sum2(nums):
if len(nums) >= 2:
return nums[0] + nums[1]
elif len(nums) == 1:
return nums[0]
else:
return 0 |
#!/usr/bin/env python
"""
@package ion.agents.platform.util.network
@file ion/agents/platform/util/network.py
@author Carlos Rueda
@brief Supporting elements for convenient representation of a platform network
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
class BaseNode(object):
"""
A con... | """
@package ion.agents.platform.util.network
@file ion/agents/platform/util/network.py
@author Carlos Rueda
@brief Supporting elements for convenient representation of a platform network
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
class Basenode(object):
"""
A convenient base class for th... |
''' r : It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed. '''
''' w : It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The... | """ r : It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed. """
' w : It opens the file to write only. It overwrites the file if previously exists \n or creates a new one if no file exists with the same name. The ... |
# !/usr/bin/env python3
#############################################################################
# #
# Program purpose: Displays a histogram from list data #
# Program Author : Happi Yvan <ivensteinpoker@gmail.co... | def histogram(someList, char):
for x in someList:
while x > 0:
print(f'{char}', end='')
x = x - 1
print(f'\n')
if __name__ == '__main__':
rand_list = [3, 7, 4, 2, 6]
histogram(randList, '*') |
class Dice(object):
def __init__(self, labels):
self.stat = labels
def roll_e(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[3], self.stat[0], self.stat[2], self.stat[5]
def roll_w(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[... | class Dice(object):
def __init__(self, labels):
self.stat = labels
def roll_e(self):
(self.stat[0], self.stat[2], self.stat[5], self.stat[3]) = (self.stat[3], self.stat[0], self.stat[2], self.stat[5])
def roll_w(self):
(self.stat[0], self.stat[2], self.stat[5], self.stat[3]) = (se... |
def sum(number1, number2):
total = number1 + number2
print(total)
print("suma de 1 + 50")
sum(1,50)
print("suma de 1 + 500")
sum(500,1)
print("programa terminado") | def sum(number1, number2):
total = number1 + number2
print(total)
print('suma de 1 + 50')
sum(1, 50)
print('suma de 1 + 500')
sum(500, 1)
print('programa terminado') |
class Solution:
def isUgly(self, n: int) -> bool:
while True:
k=n
if n%2==0:
n=n//2
if n%3==0:
n=n//3
if n%5==0:
n=n//5
if k==n:
break
if n==1:
return True
| class Solution:
def is_ugly(self, n: int) -> bool:
while True:
k = n
if n % 2 == 0:
n = n // 2
if n % 3 == 0:
n = n // 3
if n % 5 == 0:
n = n // 5
if k == n:
break
if n == 1:
... |
def palin(n):
if str(n) == str(n)[::-1]:
return True
return False
N, M = map(int, input().split())
mid = (N+M) // 2
mid1 = (N+M) // 2
mid2 = (N+M) // 2
mids = {}
while True:
mid1 += 1
if palin(mid1):
break
while True:
mid2 -= 1
if palin(mid2):
break
if abs(mid - ... | def palin(n):
if str(n) == str(n)[::-1]:
return True
return False
(n, m) = map(int, input().split())
mid = (N + M) // 2
mid1 = (N + M) // 2
mid2 = (N + M) // 2
mids = {}
while True:
mid1 += 1
if palin(mid1):
break
while True:
mid2 -= 1
if palin(mid2):
break
if abs(mid - m... |
#from .test_cluster_det import test_cluster_det
#from .train_cluster_det import train_cluster_det
#from .debug_cluster_det import debug_cluster_det
#from .get_cluster_det import get_cluster_det
__factory__ = { }
def build_handler(phase, stage):
key_handler = '{}_{}'.format(phase, stage)
if key_handler not in... | __factory__ = {}
def build_handler(phase, stage):
key_handler = '{}_{}'.format(phase, stage)
if key_handler not in __factory__:
raise key_error('Unknown op:', key_handler)
return __factory__[key_handler] |
# -*- coding: utf-8 -*-
def test_hello_world():
text = 'Hello World'
assert text == 'Hello World'
| def test_hello_world():
text = 'Hello World'
assert text == 'Hello World' |
try:
1/0
except Exception as e:
print('e : ', e)
print(f"repr(e) : {repr(e)}")
| try:
1 / 0
except Exception as e:
print('e : ', e)
print(f'repr(e) : {repr(e)}') |
#!/usr/bin/env python3
print("Welcome to the Binary/Hexadecimal Converter Application")
# User input
max_value = int(input("\nCompute binary and hexadecimal values up to the following decimal number: "))
decimal = list(range(1, max_value+1))
binary = []
hexadecimal = []
for num in decimal:
binary.append(bin(num)... | print('Welcome to the Binary/Hexadecimal Converter Application')
max_value = int(input('\nCompute binary and hexadecimal values up to the following decimal number: '))
decimal = list(range(1, max_value + 1))
binary = []
hexadecimal = []
for num in decimal:
binary.append(bin(num))
hexadecimal.append(hex(num))
pr... |
#!/usr/bin/env python3
class Colors:
""" Colorized output during run """
red = "\033[91m"
green = "\033[92m"
yellow = "\033[93m"
reset = "\033[0m"
class Config:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
... | class Colors:
""" Colorized output during run """
red = '\x1b[91m'
green = '\x1b[92m'
yellow = '\x1b[93m'
reset = '\x1b[0m'
class Config:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
sleep_time = 5 |
"""This module holds miscellaneous validator Mixin classes for validating the incoming YAML."""
class KeyExistsMixIn:
def __init__(self, payload, *args, _key, _exception, _elem, **kwargs):
"""Raise an error if _key is not in the payload."""
try:
_ = payload[_key]
except (KeyErr... | """This module holds miscellaneous validator Mixin classes for validating the incoming YAML."""
class Keyexistsmixin:
def __init__(self, payload, *args, _key, _exception, _elem, **kwargs):
"""Raise an error if _key is not in the payload."""
try:
_ = payload[_key]
except (KeyErr... |
def solve_poly_reg(x, y, max_order):
"""Fit a polynomial regression model for each order 0 through max_order.
Args:
x (ndarray): An array of shape (samples, ) that contains the input values
y (ndarray): An array of shape (samples, ) that contains the output values
max_order (scalar): The order of t... | def solve_poly_reg(x, y, max_order):
"""Fit a polynomial regression model for each order 0 through max_order.
Args:
x (ndarray): An array of shape (samples, ) that contains the input values
y (ndarray): An array of shape (samples, ) that contains the output values
max_order (scalar): The order of ... |
s = 'GTCGAAGCCATTTCGCCGTGGGGTTGCGCGTGATTCTACCATCAGTTCTTTTTACGGTTCATTTAAACCGGTAATCCAGTAGCGTCAACAAATACTACTCTATGGTTGACTGGAGACGGAACGGGCCCATCGGACGTAATTATGTGGTCTTTGCACGAGCCGGCTGATACAAGCACATGCATCGTGACCACACCGACAAAGTTGTATCTTGGTTCCCGATTTATAACGTCTGCAGAATGAGCCTGTGTGACTATTGTAGTAGGTCCGAATGCCATGTCGGGGCTCCCACCTACGCTGCCTGGCGTCTTTTTGTGC... | s = 'GTCGAAGCCATTTCGCCGTGGGGTTGCGCGTGATTCTACCATCAGTTCTTTTTACGGTTCATTTAAACCGGTAATCCAGTAGCGTCAACAAATACTACTCTATGGTTGACTGGAGACGGAACGGGCCCATCGGACGTAATTATGTGGTCTTTGCACGAGCCGGCTGATACAAGCACATGCATCGTGACCACACCGACAAAGTTGTATCTTGGTTCCCGATTTATAACGTCTGCAGAATGAGCCTGTGTGACTATTGTAGTAGGTCCGAATGCCATGTCGGGGCTCCCACCTACGCTGCCTGGCGTCTTTTTGTGC... |
# 15. 3Sum
# ttungl@gmail.com
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
# For example, given array S = [-1, 0, 1, 2, -1, -4],
# --
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
class S... | class Solution(object):
def three_sum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
(lo, hi) = (i + ... |
expected_output = {
"route-information": {
"route-table": [
{
"table-name": "inet.0",
"destination-count": "60",
"total-route-count": "66",
"active-route-count": "60",
"holddown-route-count": "1",
"hi... | expected_output = {'route-information': {'route-table': [{'table-name': 'inet.0', 'destination-count': '60', 'total-route-count': '66', 'active-route-count': '60', 'holddown-route-count': '1', 'hidden-route-count': '0', 'rt-entry': {'rt-destination': '10.169.196.254', 'rt-prefix-length': '32', 'rt-entry-count': '2', 'r... |
if __name__ == '__main__':
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
l = [fruit.upper() for fruit in fruits if "n" in fruit]
print(l)
s = {fruit.upper() for fruit in fruits if "n" in fruit}
print(s)
d = {fruit.upper() : len(fruit) for fruit in fruits if "n" in fruit}
print(d)... | if __name__ == '__main__':
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
l = [fruit.upper() for fruit in fruits if 'n' in fruit]
print(l)
s = {fruit.upper() for fruit in fruits if 'n' in fruit}
print(s)
d = {fruit.upper(): len(fruit) for fruit in fruits if 'n' in fruit}
print(d)
... |
class BaseClass:
def __init__(self):
pass
@staticmethod
def say_hi():
print("hi")
class MyClassOne(BaseClass):
def __init__(self):
pass
class MyClassTwo(BaseClass, MyClassOne):
def __init__(self):
pass
| class Baseclass:
def __init__(self):
pass
@staticmethod
def say_hi():
print('hi')
class Myclassone(BaseClass):
def __init__(self):
pass
class Myclasstwo(BaseClass, MyClassOne):
def __init__(self):
pass |
"""
django-amazon-price-monitor monitors prices of Amazon products.
"""
__version_info__ = {
'major': 0,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
version = ["{major:d}... | """
django-amazon-price-monitor monitors prices of Amazon products.
"""
__version_info__ = {'major': 0, 'minor': 7, 'micro': 0, 'releaselevel': 'final', 'serial': 0}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
version = ['{major:d}.{minor:d}'.format(**__v... |
class AndGate(BinaryGate):
def __init__(self,n):
super().__init__(n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a==1 and b==1:
return 1
else:
return 0
| class Andgate(BinaryGate):
def __init__(self, n):
super().__init__(n)
def perform_gate_logic(self):
a = self.getPinA()
b = self.getPinB()
if a == 1 and b == 1:
return 1
else:
return 0 |
"""
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
"""
def solution()... | """
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
"""
def solution(... |
#
# Copyright (c) 2019, Infosys 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 ... | ies_type = {'0': 'MME-UE-S1AP-ID', '1': 'HandoverType', '2': 'Cause', '3': 'SourceID', '4': 'TargetID', '8': 'ENB-UE-S1AP-ID', '12': 'E-RABSubjecttoDataForwardingList', '13': 'E-RABtoReleaselistHOCmd', '14': 'E-RABDataForwardingItem', '15': 'E-RABReleaseItemBearerRelComp', '16': 'E-RABToBeSetuplistBearerSUReq', '17': '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def constant_aminoacid_code():
aa_dict = {
"R" : "ARG", "H" : "HIS", "K" : "LYS", "D" : "ASP", "E" : "GLU",
"S" : "SER", "T" : "THR", "N" : "ASN", "Q" : "GLN", "C" : "CYS",
"G" : "GLY", "P" : "PRO", "A" : "ALA", "V" : "VAL", "I" : "ILE",
... | def constant_aminoacid_code():
aa_dict = {'R': 'ARG', 'H': 'HIS', 'K': 'LYS', 'D': 'ASP', 'E': 'GLU', 'S': 'SER', 'T': 'THR', 'N': 'ASN', 'Q': 'GLN', 'C': 'CYS', 'G': 'GLY', 'P': 'PRO', 'A': 'ALA', 'V': 'VAL', 'I': 'ILE', 'L': 'LEU', 'M': 'MET', 'F': 'PHE', 'Y': 'TYR', 'W': 'TRP', '-': 'MAR'}
return aa_dict
de... |
def head(n):
print(f"Calling the function head({n})")
# Base Case
if(n == 0):
print("**** Base Case **** \n")
return
# Recursive Function Call
head(n-1)
# Operation
print(n)
# head(5): -1006
# RecursionError: maximum recursion depth exceeded while pickli... | def head(n):
print(f'Calling the function head({n})')
if n == 0:
print('**** Base Case **** \n')
return
head(n - 1)
print(n)
head(5) |
{
PDBConst.Name: "notetype",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["tinyint", "not null", "primary key"]
},
{
PDBConst.Name: "Type",
PDBConst.Attributes: ["varchar(128)", "not null"]
},
{
PDBConst.Name: "SID",
PDBCons... | {PDBConst.Name: 'notetype', PDBConst.Columns: [{PDBConst.Name: 'ID', PDBConst.Attributes: ['tinyint', 'not null', 'primary key']}, {PDBConst.Name: 'Type', PDBConst.Attributes: ['varchar(128)', 'not null']}, {PDBConst.Name: 'SID', PDBConst.Attributes: ['varchar(128)', 'not null']}], PDBConst.Initials: [{'Type': "'html'"... |
# -*- python -*-
{
'includes': [
'../../../build/common.gypi',
],
'target_defaults': {
'variables':{
'target_base': 'none',
},
'target_conditions': [
['target_base=="ripple_ledger_service"', {
'sources': [
'ripple_ledger_service.h',
'ripple_ledger_service.c'... | {'includes': ['../../../build/common.gypi'], 'target_defaults': {'variables': {'target_base': 'none'}, 'target_conditions': [['target_base=="ripple_ledger_service"', {'sources': ['ripple_ledger_service.h', 'ripple_ledger_service.c'], 'xcode_settings': {'WARNING_CFLAGS': ['-Wno-missing-field-initializers']}}]]}, 'condit... |
# This code is a partial mod of of the Adafruit PyPotal lib
# https://github.com/adafruit/Adafruit_CircuitPython_PyPortal/blob/master/adafruit_pyportal.py
def wrap_nicely(string, max_chars):
"""Wrap nicely function
A helper that will return a list of lines with word-break wrapping
Parameters
-------... | def wrap_nicely(string, max_chars):
"""Wrap nicely function
A helper that will return a list of lines with word-break wrapping
Parameters
----------
string : str
The text to be wrapped
max_chars: int
The maximum number of characters on a line before wrapping
Returns
---... |
# 140000000
LILIN = 1201000
sm.setSpeakerID(LILIN)
if sm.sendAskAccept("Shall we continue with your Basic Training? Before accepting, please make sure you have properly equipped your sword and your skills and potions are readily accessible."):
sm.startQuest(parentID)
sm.removeEscapeButton()
sm.sendNext("A... | lilin = 1201000
sm.setSpeakerID(LILIN)
if sm.sendAskAccept('Shall we continue with your Basic Training? Before accepting, please make sure you have properly equipped your sword and your skills and potions are readily accessible.'):
sm.startQuest(parentID)
sm.removeEscapeButton()
sm.sendNext("Alright. This t... |
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
ress = []
locs = [-1] * n
checkarray = [[True] * n,
[True] * (2 * n - 1),
[True] * (2 * n - 1)]
def put(dep, checkarray):
if dep == n:
ress.... | class Solution(object):
def solve_n_queens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
ress = []
locs = [-1] * n
checkarray = [[True] * n, [True] * (2 * n - 1), [True] * (2 * n - 1)]
def put(dep, checkarray):
if dep == n:
r... |
def basic_align(seq1, seq2):
score = 0
if len(seq1) == len(seq2):
for base1, base2 in zip(seq1, seq2):
if base1 == base2:
score += 1
else:
score -= 0
return score
def aa_extract(file):
aa_list = []
for line in file:
if line.s... | def basic_align(seq1, seq2):
score = 0
if len(seq1) == len(seq2):
for (base1, base2) in zip(seq1, seq2):
if base1 == base2:
score += 1
else:
score -= 0
return score
def aa_extract(file):
aa_list = []
for line in file:
if line.s... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 20:51:09 2017
@author: sruti
"""
#python learning
# This program prints Hello, world!
print('Hello, world!') | """
Created on Mon Nov 20 20:51:09 2017
@author: sruti
"""
print('Hello, world!') |
## after apply any leyer of the forward function in pytorch
iimg=input[:,:3,:,].cpu().data.numpy()
# print(img.shape)
img = np.squeeze(img)
# print(img.shape)
img=np.transpose(img,(1,2,0))
img = cv2.resize(img,(256,256))
cv2.imshow('out',img)
cv2.waitKey(0)
| iimg = input[:, :3, :].cpu().data.numpy()
img = np.squeeze(img)
img = np.transpose(img, (1, 2, 0))
img = cv2.resize(img, (256, 256))
cv2.imshow('out', img)
cv2.waitKey(0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.