body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
|---|---|---|---|---|---|---|---|---|---|
9e3f33ade9ade09e83e34a6eec415df486b591b73dbe52a8c7ef9b74ead46764
|
def run_command(command, command_env):
' Run a command (process) in a given environment. stdout/stderr are output piped through.\n Args:\n command (array): the command to run, with components of the command as separate elements.\n command_env (map): environment in which the command should be run\n Returns:\n The return code of the command.\n '
returncode = 0
log(('Invoking: %s' % ' '.join(command)))
if (not testing):
proc = subprocess.Popen(command, env=command_env)
(output, error) = proc.communicate()
returncode = proc.returncode
if (returncode != 0):
log(('Return code = %s' % returncode))
return returncode
|
Run a command (process) in a given environment. stdout/stderr are output piped through.
Args:
command (array): the command to run, with components of the command as separate elements.
command_env (map): environment in which the command should be run
Returns:
The return code of the command.
|
src/tests/Common/scripts/run-pmi-diffs.py
|
run_command
|
DarkBullNull/runtime
| 9,402
|
python
|
def run_command(command, command_env):
' Run a command (process) in a given environment. stdout/stderr are output piped through.\n Args:\n command (array): the command to run, with components of the command as separate elements.\n command_env (map): environment in which the command should be run\n Returns:\n The return code of the command.\n '
returncode = 0
log(('Invoking: %s' % ' '.join(command)))
if (not testing):
proc = subprocess.Popen(command, env=command_env)
(output, error) = proc.communicate()
returncode = proc.returncode
if (returncode != 0):
log(('Return code = %s' % returncode))
return returncode
|
def run_command(command, command_env):
' Run a command (process) in a given environment. stdout/stderr are output piped through.\n Args:\n command (array): the command to run, with components of the command as separate elements.\n command_env (map): environment in which the command should be run\n Returns:\n The return code of the command.\n '
returncode = 0
log(('Invoking: %s' % ' '.join(command)))
if (not testing):
proc = subprocess.Popen(command, env=command_env)
(output, error) = proc.communicate()
returncode = proc.returncode
if (returncode != 0):
log(('Return code = %s' % returncode))
return returncode<|docstring|>Run a command (process) in a given environment. stdout/stderr are output piped through.
Args:
command (array): the command to run, with components of the command as separate elements.
command_env (map): environment in which the command should be run
Returns:
The return code of the command.<|endoftext|>
|
298d8a4e39ac45f01e427c0a339df19c84f1cf6676f7c0c11afbd462f1a7187f
|
def req_and_clean(page_size):
'Main function to instantiate and launch operations.'
r = RequestData()
data = r.exec(page_size)
c = Cleaner(data)
data = c.filter_product()
return data
|
Main function to instantiate and launch operations.
|
openfoodfact/utils.py
|
req_and_clean
|
smtr42/P10_deploy
| 0
|
python
|
def req_and_clean(page_size):
r = RequestData()
data = r.exec(page_size)
c = Cleaner(data)
data = c.filter_product()
return data
|
def req_and_clean(page_size):
r = RequestData()
data = r.exec(page_size)
c = Cleaner(data)
data = c.filter_product()
return data<|docstring|>Main function to instantiate and launch operations.<|endoftext|>
|
1d369054c028c7804f417329e1a1459f8d2781f686df321a90314f7cb1a619b0
|
def exec(self, page_size):
'Main public function executing all necessary privates functions.'
self.list_cat = self._fetch_category()
data = self._fetch_products(page_size)
return data
|
Main public function executing all necessary privates functions.
|
openfoodfact/utils.py
|
exec
|
smtr42/P10_deploy
| 0
|
python
|
def exec(self, page_size):
self.list_cat = self._fetch_category()
data = self._fetch_products(page_size)
return data
|
def exec(self, page_size):
self.list_cat = self._fetch_category()
data = self._fetch_products(page_size)
return data<|docstring|>Main public function executing all necessary privates functions.<|endoftext|>
|
2015b6e099c9ca7553dc5c5846adae008a04ccebe7f350547931166fe33c8871
|
def _fetch_category(self):
'Request the list of category from the API.'
print('Getting Categories from API')
try:
response = self._req(self.cat_url)
data = response.json()
list_cat = [i['name'] for i in data['tags']][:17]
self.data = {}
return list_cat
except requests.exceptions.Timeout as t:
print('Request Timeout, please retry : ', t)
except requests.exceptions.RequestException as err:
print('Something went bad, please retry : :', err)
|
Request the list of category from the API.
|
openfoodfact/utils.py
|
_fetch_category
|
smtr42/P10_deploy
| 0
|
python
|
def _fetch_category(self):
print('Getting Categories from API')
try:
response = self._req(self.cat_url)
data = response.json()
list_cat = [i['name'] for i in data['tags']][:17]
self.data = {}
return list_cat
except requests.exceptions.Timeout as t:
print('Request Timeout, please retry : ', t)
except requests.exceptions.RequestException as err:
print('Something went bad, please retry : :', err)
|
def _fetch_category(self):
print('Getting Categories from API')
try:
response = self._req(self.cat_url)
data = response.json()
list_cat = [i['name'] for i in data['tags']][:17]
self.data = {}
return list_cat
except requests.exceptions.Timeout as t:
print('Request Timeout, please retry : ', t)
except requests.exceptions.RequestException as err:
print('Something went bad, please retry : :', err)<|docstring|>Request the list of category from the API.<|endoftext|>
|
1a1394b570180011ca592765a17effe022492b077199386ca2c36291e175609e
|
def _fetch_products(self, page_size):
'Request the products in respect for the categories loaded.'
print('Getting Products from API in respect to the Categories previously got')
fields = ','.join(keys)
all_products = {}
for category in self.list_cat:
config = {'action': 'process', 'tagtype_0': 'categories', 'tag_0': category, 'fields': fields, 'tag_contains_0': 'contains', 'page_size': page_size, 'json': 1}
response = self._req(self.search_url, param=config)
all_products[category] = response.json()
return all_products
|
Request the products in respect for the categories loaded.
|
openfoodfact/utils.py
|
_fetch_products
|
smtr42/P10_deploy
| 0
|
python
|
def _fetch_products(self, page_size):
print('Getting Products from API in respect to the Categories previously got')
fields = ','.join(keys)
all_products = {}
for category in self.list_cat:
config = {'action': 'process', 'tagtype_0': 'categories', 'tag_0': category, 'fields': fields, 'tag_contains_0': 'contains', 'page_size': page_size, 'json': 1}
response = self._req(self.search_url, param=config)
all_products[category] = response.json()
return all_products
|
def _fetch_products(self, page_size):
print('Getting Products from API in respect to the Categories previously got')
fields = ','.join(keys)
all_products = {}
for category in self.list_cat:
config = {'action': 'process', 'tagtype_0': 'categories', 'tag_0': category, 'fields': fields, 'tag_contains_0': 'contains', 'page_size': page_size, 'json': 1}
response = self._req(self.search_url, param=config)
all_products[category] = response.json()
return all_products<|docstring|>Request the products in respect for the categories loaded.<|endoftext|>
|
38e69ebe033a3097e8fa597e2d318e617fd1a927c5d4958962cbae480a0ab3ff
|
def _req(self, url, param=None):
'Small request function used multiple times.'
response = requests.get(url, param)
return response
|
Small request function used multiple times.
|
openfoodfact/utils.py
|
_req
|
smtr42/P10_deploy
| 0
|
python
|
def _req(self, url, param=None):
response = requests.get(url, param)
return response
|
def _req(self, url, param=None):
response = requests.get(url, param)
return response<|docstring|>Small request function used multiple times.<|endoftext|>
|
2317a898b12ce98614b973655d21f48230bc05be2309fd7c33a184952f99a7a7
|
def __init__(self, data):
'Initialize variables and launch filter_products.'
self.data = data
self.keys = keys
self.list_cat = [categories for categories in self.data]
self._dict_data = {}
self.list_of_dictio = []
self.barcode_list = []
self.name_list = []
|
Initialize variables and launch filter_products.
|
openfoodfact/utils.py
|
__init__
|
smtr42/P10_deploy
| 0
|
python
|
def __init__(self, data):
self.data = data
self.keys = keys
self.list_cat = [categories for categories in self.data]
self._dict_data = {}
self.list_of_dictio = []
self.barcode_list = []
self.name_list = []
|
def __init__(self, data):
self.data = data
self.keys = keys
self.list_cat = [categories for categories in self.data]
self._dict_data = {}
self.list_of_dictio = []
self.barcode_list = []
self.name_list = []<|docstring|>Initialize variables and launch filter_products.<|endoftext|>
|
306340b3e2dc6d98ea5216fabe70b0738a115d46d2488eef5d69bfd2615b8246
|
def filter_product(self):
'Get the data from json files and run checks.'
for category in self.list_cat:
for element in self.data[category]['products']:
if self._data_exist(element):
self.list_of_dictio.append(element)
self._dict_data[category] = self.list_of_dictio
self.list_of_dictio = []
return self._dict_data
|
Get the data from json files and run checks.
|
openfoodfact/utils.py
|
filter_product
|
smtr42/P10_deploy
| 0
|
python
|
def filter_product(self):
for category in self.list_cat:
for element in self.data[category]['products']:
if self._data_exist(element):
self.list_of_dictio.append(element)
self._dict_data[category] = self.list_of_dictio
self.list_of_dictio = []
return self._dict_data
|
def filter_product(self):
for category in self.list_cat:
for element in self.data[category]['products']:
if self._data_exist(element):
self.list_of_dictio.append(element)
self._dict_data[category] = self.list_of_dictio
self.list_of_dictio = []
return self._dict_data<|docstring|>Get the data from json files and run checks.<|endoftext|>
|
e5bf0febf3b32ac5e9da172e4de621879a21317ba8e62241c95b20b698c9baf9
|
def _data_exist(self, element):
"Run trough the data, if something's missing it's discarded."
for x in self.keys:
if ((x not in element) or (element[x] == '') or (len(element['id']) != 13)):
return False
barcode = int(element['id'])
if (barcode in self.barcode_list):
return False
else:
self.barcode_list.append(barcode)
name = element['product_name_fr'].lower()
if (name in self.name_list):
return False
else:
self.name_list.append(name)
return True
|
Run trough the data, if something's missing it's discarded.
|
openfoodfact/utils.py
|
_data_exist
|
smtr42/P10_deploy
| 0
|
python
|
def _data_exist(self, element):
for x in self.keys:
if ((x not in element) or (element[x] == ) or (len(element['id']) != 13)):
return False
barcode = int(element['id'])
if (barcode in self.barcode_list):
return False
else:
self.barcode_list.append(barcode)
name = element['product_name_fr'].lower()
if (name in self.name_list):
return False
else:
self.name_list.append(name)
return True
|
def _data_exist(self, element):
for x in self.keys:
if ((x not in element) or (element[x] == ) or (len(element['id']) != 13)):
return False
barcode = int(element['id'])
if (barcode in self.barcode_list):
return False
else:
self.barcode_list.append(barcode)
name = element['product_name_fr'].lower()
if (name in self.name_list):
return False
else:
self.name_list.append(name)
return True<|docstring|>Run trough the data, if something's missing it's discarded.<|endoftext|>
|
a19d9b02400bb0ae42ab545edd0a6fafd83b0d288b33c33337d51d59ad3c6e5f
|
def GaussianRandomStockPrice(mu, sigma, n, end, freq, S0=100):
'\n This function randomly creates a stock price series bases on gaussian probabilities.\n\n Arguments:\n ----------\n - mu: float\n The mean parameter\n - sigma: float\n The standard déviation parameter\n - n: int\n Number of periods\n - end: datetime date\n The last date of thé series\n - freq: pandas frequency string\n The frequency of thé dataseries:\n - "D": days\n - "min": minutes\n - "s": seconds\n - S0: float\n The first stock price\n\n Return:\n ----------\n - RStock: Pandas DataFrame\n Contains thé datetime as index and thé random stock prices in a column\n\n '
RStock = np.random.normal(mu, sigma, n).astype('float')
RStock = pd.DataFrame(RStock)
RStock.rename(inplace=True, columns={RStock.columns[0]: 'Return'})
RStock['Price'] = ((1 + RStock['Return']).cumprod() * S0)
times = pd.date_range(end=end, freq=freq, periods=n)
RStock.index = times
RStock = pd.DataFrame(RStock['Price'])
return RStock
|
This function randomly creates a stock price series bases on gaussian probabilities.
Arguments:
----------
- mu: float
The mean parameter
- sigma: float
The standard déviation parameter
- n: int
Number of periods
- end: datetime date
The last date of thé series
- freq: pandas frequency string
The frequency of thé dataseries:
- "D": days
- "min": minutes
- "s": seconds
- S0: float
The first stock price
Return:
----------
- RStock: Pandas DataFrame
Contains thé datetime as index and thé random stock prices in a column
|
Other/GaussianRandomStockPrice.py
|
GaussianRandomStockPrice
|
AcudoDev/FinanceToolbox
| 0
|
python
|
def GaussianRandomStockPrice(mu, sigma, n, end, freq, S0=100):
'\n This function randomly creates a stock price series bases on gaussian probabilities.\n\n Arguments:\n ----------\n - mu: float\n The mean parameter\n - sigma: float\n The standard déviation parameter\n - n: int\n Number of periods\n - end: datetime date\n The last date of thé series\n - freq: pandas frequency string\n The frequency of thé dataseries:\n - "D": days\n - "min": minutes\n - "s": seconds\n - S0: float\n The first stock price\n\n Return:\n ----------\n - RStock: Pandas DataFrame\n Contains thé datetime as index and thé random stock prices in a column\n\n '
RStock = np.random.normal(mu, sigma, n).astype('float')
RStock = pd.DataFrame(RStock)
RStock.rename(inplace=True, columns={RStock.columns[0]: 'Return'})
RStock['Price'] = ((1 + RStock['Return']).cumprod() * S0)
times = pd.date_range(end=end, freq=freq, periods=n)
RStock.index = times
RStock = pd.DataFrame(RStock['Price'])
return RStock
|
def GaussianRandomStockPrice(mu, sigma, n, end, freq, S0=100):
'\n This function randomly creates a stock price series bases on gaussian probabilities.\n\n Arguments:\n ----------\n - mu: float\n The mean parameter\n - sigma: float\n The standard déviation parameter\n - n: int\n Number of periods\n - end: datetime date\n The last date of thé series\n - freq: pandas frequency string\n The frequency of thé dataseries:\n - "D": days\n - "min": minutes\n - "s": seconds\n - S0: float\n The first stock price\n\n Return:\n ----------\n - RStock: Pandas DataFrame\n Contains thé datetime as index and thé random stock prices in a column\n\n '
RStock = np.random.normal(mu, sigma, n).astype('float')
RStock = pd.DataFrame(RStock)
RStock.rename(inplace=True, columns={RStock.columns[0]: 'Return'})
RStock['Price'] = ((1 + RStock['Return']).cumprod() * S0)
times = pd.date_range(end=end, freq=freq, periods=n)
RStock.index = times
RStock = pd.DataFrame(RStock['Price'])
return RStock<|docstring|>This function randomly creates a stock price series bases on gaussian probabilities.
Arguments:
----------
- mu: float
The mean parameter
- sigma: float
The standard déviation parameter
- n: int
Number of periods
- end: datetime date
The last date of thé series
- freq: pandas frequency string
The frequency of thé dataseries:
- "D": days
- "min": minutes
- "s": seconds
- S0: float
The first stock price
Return:
----------
- RStock: Pandas DataFrame
Contains thé datetime as index and thé random stock prices in a column<|endoftext|>
|
4dadd73caedb62b0d56f5e235b4c724d397846a1eb7609995265bf6953f0cf75
|
def get_rapplied(self, sequence):
'Get a version of this `PermSpace` that has a range of `sequence`.'
if self.is_rapplied:
raise TypeError('This space is already rapplied, to rapply it to a different sequence please use `.unrapplied` first.')
sequence = sequence_tools.ensure_iterable_is_immutable_sequence(sequence)
if (len(sequence) != self.sequence_length):
raise Exception
return PermSpace(sequence, n_elements=self.n_elements, domain=self.domain, fixed_map={key: sequence[value] for (key, value) in self.fixed_map.items()}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)
|
Get a version of this `PermSpace` that has a range of `sequence`.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_rapplied
|
hboshnak/python_toolbox
| 119
|
python
|
def get_rapplied(self, sequence):
if self.is_rapplied:
raise TypeError('This space is already rapplied, to rapply it to a different sequence please use `.unrapplied` first.')
sequence = sequence_tools.ensure_iterable_is_immutable_sequence(sequence)
if (len(sequence) != self.sequence_length):
raise Exception
return PermSpace(sequence, n_elements=self.n_elements, domain=self.domain, fixed_map={key: sequence[value] for (key, value) in self.fixed_map.items()}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)
|
def get_rapplied(self, sequence):
if self.is_rapplied:
raise TypeError('This space is already rapplied, to rapply it to a different sequence please use `.unrapplied` first.')
sequence = sequence_tools.ensure_iterable_is_immutable_sequence(sequence)
if (len(sequence) != self.sequence_length):
raise Exception
return PermSpace(sequence, n_elements=self.n_elements, domain=self.domain, fixed_map={key: sequence[value] for (key, value) in self.fixed_map.items()}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)<|docstring|>Get a version of this `PermSpace` that has a range of `sequence`.<|endoftext|>
|
48af5358e18d448f7406f0a25e3b28396eb5222080e08cb0f662c2f2b119f15f
|
def get_partialled(self, n_elements):
'Get a partialled version of this `PermSpace`.'
if self.is_sliced:
raise TypeError("Can't get partial of sliced `PermSpace` directly, because the number of items would be different. Use `.unsliced` first.")
return PermSpace(self.sequence, n_elements=n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)
|
Get a partialled version of this `PermSpace`.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_partialled
|
hboshnak/python_toolbox
| 119
|
python
|
def get_partialled(self, n_elements):
if self.is_sliced:
raise TypeError("Can't get partial of sliced `PermSpace` directly, because the number of items would be different. Use `.unsliced` first.")
return PermSpace(self.sequence, n_elements=n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)
|
def get_partialled(self, n_elements):
if self.is_sliced:
raise TypeError("Can't get partial of sliced `PermSpace` directly, because the number of items would be different. Use `.unsliced` first.")
return PermSpace(self.sequence, n_elements=n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)<|docstring|>Get a partialled version of this `PermSpace`.<|endoftext|>
|
3fa7ddb9e5e3f324789138c434167c266fb56548d98cc911fc099fc551bae858
|
@caching.CachedProperty
def combinationed(self):
'Get a combination version of this perm space.'
from .comb import Comb
if self.is_sliced:
raise TypeError("Can't get a combinationed version of a sliced `PermSpace`directly, because the number of items would be different. Use `.unsliced` first.")
if self.is_typed:
raise TypeError("Can't convert typed `PermSpace` directly to combinationed, because the perm class would not be a subclass of `Comb`.")
if self.is_degreed:
raise TypeError("Can't use degrees with combination spaces.")
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, is_combination=True, perm_type=Comb)
|
Get a combination version of this perm space.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
combinationed
|
hboshnak/python_toolbox
| 119
|
python
|
@caching.CachedProperty
def combinationed(self):
from .comb import Comb
if self.is_sliced:
raise TypeError("Can't get a combinationed version of a sliced `PermSpace`directly, because the number of items would be different. Use `.unsliced` first.")
if self.is_typed:
raise TypeError("Can't convert typed `PermSpace` directly to combinationed, because the perm class would not be a subclass of `Comb`.")
if self.is_degreed:
raise TypeError("Can't use degrees with combination spaces.")
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, is_combination=True, perm_type=Comb)
|
@caching.CachedProperty
def combinationed(self):
from .comb import Comb
if self.is_sliced:
raise TypeError("Can't get a combinationed version of a sliced `PermSpace`directly, because the number of items would be different. Use `.unsliced` first.")
if self.is_typed:
raise TypeError("Can't convert typed `PermSpace` directly to combinationed, because the perm class would not be a subclass of `Comb`.")
if self.is_degreed:
raise TypeError("Can't use degrees with combination spaces.")
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, is_combination=True, perm_type=Comb)<|docstring|>Get a combination version of this perm space.<|endoftext|>
|
81773475b6d749f98959fa94f01184183969b5c2fe4e787da05ea998d352d1c8
|
def get_dapplied(self, domain):
'Get a version of this `PermSpace` that has a domain of `domain`.'
from . import variations
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DAPPLIED: True, variations.Variation.COMBINATION: True})
domain = sequence_tools.ensure_iterable_is_immutable_sequence(domain)
if (len(domain) != self.n_elements):
raise Exception
return PermSpace(self.sequence, n_elements=self.n_elements, domain=domain, fixed_map={domain[key]: value for (key, value) in self._undapplied_fixed_map}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)
|
Get a version of this `PermSpace` that has a domain of `domain`.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_dapplied
|
hboshnak/python_toolbox
| 119
|
python
|
def get_dapplied(self, domain):
from . import variations
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DAPPLIED: True, variations.Variation.COMBINATION: True})
domain = sequence_tools.ensure_iterable_is_immutable_sequence(domain)
if (len(domain) != self.n_elements):
raise Exception
return PermSpace(self.sequence, n_elements=self.n_elements, domain=domain, fixed_map={domain[key]: value for (key, value) in self._undapplied_fixed_map}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)
|
def get_dapplied(self, domain):
from . import variations
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DAPPLIED: True, variations.Variation.COMBINATION: True})
domain = sequence_tools.ensure_iterable_is_immutable_sequence(domain)
if (len(domain) != self.n_elements):
raise Exception
return PermSpace(self.sequence, n_elements=self.n_elements, domain=domain, fixed_map={domain[key]: value for (key, value) in self._undapplied_fixed_map}, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=self.perm_type)<|docstring|>Get a version of this `PermSpace` that has a domain of `domain`.<|endoftext|>
|
ec1985f1e11f4a94967264ef1728cfffe22a287bbbaf7ed64e4d32bf09edb68a
|
def get_fixed(self, fixed_map):
'Get a fixed version of this `PermSpace`.'
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_fixed(...)`. You may then re-slice the resulting space.")
combined_fixed_map = dict(self.fixed_map)
for (key, value) in fixed_map.items():
if (key in self.fixed_map):
assert (self.fixed_map[key] == value)
combined_fixed_map[key] = value
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=combined_fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)
|
Get a fixed version of this `PermSpace`.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_fixed
|
hboshnak/python_toolbox
| 119
|
python
|
def get_fixed(self, fixed_map):
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_fixed(...)`. You may then re-slice the resulting space.")
combined_fixed_map = dict(self.fixed_map)
for (key, value) in fixed_map.items():
if (key in self.fixed_map):
assert (self.fixed_map[key] == value)
combined_fixed_map[key] = value
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=combined_fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)
|
def get_fixed(self, fixed_map):
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_fixed(...)`. You may then re-slice the resulting space.")
combined_fixed_map = dict(self.fixed_map)
for (key, value) in fixed_map.items():
if (key in self.fixed_map):
assert (self.fixed_map[key] == value)
combined_fixed_map[key] = value
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=combined_fixed_map, degrees=self.degrees, slice_=None, is_combination=self.is_combination, perm_type=self.perm_type)<|docstring|>Get a fixed version of this `PermSpace`.<|endoftext|>
|
7a58ec0e1772123325b53f1963d0d3c7515330e5a43f1efe25801db5612d836e
|
def get_degreed(self, degrees):
'Get a version of this `PermSpace` restricted to certain degrees.'
from . import variations
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_degreed(...)`. You may then re-slice the resulting space.")
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DEGREED: True, variations.Variation.COMBINATION: True})
degrees = sequence_tools.to_tuple(degrees, item_type=int)
if (not degrees):
return self
degrees_to_use = (degrees if (not self.is_degreed) else (set(degrees) & set(self.degrees)))
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=degrees_to_use, is_combination=self.is_combination, perm_type=self.perm_type)
|
Get a version of this `PermSpace` restricted to certain degrees.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_degreed
|
hboshnak/python_toolbox
| 119
|
python
|
def get_degreed(self, degrees):
from . import variations
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_degreed(...)`. You may then re-slice the resulting space.")
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DEGREED: True, variations.Variation.COMBINATION: True})
degrees = sequence_tools.to_tuple(degrees, item_type=int)
if (not degrees):
return self
degrees_to_use = (degrees if (not self.is_degreed) else (set(degrees) & set(self.degrees)))
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=degrees_to_use, is_combination=self.is_combination, perm_type=self.perm_type)
|
def get_degreed(self, degrees):
from . import variations
if self.is_sliced:
raise TypeError("Can't be used on sliced perm spaces. Try `perm_space.unsliced.get_degreed(...)`. You may then re-slice the resulting space.")
if self.is_combination:
raise variations.UnallowedVariationSelectionException({variations.Variation.DEGREED: True, variations.Variation.COMBINATION: True})
degrees = sequence_tools.to_tuple(degrees, item_type=int)
if (not degrees):
return self
degrees_to_use = (degrees if (not self.is_degreed) else (set(degrees) & set(self.degrees)))
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=degrees_to_use, is_combination=self.is_combination, perm_type=self.perm_type)<|docstring|>Get a version of this `PermSpace` restricted to certain degrees.<|endoftext|>
|
9e3e07e8b39c4f34d435aa66a79f47849e35f25bd0a0c13a671442bfa79b80f6
|
def get_typed(self, perm_type):
'\n Get a version of this `PermSpace` where perms are of a custom type.\n '
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=perm_type)
|
Get a version of this `PermSpace` where perms are of a custom type.
|
python_toolbox/combi/perming/_variation_adding_mixin.py
|
get_typed
|
hboshnak/python_toolbox
| 119
|
python
|
def get_typed(self, perm_type):
'\n \n '
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=perm_type)
|
def get_typed(self, perm_type):
'\n \n '
return PermSpace(self.sequence, n_elements=self.n_elements, domain=self.domain, fixed_map=self.fixed_map, degrees=self.degrees, slice_=self.canonical_slice, is_combination=self.is_combination, perm_type=perm_type)<|docstring|>Get a version of this `PermSpace` where perms are of a custom type.<|endoftext|>
|
692a7b6fc7569dda9311ad2b2b9f23327e31cae8fe536056c37888b7faddb361
|
def test_sticky_association():
'Test that as long as distance is below threshold, the association does\n not switch, even if a detection with better IoU score appears.\n '
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 0)
assert (metrics['IDS'] == 0)
assert (metrics['FP_CLEAR'] == 1)
|
Test that as long as distance is below threshold, the association does
not switch, even if a detection with better IoU score appears.
|
tests/unit/test_clearmot.py
|
test_sticky_association
|
traffic-ai/EvalDeT
| 2
|
python
|
def test_sticky_association():
'Test that as long as distance is below threshold, the association does\n not switch, even if a detection with better IoU score appears.\n '
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 0)
assert (metrics['IDS'] == 0)
assert (metrics['FP_CLEAR'] == 1)
|
def test_sticky_association():
'Test that as long as distance is below threshold, the association does\n not switch, even if a detection with better IoU score appears.\n '
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 0)
assert (metrics['IDS'] == 0)
assert (metrics['FP_CLEAR'] == 1)<|docstring|>Test that as long as distance is below threshold, the association does
not switch, even if a detection with better IoU score appears.<|endoftext|>
|
6b907fa22c1104e798d58dd5d880782313ccec1e7feb7614593e01d41d2f67a0
|
def test_persistent_mismatch():
'Test that association (and therefore mismatch) persists even\n when the first matched hypothesis is gone, as long as another one\n is not assigned.'
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(2, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(2, [1], np.array([[0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 0)
|
Test that association (and therefore mismatch) persists even
when the first matched hypothesis is gone, as long as another one
is not assigned.
|
tests/unit/test_clearmot.py
|
test_persistent_mismatch
|
traffic-ai/EvalDeT
| 2
|
python
|
def test_persistent_mismatch():
'Test that association (and therefore mismatch) persists even\n when the first matched hypothesis is gone, as long as another one\n is not assigned.'
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(2, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(2, [1], np.array([[0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 0)
|
def test_persistent_mismatch():
'Test that association (and therefore mismatch) persists even\n when the first matched hypothesis is gone, as long as another one\n is not assigned.'
gt = Tracks()
gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))
gt.add_frame(2, [0], np.array([[0, 0, 1, 1]]))
hyp = Tracks()
hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))
hyp.add_frame(2, [1], np.array([[0, 0, 1, 1]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 0)<|docstring|>Test that association (and therefore mismatch) persists even
when the first matched hypothesis is gone, as long as another one
is not assigned.<|endoftext|>
|
445b72023d5b924fef6fc0d4b910d681c96821bd58e3fae8bf383d11f0d02e7f
|
def test_simple_case():
'Test a simple case with 3 frames and 2 detections/gts per frame.'
gt = Tracks()
gt.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
gt.add_frame(1, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
gt.add_frame(2, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
hyp = Tracks()
hyp.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [1, 1, 2, 2]]))
hyp.add_frame(2, [2, 1], np.array([[0.05, 0.05, 1.05, 1.05], [2, 2, 3, 3]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 1)
assert (metrics['MOTA'] == 0.5)
assert (metrics['MOTP'] == 0.0994008537355717)
|
Test a simple case with 3 frames and 2 detections/gts per frame.
|
tests/unit/test_clearmot.py
|
test_simple_case
|
traffic-ai/EvalDeT
| 2
|
python
|
def test_simple_case():
gt = Tracks()
gt.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
gt.add_frame(1, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
gt.add_frame(2, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
hyp = Tracks()
hyp.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [1, 1, 2, 2]]))
hyp.add_frame(2, [2, 1], np.array([[0.05, 0.05, 1.05, 1.05], [2, 2, 3, 3]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 1)
assert (metrics['MOTA'] == 0.5)
assert (metrics['MOTP'] == 0.0994008537355717)
|
def test_simple_case():
gt = Tracks()
gt.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
gt.add_frame(1, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
gt.add_frame(2, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))
hyp = Tracks()
hyp.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))
hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [1, 1, 2, 2]]))
hyp.add_frame(2, [2, 1], np.array([[0.05, 0.05, 1.05, 1.05], [2, 2, 3, 3]]))
metrics = calculate_clearmot_metrics(gt, hyp)
assert (metrics['FN_CLEAR'] == 1)
assert (metrics['IDS'] == 1)
assert (metrics['FP_CLEAR'] == 1)
assert (metrics['MOTA'] == 0.5)
assert (metrics['MOTP'] == 0.0994008537355717)<|docstring|>Test a simple case with 3 frames and 2 detections/gts per frame.<|endoftext|>
|
cccd9a7f19c87dfe272b7ee0f322f1f8ce8c5beaee3c4d2f8424e860585d8c16
|
def write_csv(write_out_path, name, headers, rows_to_write):
"\n Purpose\n -------\n This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers\n\n Parameters\n ----------\n :param name: The file name\n :type name: str\n\n :param write_out_path: The write directory\n :type write_out_path: str\n\n :param headers: The headers for the columns you want to write\n :type headers: list\n\n :param rows_to_write: A list of row data to write, each columns row should be an individual element of a list.\n :type rows_to_write: list\n\n :return: Nothing, just write out the file to the specified directory named the specified name\n :rtype: None\n "
if (type(rows_to_write[0]) != list):
rows_to_write = [[row] for row in rows_to_write]
with open(f'{write_out_path}/{name}.csv', 'w', newline='', encoding='utf-8') as csv_reader:
csv_writer = csv.writer(csv_reader)
if (len(headers) > 0):
csv_writer.writerow(headers)
for row in rows_to_write:
csv_writer.writerow(row)
|
Purpose
-------
This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers
Parameters
----------
:param name: The file name
:type name: str
:param write_out_path: The write directory
:type write_out_path: str
:param headers: The headers for the columns you want to write
:type headers: list
:param rows_to_write: A list of row data to write, each columns row should be an individual element of a list.
:type rows_to_write: list
:return: Nothing, just write out the file to the specified directory named the specified name
:rtype: None
|
csvObject/csvWriter.py
|
write_csv
|
sbaker-dev/csvObject
| 0
|
python
|
def write_csv(write_out_path, name, headers, rows_to_write):
"\n Purpose\n -------\n This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers\n\n Parameters\n ----------\n :param name: The file name\n :type name: str\n\n :param write_out_path: The write directory\n :type write_out_path: str\n\n :param headers: The headers for the columns you want to write\n :type headers: list\n\n :param rows_to_write: A list of row data to write, each columns row should be an individual element of a list.\n :type rows_to_write: list\n\n :return: Nothing, just write out the file to the specified directory named the specified name\n :rtype: None\n "
if (type(rows_to_write[0]) != list):
rows_to_write = [[row] for row in rows_to_write]
with open(f'{write_out_path}/{name}.csv', 'w', newline=, encoding='utf-8') as csv_reader:
csv_writer = csv.writer(csv_reader)
if (len(headers) > 0):
csv_writer.writerow(headers)
for row in rows_to_write:
csv_writer.writerow(row)
|
def write_csv(write_out_path, name, headers, rows_to_write):
"\n Purpose\n -------\n This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers\n\n Parameters\n ----------\n :param name: The file name\n :type name: str\n\n :param write_out_path: The write directory\n :type write_out_path: str\n\n :param headers: The headers for the columns you want to write\n :type headers: list\n\n :param rows_to_write: A list of row data to write, each columns row should be an individual element of a list.\n :type rows_to_write: list\n\n :return: Nothing, just write out the file to the specified directory named the specified name\n :rtype: None\n "
if (type(rows_to_write[0]) != list):
rows_to_write = [[row] for row in rows_to_write]
with open(f'{write_out_path}/{name}.csv', 'w', newline=, encoding='utf-8') as csv_reader:
csv_writer = csv.writer(csv_reader)
if (len(headers) > 0):
csv_writer.writerow(headers)
for row in rows_to_write:
csv_writer.writerow(row)<|docstring|>Purpose
-------
This writes out a csv file of row data with an optional header. If you don't want a header, pass None to headers
Parameters
----------
:param name: The file name
:type name: str
:param write_out_path: The write directory
:type write_out_path: str
:param headers: The headers for the columns you want to write
:type headers: list
:param rows_to_write: A list of row data to write, each columns row should be an individual element of a list.
:type rows_to_write: list
:return: Nothing, just write out the file to the specified directory named the specified name
:rtype: None<|endoftext|>
|
dcea90ea8ce0b4aaccd70a3d65a3c5e0735650e5b139d956b792061ba11f2942
|
def capabilities(self):
'Return a structure describing the capabilities of this device'
if ('capabilities' in self.config):
return self.config['capabilities']
else:
return {'getPos': (True, True, True), 'setPos': (True, True, True), 'limits': (False, False, False)}
|
Return a structure describing the capabilities of this device
|
acq4/devices/PatchStar/patchstar.py
|
capabilities
|
tropp/ACQ4
| 0
|
python
|
def capabilities(self):
if ('capabilities' in self.config):
return self.config['capabilities']
else:
return {'getPos': (True, True, True), 'setPos': (True, True, True), 'limits': (False, False, False)}
|
def capabilities(self):
if ('capabilities' in self.config):
return self.config['capabilities']
else:
return {'getPos': (True, True, True), 'setPos': (True, True, True), 'limits': (False, False, False)}<|docstring|>Return a structure describing the capabilities of this device<|endoftext|>
|
5544a6a30c72cf4576184e734858fcdccae2ae4e6ae42a9feb8f19ef4e56c990
|
def stop(self):
'Stop the manipulator immediately.\n '
with self.lock:
self.dev.stop()
if (self._lastMove is not None):
self._lastMove._stopped()
self._lastMove = None
|
Stop the manipulator immediately.
|
acq4/devices/PatchStar/patchstar.py
|
stop
|
tropp/ACQ4
| 0
|
python
|
def stop(self):
'\n '
with self.lock:
self.dev.stop()
if (self._lastMove is not None):
self._lastMove._stopped()
self._lastMove = None
|
def stop(self):
'\n '
with self.lock:
self.dev.stop()
if (self._lastMove is not None):
self._lastMove._stopped()
self._lastMove = None<|docstring|>Stop the manipulator immediately.<|endoftext|>
|
b9ce5898f4e93e4b20c5c5a8ea4fba88eb38f6029bacec7edeb08ea4a6f719e3
|
def setUserSpeed(self, v):
'Set the speed of the rotary controller (m/turn).\n '
self.userSpeed = v
self.dev.setSpeed((v / self.scale[0]))
|
Set the speed of the rotary controller (m/turn).
|
acq4/devices/PatchStar/patchstar.py
|
setUserSpeed
|
tropp/ACQ4
| 0
|
python
|
def setUserSpeed(self, v):
'\n '
self.userSpeed = v
self.dev.setSpeed((v / self.scale[0]))
|
def setUserSpeed(self, v):
'\n '
self.userSpeed = v
self.dev.setSpeed((v / self.scale[0]))<|docstring|>Set the speed of the rotary controller (m/turn).<|endoftext|>
|
130d65cc2b6da8dcfb434c0f2e99058e669b0a7efe4f293cb8bb56f22b6eeec5
|
def wasInterrupted(self):
'Return True if the move was interrupted before completing.\n '
return self._interrupted
|
Return True if the move was interrupted before completing.
|
acq4/devices/PatchStar/patchstar.py
|
wasInterrupted
|
tropp/ACQ4
| 0
|
python
|
def wasInterrupted(self):
'\n '
return self._interrupted
|
def wasInterrupted(self):
'\n '
return self._interrupted<|docstring|>Return True if the move was interrupted before completing.<|endoftext|>
|
297b7ddda0093de03ff3ff74aaba1c6b981ffc9993a4919b195fd2407c596759
|
def isDone(self):
'Return True if the move is complete.\n '
return (self._getStatus() != 0)
|
Return True if the move is complete.
|
acq4/devices/PatchStar/patchstar.py
|
isDone
|
tropp/ACQ4
| 0
|
python
|
def isDone(self):
'\n '
return (self._getStatus() != 0)
|
def isDone(self):
'\n '
return (self._getStatus() != 0)<|docstring|>Return True if the move is complete.<|endoftext|>
|
9f8bde7600c5bb7edc4f81527bf3c2f5f0dbc853fbea2d7174bf37a087fd03ff
|
def thinningSS(file, max_strain=10, interval=0.1):
"a function to conduct data thinning of SS curve at range (0, MAX_STRAIN), with INTERVAL\n This returns np.series of stress with strain in the index. \n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file\n "
import pandas as pd
import numpy as np
data = pd.read_csv(file['crv'], sep=',', encoding='shift_jis', skiprows=1, index_col=0)
data_rlt = pd.read_csv(file['rlt'], sep=',', encoding='shift_jis')
L = 64
b = float(data_rlt.iloc[(2, 3)])
h = float(data_rlt.iloc[(2, 4)])
col = ['mm', 'N']
data = data.reindex(columns=col)
data.dropna(subset=['mm'], inplace=True)
data['strain'] = (((((data['mm'] * 6) * 100) * h) / L) / L)
data['stress'] = (((data['N'] * 3) * L) / (((2 * b) * h) * h))
interval_steps = int((max_strain / interval))
marker = pd.DataFrame({'strain': np.round(np.linspace(0, max_strain, interval_steps, endpoint=False), 2), 'marker': True})
data_marked = pd.merge(data, marker, on='strain', how='outer')
data_marked.rename(data_marked['strain'], inplace=True)
data_marked.sort_values(by=['strain'], inplace=True)
data_marked.interpolate(method='slinear', limit=1, inplace=True)
data_marked['marker'].fillna('False', inplace=True)
data_skipped = data_marked[(data_marked['marker'] == True)]
thinnedSS = data_skipped['stress']
thinnedSS.name = file['name']
return thinnedSS
|
a function to conduct data thinning of SS curve at range (0, MAX_STRAIN), with INTERVAL
This returns np.series of stress with strain in the index.
FILE should be passed as dictionary containing following:
'name': name of sample like 'RL7785'
'crv': path(relative) of xxx_crv.csv file
'rlt': path(relative) of xxx_rlt.csv file
'set': path(relative) of xxx_set.csv file
|
drawSS.py
|
thinningSS
|
banroku/analySS
| 0
|
python
|
def thinningSS(file, max_strain=10, interval=0.1):
"a function to conduct data thinning of SS curve at range (0, MAX_STRAIN), with INTERVAL\n This returns np.series of stress with strain in the index. \n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file\n "
import pandas as pd
import numpy as np
data = pd.read_csv(file['crv'], sep=',', encoding='shift_jis', skiprows=1, index_col=0)
data_rlt = pd.read_csv(file['rlt'], sep=',', encoding='shift_jis')
L = 64
b = float(data_rlt.iloc[(2, 3)])
h = float(data_rlt.iloc[(2, 4)])
col = ['mm', 'N']
data = data.reindex(columns=col)
data.dropna(subset=['mm'], inplace=True)
data['strain'] = (((((data['mm'] * 6) * 100) * h) / L) / L)
data['stress'] = (((data['N'] * 3) * L) / (((2 * b) * h) * h))
interval_steps = int((max_strain / interval))
marker = pd.DataFrame({'strain': np.round(np.linspace(0, max_strain, interval_steps, endpoint=False), 2), 'marker': True})
data_marked = pd.merge(data, marker, on='strain', how='outer')
data_marked.rename(data_marked['strain'], inplace=True)
data_marked.sort_values(by=['strain'], inplace=True)
data_marked.interpolate(method='slinear', limit=1, inplace=True)
data_marked['marker'].fillna('False', inplace=True)
data_skipped = data_marked[(data_marked['marker'] == True)]
thinnedSS = data_skipped['stress']
thinnedSS.name = file['name']
return thinnedSS
|
def thinningSS(file, max_strain=10, interval=0.1):
"a function to conduct data thinning of SS curve at range (0, MAX_STRAIN), with INTERVAL\n This returns np.series of stress with strain in the index. \n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file\n "
import pandas as pd
import numpy as np
data = pd.read_csv(file['crv'], sep=',', encoding='shift_jis', skiprows=1, index_col=0)
data_rlt = pd.read_csv(file['rlt'], sep=',', encoding='shift_jis')
L = 64
b = float(data_rlt.iloc[(2, 3)])
h = float(data_rlt.iloc[(2, 4)])
col = ['mm', 'N']
data = data.reindex(columns=col)
data.dropna(subset=['mm'], inplace=True)
data['strain'] = (((((data['mm'] * 6) * 100) * h) / L) / L)
data['stress'] = (((data['N'] * 3) * L) / (((2 * b) * h) * h))
interval_steps = int((max_strain / interval))
marker = pd.DataFrame({'strain': np.round(np.linspace(0, max_strain, interval_steps, endpoint=False), 2), 'marker': True})
data_marked = pd.merge(data, marker, on='strain', how='outer')
data_marked.rename(data_marked['strain'], inplace=True)
data_marked.sort_values(by=['strain'], inplace=True)
data_marked.interpolate(method='slinear', limit=1, inplace=True)
data_marked['marker'].fillna('False', inplace=True)
data_skipped = data_marked[(data_marked['marker'] == True)]
thinnedSS = data_skipped['stress']
thinnedSS.name = file['name']
return thinnedSS<|docstring|>a function to conduct data thinning of SS curve at range (0, MAX_STRAIN), with INTERVAL
This returns np.series of stress with strain in the index.
FILE should be passed as dictionary containing following:
'name': name of sample like 'RL7785'
'crv': path(relative) of xxx_crv.csv file
'rlt': path(relative) of xxx_rlt.csv file
'set': path(relative) of xxx_set.csv file<|endoftext|>
|
31918ec20389a230a5b1bd574e831fa323aeb738cb7d181b0754a02dfe01d7aa
|
def parameters(file):
"a function to pick following parameters as pd.Series: \n parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', \n 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']\n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file "
file_rlt = file['rlt']
data_rlt = pd.read_csv(file_rlt, sep=',', skiprows=[1, 2], index_col=0, encoding='shift_jis')
parameters = ['幅', '厚さ', '弾性率', '最大点', '破壊点', '最大点.1', '破壊点.1']
data_rlt = data_rlt.loc[(['単純平均', '標準偏差'], parameters)]
data_rlt.index = ['average', 'stdev']
data_rlt.columns = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break']
data_rlt = data_rlt.values
data_flattened = [item for sublist in data_rlt for item in sublist]
parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']
data_rlt = pd.Series(data_flattened, index=parameters)
data_rlt.name = file['name']
return data_rlt
|
a function to pick following parameters as pd.Series:
parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break',
'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']
FILE should be passed as dictionary containing following:
'name': name of sample like 'RL7785'
'crv': path(relative) of xxx_crv.csv file
'rlt': path(relative) of xxx_rlt.csv file
'set': path(relative) of xxx_set.csv file
|
drawSS.py
|
parameters
|
banroku/analySS
| 0
|
python
|
def parameters(file):
"a function to pick following parameters as pd.Series: \n parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', \n 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']\n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file "
file_rlt = file['rlt']
data_rlt = pd.read_csv(file_rlt, sep=',', skiprows=[1, 2], index_col=0, encoding='shift_jis')
parameters = ['幅', '厚さ', '弾性率', '最大点', '破壊点', '最大点.1', '破壊点.1']
data_rlt = data_rlt.loc[(['単純平均', '標準偏差'], parameters)]
data_rlt.index = ['average', 'stdev']
data_rlt.columns = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break']
data_rlt = data_rlt.values
data_flattened = [item for sublist in data_rlt for item in sublist]
parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']
data_rlt = pd.Series(data_flattened, index=parameters)
data_rlt.name = file['name']
return data_rlt
|
def parameters(file):
"a function to pick following parameters as pd.Series: \n parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', \n 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']\n FILE should be passed as dictionary containing following: \n 'name': name of sample like 'RL7785'\n 'crv': path(relative) of xxx_crv.csv file\n 'rlt': path(relative) of xxx_rlt.csv file\n 'set': path(relative) of xxx_set.csv file "
file_rlt = file['rlt']
data_rlt = pd.read_csv(file_rlt, sep=',', skiprows=[1, 2], index_col=0, encoding='shift_jis')
parameters = ['幅', '厚さ', '弾性率', '最大点', '破壊点', '最大点.1', '破壊点.1']
data_rlt = data_rlt.loc[(['単純平均', '標準偏差'], parameters)]
data_rlt.index = ['average', 'stdev']
data_rlt.columns = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break']
data_rlt = data_rlt.values
data_flattened = [item for sublist in data_rlt for item in sublist]
parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break', 'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']
data_rlt = pd.Series(data_flattened, index=parameters)
data_rlt.name = file['name']
return data_rlt<|docstring|>a function to pick following parameters as pd.Series:
parameters = ['width', 'height', 'FM', 'FS_max', 'FS_break', 'FE_max', 'FE_break',
'd_width', 'd_height', 'd_FM', 'd_FS_max', 'd_FS_break', 'd_FE_max', 'd_FE_break']
FILE should be passed as dictionary containing following:
'name': name of sample like 'RL7785'
'crv': path(relative) of xxx_crv.csv file
'rlt': path(relative) of xxx_rlt.csv file
'set': path(relative) of xxx_set.csv file<|endoftext|>
|
0a3db96fccdc8a44e18490c4d5b0cff0662f1452f6f4cb4fe6087dd70be81df3
|
def dict_from_context(context):
'\n Converts context to native python dict.\n '
if isinstance(context, BaseContext):
new_dict = {}
for i in reversed(list(context)):
new_dict.update(dict_from_context(i))
return new_dict
return dict(context)
|
Converts context to native python dict.
|
django_jinja/base.py
|
dict_from_context
|
akx/django-jinja
| 210
|
python
|
def dict_from_context(context):
'\n \n '
if isinstance(context, BaseContext):
new_dict = {}
for i in reversed(list(context)):
new_dict.update(dict_from_context(i))
return new_dict
return dict(context)
|
def dict_from_context(context):
'\n \n '
if isinstance(context, BaseContext):
new_dict = {}
for i in reversed(list(context)):
new_dict.update(dict_from_context(i))
return new_dict
return dict(context)<|docstring|>Converts context to native python dict.<|endoftext|>
|
bbe67a3c21143c420f4bee9f3ff14f571fb0aeda7a4a7a5277705108e8bb0170
|
def _iter_templatetags_modules_list():
'\n Get list of modules that contains templatetags\n submodule.\n '
from django.apps import apps
all_modules = [x.name for x in apps.get_app_configs()]
for app_path in all_modules:
try:
mod = import_module((app_path + '.templatetags'))
if (getattr(mod, '__file__', None) is not None):
(yield (app_path, path.dirname(mod.__file__)))
except ImportError:
pass
|
Get list of modules that contains templatetags
submodule.
|
django_jinja/base.py
|
_iter_templatetags_modules_list
|
akx/django-jinja
| 210
|
python
|
def _iter_templatetags_modules_list():
'\n Get list of modules that contains templatetags\n submodule.\n '
from django.apps import apps
all_modules = [x.name for x in apps.get_app_configs()]
for app_path in all_modules:
try:
mod = import_module((app_path + '.templatetags'))
if (getattr(mod, '__file__', None) is not None):
(yield (app_path, path.dirname(mod.__file__)))
except ImportError:
pass
|
def _iter_templatetags_modules_list():
'\n Get list of modules that contains templatetags\n submodule.\n '
from django.apps import apps
all_modules = [x.name for x in apps.get_app_configs()]
for app_path in all_modules:
try:
mod = import_module((app_path + '.templatetags'))
if (getattr(mod, '__file__', None) is not None):
(yield (app_path, path.dirname(mod.__file__)))
except ImportError:
pass<|docstring|>Get list of modules that contains templatetags
submodule.<|endoftext|>
|
00903759ea38c88032831447a5eb9ef674f232cae5859969598ac68f3cb23e04
|
def patch_django_for_autoescape():
'\n Patch django modules for make them compatible with\n jinja autoescape implementation.\n '
from django.utils import safestring
from django.forms.boundfield import BoundField
from django.forms.utils import ErrorList
from django.forms.utils import ErrorDict
if hasattr(safestring, 'SafeText'):
if (not hasattr(safestring.SafeText, '__html__')):
safestring.SafeText.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeString'):
if (not hasattr(safestring.SafeString, '__html__')):
safestring.SafeString.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeUnicode'):
if (not hasattr(safestring.SafeUnicode, '__html__')):
safestring.SafeUnicode.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeBytes'):
if (not hasattr(safestring.SafeBytes, '__html__')):
safestring.SafeBytes.__html__ = (lambda self: str(self))
if (not hasattr(BoundField, '__html__')):
BoundField.__html__ = (lambda self: str(self))
if (not hasattr(ErrorList, '__html__')):
ErrorList.__html__ = (lambda self: str(self))
if (not hasattr(ErrorDict, '__html__')):
ErrorDict.__html__ = (lambda self: str(self))
|
Patch django modules for make them compatible with
jinja autoescape implementation.
|
django_jinja/base.py
|
patch_django_for_autoescape
|
akx/django-jinja
| 210
|
python
|
def patch_django_for_autoescape():
'\n Patch django modules for make them compatible with\n jinja autoescape implementation.\n '
from django.utils import safestring
from django.forms.boundfield import BoundField
from django.forms.utils import ErrorList
from django.forms.utils import ErrorDict
if hasattr(safestring, 'SafeText'):
if (not hasattr(safestring.SafeText, '__html__')):
safestring.SafeText.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeString'):
if (not hasattr(safestring.SafeString, '__html__')):
safestring.SafeString.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeUnicode'):
if (not hasattr(safestring.SafeUnicode, '__html__')):
safestring.SafeUnicode.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeBytes'):
if (not hasattr(safestring.SafeBytes, '__html__')):
safestring.SafeBytes.__html__ = (lambda self: str(self))
if (not hasattr(BoundField, '__html__')):
BoundField.__html__ = (lambda self: str(self))
if (not hasattr(ErrorList, '__html__')):
ErrorList.__html__ = (lambda self: str(self))
if (not hasattr(ErrorDict, '__html__')):
ErrorDict.__html__ = (lambda self: str(self))
|
def patch_django_for_autoescape():
'\n Patch django modules for make them compatible with\n jinja autoescape implementation.\n '
from django.utils import safestring
from django.forms.boundfield import BoundField
from django.forms.utils import ErrorList
from django.forms.utils import ErrorDict
if hasattr(safestring, 'SafeText'):
if (not hasattr(safestring.SafeText, '__html__')):
safestring.SafeText.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeString'):
if (not hasattr(safestring.SafeString, '__html__')):
safestring.SafeString.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeUnicode'):
if (not hasattr(safestring.SafeUnicode, '__html__')):
safestring.SafeUnicode.__html__ = (lambda self: str(self))
if hasattr(safestring, 'SafeBytes'):
if (not hasattr(safestring.SafeBytes, '__html__')):
safestring.SafeBytes.__html__ = (lambda self: str(self))
if (not hasattr(BoundField, '__html__')):
BoundField.__html__ = (lambda self: str(self))
if (not hasattr(ErrorList, '__html__')):
ErrorList.__html__ = (lambda self: str(self))
if (not hasattr(ErrorDict, '__html__')):
ErrorDict.__html__ = (lambda self: str(self))<|docstring|>Patch django modules for make them compatible with
jinja autoescape implementation.<|endoftext|>
|
5edffe4595d915aa199932d4ecfb2040e9ed2ad90d161d057d2ec73659e5df4f
|
def get_match_extension(using=None):
'\n Gets the extension that the template loader will match for\n django-jinja. This returns Jinja2.match_extension.\n\n The "using" parameter selects with Jinja2 backend to use if\n you have multiple ones configured in settings.TEMPLATES.\n If it is None and only one Jinja2 backend is defined then it\n will use that, otherwise an ImproperlyConfigured exception\n is thrown.\n '
from .backend import Jinja2
from django.template import engines
if (using is None):
engine = Jinja2.get_default()
else:
engine = engines[using]
return engine.match_extension
|
Gets the extension that the template loader will match for
django-jinja. This returns Jinja2.match_extension.
The "using" parameter selects with Jinja2 backend to use if
you have multiple ones configured in settings.TEMPLATES.
If it is None and only one Jinja2 backend is defined then it
will use that, otherwise an ImproperlyConfigured exception
is thrown.
|
django_jinja/base.py
|
get_match_extension
|
akx/django-jinja
| 210
|
python
|
def get_match_extension(using=None):
'\n Gets the extension that the template loader will match for\n django-jinja. This returns Jinja2.match_extension.\n\n The "using" parameter selects with Jinja2 backend to use if\n you have multiple ones configured in settings.TEMPLATES.\n If it is None and only one Jinja2 backend is defined then it\n will use that, otherwise an ImproperlyConfigured exception\n is thrown.\n '
from .backend import Jinja2
from django.template import engines
if (using is None):
engine = Jinja2.get_default()
else:
engine = engines[using]
return engine.match_extension
|
def get_match_extension(using=None):
'\n Gets the extension that the template loader will match for\n django-jinja. This returns Jinja2.match_extension.\n\n The "using" parameter selects with Jinja2 backend to use if\n you have multiple ones configured in settings.TEMPLATES.\n If it is None and only one Jinja2 backend is defined then it\n will use that, otherwise an ImproperlyConfigured exception\n is thrown.\n '
from .backend import Jinja2
from django.template import engines
if (using is None):
engine = Jinja2.get_default()
else:
engine = engines[using]
return engine.match_extension<|docstring|>Gets the extension that the template loader will match for
django-jinja. This returns Jinja2.match_extension.
The "using" parameter selects with Jinja2 backend to use if
you have multiple ones configured in settings.TEMPLATES.
If it is None and only one Jinja2 backend is defined then it
will use that, otherwise an ImproperlyConfigured exception
is thrown.<|endoftext|>
|
45a9d241adf6f17818e2664e1d2ed73df2c1c937c12f3dc2cb809a8c24a3f0a7
|
def _monitor_callback_wrapper(callback):
'A wrapper for the user-defined handle.'
def callback_handle(name, opr_name, array, _):
' ctypes function '
callback(name, opr_name, array)
return callback_handle
|
A wrapper for the user-defined handle.
|
python/mxnet/_ctypes/ndarray.py
|
_monitor_callback_wrapper
|
guanxinq/incubator-mxnet
| 3
|
python
|
def _monitor_callback_wrapper(callback):
def callback_handle(name, opr_name, array, _):
' ctypes function '
callback(name, opr_name, array)
return callback_handle
|
def _monitor_callback_wrapper(callback):
def callback_handle(name, opr_name, array, _):
' ctypes function '
callback(name, opr_name, array)
return callback_handle<|docstring|>A wrapper for the user-defined handle.<|endoftext|>
|
e8bc41e01cbbee8322e0d0a505404efb743281930096db2f807f7cc64e78105d
|
def _set_ndarray_class(cls):
'Set the symbolic class to be cls'
global _ndarray_cls
_ndarray_cls = cls
|
Set the symbolic class to be cls
|
python/mxnet/_ctypes/ndarray.py
|
_set_ndarray_class
|
guanxinq/incubator-mxnet
| 3
|
python
|
def _set_ndarray_class(cls):
global _ndarray_cls
_ndarray_cls = cls
|
def _set_ndarray_class(cls):
global _ndarray_cls
_ndarray_cls = cls<|docstring|>Set the symbolic class to be cls<|endoftext|>
|
67c947eaa2e5cdb6af0200c942c343d4efa64b6b19c2b6e320998bbe25383c7b
|
def _set_np_ndarray_class(cls):
'Set the symbolic class to be cls'
global _np_ndarray_cls
_np_ndarray_cls = cls
|
Set the symbolic class to be cls
|
python/mxnet/_ctypes/ndarray.py
|
_set_np_ndarray_class
|
guanxinq/incubator-mxnet
| 3
|
python
|
def _set_np_ndarray_class(cls):
global _np_ndarray_cls
_np_ndarray_cls = cls
|
def _set_np_ndarray_class(cls):
global _np_ndarray_cls
_np_ndarray_cls = cls<|docstring|>Set the symbolic class to be cls<|endoftext|>
|
4177d2f7e4c84ebfaf904d57050185b12eaec7e858c5ed1e837103924e6c2352
|
def _imperative_invoke(handle, ndargs, keys, vals, out, is_np_op, output_is_list):
'ctypes implementation of imperative invoke wrapper'
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXImperativeInvokeEx(ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes)))
create_ndarray_fn = (_np_ndarray_cls if is_np_op else _ndarray_cls)
if (original_output is not None):
return original_output
if ((num_output.value == 1) and (not output_is_list)):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
|
ctypes implementation of imperative invoke wrapper
|
python/mxnet/_ctypes/ndarray.py
|
_imperative_invoke
|
guanxinq/incubator-mxnet
| 3
|
python
|
def _imperative_invoke(handle, ndargs, keys, vals, out, is_np_op, output_is_list):
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXImperativeInvokeEx(ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes)))
create_ndarray_fn = (_np_ndarray_cls if is_np_op else _ndarray_cls)
if (original_output is not None):
return original_output
if ((num_output.value == 1) and (not output_is_list)):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
|
def _imperative_invoke(handle, ndargs, keys, vals, out, is_np_op, output_is_list):
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXImperativeInvokeEx(ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes)))
create_ndarray_fn = (_np_ndarray_cls if is_np_op else _ndarray_cls)
if (original_output is not None):
return original_output
if ((num_output.value == 1) and (not output_is_list)):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]<|docstring|>ctypes implementation of imperative invoke wrapper<|endoftext|>
|
40f989e088f314f08c371f950b41db79ac72c4440143830f2cc0b4835b61e4b1
|
def callback_handle(name, opr_name, array, _):
' ctypes function '
callback(name, opr_name, array)
|
ctypes function
|
python/mxnet/_ctypes/ndarray.py
|
callback_handle
|
guanxinq/incubator-mxnet
| 3
|
python
|
def callback_handle(name, opr_name, array, _):
' '
callback(name, opr_name, array)
|
def callback_handle(name, opr_name, array, _):
' '
callback(name, opr_name, array)<|docstring|>ctypes function<|endoftext|>
|
2aed5fd5cd2a299416e707bbca1a6b248e559cd71b3b7d9b6a86bfd5c33a358e
|
def __init__(self, handle, writable=True):
'initialize a new NDArray\n\n Parameters\n ----------\n handle : NDArrayHandle\n NDArray handle of C API\n '
if (handle is not None):
assert isinstance(handle, NDArrayHandle)
self.handle = handle
self.writable = writable
|
initialize a new NDArray
Parameters
----------
handle : NDArrayHandle
NDArray handle of C API
|
python/mxnet/_ctypes/ndarray.py
|
__init__
|
guanxinq/incubator-mxnet
| 3
|
python
|
def __init__(self, handle, writable=True):
'initialize a new NDArray\n\n Parameters\n ----------\n handle : NDArrayHandle\n NDArray handle of C API\n '
if (handle is not None):
assert isinstance(handle, NDArrayHandle)
self.handle = handle
self.writable = writable
|
def __init__(self, handle, writable=True):
'initialize a new NDArray\n\n Parameters\n ----------\n handle : NDArrayHandle\n NDArray handle of C API\n '
if (handle is not None):
assert isinstance(handle, NDArrayHandle)
self.handle = handle
self.writable = writable<|docstring|>initialize a new NDArray
Parameters
----------
handle : NDArrayHandle
NDArray handle of C API<|endoftext|>
|
1f5bda2398c57425a3b6602546e00b46457d6959c6922406efe66c6a30955221
|
def __call__(self, *args, **kwargs):
'ctypes implementation of imperative invoke wrapper'
out = kwargs.pop('out', None)
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
if kwargs:
raise TypeError(('CachedOp.__call__ got unexpected keyword argument(s): ' + ', '.join(kwargs.keys())))
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXInvokeCachedOpEx(self.handle, ctypes.c_int(len(args)), c_handle_array(args), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.byref(out_stypes)))
if (original_output is not None):
return original_output
create_ndarray_fn = (_np_ndarray_cls if self.is_np_sym else _ndarray_cls)
if (num_output.value == 1):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
|
ctypes implementation of imperative invoke wrapper
|
python/mxnet/_ctypes/ndarray.py
|
__call__
|
guanxinq/incubator-mxnet
| 3
|
python
|
def __call__(self, *args, **kwargs):
out = kwargs.pop('out', None)
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
if kwargs:
raise TypeError(('CachedOp.__call__ got unexpected keyword argument(s): ' + ', '.join(kwargs.keys())))
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXInvokeCachedOpEx(self.handle, ctypes.c_int(len(args)), c_handle_array(args), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.byref(out_stypes)))
if (original_output is not None):
return original_output
create_ndarray_fn = (_np_ndarray_cls if self.is_np_sym else _ndarray_cls)
if (num_output.value == 1):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
|
def __call__(self, *args, **kwargs):
out = kwargs.pop('out', None)
if (out is not None):
original_output = out
if isinstance(out, NDArrayBase):
out = (out,)
num_output = ctypes.c_int(len(out))
output_vars = c_handle_array(out)
output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))
else:
original_output = None
output_vars = ctypes.POINTER(NDArrayHandle)()
num_output = ctypes.c_int(0)
if kwargs:
raise TypeError(('CachedOp.__call__ got unexpected keyword argument(s): ' + ', '.join(kwargs.keys())))
out_stypes = ctypes.POINTER(ctypes.c_int)()
check_call(_LIB.MXInvokeCachedOpEx(self.handle, ctypes.c_int(len(args)), c_handle_array(args), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.byref(out_stypes)))
if (original_output is not None):
return original_output
create_ndarray_fn = (_np_ndarray_cls if self.is_np_sym else _ndarray_cls)
if (num_output.value == 1):
return create_ndarray_fn(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0])
else:
return [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]<|docstring|>ctypes implementation of imperative invoke wrapper<|endoftext|>
|
40e54cbc60d420f0ecf41925b068e3dcb56ce333b23fcb7d26d15b3ea862288a
|
def _register_op_hook(self, callback, monitor_all=False):
'Install callback for monitor.\n\n Parameters\n ----------\n callback : function\n Takes a string for node_name, string for op_name and a NDArrayHandle.\n monitor_all : bool, default False\n If true, monitor both input _imperative_invoked output, otherwise monitor output only.\n '
cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
if callback:
self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
check_call(_LIB.MXCachedOpRegisterOpHook(self.handle, self._monitor_callback, ctypes.c_int(monitor_all)))
|
Install callback for monitor.
Parameters
----------
callback : function
Takes a string for node_name, string for op_name and a NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input _imperative_invoked output, otherwise monitor output only.
|
python/mxnet/_ctypes/ndarray.py
|
_register_op_hook
|
guanxinq/incubator-mxnet
| 3
|
python
|
def _register_op_hook(self, callback, monitor_all=False):
'Install callback for monitor.\n\n Parameters\n ----------\n callback : function\n Takes a string for node_name, string for op_name and a NDArrayHandle.\n monitor_all : bool, default False\n If true, monitor both input _imperative_invoked output, otherwise monitor output only.\n '
cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
if callback:
self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
check_call(_LIB.MXCachedOpRegisterOpHook(self.handle, self._monitor_callback, ctypes.c_int(monitor_all)))
|
def _register_op_hook(self, callback, monitor_all=False):
'Install callback for monitor.\n\n Parameters\n ----------\n callback : function\n Takes a string for node_name, string for op_name and a NDArrayHandle.\n monitor_all : bool, default False\n If true, monitor both input _imperative_invoked output, otherwise monitor output only.\n '
cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
if callback:
self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
check_call(_LIB.MXCachedOpRegisterOpHook(self.handle, self._monitor_callback, ctypes.c_int(monitor_all)))<|docstring|>Install callback for monitor.
Parameters
----------
callback : function
Takes a string for node_name, string for op_name and a NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input _imperative_invoked output, otherwise monitor output only.<|endoftext|>
|
39b93b9b130ca15f4ed944682bb6464611df409a13ca72a376c5a9cda7b2ec8c
|
def display(self, logger):
'Display Configuration values.'
print('\nConfigurations:')
logger.info('\nConfigurations:')
for a in dir(self):
if ((not a.startswith('__')) and (not callable(getattr(self, a)))):
print('{:30} {}'.format(a, getattr(self, a)))
logger.info('{:30} {}'.format(a, getattr(self, a)))
print('\n')
|
Display Configuration values.
|
train_nuclei.py
|
display
|
xumm94/2018_data_science_bowl
| 0
|
python
|
def display(self, logger):
print('\nConfigurations:')
logger.info('\nConfigurations:')
for a in dir(self):
if ((not a.startswith('__')) and (not callable(getattr(self, a)))):
print('{:30} {}'.format(a, getattr(self, a)))
logger.info('{:30} {}'.format(a, getattr(self, a)))
print('\n')
|
def display(self, logger):
print('\nConfigurations:')
logger.info('\nConfigurations:')
for a in dir(self):
if ((not a.startswith('__')) and (not callable(getattr(self, a)))):
print('{:30} {}'.format(a, getattr(self, a)))
logger.info('{:30} {}'.format(a, getattr(self, a)))
print('\n')<|docstring|>Display Configuration values.<|endoftext|>
|
9816baf47462b712f5af49a0ce60105cfe862ee1992a45e2537c8fa61102a731
|
def load_image_info(self, data_path, img_set=None):
'Get the picture names(ids) of the dataset.'
self.add_class('nucleis', 1, 'regular')
if (img_set is None):
train_ids = next(os.walk(data_path))[1]
else:
with open(img_set) as f:
read_data = f.readlines()
train_ids = [read_data[i][:(- 1)] for i in range(0, len(read_data))]
for (i, id_) in enumerate(train_ids):
file_path = os.path.join(data_path, id_)
img_path = os.path.join(file_path, 'images')
masks_path = os.path.join(file_path, 'masks')
img_name = (id_ + '.png')
img = cv2.imread(os.path.join(img_path, img_name))
(width, height, _) = img.shape
self.add_image('nucleis', image_id=id_, path=file_path, img_path=img_path, masks_path=masks_path, width=width, height=height, nucleis='nucleis')
|
Get the picture names(ids) of the dataset.
|
train_nuclei.py
|
load_image_info
|
xumm94/2018_data_science_bowl
| 0
|
python
|
def load_image_info(self, data_path, img_set=None):
self.add_class('nucleis', 1, 'regular')
if (img_set is None):
train_ids = next(os.walk(data_path))[1]
else:
with open(img_set) as f:
read_data = f.readlines()
train_ids = [read_data[i][:(- 1)] for i in range(0, len(read_data))]
for (i, id_) in enumerate(train_ids):
file_path = os.path.join(data_path, id_)
img_path = os.path.join(file_path, 'images')
masks_path = os.path.join(file_path, 'masks')
img_name = (id_ + '.png')
img = cv2.imread(os.path.join(img_path, img_name))
(width, height, _) = img.shape
self.add_image('nucleis', image_id=id_, path=file_path, img_path=img_path, masks_path=masks_path, width=width, height=height, nucleis='nucleis')
|
def load_image_info(self, data_path, img_set=None):
self.add_class('nucleis', 1, 'regular')
if (img_set is None):
train_ids = next(os.walk(data_path))[1]
else:
with open(img_set) as f:
read_data = f.readlines()
train_ids = [read_data[i][:(- 1)] for i in range(0, len(read_data))]
for (i, id_) in enumerate(train_ids):
file_path = os.path.join(data_path, id_)
img_path = os.path.join(file_path, 'images')
masks_path = os.path.join(file_path, 'masks')
img_name = (id_ + '.png')
img = cv2.imread(os.path.join(img_path, img_name))
(width, height, _) = img.shape
self.add_image('nucleis', image_id=id_, path=file_path, img_path=img_path, masks_path=masks_path, width=width, height=height, nucleis='nucleis')<|docstring|>Get the picture names(ids) of the dataset.<|endoftext|>
|
a05414ba46aa89cb1bf5c53911d90e807472e02711ae85dbe217196935192805
|
def load_image(self, image_id):
'Load image from file of the given image ID.'
info = self.image_info[image_id]
img_path = info['img_path']
img_name = (info['id'] + '.png')
image = cv2.imread(os.path.join(img_path, img_name))
return image
|
Load image from file of the given image ID.
|
train_nuclei.py
|
load_image
|
xumm94/2018_data_science_bowl
| 0
|
python
|
def load_image(self, image_id):
info = self.image_info[image_id]
img_path = info['img_path']
img_name = (info['id'] + '.png')
image = cv2.imread(os.path.join(img_path, img_name))
return image
|
def load_image(self, image_id):
info = self.image_info[image_id]
img_path = info['img_path']
img_name = (info['id'] + '.png')
image = cv2.imread(os.path.join(img_path, img_name))
return image<|docstring|>Load image from file of the given image ID.<|endoftext|>
|
9b239a5ae709b13bd85e2518a30a891491ccc25a99c34e4bfd1fe3c996429c96
|
def image_reference(self, image_id):
'Return the path of the given image ID.'
info = self.image_info[image_id]
if (info['source'] == 'nucleis'):
return info['path']
else:
super(self.__class__).image_reference(self, image_id)
|
Return the path of the given image ID.
|
train_nuclei.py
|
image_reference
|
xumm94/2018_data_science_bowl
| 0
|
python
|
def image_reference(self, image_id):
info = self.image_info[image_id]
if (info['source'] == 'nucleis'):
return info['path']
else:
super(self.__class__).image_reference(self, image_id)
|
def image_reference(self, image_id):
info = self.image_info[image_id]
if (info['source'] == 'nucleis'):
return info['path']
else:
super(self.__class__).image_reference(self, image_id)<|docstring|>Return the path of the given image ID.<|endoftext|>
|
b711b7379e4e6125fee0e42d76eb330e352ea185fa227db26645caa9321438f7
|
def load_mask(self, image_id):
'Load the instance masks of the given image ID.'
info = self.image_info[image_id]
mask_files = next(os.walk(info['masks_path']))[2]
masks = np.zeros([info['width'], info['height'], len(mask_files)], dtype=np.uint8)
for (i, id_) in enumerate(mask_files):
single_mask = cv2.imread(os.path.join(info['masks_path'], id_), 0)
masks[(:, :, i:(i + 1))] = single_mask[(:, :, np.newaxis)]
class_ids = np.ones(len(mask_files))
return (masks, class_ids.astype(np.int32))
|
Load the instance masks of the given image ID.
|
train_nuclei.py
|
load_mask
|
xumm94/2018_data_science_bowl
| 0
|
python
|
def load_mask(self, image_id):
info = self.image_info[image_id]
mask_files = next(os.walk(info['masks_path']))[2]
masks = np.zeros([info['width'], info['height'], len(mask_files)], dtype=np.uint8)
for (i, id_) in enumerate(mask_files):
single_mask = cv2.imread(os.path.join(info['masks_path'], id_), 0)
masks[(:, :, i:(i + 1))] = single_mask[(:, :, np.newaxis)]
class_ids = np.ones(len(mask_files))
return (masks, class_ids.astype(np.int32))
|
def load_mask(self, image_id):
info = self.image_info[image_id]
mask_files = next(os.walk(info['masks_path']))[2]
masks = np.zeros([info['width'], info['height'], len(mask_files)], dtype=np.uint8)
for (i, id_) in enumerate(mask_files):
single_mask = cv2.imread(os.path.join(info['masks_path'], id_), 0)
masks[(:, :, i:(i + 1))] = single_mask[(:, :, np.newaxis)]
class_ids = np.ones(len(mask_files))
return (masks, class_ids.astype(np.int32))<|docstring|>Load the instance masks of the given image ID.<|endoftext|>
|
1b1ff0fe4c440b5cea5f7a0d88f563f5e1c84712f4ba3ddf8104dd1a58e5fbe0
|
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False):
'converts a (0,0) based coordinate to an excel address'
addr = ''
A = ord('A')
col += 1
while (col > 0):
addr = (chr((A + ((col - 1) % 26))) + addr)
col = ((col - 1) // 26)
prefix = (("'%s'!" % worksheet) if worksheet else '')
col_modifier = ('$' if col_fixed else '')
row_modifier = ('$' if row_fixed else '')
return (prefix + ('%s%s%s%d' % (col_modifier, addr, row_modifier, (row + 1))))
|
converts a (0,0) based coordinate to an excel address
|
xltable/expression.py
|
_to_addr
|
fkarb/xltable
| 4
|
python
|
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False):
addr =
A = ord('A')
col += 1
while (col > 0):
addr = (chr((A + ((col - 1) % 26))) + addr)
col = ((col - 1) // 26)
prefix = (("'%s'!" % worksheet) if worksheet else )
col_modifier = ('$' if col_fixed else )
row_modifier = ('$' if row_fixed else )
return (prefix + ('%s%s%s%d' % (col_modifier, addr, row_modifier, (row + 1))))
|
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False):
addr =
A = ord('A')
col += 1
while (col > 0):
addr = (chr((A + ((col - 1) % 26))) + addr)
col = ((col - 1) // 26)
prefix = (("'%s'!" % worksheet) if worksheet else )
col_modifier = ('$' if col_fixed else )
row_modifier = ('$' if row_fixed else )
return (prefix + ('%s%s%s%d' % (col_modifier, addr, row_modifier, (row + 1))))<|docstring|>converts a (0,0) based coordinate to an excel address<|endoftext|>
|
ac73f8157e08213d757052a5526e94e2e7a2b4e87d8dbdf2042f6816b22de13f
|
@property
def value(self):
'Set a calculated value for this Expression.\n Used when writing formulas using XlsxWriter to give cells\n an initial value when the sheet is loaded without being calculated.\n '
try:
if isinstance(self.__value, Expression):
return self.__value.value
return self.__value
except AttributeError:
return 0
|
Set a calculated value for this Expression.
Used when writing formulas using XlsxWriter to give cells
an initial value when the sheet is loaded without being calculated.
|
xltable/expression.py
|
value
|
fkarb/xltable
| 4
|
python
|
@property
def value(self):
'Set a calculated value for this Expression.\n Used when writing formulas using XlsxWriter to give cells\n an initial value when the sheet is loaded without being calculated.\n '
try:
if isinstance(self.__value, Expression):
return self.__value.value
return self.__value
except AttributeError:
return 0
|
@property
def value(self):
'Set a calculated value for this Expression.\n Used when writing formulas using XlsxWriter to give cells\n an initial value when the sheet is loaded without being calculated.\n '
try:
if isinstance(self.__value, Expression):
return self.__value.value
return self.__value
except AttributeError:
return 0<|docstring|>Set a calculated value for this Expression.
Used when writing formulas using XlsxWriter to give cells
an initial value when the sheet is loaded without being calculated.<|endoftext|>
|
18cc0cda63308de8166d920497092f7da526f82fc3ca9d70555fbe857bc34b9c
|
@property
def has_value(self):
'return True if value has been set'
try:
if isinstance(self.__value, Expression):
return self.__value.has_value
return True
except AttributeError:
return False
|
return True if value has been set
|
xltable/expression.py
|
has_value
|
fkarb/xltable
| 4
|
python
|
@property
def has_value(self):
try:
if isinstance(self.__value, Expression):
return self.__value.has_value
return True
except AttributeError:
return False
|
@property
def has_value(self):
try:
if isinstance(self.__value, Expression):
return self.__value.has_value
return True
except AttributeError:
return False<|docstring|>return True if value has been set<|endoftext|>
|
61d90e46738d87fd95cfdb8afb810c7b5d435eb41662512f4517222c8e8416cd
|
def questao01():
'\n Elabore um programa que efetue a leitura de duas strings e informe o seu conteúdo,\n seguido de seu compri- mento. Indique também se as\n duas strings possuem o mesmo comprimento e se são iguais ou diferentes no conteúdo.\n '
dicionario = {}
for i in range(2):
palavra = input('Digite uma palavra: ')
dicionario[i] = [palavra, len(palavra)]
print(dicionario)
if (dicionario[0][0] == dicionario[1][0]):
print('Conteúdo iguais')
if (dicionario[0][1] == dicionario[1][1]):
print('Comprimento iguais')
|
Elabore um programa que efetue a leitura de duas strings e informe o seu conteúdo,
seguido de seu compri- mento. Indique também se as
duas strings possuem o mesmo comprimento e se são iguais ou diferentes no conteúdo.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao01
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao01():
'\n Elabore um programa que efetue a leitura de duas strings e informe o seu conteúdo,\n seguido de seu compri- mento. Indique também se as\n duas strings possuem o mesmo comprimento e se são iguais ou diferentes no conteúdo.\n '
dicionario = {}
for i in range(2):
palavra = input('Digite uma palavra: ')
dicionario[i] = [palavra, len(palavra)]
print(dicionario)
if (dicionario[0][0] == dicionario[1][0]):
print('Conteúdo iguais')
if (dicionario[0][1] == dicionario[1][1]):
print('Comprimento iguais')
|
def questao01():
'\n Elabore um programa que efetue a leitura de duas strings e informe o seu conteúdo,\n seguido de seu compri- mento. Indique também se as\n duas strings possuem o mesmo comprimento e se são iguais ou diferentes no conteúdo.\n '
dicionario = {}
for i in range(2):
palavra = input('Digite uma palavra: ')
dicionario[i] = [palavra, len(palavra)]
print(dicionario)
if (dicionario[0][0] == dicionario[1][0]):
print('Conteúdo iguais')
if (dicionario[0][1] == dicionario[1][1]):
print('Comprimento iguais')<|docstring|>Elabore um programa que efetue a leitura de duas strings e informe o seu conteúdo,
seguido de seu compri- mento. Indique também se as
duas strings possuem o mesmo comprimento e se são iguais ou diferentes no conteúdo.<|endoftext|>
|
68f617ca5540d321324e68bb04f4b96bb915ee04cb339dcd8c435e6a3928dac5
|
def questao02():
'\n Elabore um programa que solicite ao usuário, o seu nome e em seguida\n mostre o seu nome de trás para frente utilizando somente letras maiúsculas.\n '
nome = input('Digite seu nome: ')
print(nome[::(- 1)].upper())
|
Elabore um programa que solicite ao usuário, o seu nome e em seguida
mostre o seu nome de trás para frente utilizando somente letras maiúsculas.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao02
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao02():
'\n Elabore um programa que solicite ao usuário, o seu nome e em seguida\n mostre o seu nome de trás para frente utilizando somente letras maiúsculas.\n '
nome = input('Digite seu nome: ')
print(nome[::(- 1)].upper())
|
def questao02():
'\n Elabore um programa que solicite ao usuário, o seu nome e em seguida\n mostre o seu nome de trás para frente utilizando somente letras maiúsculas.\n '
nome = input('Digite seu nome: ')
print(nome[::(- 1)].upper())<|docstring|>Elabore um programa que solicite ao usuário, o seu nome e em seguida
mostre o seu nome de trás para frente utilizando somente letras maiúsculas.<|endoftext|>
|
4efbe2fa888dd5cfe81b6be502cd419ec21abf9a0bfbd430cb99ea52d5c0763a
|
def questao03():
'\n Elaborar um programa que solicite a digitação de um número\n de CPF no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido\n através da validação dos dígitos verificadores e dos caracteres de formatação.\n '
cpf = input('Digite seu CPF\n')
if ((len(cpf) == 14) and (cpf[3] == '.') and (cpf[7] == '.') and (cpf[11] == '-')):
print('É um CPF')
else:
print('Não é um CPF')
|
Elaborar um programa que solicite a digitação de um número
de CPF no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido
através da validação dos dígitos verificadores e dos caracteres de formatação.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao03
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao03():
'\n Elaborar um programa que solicite a digitação de um número\n de CPF no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido\n através da validação dos dígitos verificadores e dos caracteres de formatação.\n '
cpf = input('Digite seu CPF\n')
if ((len(cpf) == 14) and (cpf[3] == '.') and (cpf[7] == '.') and (cpf[11] == '-')):
print('É um CPF')
else:
print('Não é um CPF')
|
def questao03():
'\n Elaborar um programa que solicite a digitação de um número\n de CPF no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido\n através da validação dos dígitos verificadores e dos caracteres de formatação.\n '
cpf = input('Digite seu CPF\n')
if ((len(cpf) == 14) and (cpf[3] == '.') and (cpf[7] == '.') and (cpf[11] == '-')):
print('É um CPF')
else:
print('Não é um CPF')<|docstring|>Elaborar um programa que solicite a digitação de um número
de CPF no formato xxx.xxx.xxx-xx e indique se é um número válido ou inválido
através da validação dos dígitos verificadores e dos caracteres de formatação.<|endoftext|>
|
7178c1bdfcc01802364d9faa8bf216fd9c49249428629d5677295572ce97fdfc
|
def questao04():
'\n Elaborar um programa que a partir da digitação de uma frase,\n o programa informe quantos espaços\n em branco e quantos são, e quantas vezes aparecem cada uma das vogais a, e, i, o, u.\n '
frase = input('Digite uma frase: ').lower()
vogais = ['a', 'e', 'i', 'o', 'u']
vogais_na_frase = 0
espacos_em_branco = 0
for i in frase:
if (i in vogais):
vogais_na_frase += 1
if (i in ' '):
espacos_em_branco += 1
print(f'Numeros de vogais: {vogais_na_frase}')
print(f'Numeros de espacos em branco: {espacos_em_branco}')
|
Elaborar um programa que a partir da digitação de uma frase,
o programa informe quantos espaços
em branco e quantos são, e quantas vezes aparecem cada uma das vogais a, e, i, o, u.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao04
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao04():
'\n Elaborar um programa que a partir da digitação de uma frase,\n o programa informe quantos espaços\n em branco e quantos são, e quantas vezes aparecem cada uma das vogais a, e, i, o, u.\n '
frase = input('Digite uma frase: ').lower()
vogais = ['a', 'e', 'i', 'o', 'u']
vogais_na_frase = 0
espacos_em_branco = 0
for i in frase:
if (i in vogais):
vogais_na_frase += 1
if (i in ' '):
espacos_em_branco += 1
print(f'Numeros de vogais: {vogais_na_frase}')
print(f'Numeros de espacos em branco: {espacos_em_branco}')
|
def questao04():
'\n Elaborar um programa que a partir da digitação de uma frase,\n o programa informe quantos espaços\n em branco e quantos são, e quantas vezes aparecem cada uma das vogais a, e, i, o, u.\n '
frase = input('Digite uma frase: ').lower()
vogais = ['a', 'e', 'i', 'o', 'u']
vogais_na_frase = 0
espacos_em_branco = 0
for i in frase:
if (i in vogais):
vogais_na_frase += 1
if (i in ' '):
espacos_em_branco += 1
print(f'Numeros de vogais: {vogais_na_frase}')
print(f'Numeros de espacos em branco: {espacos_em_branco}')<|docstring|>Elaborar um programa que a partir da digitação de uma frase,
o programa informe quantos espaços
em branco e quantos são, e quantas vezes aparecem cada uma das vogais a, e, i, o, u.<|endoftext|>
|
93e7869565ef3a19bcd349f2580961c094af99a66a5546121c7671658464d539
|
def questao05():
'\n Faça um programa que leia um número de telefone,\n e corrija o número no caso deste conter somente 7 dígitos,\n acrescentando o ’3’ na frente.\n O usuário pode informar o número com ou sem o traço separador.\n '
telefone = input('Digite um telefone: ')
traco = False
for i in telefone:
if (i == '-'):
traco = True
if ((len(telefone) == 7) or ((len(telefone) == 8) and traco)):
telefone = ('3' + telefone)
print(f'Seu telefone é: {telefone}')
|
Faça um programa que leia um número de telefone,
e corrija o número no caso deste conter somente 7 dígitos,
acrescentando o ’3’ na frente.
O usuário pode informar o número com ou sem o traço separador.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao05
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao05():
'\n Faça um programa que leia um número de telefone,\n e corrija o número no caso deste conter somente 7 dígitos,\n acrescentando o ’3’ na frente.\n O usuário pode informar o número com ou sem o traço separador.\n '
telefone = input('Digite um telefone: ')
traco = False
for i in telefone:
if (i == '-'):
traco = True
if ((len(telefone) == 7) or ((len(telefone) == 8) and traco)):
telefone = ('3' + telefone)
print(f'Seu telefone é: {telefone}')
|
def questao05():
'\n Faça um programa que leia um número de telefone,\n e corrija o número no caso deste conter somente 7 dígitos,\n acrescentando o ’3’ na frente.\n O usuário pode informar o número com ou sem o traço separador.\n '
telefone = input('Digite um telefone: ')
traco = False
for i in telefone:
if (i == '-'):
traco = True
if ((len(telefone) == 7) or ((len(telefone) == 8) and traco)):
telefone = ('3' + telefone)
print(f'Seu telefone é: {telefone}')<|docstring|>Faça um programa que leia um número de telefone,
e corrija o número no caso deste conter somente 7 dígitos,
acrescentando o ’3’ na frente.
O usuário pode informar o número com ou sem o traço separador.<|endoftext|>
|
c45b8ba07a88ec0f9f42ebb44d33fa417e822069aad1bc25ce4d919c2720d28a
|
def questao06():
'\n Desenvolva um jogo em que o usuário tenha que adivinhar uma palavra que\n será mostrada com as letras embaralhadas. O programa terá uma lista de\n palavras lidas de uma lista a ser fixada inicialmente pelo programador e\n escolherá uma aleatoriamente. O jogador terá uma única tentativa para adivinhar\n a palavra. Ao final a palavra deve ser mostrada na tela, informando se o usuário\n ganhou ou perdeu o jogo.\n Observação: Refaça, possibilitando ao jogador tentar até 5 vezes.\n '
import random
animais = ['gato', 'cachorro', 'cavalo', 'jumento', 'peixe', 'zebra', 'papagaio', 'girafa', 'pomba', 'lagosta']
escolhida = random.choice(animais)
shuffled = list(escolhida)
random.shuffle(shuffled)
shuffled = ''.join(shuffled)
print(f'''A palavra embaralhada é {shuffled}
''')
tentativa = input('Qual a palavra embaralhada? ')
if (escolhida == tentativa.lower()):
print('Você acertou, parabéns')
else:
print('Você errou')
print(f'A palavra era {escolhida}')
|
Desenvolva um jogo em que o usuário tenha que adivinhar uma palavra que
será mostrada com as letras embaralhadas. O programa terá uma lista de
palavras lidas de uma lista a ser fixada inicialmente pelo programador e
escolherá uma aleatoriamente. O jogador terá uma única tentativa para adivinhar
a palavra. Ao final a palavra deve ser mostrada na tela, informando se o usuário
ganhou ou perdeu o jogo.
Observação: Refaça, possibilitando ao jogador tentar até 5 vezes.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao06
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao06():
'\n Desenvolva um jogo em que o usuário tenha que adivinhar uma palavra que\n será mostrada com as letras embaralhadas. O programa terá uma lista de\n palavras lidas de uma lista a ser fixada inicialmente pelo programador e\n escolherá uma aleatoriamente. O jogador terá uma única tentativa para adivinhar\n a palavra. Ao final a palavra deve ser mostrada na tela, informando se o usuário\n ganhou ou perdeu o jogo.\n Observação: Refaça, possibilitando ao jogador tentar até 5 vezes.\n '
import random
animais = ['gato', 'cachorro', 'cavalo', 'jumento', 'peixe', 'zebra', 'papagaio', 'girafa', 'pomba', 'lagosta']
escolhida = random.choice(animais)
shuffled = list(escolhida)
random.shuffle(shuffled)
shuffled = .join(shuffled)
print(f'A palavra embaralhada é {shuffled}
')
tentativa = input('Qual a palavra embaralhada? ')
if (escolhida == tentativa.lower()):
print('Você acertou, parabéns')
else:
print('Você errou')
print(f'A palavra era {escolhida}')
|
def questao06():
'\n Desenvolva um jogo em que o usuário tenha que adivinhar uma palavra que\n será mostrada com as letras embaralhadas. O programa terá uma lista de\n palavras lidas de uma lista a ser fixada inicialmente pelo programador e\n escolherá uma aleatoriamente. O jogador terá uma única tentativa para adivinhar\n a palavra. Ao final a palavra deve ser mostrada na tela, informando se o usuário\n ganhou ou perdeu o jogo.\n Observação: Refaça, possibilitando ao jogador tentar até 5 vezes.\n '
import random
animais = ['gato', 'cachorro', 'cavalo', 'jumento', 'peixe', 'zebra', 'papagaio', 'girafa', 'pomba', 'lagosta']
escolhida = random.choice(animais)
shuffled = list(escolhida)
random.shuffle(shuffled)
shuffled = .join(shuffled)
print(f'A palavra embaralhada é {shuffled}
')
tentativa = input('Qual a palavra embaralhada? ')
if (escolhida == tentativa.lower()):
print('Você acertou, parabéns')
else:
print('Você errou')
print(f'A palavra era {escolhida}')<|docstring|>Desenvolva um jogo em que o usuário tenha que adivinhar uma palavra que
será mostrada com as letras embaralhadas. O programa terá uma lista de
palavras lidas de uma lista a ser fixada inicialmente pelo programador e
escolherá uma aleatoriamente. O jogador terá uma única tentativa para adivinhar
a palavra. Ao final a palavra deve ser mostrada na tela, informando se o usuário
ganhou ou perdeu o jogo.
Observação: Refaça, possibilitando ao jogador tentar até 5 vezes.<|endoftext|>
|
7de777315609c7deccea64a91ef5fa9f1d26c82be00eee9e50baee164a9b275d
|
def questao07():
'\n Elabore um programa que efetue a leitura de\n cinco números inteiros, adicione-os a uma lista e mostre-a.\n '
lista = []
for i in range(5):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista)
|
Elabore um programa que efetue a leitura de
cinco números inteiros, adicione-os a uma lista e mostre-a.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao07
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao07():
'\n Elabore um programa que efetue a leitura de\n cinco números inteiros, adicione-os a uma lista e mostre-a.\n '
lista = []
for i in range(5):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista)
|
def questao07():
'\n Elabore um programa que efetue a leitura de\n cinco números inteiros, adicione-os a uma lista e mostre-a.\n '
lista = []
for i in range(5):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista)<|docstring|>Elabore um programa que efetue a leitura de
cinco números inteiros, adicione-os a uma lista e mostre-a.<|endoftext|>
|
8eab19379c247fae2e7b2c04c0ad9cfa8bc85bd38bbfa7ebcb9641a50eee7536
|
def questao08():
'\n Elabore um programa que efetue a leitura de quinze números inteiros,\n adicione-os a uma lista e mostre-a de forma invertida, do último para o primeiro.\n '
lista = []
for i in range(15):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista[::(- 1)])
|
Elabore um programa que efetue a leitura de quinze números inteiros,
adicione-os a uma lista e mostre-a de forma invertida, do último para o primeiro.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao08
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao08():
'\n Elabore um programa que efetue a leitura de quinze números inteiros,\n adicione-os a uma lista e mostre-a de forma invertida, do último para o primeiro.\n '
lista = []
for i in range(15):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista[::(- 1)])
|
def questao08():
'\n Elabore um programa que efetue a leitura de quinze números inteiros,\n adicione-os a uma lista e mostre-a de forma invertida, do último para o primeiro.\n '
lista = []
for i in range(15):
numero = int(input('Digite o um número: '))
lista.append(numero)
print(lista[::(- 1)])<|docstring|>Elabore um programa que efetue a leitura de quinze números inteiros,
adicione-os a uma lista e mostre-a de forma invertida, do último para o primeiro.<|endoftext|>
|
7f50f453c715d120751d3e61704f1b5456590caf7ae24bd77b88407824e72f8c
|
def questao09():
'\n Elabore um programa que efetue a leitura de quatro notas reais,\n adicione-as a uma lista e mostre-as, inclusive a média aritmética,\n arredondar duas casas decimais. Verifique e exiba as devidas mensagens\n se o aluno está aprovado ou não, considerando que a média de aprovação\n é maior ou igual a 7.0, e em prova exame, se\n média aritmética entre 4.0 e menor que 7.0. E reprovado, se menor que 4.0.\n '
lista = []
soma = 0
for i in range(4):
nota = float(input('Digite sua nota: '))
soma = (soma + nota)
lista.append(nota)
media = round((soma / 4), 2)
print(f'Suas notas são {lista}sendo assim sua média é {media}')
if (media >= 7):
print('Você está aprovado')
elif (4 <= media < 7):
print('Pegou exame')
else:
print('Reprovou')
|
Elabore um programa que efetue a leitura de quatro notas reais,
adicione-as a uma lista e mostre-as, inclusive a média aritmética,
arredondar duas casas decimais. Verifique e exiba as devidas mensagens
se o aluno está aprovado ou não, considerando que a média de aprovação
é maior ou igual a 7.0, e em prova exame, se
média aritmética entre 4.0 e menor que 7.0. E reprovado, se menor que 4.0.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao09
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao09():
'\n Elabore um programa que efetue a leitura de quatro notas reais,\n adicione-as a uma lista e mostre-as, inclusive a média aritmética,\n arredondar duas casas decimais. Verifique e exiba as devidas mensagens\n se o aluno está aprovado ou não, considerando que a média de aprovação\n é maior ou igual a 7.0, e em prova exame, se\n média aritmética entre 4.0 e menor que 7.0. E reprovado, se menor que 4.0.\n '
lista = []
soma = 0
for i in range(4):
nota = float(input('Digite sua nota: '))
soma = (soma + nota)
lista.append(nota)
media = round((soma / 4), 2)
print(f'Suas notas são {lista}sendo assim sua média é {media}')
if (media >= 7):
print('Você está aprovado')
elif (4 <= media < 7):
print('Pegou exame')
else:
print('Reprovou')
|
def questao09():
'\n Elabore um programa que efetue a leitura de quatro notas reais,\n adicione-as a uma lista e mostre-as, inclusive a média aritmética,\n arredondar duas casas decimais. Verifique e exiba as devidas mensagens\n se o aluno está aprovado ou não, considerando que a média de aprovação\n é maior ou igual a 7.0, e em prova exame, se\n média aritmética entre 4.0 e menor que 7.0. E reprovado, se menor que 4.0.\n '
lista = []
soma = 0
for i in range(4):
nota = float(input('Digite sua nota: '))
soma = (soma + nota)
lista.append(nota)
media = round((soma / 4), 2)
print(f'Suas notas são {lista}sendo assim sua média é {media}')
if (media >= 7):
print('Você está aprovado')
elif (4 <= media < 7):
print('Pegou exame')
else:
print('Reprovou')<|docstring|>Elabore um programa que efetue a leitura de quatro notas reais,
adicione-as a uma lista e mostre-as, inclusive a média aritmética,
arredondar duas casas decimais. Verifique e exiba as devidas mensagens
se o aluno está aprovado ou não, considerando que a média de aprovação
é maior ou igual a 7.0, e em prova exame, se
média aritmética entre 4.0 e menor que 7.0. E reprovado, se menor que 4.0.<|endoftext|>
|
58913b5237826e103a4b1d2e930406e1e12f498f4d9af64e00250edd732f6656
|
def questao10():
'\n Faça um programa que leia uma lista com dez caracteres,\n e diga quantas consoantes foram lidas. Imprima as consoantes.\n '
vogais = ['a', 'e', 'i', 'o', 'u']
lista = []
j = 0
for i in range(10):
caracter = input('Digite um caracter: ')
caracter = caracter.lower()
if (caracter in vogais):
pass
else:
lista.append(caracter)
j += 1
print(f'Foram inseridas {j} consoantes, são elas {lista}')
|
Faça um programa que leia uma lista com dez caracteres,
e diga quantas consoantes foram lidas. Imprima as consoantes.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao10
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao10():
'\n Faça um programa que leia uma lista com dez caracteres,\n e diga quantas consoantes foram lidas. Imprima as consoantes.\n '
vogais = ['a', 'e', 'i', 'o', 'u']
lista = []
j = 0
for i in range(10):
caracter = input('Digite um caracter: ')
caracter = caracter.lower()
if (caracter in vogais):
pass
else:
lista.append(caracter)
j += 1
print(f'Foram inseridas {j} consoantes, são elas {lista}')
|
def questao10():
'\n Faça um programa que leia uma lista com dez caracteres,\n e diga quantas consoantes foram lidas. Imprima as consoantes.\n '
vogais = ['a', 'e', 'i', 'o', 'u']
lista = []
j = 0
for i in range(10):
caracter = input('Digite um caracter: ')
caracter = caracter.lower()
if (caracter in vogais):
pass
else:
lista.append(caracter)
j += 1
print(f'Foram inseridas {j} consoantes, são elas {lista}')<|docstring|>Faça um programa que leia uma lista com dez caracteres,
e diga quantas consoantes foram lidas. Imprima as consoantes.<|endoftext|>
|
6e7a9ae8f8ca0b4bc730c22edf15081f604148d4abc13dbbc4096e1199ba24df
|
def questao11():
'\n Faça um programa que leia 15 números inteiros e armazene-os em uma lista NUMEROS.\n Armazene os números\n pares na lista PAR e os números ímpares na lista IMPAR. Imprima os três vetores.\n '
numeros = []
par = []
impar = []
for i in range(10):
numero = int(input('Digite um número: '))
numeros.append(numero)
if ((numero % 2) == 0):
par.append(numero)
else:
impar.append(numero)
print(f'''Os números digitados foram {numeros}
Dentre eles esses são pares {par} e estes são ímpares {impar}''')
|
Faça um programa que leia 15 números inteiros e armazene-os em uma lista NUMEROS.
Armazene os números
pares na lista PAR e os números ímpares na lista IMPAR. Imprima os três vetores.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao11
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao11():
'\n Faça um programa que leia 15 números inteiros e armazene-os em uma lista NUMEROS.\n Armazene os números\n pares na lista PAR e os números ímpares na lista IMPAR. Imprima os três vetores.\n '
numeros = []
par = []
impar = []
for i in range(10):
numero = int(input('Digite um número: '))
numeros.append(numero)
if ((numero % 2) == 0):
par.append(numero)
else:
impar.append(numero)
print(f'Os números digitados foram {numeros}
Dentre eles esses são pares {par} e estes são ímpares {impar}')
|
def questao11():
'\n Faça um programa que leia 15 números inteiros e armazene-os em uma lista NUMEROS.\n Armazene os números\n pares na lista PAR e os números ímpares na lista IMPAR. Imprima os três vetores.\n '
numeros = []
par = []
impar = []
for i in range(10):
numero = int(input('Digite um número: '))
numeros.append(numero)
if ((numero % 2) == 0):
par.append(numero)
else:
impar.append(numero)
print(f'Os números digitados foram {numeros}
Dentre eles esses são pares {par} e estes são ímpares {impar}')<|docstring|>Faça um programa que leia 15 números inteiros e armazene-os em uma lista NUMEROS.
Armazene os números
pares na lista PAR e os números ímpares na lista IMPAR. Imprima os três vetores.<|endoftext|>
|
44c989dd105a5cf6a584a8e44e1a77c6d4a1626065ed2af0cf5359efa15ab760
|
def questao12():
'\n Elabore um programa que efetue a leitura de quatro notas reais de10 alunos,\n calcule e armazene em uma lista,\n a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0.\n '
lista = []
k = 0
for i in range(1, 11):
soma = 0
for j in range(1, 5):
nota = float(input(f'''Digite a {j}ª nota do aluno "{i}
'''))
soma = (soma + nota)
media = (soma / 4)
lista.append(media)
if (media >= 7):
k += 1
print(f'A média dos 10 alunos eh {lista} sendo {k} acima da média')
|
Elabore um programa que efetue a leitura de quatro notas reais de10 alunos,
calcule e armazene em uma lista,
a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao12
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao12():
'\n Elabore um programa que efetue a leitura de quatro notas reais de10 alunos,\n calcule e armazene em uma lista,\n a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0.\n '
lista = []
k = 0
for i in range(1, 11):
soma = 0
for j in range(1, 5):
nota = float(input(f'Digite a {j}ª nota do aluno "{i}
'))
soma = (soma + nota)
media = (soma / 4)
lista.append(media)
if (media >= 7):
k += 1
print(f'A média dos 10 alunos eh {lista} sendo {k} acima da média')
|
def questao12():
'\n Elabore um programa que efetue a leitura de quatro notas reais de10 alunos,\n calcule e armazene em uma lista,\n a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0.\n '
lista = []
k = 0
for i in range(1, 11):
soma = 0
for j in range(1, 5):
nota = float(input(f'Digite a {j}ª nota do aluno "{i}
'))
soma = (soma + nota)
media = (soma / 4)
lista.append(media)
if (media >= 7):
k += 1
print(f'A média dos 10 alunos eh {lista} sendo {k} acima da média')<|docstring|>Elabore um programa que efetue a leitura de quatro notas reais de10 alunos,
calcule e armazene em uma lista,
a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0.<|endoftext|>
|
670e639929d7ec4a91f2f944b11b9954e60615728d10bebb1852d10e158f56c3
|
def questao13():
'\n Faça um programa que carregue uma lista com os modelos\n de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc).\n Carregue uma outra lista com o consumo desses carros, isto é,\n quantos quilômetros cada um desses carros faz com um litro de combustível.\n Calcule e mostre:\n\n O modelo do carro mais econômico;\n Quantos litros de combustível cada um dos carros\n cadastrados consome para percorrer uma distância de\n 1000 quilômetros e quanto isto custará, considerando\n um que a gasolina custe 2,25 o litro.\n Abaixo segue uma tela de exemplo. O disposição das\n informações deve ser o mais próxima possível ao exemplo.\n Os dados são fictícios e podem mudar a cada execução do programa.\n Relatório Final\n 1 - SUV - 10.0 - 100.0 litros - R 399.0\n 2 - IDEA - 12.0 - 83.3 litros - R 332.5\n 3 - GOL - 10.0 - 100.0 litros - R 399.0\n 4 - BMW - 20.0 - 50.0 litros - R 199.5\n 5 - UNO - 2.0 - 500.0 litros - R 1995.0\n O menor consumo é do BMW.\n\n '
carros = ['Fusca', 'Gol', 'Vectra', 'Uno', 'Amarok']
consumo = [20.0, 18.0, 9.5, 15.0, 5.7]
economico = 9999
j = 0
for i in consumo:
print(f'{(j + 1)}-{carros[j]} - {i} - {round((1000 / i), 1)} litros - R${round(((1000 / i) * 2.25), 1)}')
if (i < economico):
economico = i
carro = j
j += 1
print(f'O menor consumo é do {carros[carro]}')
|
Faça um programa que carregue uma lista com os modelos
de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc).
Carregue uma outra lista com o consumo desses carros, isto é,
quantos quilômetros cada um desses carros faz com um litro de combustível.
Calcule e mostre:
O modelo do carro mais econômico;
Quantos litros de combustível cada um dos carros
cadastrados consome para percorrer uma distância de
1000 quilômetros e quanto isto custará, considerando
um que a gasolina custe 2,25 o litro.
Abaixo segue uma tela de exemplo. O disposição das
informações deve ser o mais próxima possível ao exemplo.
Os dados são fictícios e podem mudar a cada execução do programa.
Relatório Final
1 - SUV - 10.0 - 100.0 litros - R 399.0
2 - IDEA - 12.0 - 83.3 litros - R 332.5
3 - GOL - 10.0 - 100.0 litros - R 399.0
4 - BMW - 20.0 - 50.0 litros - R 199.5
5 - UNO - 2.0 - 500.0 litros - R 1995.0
O menor consumo é do BMW.
|
ProgramsToRead/ExercisesLists/List004.py
|
questao13
|
ItanuRomero/PythonStudyPrograms
| 0
|
python
|
def questao13():
'\n Faça um programa que carregue uma lista com os modelos\n de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc).\n Carregue uma outra lista com o consumo desses carros, isto é,\n quantos quilômetros cada um desses carros faz com um litro de combustível.\n Calcule e mostre:\n\n O modelo do carro mais econômico;\n Quantos litros de combustível cada um dos carros\n cadastrados consome para percorrer uma distância de\n 1000 quilômetros e quanto isto custará, considerando\n um que a gasolina custe 2,25 o litro.\n Abaixo segue uma tela de exemplo. O disposição das\n informações deve ser o mais próxima possível ao exemplo.\n Os dados são fictícios e podem mudar a cada execução do programa.\n Relatório Final\n 1 - SUV - 10.0 - 100.0 litros - R 399.0\n 2 - IDEA - 12.0 - 83.3 litros - R 332.5\n 3 - GOL - 10.0 - 100.0 litros - R 399.0\n 4 - BMW - 20.0 - 50.0 litros - R 199.5\n 5 - UNO - 2.0 - 500.0 litros - R 1995.0\n O menor consumo é do BMW.\n\n '
carros = ['Fusca', 'Gol', 'Vectra', 'Uno', 'Amarok']
consumo = [20.0, 18.0, 9.5, 15.0, 5.7]
economico = 9999
j = 0
for i in consumo:
print(f'{(j + 1)}-{carros[j]} - {i} - {round((1000 / i), 1)} litros - R${round(((1000 / i) * 2.25), 1)}')
if (i < economico):
economico = i
carro = j
j += 1
print(f'O menor consumo é do {carros[carro]}')
|
def questao13():
'\n Faça um programa que carregue uma lista com os modelos\n de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc).\n Carregue uma outra lista com o consumo desses carros, isto é,\n quantos quilômetros cada um desses carros faz com um litro de combustível.\n Calcule e mostre:\n\n O modelo do carro mais econômico;\n Quantos litros de combustível cada um dos carros\n cadastrados consome para percorrer uma distância de\n 1000 quilômetros e quanto isto custará, considerando\n um que a gasolina custe 2,25 o litro.\n Abaixo segue uma tela de exemplo. O disposição das\n informações deve ser o mais próxima possível ao exemplo.\n Os dados são fictícios e podem mudar a cada execução do programa.\n Relatório Final\n 1 - SUV - 10.0 - 100.0 litros - R 399.0\n 2 - IDEA - 12.0 - 83.3 litros - R 332.5\n 3 - GOL - 10.0 - 100.0 litros - R 399.0\n 4 - BMW - 20.0 - 50.0 litros - R 199.5\n 5 - UNO - 2.0 - 500.0 litros - R 1995.0\n O menor consumo é do BMW.\n\n '
carros = ['Fusca', 'Gol', 'Vectra', 'Uno', 'Amarok']
consumo = [20.0, 18.0, 9.5, 15.0, 5.7]
economico = 9999
j = 0
for i in consumo:
print(f'{(j + 1)}-{carros[j]} - {i} - {round((1000 / i), 1)} litros - R${round(((1000 / i) * 2.25), 1)}')
if (i < economico):
economico = i
carro = j
j += 1
print(f'O menor consumo é do {carros[carro]}')<|docstring|>Faça um programa que carregue uma lista com os modelos
de cinco carros (exemplo de modelos: FUSCA, GOL, VECTRA etc).
Carregue uma outra lista com o consumo desses carros, isto é,
quantos quilômetros cada um desses carros faz com um litro de combustível.
Calcule e mostre:
O modelo do carro mais econômico;
Quantos litros de combustível cada um dos carros
cadastrados consome para percorrer uma distância de
1000 quilômetros e quanto isto custará, considerando
um que a gasolina custe 2,25 o litro.
Abaixo segue uma tela de exemplo. O disposição das
informações deve ser o mais próxima possível ao exemplo.
Os dados são fictícios e podem mudar a cada execução do programa.
Relatório Final
1 - SUV - 10.0 - 100.0 litros - R 399.0
2 - IDEA - 12.0 - 83.3 litros - R 332.5
3 - GOL - 10.0 - 100.0 litros - R 399.0
4 - BMW - 20.0 - 50.0 litros - R 199.5
5 - UNO - 2.0 - 500.0 litros - R 1995.0
O menor consumo é do BMW.<|endoftext|>
|
d90b195eeb26975e1a8ab3de5ceaacca4688ba3e20e0cc3702e6fc2e5c64f687
|
def clip_boxes(bboxes, imshape):
'\n Clips bounding boxes to image boundaries based on image shape.\n\n Args:\n bboxes: Tensor with shape (num_bboxes, 4)\n where point order is x1, y1, x2, y2.\n\n imshape: Tensor with shape (2, )\n where the first value is height and the next is width.\n\n Returns\n Tensor with same shape as bboxes but making sure that none\n of the bboxes are outside the image.\n '
with tf.name_scope('BoundingBoxTransform/clip_bboxes'):
bboxes = tf.cast(bboxes, dtype=tf.float32)
imshape = tf.cast(imshape, dtype=tf.float32)
(x1, y1, x2, y2) = tf.split(bboxes, 4, axis=1)
width = imshape[1]
height = imshape[0]
x1 = tf.maximum(tf.minimum(x1, (width - 1.0)), 0.0)
x2 = tf.maximum(tf.minimum(x2, (width - 1.0)), 0.0)
y1 = tf.maximum(tf.minimum(y1, (height - 1.0)), 0.0)
y2 = tf.maximum(tf.minimum(y2, (height - 1.0)), 0.0)
bboxes = tf.concat([x1, y1, x2, y2], axis=1)
return bboxes
|
Clips bounding boxes to image boundaries based on image shape.
Args:
bboxes: Tensor with shape (num_bboxes, 4)
where point order is x1, y1, x2, y2.
imshape: Tensor with shape (2, )
where the first value is height and the next is width.
Returns
Tensor with same shape as bboxes but making sure that none
of the bboxes are outside the image.
|
luminoth/utils/bbox_transform_tf.py
|
clip_boxes
|
KeyuLi2020/luminoth
| 2,584
|
python
|
def clip_boxes(bboxes, imshape):
'\n Clips bounding boxes to image boundaries based on image shape.\n\n Args:\n bboxes: Tensor with shape (num_bboxes, 4)\n where point order is x1, y1, x2, y2.\n\n imshape: Tensor with shape (2, )\n where the first value is height and the next is width.\n\n Returns\n Tensor with same shape as bboxes but making sure that none\n of the bboxes are outside the image.\n '
with tf.name_scope('BoundingBoxTransform/clip_bboxes'):
bboxes = tf.cast(bboxes, dtype=tf.float32)
imshape = tf.cast(imshape, dtype=tf.float32)
(x1, y1, x2, y2) = tf.split(bboxes, 4, axis=1)
width = imshape[1]
height = imshape[0]
x1 = tf.maximum(tf.minimum(x1, (width - 1.0)), 0.0)
x2 = tf.maximum(tf.minimum(x2, (width - 1.0)), 0.0)
y1 = tf.maximum(tf.minimum(y1, (height - 1.0)), 0.0)
y2 = tf.maximum(tf.minimum(y2, (height - 1.0)), 0.0)
bboxes = tf.concat([x1, y1, x2, y2], axis=1)
return bboxes
|
def clip_boxes(bboxes, imshape):
'\n Clips bounding boxes to image boundaries based on image shape.\n\n Args:\n bboxes: Tensor with shape (num_bboxes, 4)\n where point order is x1, y1, x2, y2.\n\n imshape: Tensor with shape (2, )\n where the first value is height and the next is width.\n\n Returns\n Tensor with same shape as bboxes but making sure that none\n of the bboxes are outside the image.\n '
with tf.name_scope('BoundingBoxTransform/clip_bboxes'):
bboxes = tf.cast(bboxes, dtype=tf.float32)
imshape = tf.cast(imshape, dtype=tf.float32)
(x1, y1, x2, y2) = tf.split(bboxes, 4, axis=1)
width = imshape[1]
height = imshape[0]
x1 = tf.maximum(tf.minimum(x1, (width - 1.0)), 0.0)
x2 = tf.maximum(tf.minimum(x2, (width - 1.0)), 0.0)
y1 = tf.maximum(tf.minimum(y1, (height - 1.0)), 0.0)
y2 = tf.maximum(tf.minimum(y2, (height - 1.0)), 0.0)
bboxes = tf.concat([x1, y1, x2, y2], axis=1)
return bboxes<|docstring|>Clips bounding boxes to image boundaries based on image shape.
Args:
bboxes: Tensor with shape (num_bboxes, 4)
where point order is x1, y1, x2, y2.
imshape: Tensor with shape (2, )
where the first value is height and the next is width.
Returns
Tensor with same shape as bboxes but making sure that none
of the bboxes are outside the image.<|endoftext|>
|
52ab3db470b4358b3867b750afb0e1555107a3410b28cec6e8711342cec880b9
|
def change_order(bboxes):
"Change bounding box encoding order.\n\n TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work\n with the (x_min, y_min, x_max, y_min).\n\n While both encoding options have its advantages and disadvantages we\n decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to\n TensorFlow's every time we want to use a std function that handles bounding\n boxes.\n\n Args:\n bboxes: A Tensor of shape (total_bboxes, 4)\n\n Returns:\n bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.\n "
with tf.name_scope('BoundingBoxTransform/change_order'):
(first_min, second_min, first_max, second_max) = tf.unstack(bboxes, axis=1)
bboxes = tf.stack([second_min, first_min, second_max, first_max], axis=1)
return bboxes
|
Change bounding box encoding order.
TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work
with the (x_min, y_min, x_max, y_min).
While both encoding options have its advantages and disadvantages we
decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to
TensorFlow's every time we want to use a std function that handles bounding
boxes.
Args:
bboxes: A Tensor of shape (total_bboxes, 4)
Returns:
bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.
|
luminoth/utils/bbox_transform_tf.py
|
change_order
|
KeyuLi2020/luminoth
| 2,584
|
python
|
def change_order(bboxes):
"Change bounding box encoding order.\n\n TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work\n with the (x_min, y_min, x_max, y_min).\n\n While both encoding options have its advantages and disadvantages we\n decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to\n TensorFlow's every time we want to use a std function that handles bounding\n boxes.\n\n Args:\n bboxes: A Tensor of shape (total_bboxes, 4)\n\n Returns:\n bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.\n "
with tf.name_scope('BoundingBoxTransform/change_order'):
(first_min, second_min, first_max, second_max) = tf.unstack(bboxes, axis=1)
bboxes = tf.stack([second_min, first_min, second_max, first_max], axis=1)
return bboxes
|
def change_order(bboxes):
"Change bounding box encoding order.\n\n TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work\n with the (x_min, y_min, x_max, y_min).\n\n While both encoding options have its advantages and disadvantages we\n decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to\n TensorFlow's every time we want to use a std function that handles bounding\n boxes.\n\n Args:\n bboxes: A Tensor of shape (total_bboxes, 4)\n\n Returns:\n bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.\n "
with tf.name_scope('BoundingBoxTransform/change_order'):
(first_min, second_min, first_max, second_max) = tf.unstack(bboxes, axis=1)
bboxes = tf.stack([second_min, first_min, second_max, first_max], axis=1)
return bboxes<|docstring|>Change bounding box encoding order.
TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work
with the (x_min, y_min, x_max, y_min).
While both encoding options have its advantages and disadvantages we
decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to
TensorFlow's every time we want to use a std function that handles bounding
boxes.
Args:
bboxes: A Tensor of shape (total_bboxes, 4)
Returns:
bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.<|endoftext|>
|
6586f638900775bb4b121c38176bcb665088a7d9de7f834d48950dc187f7ee21
|
def log_enter_exit(logger):
'\n Log decorator to log function enter and exit\n '
def log_decorator(func):
def wrapper(*args, **kwargs):
logger.debug('{} entered.'.format(func.__name__))
result = func(*args, **kwargs)
logger.debug('{} exited.'.format(func.__name__))
return result
return wrapper
return log_decorator
|
Log decorator to log function enter and exit
|
TA-linode/bin/ta_linode/aob_py3/splunktalib/common/log.py
|
log_enter_exit
|
jriddle-linode/splunk-addon-linode
| 11
|
python
|
def log_enter_exit(logger):
'\n \n '
def log_decorator(func):
def wrapper(*args, **kwargs):
logger.debug('{} entered.'.format(func.__name__))
result = func(*args, **kwargs)
logger.debug('{} exited.'.format(func.__name__))
return result
return wrapper
return log_decorator
|
def log_enter_exit(logger):
'\n \n '
def log_decorator(func):
def wrapper(*args, **kwargs):
logger.debug('{} entered.'.format(func.__name__))
result = func(*args, **kwargs)
logger.debug('{} exited.'.format(func.__name__))
return result
return wrapper
return log_decorator<|docstring|>Log decorator to log function enter and exit<|endoftext|>
|
2a8a84f3175c1e52537cac67e7a32df1495f3515a911ae1f330829800418447e
|
def reset_logger(name):
'\n Reset global logger.\n '
global logger
logger = Logs().get_logger(name)
|
Reset global logger.
|
TA-linode/bin/ta_linode/aob_py3/splunktalib/common/log.py
|
reset_logger
|
jriddle-linode/splunk-addon-linode
| 11
|
python
|
def reset_logger(name):
'\n \n '
global logger
logger = Logs().get_logger(name)
|
def reset_logger(name):
'\n \n '
global logger
logger = Logs().get_logger(name)<|docstring|>Reset global logger.<|endoftext|>
|
cf2fdbf0f6a48b8d7b55e0fd3eb688235c19442647a44a9596ba561cd4580d18
|
def get_logger(self, name, level=None, maxBytes=25000000, backupCount=5):
'\n Set up a default logger.\n\n :param name: The log file name.\n :param level: The logging level.\n :param maxBytes: The maximum log file size before rollover.\n :param backupCount: The number of log files to retain.\n '
if (level is None):
level = self._default_level
name = self._get_log_name(name)
if (name in self._loggers):
return self._loggers[name]
logfile = make_splunkhome_path(['var', 'log', 'splunk', name])
logger = logging.getLogger(name)
handler_exists = any([True for h in logger.handlers if (h.baseFilename == logfile)])
if (not handler_exists):
file_handler = handlers.RotatingFileHandler(logfile, mode='a', maxBytes=maxBytes, backupCount=backupCount)
formatter = logging.Formatter('%(asctime)s +0000 log_level=%(levelname)s, pid=%(process)d, tid=%(threadName)s, file=%(filename)s, func_name=%(funcName)s, code_line_no=%(lineno)d | %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(level)
logger.propagate = False
self._loggers[name] = logger
return logger
|
Set up a default logger.
:param name: The log file name.
:param level: The logging level.
:param maxBytes: The maximum log file size before rollover.
:param backupCount: The number of log files to retain.
|
TA-linode/bin/ta_linode/aob_py3/splunktalib/common/log.py
|
get_logger
|
jriddle-linode/splunk-addon-linode
| 11
|
python
|
def get_logger(self, name, level=None, maxBytes=25000000, backupCount=5):
'\n Set up a default logger.\n\n :param name: The log file name.\n :param level: The logging level.\n :param maxBytes: The maximum log file size before rollover.\n :param backupCount: The number of log files to retain.\n '
if (level is None):
level = self._default_level
name = self._get_log_name(name)
if (name in self._loggers):
return self._loggers[name]
logfile = make_splunkhome_path(['var', 'log', 'splunk', name])
logger = logging.getLogger(name)
handler_exists = any([True for h in logger.handlers if (h.baseFilename == logfile)])
if (not handler_exists):
file_handler = handlers.RotatingFileHandler(logfile, mode='a', maxBytes=maxBytes, backupCount=backupCount)
formatter = logging.Formatter('%(asctime)s +0000 log_level=%(levelname)s, pid=%(process)d, tid=%(threadName)s, file=%(filename)s, func_name=%(funcName)s, code_line_no=%(lineno)d | %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(level)
logger.propagate = False
self._loggers[name] = logger
return logger
|
def get_logger(self, name, level=None, maxBytes=25000000, backupCount=5):
'\n Set up a default logger.\n\n :param name: The log file name.\n :param level: The logging level.\n :param maxBytes: The maximum log file size before rollover.\n :param backupCount: The number of log files to retain.\n '
if (level is None):
level = self._default_level
name = self._get_log_name(name)
if (name in self._loggers):
return self._loggers[name]
logfile = make_splunkhome_path(['var', 'log', 'splunk', name])
logger = logging.getLogger(name)
handler_exists = any([True for h in logger.handlers if (h.baseFilename == logfile)])
if (not handler_exists):
file_handler = handlers.RotatingFileHandler(logfile, mode='a', maxBytes=maxBytes, backupCount=backupCount)
formatter = logging.Formatter('%(asctime)s +0000 log_level=%(levelname)s, pid=%(process)d, tid=%(threadName)s, file=%(filename)s, func_name=%(funcName)s, code_line_no=%(lineno)d | %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(level)
logger.propagate = False
self._loggers[name] = logger
return logger<|docstring|>Set up a default logger.
:param name: The log file name.
:param level: The logging level.
:param maxBytes: The maximum log file size before rollover.
:param backupCount: The number of log files to retain.<|endoftext|>
|
c2001d98f7aa8ddcb9a395323619d5c81718f4b701fa89fc3b9199b16be0be41
|
def set_level(self, level, name=None):
'\n Change the log level of the logging\n\n :param level: the level of the logging to be setLevel\n :param name: the name of the logging to set, in case it is not set,\n all the loggers will be affected\n '
if (name is not None):
name = self._get_log_name(name)
logger = self._loggers.get(name)
if (logger is not None):
logger.setLevel(level)
else:
self._default_level = level
for logger in self._loggers.values():
logger.setLevel(level)
|
Change the log level of the logging
:param level: the level of the logging to be setLevel
:param name: the name of the logging to set, in case it is not set,
all the loggers will be affected
|
TA-linode/bin/ta_linode/aob_py3/splunktalib/common/log.py
|
set_level
|
jriddle-linode/splunk-addon-linode
| 11
|
python
|
def set_level(self, level, name=None):
'\n Change the log level of the logging\n\n :param level: the level of the logging to be setLevel\n :param name: the name of the logging to set, in case it is not set,\n all the loggers will be affected\n '
if (name is not None):
name = self._get_log_name(name)
logger = self._loggers.get(name)
if (logger is not None):
logger.setLevel(level)
else:
self._default_level = level
for logger in self._loggers.values():
logger.setLevel(level)
|
def set_level(self, level, name=None):
'\n Change the log level of the logging\n\n :param level: the level of the logging to be setLevel\n :param name: the name of the logging to set, in case it is not set,\n all the loggers will be affected\n '
if (name is not None):
name = self._get_log_name(name)
logger = self._loggers.get(name)
if (logger is not None):
logger.setLevel(level)
else:
self._default_level = level
for logger in self._loggers.values():
logger.setLevel(level)<|docstring|>Change the log level of the logging
:param level: the level of the logging to be setLevel
:param name: the name of the logging to set, in case it is not set,
all the loggers will be affected<|endoftext|>
|
3113b95058ce3336bdaae98db879d0c92a7b02c9fb1216cf1b2f670cb5f0bdb2
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)
|
Forward pass through the network.
These inputs are x, and the hidden/cell state `hidden`.
|
LSTM for language modeling/Question2_Part_1_To_2.py
|
forward
|
sotudian/Natural-Language-Processing
| 0
|
python
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)<|docstring|>Forward pass through the network.
These inputs are x, and the hidden/cell state `hidden`.<|endoftext|>
|
e486d66f5fdc03ca8fa22347b95e04cf89fc322aeca96767c2685cbd005badc7
|
def init_hidden(self, batch_size):
' initializes hidden state '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden
|
initializes hidden state
|
LSTM for language modeling/Question2_Part_1_To_2.py
|
init_hidden
|
sotudian/Natural-Language-Processing
| 0
|
python
|
def init_hidden(self, batch_size):
' '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden
|
def init_hidden(self, batch_size):
' '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden<|docstring|>initializes hidden state<|endoftext|>
|
3113b95058ce3336bdaae98db879d0c92a7b02c9fb1216cf1b2f670cb5f0bdb2
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)
|
Forward pass through the network.
These inputs are x, and the hidden/cell state `hidden`.
|
LSTM for language modeling/Question2_Part_1_To_2.py
|
forward
|
sotudian/Natural-Language-Processing
| 0
|
python
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)
|
def forward(self, x, hidden):
' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '
embedded = self.emb_layer(x)
(lstm_output, hidden) = self.lstm(embedded, hidden)
out = self.dropout(lstm_output)
out = out.reshape((- 1), self.n_hidden)
out = self.fc(out)
return (out, hidden)<|docstring|>Forward pass through the network.
These inputs are x, and the hidden/cell state `hidden`.<|endoftext|>
|
e486d66f5fdc03ca8fa22347b95e04cf89fc322aeca96767c2685cbd005badc7
|
def init_hidden(self, batch_size):
' initializes hidden state '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden
|
initializes hidden state
|
LSTM for language modeling/Question2_Part_1_To_2.py
|
init_hidden
|
sotudian/Natural-Language-Processing
| 0
|
python
|
def init_hidden(self, batch_size):
' '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden
|
def init_hidden(self, batch_size):
' '
weight = next(self.parameters()).data
if torch.cuda.is_available():
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(), weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
return hidden<|docstring|>initializes hidden state<|endoftext|>
|
9748f7a027b9b28aaf3c4795bfbee2fcc68b9d6171c4815d378459c2349b3095
|
def set_option(name, option):
'\n Set the given LLVM "command-line" option.\n\n For example set_option("test", "-debug-pass=Structure") would display\n all optimization passes when generating code.\n '
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option))
|
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
|
llvmlite/binding/options.py
|
set_option
|
isuruf/llvmlite
| 1,738
|
python
|
def set_option(name, option):
'\n Set the given LLVM "command-line" option.\n\n For example set_option("test", "-debug-pass=Structure") would display\n all optimization passes when generating code.\n '
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option))
|
def set_option(name, option):
'\n Set the given LLVM "command-line" option.\n\n For example set_option("test", "-debug-pass=Structure") would display\n all optimization passes when generating code.\n '
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), _encode_string(option))<|docstring|>Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.<|endoftext|>
|
e5e5c262159805bda56eb73a009a24e1ed50abab26ddd397934ea55109866238
|
def generateLinearData(dimension, num):
'\n 随机产生线性模型数据\n\n 参数\n ----\n dimension :int,自变量个数\n\n num :int,数据个数\n\n 返回\n ----\n x :np.array,自变量\n\n y :np.array,因变量\n '
np.random.seed(1024)
beta = (np.array(range(dimension)) + 1)
x = np.random.random((num, dimension))
epsilon = np.random.random((num, 1))
y = (x.dot(beta).reshape(((- 1), 1)) + epsilon)
return (x, y)
|
随机产生线性模型数据
参数
----
dimension :int,自变量个数
num :int,数据个数
返回
----
x :np.array,自变量
y :np.array,因变量
|
ch06-sgd/utils.py
|
generateLinearData
|
GaoX2015/intro_ds
| 314
|
python
|
def generateLinearData(dimension, num):
'\n 随机产生线性模型数据\n\n 参数\n ----\n dimension :int,自变量个数\n\n num :int,数据个数\n\n 返回\n ----\n x :np.array,自变量\n\n y :np.array,因变量\n '
np.random.seed(1024)
beta = (np.array(range(dimension)) + 1)
x = np.random.random((num, dimension))
epsilon = np.random.random((num, 1))
y = (x.dot(beta).reshape(((- 1), 1)) + epsilon)
return (x, y)
|
def generateLinearData(dimension, num):
'\n 随机产生线性模型数据\n\n 参数\n ----\n dimension :int,自变量个数\n\n num :int,数据个数\n\n 返回\n ----\n x :np.array,自变量\n\n y :np.array,因变量\n '
np.random.seed(1024)
beta = (np.array(range(dimension)) + 1)
x = np.random.random((num, dimension))
epsilon = np.random.random((num, 1))
y = (x.dot(beta).reshape(((- 1), 1)) + epsilon)
return (x, y)<|docstring|>随机产生线性模型数据
参数
----
dimension :int,自变量个数
num :int,数据个数
返回
----
x :np.array,自变量
y :np.array,因变量<|endoftext|>
|
70f7790627e05cf0d16ceeb2af9d78f54684bef4eba7b937de84dce4e520b20f
|
def createLinearModel(dimension):
'\n 搭建模型,包括数据中的自变量,应变量和损失函数\n\n 参数\n ----\n dimension : int,自变量的个数\n\n 返回\n ----\n model :dict,里面包含模型的参数,损失函数,自变量,应变量\n '
np.random.seed(1024)
x = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
y = tf.placeholder(tf.float64, shape=[None, 1], name='y')
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name='y_pred')
loss = tf.reduce_mean(tf.square((yPred - y)))
model = {'loss_function': loss, 'independent_variable': x, 'dependent_variable': y, 'prediction': yPred, 'model_params': betaPred}
return model
|
搭建模型,包括数据中的自变量,应变量和损失函数
参数
----
dimension : int,自变量的个数
返回
----
model :dict,里面包含模型的参数,损失函数,自变量,应变量
|
ch06-sgd/utils.py
|
createLinearModel
|
GaoX2015/intro_ds
| 314
|
python
|
def createLinearModel(dimension):
'\n 搭建模型,包括数据中的自变量,应变量和损失函数\n\n 参数\n ----\n dimension : int,自变量的个数\n\n 返回\n ----\n model :dict,里面包含模型的参数,损失函数,自变量,应变量\n '
np.random.seed(1024)
x = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
y = tf.placeholder(tf.float64, shape=[None, 1], name='y')
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name='y_pred')
loss = tf.reduce_mean(tf.square((yPred - y)))
model = {'loss_function': loss, 'independent_variable': x, 'dependent_variable': y, 'prediction': yPred, 'model_params': betaPred}
return model
|
def createLinearModel(dimension):
'\n 搭建模型,包括数据中的自变量,应变量和损失函数\n\n 参数\n ----\n dimension : int,自变量的个数\n\n 返回\n ----\n model :dict,里面包含模型的参数,损失函数,自变量,应变量\n '
np.random.seed(1024)
x = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
y = tf.placeholder(tf.float64, shape=[None, 1], name='y')
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name='y_pred')
loss = tf.reduce_mean(tf.square((yPred - y)))
model = {'loss_function': loss, 'independent_variable': x, 'dependent_variable': y, 'prediction': yPred, 'model_params': betaPred}
return model<|docstring|>搭建模型,包括数据中的自变量,应变量和损失函数
参数
----
dimension : int,自变量的个数
返回
----
model :dict,里面包含模型的参数,损失函数,自变量,应变量<|endoftext|>
|
207774ae223efe906f006bb68ecb8e08bf8f2bba0388bb43c7a0750b62d9654b
|
def createSummaryWriter(logPath):
'\n 检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象\n\n 参数\n ----\n logPath :string,日志存储路径\n\n 返回\n ----\n summaryWriter :FileWriter,日志写入器\n '
if tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter
|
检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象
参数
----
logPath :string,日志存储路径
返回
----
summaryWriter :FileWriter,日志写入器
|
ch06-sgd/utils.py
|
createSummaryWriter
|
GaoX2015/intro_ds
| 314
|
python
|
def createSummaryWriter(logPath):
'\n 检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象\n\n 参数\n ----\n logPath :string,日志存储路径\n\n 返回\n ----\n summaryWriter :FileWriter,日志写入器\n '
if tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter
|
def createSummaryWriter(logPath):
'\n 检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象\n\n 参数\n ----\n logPath :string,日志存储路径\n\n 返回\n ----\n summaryWriter :FileWriter,日志写入器\n '
if tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter<|docstring|>检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象
参数
----
logPath :string,日志存储路径
返回
----
summaryWriter :FileWriter,日志写入器<|endoftext|>
|
893055562fc588357c170434516675b7e16f3b2b67d0daf36a2591fcd217d76b
|
def increasing_tone(initial_tone, tone_rate_increase, speed, robot):
':type robot: rosebot.RoseBot'
robot.drive_system.go(speed, speed)
starting_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
while True:
new_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
if (new_distance < starting_distance):
initial_tone = (initial_tone + tone_rate_increase)
starting_distance = new_distance
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 1):
break
robot.sound_system.tone_maker.play_tone(initial_tone, 150)
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
|
:type robot: rosebot.RoseBot
|
src/m2_extra.py
|
increasing_tone
|
josephklaw/99-CapstoneProject-201920
| 0
|
python
|
def increasing_tone(initial_tone, tone_rate_increase, speed, robot):
robot.drive_system.go(speed, speed)
starting_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
while True:
new_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
if (new_distance < starting_distance):
initial_tone = (initial_tone + tone_rate_increase)
starting_distance = new_distance
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 1):
break
robot.sound_system.tone_maker.play_tone(initial_tone, 150)
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
|
def increasing_tone(initial_tone, tone_rate_increase, speed, robot):
robot.drive_system.go(speed, speed)
starting_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
while True:
new_distance = robot.sensor_system.ir_proximity_sensor.get_distance_in_inches()
if (new_distance < starting_distance):
initial_tone = (initial_tone + tone_rate_increase)
starting_distance = new_distance
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 1):
break
robot.sound_system.tone_maker.play_tone(initial_tone, 150)
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()<|docstring|>:type robot: rosebot.RoseBot<|endoftext|>
|
01551ddd4e6c640ffc7fd9aac731151edefa563b867bc2ed1cf25e4544a1d2b2
|
def point_to_object(direction, speed, initial_tone, tone_rate_increase, robot):
':type robot: rosebot.RoseBot'
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
if (direction == 'CCW'):
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
if (direction == 'CW'):
robot.drive_system.spin_clockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
increasing_tone(initial_tone, tone_rate_increase, speed, robot)
|
:type robot: rosebot.RoseBot
|
src/m2_extra.py
|
point_to_object
|
josephklaw/99-CapstoneProject-201920
| 0
|
python
|
def point_to_object(direction, speed, initial_tone, tone_rate_increase, robot):
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
if (direction == 'CCW'):
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
if (direction == 'CW'):
robot.drive_system.spin_clockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
increasing_tone(initial_tone, tone_rate_increase, speed, robot)
|
def point_to_object(direction, speed, initial_tone, tone_rate_increase, robot):
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
if (direction == 'CCW'):
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
if (direction == 'CW'):
robot.drive_system.spin_clockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
increasing_tone(initial_tone, tone_rate_increase, speed, robot)<|docstring|>:type robot: rosebot.RoseBot<|endoftext|>
|
ff0c88862a2778eed9ba46a7db29ad6899eb2a7050efe399aa37f15c789d9247
|
def color_finder(color, robot):
':type robot: rosebot.RoseBot'
robot.drive_system.go(75, 75)
while True:
if (robot.sensor_system.color_sensor.get_color() == int(color)):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak('I found the color')
print(robot.sensor_system.color_sensor.get_color())
break
|
:type robot: rosebot.RoseBot
|
src/m2_extra.py
|
color_finder
|
josephklaw/99-CapstoneProject-201920
| 0
|
python
|
def color_finder(color, robot):
robot.drive_system.go(75, 75)
while True:
if (robot.sensor_system.color_sensor.get_color() == int(color)):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak('I found the color')
print(robot.sensor_system.color_sensor.get_color())
break
|
def color_finder(color, robot):
robot.drive_system.go(75, 75)
while True:
if (robot.sensor_system.color_sensor.get_color() == int(color)):
robot.drive_system.stop()
robot.sound_system.speech_maker.speak('I found the color')
print(robot.sensor_system.color_sensor.get_color())
break<|docstring|>:type robot: rosebot.RoseBot<|endoftext|>
|
53a7cc0ce67a49cc2c242c85343e6c1cf8fab53a69b7d48b1c02e67e82f99080
|
def find_object(speed, robot):
':type robot: rosebot.RoseBot'
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
robot.drive_system.go_straight_for_seconds(3, speed)
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
robot.drive_system.go(speed, speed)
while True:
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 0.75):
break
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
|
:type robot: rosebot.RoseBot
|
src/m2_extra.py
|
find_object
|
josephklaw/99-CapstoneProject-201920
| 0
|
python
|
def find_object(speed, robot):
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
robot.drive_system.go_straight_for_seconds(3, speed)
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
robot.drive_system.go(speed, speed)
while True:
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 0.75):
break
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()
|
def find_object(speed, robot):
p = ev3.Sensor(driver_name='pixy-lego')
p.mode = 'SIG1'
robot.drive_system.go_straight_for_seconds(3, speed)
robot.drive_system.spin_counterclockwise_until_sees_object(int(speed), (p.value(3) * p.value(4)))
robot.drive_system.go(speed, speed)
while True:
if (robot.sensor_system.ir_proximity_sensor.get_distance_in_inches() < 0.75):
break
robot.drive_system.stop()
robot.arm_and_claw.raise_arm()<|docstring|>:type robot: rosebot.RoseBot<|endoftext|>
|
44e4e49538a43e96ae715bbe09c35b24180b10326f75358d4961b96390c4256e
|
def line_following(robot):
':type robot: rosebot.RoseBot'
robot.drive_system.go(50, 50)
while True:
if (robot.sensor_system.color_sensor.get_color() == 1):
robot.drive_system.right_motor.turn_off()
robot.drive_system.left_motor.turn_off()
robot.drive_system.go(50, 50)
if (robot.sensor_system.color_sensor.get_color() == 4):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on((- 20))
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(50)
if (robot.sensor_system.color_sensor.get_color() == 5):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(50)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on((- 20))
if (robot.sensor_system.color_sensor.get_color() == 6):
robot.drive_system.stop()
robot.arm_and_claw.move_arm_to_position(0)
break
time.sleep(0.01)
|
:type robot: rosebot.RoseBot
|
src/m2_extra.py
|
line_following
|
josephklaw/99-CapstoneProject-201920
| 0
|
python
|
def line_following(robot):
robot.drive_system.go(50, 50)
while True:
if (robot.sensor_system.color_sensor.get_color() == 1):
robot.drive_system.right_motor.turn_off()
robot.drive_system.left_motor.turn_off()
robot.drive_system.go(50, 50)
if (robot.sensor_system.color_sensor.get_color() == 4):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on((- 20))
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(50)
if (robot.sensor_system.color_sensor.get_color() == 5):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(50)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on((- 20))
if (robot.sensor_system.color_sensor.get_color() == 6):
robot.drive_system.stop()
robot.arm_and_claw.move_arm_to_position(0)
break
time.sleep(0.01)
|
def line_following(robot):
robot.drive_system.go(50, 50)
while True:
if (robot.sensor_system.color_sensor.get_color() == 1):
robot.drive_system.right_motor.turn_off()
robot.drive_system.left_motor.turn_off()
robot.drive_system.go(50, 50)
if (robot.sensor_system.color_sensor.get_color() == 4):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on((- 20))
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on(50)
if (robot.sensor_system.color_sensor.get_color() == 5):
robot.drive_system.right_motor.turn_off()
robot.drive_system.right_motor.turn_on(50)
robot.drive_system.left_motor.turn_off()
robot.drive_system.left_motor.turn_on((- 20))
if (robot.sensor_system.color_sensor.get_color() == 6):
robot.drive_system.stop()
robot.arm_and_claw.move_arm_to_position(0)
break
time.sleep(0.01)<|docstring|>:type robot: rosebot.RoseBot<|endoftext|>
|
4299c5506368cda2925cace9ef95bd135776a6d922a559ee7bbd19b3d329bf77
|
def get_fw_inventory(ip, login_account, login_password):
'Get BMC inventory \n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :returns: returns firmware inventory when succeeded or error message when failed\n '
result = {}
try:
login_host = ('https://' + ip)
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth=utils.g_AUTH)
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check if the username, password, IP is correct.'}
return result
fw_version = []
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
update_service_url = response_base_url.dict['UpdateService']['@odata.id']
else:
result = {'ret': False, 'msg': ('response base url Error code %s' % response_base_url.status)}
REDFISH_OBJ.logout()
return result
response_update_service_url = REDFISH_OBJ.get(update_service_url, None)
if (response_update_service_url.status == 200):
firmware_inventory_url = response_update_service_url.dict['FirmwareInventory']['@odata.id']
response_firmware_url = REDFISH_OBJ.get(firmware_inventory_url, None)
if (response_firmware_url.status == 200):
for firmware_url in response_firmware_url.dict['Members']:
firmware_version_url = firmware_url['@odata.id']
firmware_list = firmware_version_url.split('/')
response_firmware_version = REDFISH_OBJ.get(firmware_version_url, None)
if (response_firmware_version.status == 200):
fw = {}
for property in ['Version', 'SoftwareId', 'Description', 'Status']:
if (property in response_firmware_version.dict):
fw[property] = response_firmware_version.dict[property]
fw = {firmware_list[(- 1)]: fw}
fw_version.append(fw)
else:
result = {'ret': False, 'msg': ('response firmware version Error code %s' % response_firmware_version.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response firmware url Error code %s' % response_firmware_url.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response update service_url Error code %s' % response_update_service_url.status)}
REDFISH_OBJ.logout()
return result
result['ret'] = True
result['fw_version_detail'] = fw_version
try:
REDFISH_OBJ.logout()
except:
pass
return result
|
Get BMC inventory
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:returns: returns firmware inventory when succeeded or error message when failed
|
examples/get_fw_inventory.py
|
get_fw_inventory
|
wgf0210/python-redfish-lenovo
| 56
|
python
|
def get_fw_inventory(ip, login_account, login_password):
'Get BMC inventory \n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :returns: returns firmware inventory when succeeded or error message when failed\n '
result = {}
try:
login_host = ('https://' + ip)
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth=utils.g_AUTH)
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check if the username, password, IP is correct.'}
return result
fw_version = []
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
update_service_url = response_base_url.dict['UpdateService']['@odata.id']
else:
result = {'ret': False, 'msg': ('response base url Error code %s' % response_base_url.status)}
REDFISH_OBJ.logout()
return result
response_update_service_url = REDFISH_OBJ.get(update_service_url, None)
if (response_update_service_url.status == 200):
firmware_inventory_url = response_update_service_url.dict['FirmwareInventory']['@odata.id']
response_firmware_url = REDFISH_OBJ.get(firmware_inventory_url, None)
if (response_firmware_url.status == 200):
for firmware_url in response_firmware_url.dict['Members']:
firmware_version_url = firmware_url['@odata.id']
firmware_list = firmware_version_url.split('/')
response_firmware_version = REDFISH_OBJ.get(firmware_version_url, None)
if (response_firmware_version.status == 200):
fw = {}
for property in ['Version', 'SoftwareId', 'Description', 'Status']:
if (property in response_firmware_version.dict):
fw[property] = response_firmware_version.dict[property]
fw = {firmware_list[(- 1)]: fw}
fw_version.append(fw)
else:
result = {'ret': False, 'msg': ('response firmware version Error code %s' % response_firmware_version.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response firmware url Error code %s' % response_firmware_url.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response update service_url Error code %s' % response_update_service_url.status)}
REDFISH_OBJ.logout()
return result
result['ret'] = True
result['fw_version_detail'] = fw_version
try:
REDFISH_OBJ.logout()
except:
pass
return result
|
def get_fw_inventory(ip, login_account, login_password):
'Get BMC inventory \n :params ip: BMC IP address\n :type ip: string\n :params login_account: BMC user name\n :type login_account: string\n :params login_password: BMC user password\n :type login_password: string\n :returns: returns firmware inventory when succeeded or error message when failed\n '
result = {}
try:
login_host = ('https://' + ip)
REDFISH_OBJ = redfish.redfish_client(base_url=login_host, username=login_account, timeout=utils.g_timeout, password=login_password, default_prefix='/redfish/v1', cafile=utils.g_CAFILE)
REDFISH_OBJ.login(auth=utils.g_AUTH)
except:
traceback.print_exc()
result = {'ret': False, 'msg': 'Please check if the username, password, IP is correct.'}
return result
fw_version = []
response_base_url = REDFISH_OBJ.get('/redfish/v1', None)
if (response_base_url.status == 200):
update_service_url = response_base_url.dict['UpdateService']['@odata.id']
else:
result = {'ret': False, 'msg': ('response base url Error code %s' % response_base_url.status)}
REDFISH_OBJ.logout()
return result
response_update_service_url = REDFISH_OBJ.get(update_service_url, None)
if (response_update_service_url.status == 200):
firmware_inventory_url = response_update_service_url.dict['FirmwareInventory']['@odata.id']
response_firmware_url = REDFISH_OBJ.get(firmware_inventory_url, None)
if (response_firmware_url.status == 200):
for firmware_url in response_firmware_url.dict['Members']:
firmware_version_url = firmware_url['@odata.id']
firmware_list = firmware_version_url.split('/')
response_firmware_version = REDFISH_OBJ.get(firmware_version_url, None)
if (response_firmware_version.status == 200):
fw = {}
for property in ['Version', 'SoftwareId', 'Description', 'Status']:
if (property in response_firmware_version.dict):
fw[property] = response_firmware_version.dict[property]
fw = {firmware_list[(- 1)]: fw}
fw_version.append(fw)
else:
result = {'ret': False, 'msg': ('response firmware version Error code %s' % response_firmware_version.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response firmware url Error code %s' % response_firmware_url.status)}
REDFISH_OBJ.logout()
return result
else:
result = {'ret': False, 'msg': ('response update service_url Error code %s' % response_update_service_url.status)}
REDFISH_OBJ.logout()
return result
result['ret'] = True
result['fw_version_detail'] = fw_version
try:
REDFISH_OBJ.logout()
except:
pass
return result<|docstring|>Get BMC inventory
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:returns: returns firmware inventory when succeeded or error message when failed<|endoftext|>
|
93bff51143c0ce157021320c302734e22d229c9304ebbd900ce20a8fc29b84f7
|
def add_parameter():
'Add parameter'
argget = utils.create_common_parameter_list()
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
return parameter_info
|
Add parameter
|
examples/get_fw_inventory.py
|
add_parameter
|
wgf0210/python-redfish-lenovo
| 56
|
python
|
def add_parameter():
argget = utils.create_common_parameter_list()
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
return parameter_info
|
def add_parameter():
argget = utils.create_common_parameter_list()
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
return parameter_info<|docstring|>Add parameter<|endoftext|>
|
35ccfb5ccbd1dbad17bec7d80c4a5787daebdb51da4293557c1e4ed72dd1f6be
|
def return_entry(self, arg=None):
'Gets the result from Entry and return it to the Label'
result = self.entry_payload.get()
self.output_label.config(text=result)
self.value = result
self.entry_payload.delete(0, tk.END)
|
Gets the result from Entry and return it to the Label
|
src/GUI_Elements/Entries.py
|
return_entry
|
cedric-romain/lins
| 0
|
python
|
def return_entry(self, arg=None):
result = self.entry_payload.get()
self.output_label.config(text=result)
self.value = result
self.entry_payload.delete(0, tk.END)
|
def return_entry(self, arg=None):
result = self.entry_payload.get()
self.output_label.config(text=result)
self.value = result
self.entry_payload.delete(0, tk.END)<|docstring|>Gets the result from Entry and return it to the Label<|endoftext|>
|
f5d8bf628bbb3573effe1658ec0c8c867428c99d524561ba35a62bd171cc46b9
|
@api.doc('get_current_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
'Get the current forecast report from today for the given overview identifier'
result = db.execute_query(Query.select_forecast_current, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)
|
Get the current forecast report from today for the given overview identifier
|
apis/forecast.py
|
get
|
mrasap/powderbooking_backend
| 0
|
python
|
@api.doc('get_current_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
result = db.execute_query(Query.select_forecast_current, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)
|
@api.doc('get_current_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
result = db.execute_query(Query.select_forecast_current, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)<|docstring|>Get the current forecast report from today for the given overview identifier<|endoftext|>
|
a631302460f3d89922c019231098df6aafeba80aa9bb5e22a00c49c77633bb10
|
@api.doc('get_past_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
'Get the past forecast reports of today for the given overview identifier'
result = db.execute_query(Query.select_forecast_past, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)
|
Get the past forecast reports of today for the given overview identifier
|
apis/forecast.py
|
get
|
mrasap/powderbooking_backend
| 0
|
python
|
@api.doc('get_past_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
result = db.execute_query(Query.select_forecast_past, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)
|
@api.doc('get_past_forecast_report')
@api.marshal_list_with(fields=forecast)
def get(self, resort_id: int):
result = db.execute_query(Query.select_forecast_past, resort_id=resort_id)
if (result.rowcount > 0):
return result.fetchall()
api.abort(404)<|docstring|>Get the past forecast reports of today for the given overview identifier<|endoftext|>
|
516ed9ab9e8153bc4b18bf347c223faf44fa61506cbdac95ae24121a915968f5
|
def convert_sun_mass_to_kg(self, mass):
'Convert mass in the solar mass to kilograms.'
return (mass * self.SUN_MASS)
|
Convert mass in the solar mass to kilograms.
|
bidobe/astunit.py
|
convert_sun_mass_to_kg
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_sun_mass_to_kg(self, mass):
return (mass * self.SUN_MASS)
|
def convert_sun_mass_to_kg(self, mass):
return (mass * self.SUN_MASS)<|docstring|>Convert mass in the solar mass to kilograms.<|endoftext|>
|
c32ee6b33a9b5e63396fd5382ba11c33df6d7b747e44091057a4d378afaaf3ec
|
def convert_kg_to_sun_mass(self, mass):
'Convert mass in kilograms to the solar mass.'
return (mass / self.SUN_MASS)
|
Convert mass in kilograms to the solar mass.
|
bidobe/astunit.py
|
convert_kg_to_sun_mass
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_kg_to_sun_mass(self, mass):
return (mass / self.SUN_MASS)
|
def convert_kg_to_sun_mass(self, mass):
return (mass / self.SUN_MASS)<|docstring|>Convert mass in kilograms to the solar mass.<|endoftext|>
|
cee208a6952403ca7da591d86806d3991c15c78a5c2ec345a97bd1c3279fb816
|
def convert_days_to_sec(self, days):
'Convert time in days to seconds.'
return (days * self.DAY)
|
Convert time in days to seconds.
|
bidobe/astunit.py
|
convert_days_to_sec
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_days_to_sec(self, days):
return (days * self.DAY)
|
def convert_days_to_sec(self, days):
return (days * self.DAY)<|docstring|>Convert time in days to seconds.<|endoftext|>
|
1f2fdc631bf6514f17e415c3831be1359d5e10ebf3f71306a817a1e36726721f
|
def convert_sec_to_days(self, seconds):
'Convert time in seconds to days.'
return (seconds / self.DAY)
|
Convert time in seconds to days.
|
bidobe/astunit.py
|
convert_sec_to_days
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_sec_to_days(self, seconds):
return (seconds / self.DAY)
|
def convert_sec_to_days(self, seconds):
return (seconds / self.DAY)<|docstring|>Convert time in seconds to days.<|endoftext|>
|
b8ac7a9fdd66f88fe88c4f3ccf8ece203f85f18d4e60273f8edcb1188bd4dee0
|
def convert_min_to_sec(self, minutes):
'Convert time in minutes to seconds.'
return (self.MINUTE * minutes)
|
Convert time in minutes to seconds.
|
bidobe/astunit.py
|
convert_min_to_sec
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_min_to_sec(self, minutes):
return (self.MINUTE * minutes)
|
def convert_min_to_sec(self, minutes):
return (self.MINUTE * minutes)<|docstring|>Convert time in minutes to seconds.<|endoftext|>
|
1d8e5848396172963ea37417d38d6f5c2dfc9d9cde31a5223acb3c86b010b2cc
|
def convert_sec_to_min(self, seconds):
'Convert time in seconds to minutes.'
return (seconds / self.MINUTE)
|
Convert time in seconds to minutes.
|
bidobe/astunit.py
|
convert_sec_to_min
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_sec_to_min(self, seconds):
return (seconds / self.MINUTE)
|
def convert_sec_to_min(self, seconds):
return (seconds / self.MINUTE)<|docstring|>Convert time in seconds to minutes.<|endoftext|>
|
e6579b67b262b4f6bd0823b8919098be70b68dcc7ca2490b59a06732211ed451
|
def convert_hours_to_sec(self, minutes):
'Convert time in hours to seconds.'
return ((self.MINUTE ** 2) * minutes)
|
Convert time in hours to seconds.
|
bidobe/astunit.py
|
convert_hours_to_sec
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_hours_to_sec(self, minutes):
return ((self.MINUTE ** 2) * minutes)
|
def convert_hours_to_sec(self, minutes):
return ((self.MINUTE ** 2) * minutes)<|docstring|>Convert time in hours to seconds.<|endoftext|>
|
e2346ce93008c0c89580c7465c50ba59086f5270cd46a9ed69166d6664e056b8
|
def convert_sec_to_hours(self, seconds):
'Convert time in seconds to hours.'
return (seconds / (self.MINUTE ** 2))
|
Convert time in seconds to hours.
|
bidobe/astunit.py
|
convert_sec_to_hours
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_sec_to_hours(self, seconds):
return (seconds / (self.MINUTE ** 2))
|
def convert_sec_to_hours(self, seconds):
return (seconds / (self.MINUTE ** 2))<|docstring|>Convert time in seconds to hours.<|endoftext|>
|
44ece7fd0c9d2cd4716c88e85abc9b598e5fcae1e8931c0d704c0d6cd6e6356f
|
def convert_au_to_m(self, au):
'Convert length in the Astronomical Units to meters.'
return (au * self.AU)
|
Convert length in the Astronomical Units to meters.
|
bidobe/astunit.py
|
convert_au_to_m
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_au_to_m(self, au):
return (au * self.AU)
|
def convert_au_to_m(self, au):
return (au * self.AU)<|docstring|>Convert length in the Astronomical Units to meters.<|endoftext|>
|
88a3429bdaf5c05faef196943060f28b9fa2df7aeab3e7a729ca037874671381
|
def convert_m_to_au(self, meters):
'Convert length in meters to the Astronomical Units.'
return (meters / self.AU)
|
Convert length in meters to the Astronomical Units.
|
bidobe/astunit.py
|
convert_m_to_au
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_m_to_au(self, meters):
return (meters / self.AU)
|
def convert_m_to_au(self, meters):
return (meters / self.AU)<|docstring|>Convert length in meters to the Astronomical Units.<|endoftext|>
|
a1c419f943fadbc46e623c04f284fe5aadf3cd35bdb58f32e03bc87570f0f1b9
|
def convert_kmps_to_mps(self, speed):
'Convert speed in kilometers per second to meters per second.'
return (1000.0 * speed)
|
Convert speed in kilometers per second to meters per second.
|
bidobe/astunit.py
|
convert_kmps_to_mps
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_kmps_to_mps(self, speed):
return (1000.0 * speed)
|
def convert_kmps_to_mps(self, speed):
return (1000.0 * speed)<|docstring|>Convert speed in kilometers per second to meters per second.<|endoftext|>
|
6a72722a661e7fd8b44bc325aeb326e07075df29c06fe87c1e06170070faf3f6
|
def convert_mps_to_kmps(self, speed):
'Convert speed in meters per second to kilometers per second.'
return (speed / 1000.0)
|
Convert speed in meters per second to kilometers per second.
|
bidobe/astunit.py
|
convert_mps_to_kmps
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_mps_to_kmps(self, speed):
return (speed / 1000.0)
|
def convert_mps_to_kmps(self, speed):
return (speed / 1000.0)<|docstring|>Convert speed in meters per second to kilometers per second.<|endoftext|>
|
a174b44a93ba93a536555c10db6be360aa5fe972bcdb0ff85b217ed6c79133d5
|
def convert_m_to_sun_radius(self, meters):
'Convert length in meters to the solar radius.'
return (meters / self.SUN_RADIUS)
|
Convert length in meters to the solar radius.
|
bidobe/astunit.py
|
convert_m_to_sun_radius
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_m_to_sun_radius(self, meters):
return (meters / self.SUN_RADIUS)
|
def convert_m_to_sun_radius(self, meters):
return (meters / self.SUN_RADIUS)<|docstring|>Convert length in meters to the solar radius.<|endoftext|>
|
f6a5d2fc8257c53d4c030ba1c1d445bdb73cca7984b95c889802ad0fdc440031
|
def convert_sun_radius_to_m(self, radii):
'Convert length in the solar radius to meters.'
return (self.SUN_RADIUS * radii)
|
Convert length in the solar radius to meters.
|
bidobe/astunit.py
|
convert_sun_radius_to_m
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_sun_radius_to_m(self, radii):
return (self.SUN_RADIUS * radii)
|
def convert_sun_radius_to_m(self, radii):
return (self.SUN_RADIUS * radii)<|docstring|>Convert length in the solar radius to meters.<|endoftext|>
|
8cfdfbfcb9fee1c991538ddcfa8a2cfd40bfb54b42fe4acb36f9fc5d483b59b2
|
def convert_m_to_parsec(self, meters):
'Convert length in meters to parsec.'
return (meters / self.PARSEC)
|
Convert length in meters to parsec.
|
bidobe/astunit.py
|
convert_m_to_parsec
|
pbrus/binary-doppler-beaming
| 1
|
python
|
def convert_m_to_parsec(self, meters):
return (meters / self.PARSEC)
|
def convert_m_to_parsec(self, meters):
return (meters / self.PARSEC)<|docstring|>Convert length in meters to parsec.<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.