content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class TP_Texts:
# __init__()
init_error1 = "Start and End must be of type datetime.datetime!"
init_error2 = "End must be larger than start!"
# start()
start_error1 = "Time must be of type datetime.datetime!"
start_error2 = "start must be smaller than end of Time_Period!"
# end()
... | class Tp_Texts:
init_error1 = 'Start and End must be of type datetime.datetime!'
init_error2 = 'End must be larger than start!'
start_error1 = 'Time must be of type datetime.datetime!'
start_error2 = 'start must be smaller than end of Time_Period!'
end_error1 = 'end must be larger than start of Time... |
#
# PySNMP MIB module CISCO-OTV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OTV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:09:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint, constraints_union) ... |
class ServerError(Exception):
def __init__(self, details, model, response):
self.details = details
self.model = model
self.response = response
super(ServerError, self).__init__(self.details)
def encode(self):
return {
"details": self.details,
"exp... | class Servererror(Exception):
def __init__(self, details, model, response):
self.details = details
self.model = model
self.response = response
super(ServerError, self).__init__(self.details)
def encode(self):
return {'details': self.details, 'expected': str(self.model),... |
"""
jsonable.py:
Folder with helper methods that allow for seamless conversion of F prime types to JSON types. This allows us to produce
data in JSON format with ease, assuming that the correct encoder is registered.
Note: JSON types must use only the following data types
1. booleans
2. numbers
3. strings
4. lis... | """
jsonable.py:
Folder with helper methods that allow for seamless conversion of F prime types to JSON types. This allows us to produce
data in JSON format with ease, assuming that the correct encoder is registered.
Note: JSON types must use only the following data types
1. booleans
2. numbers
3. strings
4. lis... |
# Ariant Treasure Vault Entrance (915020100) => Ariant Treasure Vault
if 2400 <= chr.getJob() <= 2412 and not sm.hasMobsInField():
sm.warp(915020101, 1)
elif sm.hasMobsInField():
sm.chat("Eliminate all of the intruders first.") | if 2400 <= chr.getJob() <= 2412 and (not sm.hasMobsInField()):
sm.warp(915020101, 1)
elif sm.hasMobsInField():
sm.chat('Eliminate all of the intruders first.') |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'libflac',
'product_name': 'flac',
'type': 'static_library',
'sources': [
'include/... | {'targets': [{'target_name': 'libflac', 'product_name': 'flac', 'type': 'static_library', 'sources': ['include/FLAC/all.h', 'include/FLAC/assert.h', 'include/FLAC/callback.h', 'include/FLAC/export.h', 'include/FLAC/format.h', 'include/FLAC/metadata.h', 'include/FLAC/ordinals.h', 'include/FLAC/stream_decoder.h', 'includ... |
class LUISEmulator(object):
def __init__(self):
self.name='luis'
def normalise_request_json(self,data):
_data = {}
_data["text"]=data['q'][0]
return _data
def normalise_response_json(self,data):
return {
"query": data["text"],
"topScoringInte... | class Luisemulator(object):
def __init__(self):
self.name = 'luis'
def normalise_request_json(self, data):
_data = {}
_data['text'] = data['q'][0]
return _data
def normalise_response_json(self, data):
return {'query': data['text'], 'topScoringIntent': {'intent': 'i... |
def test_vm_reconfigured(controller, vm_service, vn_service, vmi_service, vrouter_port_service,
vm_reconfigured_update):
controller.handle_update(vm_reconfigured_update)
vm_service.update_vm_models_interfaces.assert_called_once()
vn_service.update_vns.assert_called_once()
vmi_s... | def test_vm_reconfigured(controller, vm_service, vn_service, vmi_service, vrouter_port_service, vm_reconfigured_update):
controller.handle_update(vm_reconfigured_update)
vm_service.update_vm_models_interfaces.assert_called_once()
vn_service.update_vns.assert_called_once()
vmi_service.update_vmis.assert_... |
"""
Module: 'flowlib.units._adc' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
ADDRESS = 72
class Adc:
''
def _available():
pass
def _read_u16():
pa... | """
Module: 'flowlib.units._adc' on M5 FlowUI v1.4.0-beta
"""
address = 72
class Adc:
""""""
def _available():
pass
def _read_u16():
pass
def _write_u8():
pass
def deinit():
pass
def measure_set():
pass
voltage = None
gain_eight = 3
gain_four = 2... |
with open('lexical.csv') as f:
string=f.read()
arr=string.split('\n')
arr=arr[:10000]
result='\n'.join(arr)
with open('sub.csv','w') as f:
f.write(result) | with open('lexical.csv') as f:
string = f.read()
arr = string.split('\n')
arr = arr[:10000]
result = '\n'.join(arr)
with open('sub.csv', 'w') as f:
f.write(result) |
# program to restore the original string by entering the compressed string with this rule. However,
# the # character does not appear in the restored character string.
def restore_original_str(a1):
result = ""
ind = 0
end = len(a1)
while ind < end:
if a1[ind] == "#":
result += a1[ind + 2] * int(a1[in... | def restore_original_str(a1):
result = ''
ind = 0
end = len(a1)
while ind < end:
if a1[ind] == '#':
result += a1[ind + 2] * int(a1[ind + 1])
ind += 3
else:
result += a1[ind]
ind += 1
return result
print('Original text:', 'XY#6Z1#4023')
... |
# Given an array of integers, every element appears twice except for one. Find that single one.
#
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#
# Python, Python3 all accepted.
class SingleNumber:
def singleNumber(self, nums):
"""
... | class Singlenumber:
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = 0
if nums is None:
return s
for i in nums:
s ^= i
return s |
def example2(n):
h = lambda : print(n)
return(h)
ourfunc = example2(5)
ourfunc()
| def example2(n):
h = lambda : print(n)
return h
ourfunc = example2(5)
ourfunc() |
# -*- coding: utf-8 -*-
""" Platform specific utility functions, dummy version
This has empty implementation of the platutils functions, used for
unsupported operating systems.
Authors
-------
- Ville Vainio <vivainio@gmail.com>
"""
#*****************************************************************************
# ... | """ Platform specific utility functions, dummy version
This has empty implementation of the platutils functions, used for
unsupported operating systems.
Authors
-------
- Ville Vainio <vivainio@gmail.com>
"""
ignore_termtitle = True
def set_term_title(*args, **kw):
"""Dummy no-op."""
pass
def find_cmd(cmd... |
"""Axes behaviour."""
def lines(
*,
base_width=0.5,
line_base_ratio=2.0,
tick_major_base_ratio=1.0,
tick_minor_base_ratio=0.5,
tick_size_width_ratio=3.0,
tick_major_size_min=3.0,
tick_minor_size_min=2.0,
axisbelow=True,
):
"""Adjust linewidth(s) according to a base width."""
... | """Axes behaviour."""
def lines(*, base_width=0.5, line_base_ratio=2.0, tick_major_base_ratio=1.0, tick_minor_base_ratio=0.5, tick_size_width_ratio=3.0, tick_major_size_min=3.0, tick_minor_size_min=2.0, axisbelow=True):
"""Adjust linewidth(s) according to a base width."""
tick_major_width = tick_major_base_rat... |
#!/usr/bin/env python
"""
Base class and common functions for compressor implementations.
"""
# pylint: disable=W0311
class BaseProcessor(object):
"Base class for compression processors."
def __init__(self, options, is_request, params):
self.options = options
self.is_request = is_request
name = self.... | """
Base class and common functions for compressor implementations.
"""
class Baseprocessor(object):
"""Base class for compression processors."""
def __init__(self, options, is_request, params):
self.options = options
self.is_request = is_request
name = self.__module__.split('.')[-1]
... |
# Outputs the sum of the range of all numbers from 1 to n.
# Source: https://pynative.com/python-program-to-calculate-sum-and-average-of-numbers/
def main():
print("\n")
input_string = input('Enter numbers separated by space ')
print("\n")
# Take input numbers into list
numbers = input_string.spli... | def main():
print('\n')
input_string = input('Enter numbers separated by space ')
print('\n')
numbers = input_string.split()
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print('Sum = ', sum(numbers))
print('Average = ', sum(numbers) / len(numbers))
if __name__ == '__mai... |
# https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/
class Solution:
def sumZero(self, n: int) -> List[int]:
res = []
if n % 2 == 0:
for i in range(1, (n // 2) + 1):
res.append(i)
for i in range(-(n // 2), 0):
res.... | class Solution:
def sum_zero(self, n: int) -> List[int]:
res = []
if n % 2 == 0:
for i in range(1, n // 2 + 1):
res.append(i)
for i in range(-(n // 2), 0):
res.append(i)
return res
else:
for i in range(1, n // 2... |
#
# PySNMP MIB module ARBOR-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARBOR-SMI
# Produced by pysmi-0.3.4 at Mon Apr 29 17:08:55 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:23... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
# default value from class context
class A:
FOO = 1
def foo(self, param=F<ref>OO):
pass
| class A:
foo = 1
def foo(self, param=F < ref > OO):
pass |
class InfectionObserver:
"""
As the output.hdf table for a distributed run has only one row per run,
this data needs to be saved in wide format
For each step, it will have one column for infection prevalence, and one column for infection incidence
"""
def __init__(self):
self.step = 0
... | class Infectionobserver:
"""
As the output.hdf table for a distributed run has only one row per run,
this data needs to be saved in wide format
For each step, it will have one column for infection prevalence, and one column for infection incidence
"""
def __init__(self):
self.step = 0
... |
class EvaluationTask:
"""EvaluationTask class, containing EvaluationTask information."""
def __init__(self, json, client):
self._json = json
self.id = json["id"]
self.initial_response = getattr(json, "initial_response", None)
self.expected_response = json["expected_response"]
... | class Evaluationtask:
"""EvaluationTask class, containing EvaluationTask information."""
def __init__(self, json, client):
self._json = json
self.id = json['id']
self.initial_response = getattr(json, 'initial_response', None)
self.expected_response = json['expected_response']
... |
LOREM_IPSUM = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum ... | lorem_ipsum = '\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna\naliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum... |
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1 or n == 0:
return 1
prev, curr = 1, 1
for i in range(2, n + 1):
temp = curr
curr += prev
prev = temp
return curr
| class Solution:
def climb_stairs(self, n: int) -> int:
if n == 1 or n == 0:
return 1
(prev, curr) = (1, 1)
for i in range(2, n + 1):
temp = curr
curr += prev
prev = temp
return curr |
#Given two cells of a chessboard. If they are painted in one color, print the word YES, and if in a different color - NO.
r = int(input("Row number of the first cell on Chessboard, r = ?"))
if ((r > 8) or (r < 1)):
print("Invalid row number for a Chessboard!")
exit()
c = int(input("The column number for the f... | r = int(input('Row number of the first cell on Chessboard, r = ?'))
if r > 8 or r < 1:
print('Invalid row number for a Chessboard!')
exit()
c = int(input('The column number for the first cell on Chessboard, c = ?'))
if c > 8 or c < 1:
print('Invalid column number for a Chessboard!')
exit()
r = int(input... |
#!/usr/bin/python3
def sin(x):
"""
sin(x)
"""
return 42
| def sin(x):
"""
sin(x)
"""
return 42 |
def extractBinhjamin(item):
"""
# Binhjamin
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (vol or chp or frag or postfix):
return False
if ('SRKJ' in item['title'] or 'SRKJ-Sayonara Ryuu' in item['tags']) and (chp or vol):
return buildReleaseMessageWithType(item, 'Sayon... | def extract_binhjamin(item):
"""
# Binhjamin
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (vol or chp or frag or postfix):
return False
if ('SRKJ' in item['title'] or 'SRKJ-Sayonara Ryuu' in item['tags']) and (chp or vol):
return build_rel... |
def int_to_byte(i):
return i.to_bytes(1, byteorder='big')
def byte_to_int(b):
return int.from_bytes(b, byteorder='big', signed=False)
| def int_to_byte(i):
return i.to_bytes(1, byteorder='big')
def byte_to_int(b):
return int.from_bytes(b, byteorder='big', signed=False) |
class ServicePrincipal:
def __init__(self, client_id=None, tenant_id=None, credential=None):
self.client_id = client_id
self.tenant_id = tenant_id
self.credential = credential
def from_dict(self, service_principal_dict):
self.client_id = service_principal_dict['client_id']
... | class Serviceprincipal:
def __init__(self, client_id=None, tenant_id=None, credential=None):
self.client_id = client_id
self.tenant_id = tenant_id
self.credential = credential
def from_dict(self, service_principal_dict):
self.client_id = service_principal_dict['client_id']
... |
class _MockRouter:
root_viewset_cls = None
class NestedRouteTestCaseMixin:
def wrap_with_parents(self, child_class, *parent_classes):
"""
Wraps the child_class to be a nested route below the given
parent classes, where the last parent class is the "top route"
"""
all_... | class _Mockrouter:
root_viewset_cls = None
class Nestedroutetestcasemixin:
def wrap_with_parents(self, child_class, *parent_classes):
"""
Wraps the child_class to be a nested route below the given
parent classes, where the last parent class is the "top route"
"""
all_vi... |
num_inpt = a = 7484
num_inpt_2 = b = 12312
while num_inpt != num_inpt_2: # nod
if num_inpt > num_inpt_2:
num_inpt = num_inpt - num_inpt_2
elif num_inpt_2 > num_inpt:
num_inpt_2 = num_inpt_2 - num_inpt
nok = a * b // num_inpt_2 #nok
print(nok)
| num_inpt = a = 7484
num_inpt_2 = b = 12312
while num_inpt != num_inpt_2:
if num_inpt > num_inpt_2:
num_inpt = num_inpt - num_inpt_2
elif num_inpt_2 > num_inpt:
num_inpt_2 = num_inpt_2 - num_inpt
nok = a * b // num_inpt_2
print(nok) |
"""This problem was asked by Dropbox.
Given a list of words, determine whether the words can be chained to form a circle.
A word X can be placed in front of another word Y in a circle if the last character
of X is same as the first character of Y.
For example, the words ['chair', 'height', 'racket', touch', 'tunic'... | """This problem was asked by Dropbox.
Given a list of words, determine whether the words can be chained to form a circle.
A word X can be placed in front of another word Y in a circle if the last character
of X is same as the first character of Y.
For example, the words ['chair', 'height', 'racket', touch', 'tunic'... |
def count_and_print(f, l):
c=0
for e in l:
f.write(e)
f.write("\n")
c+=1
f.close()
return c
| def count_and_print(f, l):
c = 0
for e in l:
f.write(e)
f.write('\n')
c += 1
f.close()
return c |
def readFlat(filename, delimiter):
f = open(filename)
ans = []
for line in f:
ans.append(map(lambda x:float(x), filter(lambda x:len(x)>0,line.split(delimiter))))
return ans
| def read_flat(filename, delimiter):
f = open(filename)
ans = []
for line in f:
ans.append(map(lambda x: float(x), filter(lambda x: len(x) > 0, line.split(delimiter))))
return ans |
"""
test_multi_group.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Sun Mar 24 01:04:54 2013
Description:
"""
| """
test_multi_group.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Sun Mar 24 01:04:54 2013
Description:
""" |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
def b(x):
msg = "x is %s" % x
print(msg)
| def b(x):
msg = 'x is %s' % x
print(msg) |
class DoubleNode:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
if self.head == None:
self.head = DoubleN... | class Doublenode:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
class Doublylinkedlist:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
if self.head == None:
self.head = doubl... |
# Authors: Soledad Galli <solegalli@protonmail.com>
# License: BSD 3 clause
# functions shared across transformers
def _define_variables(variables):
# Check that variable names are passed in a list.
# Can take None as value
if not variables or isinstance(variables, list):
variables = variables
... | def _define_variables(variables):
if not variables or isinstance(variables, list):
variables = variables
else:
variables = [variables]
return variables
def _find_numerical_variables(X, variables=None):
if not variables:
variables = list(X.select_dtypes(include='number').columns)... |
K, A, B = map(int, input().split())
if B-A <= 2:
print(K+1)
exit(0)
if 1+(K-2) < A:
print(K+1)
exit(0)
exchange_times, last = divmod(K-(A-1), 2)
profit = B - A
ans = A + exchange_times * profit + last
print(ans)
| (k, a, b) = map(int, input().split())
if B - A <= 2:
print(K + 1)
exit(0)
if 1 + (K - 2) < A:
print(K + 1)
exit(0)
(exchange_times, last) = divmod(K - (A - 1), 2)
profit = B - A
ans = A + exchange_times * profit + last
print(ans) |
def foo():
"""
Parameters:
a: foo
Returns:
None
""" | def foo():
"""
Parameters:
a: foo
Returns:
None
""" |
m = "sdjlwdd"
c
print(mBytes)
mInt = int.from_bytes(mBytes, byteorder="big")
mBytes2 = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")
m2 = mBytes2.decode("utf-8")
print(m == m2) | m = 'sdjlwdd'
c
print(mBytes)
m_int = int.from_bytes(mBytes, byteorder='big')
m_bytes2 = mInt.to_bytes((mInt.bit_length() + 7) // 8, byteorder='big')
m2 = mBytes2.decode('utf-8')
print(m == m2) |
"""
Given the names and grades for each student in a Physics class of N students, store them in a nested list
and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
"""
python... | """
Given the names and grades for each student in a Physics class of N students, store them in a nested list
and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
"""
python_... |
# -*- coding: UTF-8 -*-
# vim: ts=4 sts=4 sw=4 tw=100 sta et
class NotInRole(Exception):
pass
def check_role(my_roles, requested_roles):
if not my_roles:
return True
for role in my_roles:
if role in requested_roles:
return True
raise NotInRole()
| class Notinrole(Exception):
pass
def check_role(my_roles, requested_roles):
if not my_roles:
return True
for role in my_roles:
if role in requested_roles:
return True
raise not_in_role() |
"""Write a program which will find all such numbers which are divisible
by 7 but are not a multiple of 5, between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a
single line."""
for num in range(2000, 3201):
if num % 7 == 0 and num % 5 != 0:
prin... | """Write a program which will find all such numbers which are divisible
by 7 but are not a multiple of 5, between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a
single line."""
for num in range(2000, 3201):
if num % 7 == 0 and num % 5 != 0:
print(... |
# -*- coding: utf-8 -*-
{
'name': "odoo-s3",
'summary': """
Stores attachments in Amazon S3 instead of the local drive""",
'description': """
In large deployments, Odoo workers need to share a distributed
filestore. Amazon S3 can store files (e.g. attachments and
pictures),... | {'name': 'odoo-s3', 'summary': '\n Stores attachments in Amazon S3 instead of the local drive', 'description': '\n In large deployments, Odoo workers need to share a distributed\n filestore. Amazon S3 can store files (e.g. attachments and\n pictures), such that all Odoo workers can access th... |
class PingError(Exception):
pass
class TimeExceeded(PingError):
pass
class TimeToLiveExpired(TimeExceeded):
def __init__(self, message="Time exceeded: Time To Live expired.", ip_header=None, icmp_header=None):
self.ip_header = ip_header
self.icmp_header = icmp_header
self.message... | class Pingerror(Exception):
pass
class Timeexceeded(PingError):
pass
class Timetoliveexpired(TimeExceeded):
def __init__(self, message='Time exceeded: Time To Live expired.', ip_header=None, icmp_header=None):
self.ip_header = ip_header
self.icmp_header = icmp_header
self.message ... |
# -*- coding: utf-8 -*-
description = 'Sample table'
group = 'lowlevel'
devices = dict(
st_phi = device('nicos.devices.generic.VirtualMotor',
unit = 'deg',
abslimits = (-50, 116.1),
speed = 1.5,
visibility = (),
),
co_phi = device('nicos.devices.generic.VirtualCoder',
... | description = 'Sample table'
group = 'lowlevel'
devices = dict(st_phi=device('nicos.devices.generic.VirtualMotor', unit='deg', abslimits=(-50, 116.1), speed=1.5, visibility=()), co_phi=device('nicos.devices.generic.VirtualCoder', motor='st_phi', visibility=()), phi=device('nicos.devices.generic.Axis', description='Samp... |
# demo of looping through the characters of a string, using the sorted and reversed functions
s = input("Enter a string:")
n = len(s)
print("The first character of", s, "is", s[0])
print("The entered string will appear character wise as:")
for i in range(0, n):
print(s[i])
print("The entered string will appear char... | s = input('Enter a string:')
n = len(s)
print('The first character of', s, 'is', s[0])
print('The entered string will appear character wise as:')
for i in range(0, n):
print(s[i])
print('The entered string will appear character wise as:')
for i in s:
print(i)
print('String with its characters sorted is', sorted... |
# ------------------------------------------------------------------------------------
# Tutorial: How to make a recursive function
# A recursive function is a function that calls itself
# ------------------------------------------------------------------------------------
# find the factorial of a user entered numbe... | mul = 1
def fact(num):
if num == 1:
return num
else:
return num * fact(num - 1)
num = int(input('Enter a number to get the factorial of it: '))
if num == 0:
print('Factorial of 0: 1')
else:
print('Factorial of ', num, ':', fact(num)) |
class BaseError(Exception):
"""Base Error Class"""
def __init__(self, code=400, message='', status='', field=None):
Exception.__init__(self)
self.code = code
self.message = message
self.status = status
self.field = field
def to_dict(self):
return {'code': se... | class Baseerror(Exception):
"""Base Error Class"""
def __init__(self, code=400, message='', status='', field=None):
Exception.__init__(self)
self.code = code
self.message = message
self.status = status
self.field = field
def to_dict(self):
return {'code': se... |
"""
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary
representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def count_bit... | """
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary
representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
"""
def count_bits... |
#03_personal-info.py
space= " "
firstName = input("What is your first name?")
lastName = input("What is your last name?")
location = input("What is your location?")
age = input("What is your age?")
print("Hi "+ firstName + space + lastName +"! Your location is "+ location + " and you are "+age + " years old!")
| space = ' '
first_name = input('What is your first name?')
last_name = input('What is your last name?')
location = input('What is your location?')
age = input('What is your age?')
print('Hi ' + firstName + space + lastName + '! Your location is ' + location + ' and you are ' + age + ' years old!') |
class Reply(object):
"""{
"kind": "drive#commentReply",
"replyId": string,
"createdDate": datetime,
"modifiedDate": datetime,
"author": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},... | class Reply(object):
"""{
"kind": "drive#commentReply",
"replyId": string,
"createdDate": datetime,
"modifiedDate": datetime,
"author": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},... |
# Space : O(len(word))
# Time : O(n * len(word))
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans = []
pn = len(pattern)
for word in words:
if len(word) != pn:
continue
mem1, mem2 = {}, {}
... | class Solution:
def find_and_replace_pattern(self, words: List[str], pattern: str) -> List[str]:
ans = []
pn = len(pattern)
for word in words:
if len(word) != pn:
continue
(mem1, mem2) = ({}, {})
defect = False
for i in range(p... |
def indent(string, level=1, lstrip_first=False):
"""Multiline string indent.
Indent each line of the provided string by the specified level.
Args:
string: The string to indent, possibly containing linebreaks.
level: The level to indent (``level * ' '``). Defaults to 1.
lstrip_first... | def indent(string, level=1, lstrip_first=False):
"""Multiline string indent.
Indent each line of the provided string by the specified level.
Args:
string: The string to indent, possibly containing linebreaks.
level: The level to indent (``level * ' '``). Defaults to 1.
lstrip_first... |
'''Crie um programa que leia idade e sexo de varias pessoas
e pergunte se o usuario quer conrinuar
no final mostre
quantas pessoas tem mais de 18 anos
quantos homens foram cadastrados
e quantas mulheres tem menos de 20 anos'''
pessoas_18 = mulher_20 = homen = 0
while True:
idade = int(input('Digite a Idade: '))
... | """Crie um programa que leia idade e sexo de varias pessoas
e pergunte se o usuario quer conrinuar
no final mostre
quantas pessoas tem mais de 18 anos
quantos homens foram cadastrados
e quantas mulheres tem menos de 20 anos"""
pessoas_18 = mulher_20 = homen = 0
while True:
idade = int(input('Digite a Idade: '))
... |
class GuidAttribute:
"""
Supplies an explicit System.Guid when an automatic GUID is undesirable.
GuidAttribute(guid: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return GuidAttribute()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def __init__(self,*arg... | class Guidattribute:
"""
Supplies an explicit System.Guid when an automatic GUID is undesirable.
GuidAttribute(guid: str)
"""
def zzz(self):
"""hardcoded/mock instance of the class"""
return guid_attribute()
instance = zzz()
'hardcoded/returns an instance of the class'
def _... |
# Common use case - File IO
# "Everything not saved will be lost."
#
# Prereq:
# string operations: split(), strip(), format(), join()
# list operations: append()
# built-in functions: len(), open()
#
# Reading:
# open()
# https://docs.python.org/3/library/functions.html#open
# string.strip()
# ht... | f = open('offshore_assets.txt', 'w')
f.write('squirrel tail')
f.write('basilisk hide')
f.write('kikimore claw')
f.write('may contain peanut')
f.close()
f = open('offshore_assets.txt')
while True:
line = f.readline()
if len(line) > 0:
print(line)
else:
break
f.close()
for line in open('offsho... |
class admin():
def __init__(self):
pass
def get_id(self):
pass | class Admin:
def __init__(self):
pass
def get_id(self):
pass |
def get_hello():
return 'Hello'
class HelloSayer():
def say_hello(self):
print('Hello') | def get_hello():
return 'Hello'
class Hellosayer:
def say_hello(self):
print('Hello') |
####################################
### The router base class
class Router(object):
'''Common superclass of routers'''
pass
| class Router(object):
"""Common superclass of routers"""
pass |
# Global parameter
examples_root = None
process_type_name_ns_to_clean = None
synopsis_maxlen_function = 120
synopsis_class_list = None
| examples_root = None
process_type_name_ns_to_clean = None
synopsis_maxlen_function = 120
synopsis_class_list = None |
sum=0
i=0
while i<=4:
if sum<=5000:
item=int(input("Enter the item amount"))
sum=sum+item
i=i+1
print("Total items",i,"selected and total amount is:",sum)
else:
print("Account limit crossed")
break
| sum = 0
i = 0
while i <= 4:
if sum <= 5000:
item = int(input('Enter the item amount'))
sum = sum + item
i = i + 1
print('Total items', i, 'selected and total amount is:', sum)
else:
print('Account limit crossed')
break |
class Coord(tuple):
def __add__(self, other):
if isinstance(other, Coord) and len(self) == len(other):
return Coord(i+j for i, j in zip(self, other))
def trees(inp, step: tuple):
step = Coord(step)
current = step
while current[0] < len(inp):
yield inp[current[0]][current[1]... | class Coord(tuple):
def __add__(self, other):
if isinstance(other, Coord) and len(self) == len(other):
return coord((i + j for (i, j) in zip(self, other)))
def trees(inp, step: tuple):
step = coord(step)
current = step
while current[0] < len(inp):
yield (inp[current[0]][cur... |
DOWNLOAD_CHUNK_SIZE = 32768
FETCH_LIMIT = 200
def count_motions(db, project_ids=None, institution_ids=None, description_filter=None):
count = db.countMotions(None, project_ids, institution_ids, None, None, description_filter)
return count
def fetch_motions(db, project_ids=None, institution_ids=None, description_f... | download_chunk_size = 32768
fetch_limit = 200
def count_motions(db, project_ids=None, institution_ids=None, description_filter=None):
count = db.countMotions(None, project_ids, institution_ids, None, None, description_filter)
return count
def fetch_motions(db, project_ids=None, institution_ids=None, descripti... |
# Recursive function to perform pre-order traversal of the tree
def preorder(root):
# return if the current node is empty
if root is None:
return
# Display the data part of the root (or current node)
print(root.data, end=' ')
# Traverse the left subtree
preorder(root.left)
# ... | def preorder(root):
if root is None:
return
print(root.data, end=' ')
preorder(root.left)
preorder(root.right) |
# defining object file1 to
# open GeeksforGeeks file in
# read mode
file1 = open('GeeksforGeeks.txt',
'r')
# defining object file2 to
# open GeeksforGeeksUpdated file
# in write mode
file2 = open('GeeksforGeeksUpdated.txt',
'w')
# reading each line from original
# text file
for line in file1.readlin... | file1 = open('GeeksforGeeks.txt', 'r')
file2 = open('GeeksforGeeksUpdated.txt', 'w')
for line in file1.readlines():
if not line.startswith('TextGenerator'):
print(line)
file2.write(line)
file2.close()
file1.close() |
template_string = '''#!/bin/bash
#PBS -S /bin/bash
#PBS -N ${jobname}
#PBS -m n
#PBS -l walltime=$walltime
#PBS -l select=${nodes_per_block}:ncpus=${ncpus}${select_options}
#PBS -o ${submit_script_dir}/${jobname}.submit.stdout
#PBS -e ${submit_script_dir}/${jobname}.submit.stderr
${scheduler_options}
${worker_init}
... | template_string = '#!/bin/bash\n\n#PBS -S /bin/bash\n#PBS -N ${jobname}\n#PBS -m n\n#PBS -l walltime=$walltime\n#PBS -l select=${nodes_per_block}:ncpus=${ncpus}${select_options}\n#PBS -o ${submit_script_dir}/${jobname}.submit.stdout\n#PBS -e ${submit_script_dir}/${jobname}.submit.stderr\n${scheduler_options}\n\n${worke... |
number = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729... | number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729... |
# This program demonstrates the use of the == operator using numbers
print (5 == 6)
# Using variables
x = 5
y = 8
print(x == y)
| print(5 == 6)
x = 5
y = 8
print(x == y) |
class Core:
def gen_range(self, StartNumber, EndNumber, GapNumber):
number_range_result = []
row_number_sp = StartNumber
gap = int(EndNumber) - int(StartNumber)
if gap > GapNumber:
for X in range(int(gap / GapNumber)):
temp = []
temp.appen... | class Core:
def gen_range(self, StartNumber, EndNumber, GapNumber):
number_range_result = []
row_number_sp = StartNumber
gap = int(EndNumber) - int(StartNumber)
if gap > GapNumber:
for x in range(int(gap / GapNumber)):
temp = []
temp.appen... |
"""
Day 14 - Part 1
https://adventofcode.com/2021/day/14
By NORXND @ 14.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open("Day14/input.txt", "r")
input_segments = input_file.read().split("\n\n")
template = input_segments[0]
rules = {}
for raw_rule in input_segments[1].splitlines():
rule = raw... | """
Day 14 - Part 1
https://adventofcode.com/2021/day/14
By NORXND @ 14.12.2021
(C) NORXND 2021 - Under The MIT License
"""
input_file = open('Day14/input.txt', 'r')
input_segments = input_file.read().split('\n\n')
template = input_segments[0]
rules = {}
for raw_rule in input_segments[1].splitlines():
rule = raw_r... |
manager_num1 =10
manager_num2 =11
zhangsan_num1 = 22
num3 = 30
pp = 36
ll = 23
nishuia
| manager_num1 = 10
manager_num2 = 11
zhangsan_num1 = 22
num3 = 30
pp = 36
ll = 23
nishuia |
class FilterModule:
def filters(self):
return {
'user_home': self.user_home
}
def user_home(self, d, username):
for user in d["results"]:
if user["item"] == username:
return user["home"]
return ValueError("Cannot find the home directory f... | class Filtermodule:
def filters(self):
return {'user_home': self.user_home}
def user_home(self, d, username):
for user in d['results']:
if user['item'] == username:
return user['home']
return value_error('Cannot find the home directory for user {}'.format(us... |
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
dic = {}
level = 0
q = collections.deque()
q.append(nestedList)
res = 0
while q:
size = len(q)
level += 1
sums = 0
for _ in range(size):
... | class Solution:
def depth_sum_inverse(self, nestedList: List[NestedInteger]) -> int:
dic = {}
level = 0
q = collections.deque()
q.append(nestedList)
res = 0
while q:
size = len(q)
level += 1
sums = 0
for _ in range(size... |
class Solution:
def reverseWords(self, s: str) -> str:
# Using Python's built-in string manipulation methods
# Split the string into words at the spaces, reverse and join the
# individual words, then rejoin the words with a space
s = s.split(' ')
for i, word in enumerate(s):
... | class Solution:
def reverse_words(self, s: str) -> str:
s = s.split(' ')
for (i, word) in enumerate(s):
s[i] = ''.join(list(reversed(word)))
return ' '.join(s) |
KEY_QUESTION_TYPE = 'question_type'
KEY_QUESTION = 'question'
KEY_ANSWER = 'answer'
KEY_OPTIONS = 'options'
KEY_COMPREHENSION = 'comprehension'
KEY_EXPLANATION = 'explanation'
| key_question_type = 'question_type'
key_question = 'question'
key_answer = 'answer'
key_options = 'options'
key_comprehension = 'comprehension'
key_explanation = 'explanation' |
def isExistingClassification(t):
pass
def getSrcNodeName(dst):
"""
Get the name of the node connected to the argument dst plug.
"""
pass
def getCollectionsRecursive(parent):
pass
def disconnect(src, dst):
pass
def findVolumeShader(shadingEngine, search='False'):
"""
Returns ... | def is_existing_classification(t):
pass
def get_src_node_name(dst):
"""
Get the name of the node connected to the argument dst plug.
"""
pass
def get_collections_recursive(parent):
pass
def disconnect(src, dst):
pass
def find_volume_shader(shadingEngine, search='False'):
"""
Retu... |
# 1. Property-specific details
# Timezone string follows TZ format (see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
PROP_NAME = "Ascott Raffles Place Singapore"
TIMEZONE = "Asia/Singapore"
# 2. Languages expected to be in use at this property
BABEL_LOCALES = ('en', 'zh', 'ms', 'ta')
BABEL_DEFAULT_LO... | prop_name = 'Ascott Raffles Place Singapore'
timezone = 'Asia/Singapore'
babel_locales = ('en', 'zh', 'ms', 'ta')
babel_default_locale = 'en'
debug = False
mysql_database_user = 'root'
mysql_database_password = 'classroom'
mysql_database_db = 'Ascott_InvMgmt'
mysql_database_host = 'ascott.coxb3venarbl.ap-southeast-1.rd... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 31 16:00:39 2019
@author: Administrator
"""
class Solution:
def flipAndInvertImage(self, A: list) -> list:
for a in A:
p, q = 0, len(a)-1
while p<=q:
if p == q:
a[p] = 1 - a[p]
br... | """
Created on Fri May 31 16:00:39 2019
@author: Administrator
"""
class Solution:
def flip_and_invert_image(self, A: list) -> list:
for a in A:
(p, q) = (0, len(a) - 1)
while p <= q:
if p == q:
a[p] = 1 - a[p]
break
... |
"""
Given a 32-bit signed integer, reverse digits of an integer.
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
s = str(x)
s = s[1:]
a = int(s[::-1])
return -a
else:
s = str(x)
return int(s[::-1])
prin... | """
Given a 32-bit signed integer, reverse digits of an integer.
"""
class Solution:
def is_palindrome(self, x: int) -> bool:
if x < 0:
s = str(x)
s = s[1:]
a = int(s[::-1])
return -a
else:
s = str(x)
return int(s[::-1])
print... |
result = []
for count in range (1,100):
if count % 3 == 0:
result.append("Fizz")
if count % 5 == 0:
result.append("Buzz")
else:
result.append(count)
print(result)
| result = []
for count in range(1, 100):
if count % 3 == 0:
result.append('Fizz')
if count % 5 == 0:
result.append('Buzz')
else:
result.append(count)
print(result) |
def on_data_received():
global cmd
cmd = serial.read_until(serial.delimiters(Delimiters.HASH))
basic.show_string(cmd)
if cmd == "0":
basic.show_leds("""
. # # # .
. # . # .
. # . # .
. # . # .
... | def on_data_received():
global cmd
cmd = serial.read_until(serial.delimiters(Delimiters.HASH))
basic.show_string(cmd)
if cmd == '0':
basic.show_leds('\n . # # # .\n . # . # .\n . # . # .\n . # . # .\n ... |
class SgfTree(object):
def __init__(self, properties=None, children=None):
self.properties = properties or {}
self.children = children or []
def __eq__(self, other):
if not isinstance(other, SgfTree):
return False
for k, v in self.properties.items():
if k... | class Sgftree(object):
def __init__(self, properties=None, children=None):
self.properties = properties or {}
self.children = children or []
def __eq__(self, other):
if not isinstance(other, SgfTree):
return False
for (k, v) in self.properties.items():
i... |
# <<<DBGL8R>>>
def add_floats(float_1, float_2):
""" Add two floating point numbers together. """
return float_1 + float_2
print('Hello world') # <<<DBGL8R
| def add_floats(float_1, float_2):
""" Add two floating point numbers together. """
return float_1 + float_2
print('Hello world') |
class ListView:
__slots__ = ['_list']
def __init__(self, list_object):
self._list = list_object
def __add__(self, other):
return self._list.__add__(other)
def __getitem__(self, other):
return self._list.__getitem__(other)
def __contains__(self, item):
return self.... | class Listview:
__slots__ = ['_list']
def __init__(self, list_object):
self._list = list_object
def __add__(self, other):
return self._list.__add__(other)
def __getitem__(self, other):
return self._list.__getitem__(other)
def __contains__(self, item):
return self.... |
def print_with_linenumbers(*args, numberwidth=3):
"""Prints every argument in a new line and adds line numbers"""
for i,arg in enumerate(args):
print(f"{i:0{numberwidth}d}: {arg}")
| def print_with_linenumbers(*args, numberwidth=3):
"""Prints every argument in a new line and adds line numbers"""
for (i, arg) in enumerate(args):
print(f'{i:0{numberwidth}d}: {arg}') |
class DSSnet_hosts:
'class for meta process/IED info'
p_id = 0
def __init__(self, msg, IED_id, command, ip, pipe = True):
self.properties= msg
self.IED_id = IED_id
self.process_id= DSSnet_hosts.p_id
self.command = command
self.ip = ip
self.pipe = pipe... | class Dssnet_Hosts:
"""class for meta process/IED info"""
p_id = 0
def __init__(self, msg, IED_id, command, ip, pipe=True):
self.properties = msg
self.IED_id = IED_id
self.process_id = DSSnet_hosts.p_id
self.command = command
self.ip = ip
self.pipe = pipe
... |
'''
Longest Increasing Subarray
Find the longest increasing subarray (subarray is when all elements are neighboring in the original array).
Input: [10, 1, 3, 8, 2, 0, 5, 7, 12, 3]
Output: 4
=========================================
Only in one iteration, check if the current element is bigger than the previous and i... | """
Longest Increasing Subarray
Find the longest increasing subarray (subarray is when all elements are neighboring in the original array).
Input: [10, 1, 3, 8, 2, 0, 5, 7, 12, 3]
Output: 4
=========================================
Only in one iteration, check if the current element is bigger than the previous and i... |
# This method breaks up text into words for us
def break_words(text):
words = text.split()
return words
# Counts the number of words
def count_words(words):
return len(words)
# Sorts the words (alphabetically)
def sort_words(words):
words.sort()
return words
# Takes in a full sentence and returns... | def break_words(text):
words = text.split()
return words
def count_words(words):
return len(words)
def sort_words(words):
words.sort()
return words
def sort_sentence(sentence):
words = break_words(sentence)
return words
def print_first_word(words):
word = words.pop(0)
return word... |
def esc_kw(kw):
""" Take a keyword and escape all the
Solr parts we want to escape!"""
kw = kw.replace('\\', '\\\\') # be sure to do this first, as we inject \!
kw = kw.replace('(', '\(')
kw = kw.replace(')', '\)')
kw = kw.replace('+', '\+')
kw = kw.replace('-', '\-')
kw = kw.replace... | def esc_kw(kw):
""" Take a keyword and escape all the
Solr parts we want to escape!"""
kw = kw.replace('\\', '\\\\')
kw = kw.replace('(', '\\(')
kw = kw.replace(')', '\\)')
kw = kw.replace('+', '\\+')
kw = kw.replace('-', '\\-')
kw = kw.replace(':', '\\:')
kw = kw.replace('/', '\... |
def main():
# input
a, b = input().split()
# compute
# output
print('H' if a==b else 'D')
if __name__ == '__main__':
main()
| def main():
(a, b) = input().split()
print('H' if a == b else 'D')
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
description = 'DNS detector setup'
group = 'lowlevel'
includes = ['counter']
sysconfig = dict(
datasinks = ['LiveView'],
)
tango_base = 'tango://phys.dns.frm2:10000/dns/'
devices = dict(
LiveView = device('nicos.devices.datasinks.LiveViewSink',
),
dettof = device('nicos_mlz.... | description = 'DNS detector setup'
group = 'lowlevel'
includes = ['counter']
sysconfig = dict(datasinks=['LiveView'])
tango_base = 'tango://phys.dns.frm2:10000/dns/'
devices = dict(LiveView=device('nicos.devices.datasinks.LiveViewSink'), dettof=device('nicos_mlz.dns.devices.detector.TofChannel', description='TOF data c... |
#/* n=int(input("Enter the number to print the tables for:"))
#for i in range(1,11):
# print(n,"x",i,"=",n*i)
n=int(input("Enter the number"))
for i in range(1,11):
print (n ,"x", i, "=", n * i)
| n = int(input('Enter the number'))
for i in range(1, 11):
print(n, 'x', i, '=', n * i) |
# -*- coding: utf-8 -*-
"""
File: config.sample.py
- Copy `config.sample.py` to `config.py`.
"""
# Subscription Key for calling the Cognitive Face API.
FACE_API_KEY = "your_face_api_key"
# subscription key for speach API
SPEACH_API_KEY = "your_speach_api_key"
# Base URL for calling the Cognitive Face API.
BASE_URL =... | """
File: config.sample.py
- Copy `config.sample.py` to `config.py`.
"""
face_api_key = 'your_face_api_key'
speach_api_key = 'your_speach_api_key'
base_url = 'your_base_url'
time_sleep = 3
group_id = 'your_group_id' |
class CMDDiffLevelEnum:
BreakingChange = 1 # diff breaking change part
Structure = 2 #
Associate = 5 # include diff for links
All = 10 # including description and help messages
| class Cmddifflevelenum:
breaking_change = 1
structure = 2
associate = 5
all = 10 |
def isColoured(mult,i,j):
if i//mult%2==j//mult%2:
return True
return False
def colour(i,j):
col = False
for each in mults:
if isColoured(each,i,j):
col = (col==False)
return col
data = open("DATA21.txt")
input = data.readline
for j in range(10):
n = int(input())
mults = []
for i in ... | def is_coloured(mult, i, j):
if i // mult % 2 == j // mult % 2:
return True
return False
def colour(i, j):
col = False
for each in mults:
if is_coloured(each, i, j):
col = col == False
return col
data = open('DATA21.txt')
input = data.readline
for j in range(10):
n =... |
def is_narcissistic_number(n):
original_number = n
number_of_digits = get_number_of_digits(n)
sum = 0
while n != 0:
sum += (n % 10) ** number_of_digits
n //= 10
return original_number == sum
def get_number_of_digits(n):
return len(str(n))
if __name__ == "__main__":
n = ... | def is_narcissistic_number(n):
original_number = n
number_of_digits = get_number_of_digits(n)
sum = 0
while n != 0:
sum += (n % 10) ** number_of_digits
n //= 10
return original_number == sum
def get_number_of_digits(n):
return len(str(n))
if __name__ == '__main__':
n = int(i... |
# Program to work with file input / output (i/o)
# This is pulling the days.txt file in this directory in this repo
path = 'days.txt'
days_file = open(path,'r')
days = days_file.read()
new_path = 'new_days.txt'
new_days = open(new_path,'w')
title = 'Days of the Week\n'
new_days.write(title)
print(title)
new_days.w... | path = 'days.txt'
days_file = open(path, 'r')
days = days_file.read()
new_path = 'new_days.txt'
new_days = open(new_path, 'w')
title = 'Days of the Week\n'
new_days.write(title)
print(title)
new_days.write(days)
print(days)
days_file.close()
new_days.close() |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
# DEMO OF WEAK TYPING in PYTHON
# int age = 4 <-strongly typed variables, declare type along with id
age = 4; # we CANNOT declare a type for variable age
print(age)
print(type(age))
age = ('calico','calico','himalyian')
print(age)
print(type(age))
# # Allegheny county... | age = 4
print(age)
print(type(age))
age = ('calico', 'calico', 'himalyian')
print(age)
print(type(age))
def iterate_ems_records(file_path):
"""
Retrieve each record from a CSV of EMS records from the filepath
Intended for use with the WPRDC's record of EMS dispatches
in Allegheny County and will p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.