blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b17cc3de2699bc9c2e6d1909d80eeecd1bc07a76 | 62e27febb6c9891d02c792620ca2a8b3e4e8fd09 | /ai.py | e2ef16676cd84e6ca95beaf9071498d8365f2f5c | [] | no_license | ffidni/tictactoe | cc08cb736cc6eb277bee6c211c09aed0a7c6e006 | 125e9497ffa38abd72b9488b66945c5797c7790c | refs/heads/master | 2023-06-10T14:23:08.861220 | 2021-07-06T04:08:09 | 2021-07-06T04:08:09 | 375,467,021 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,477 | py | from random import choice
#Credit to divyesh072019 for this code
def isMovesLeft(board) :
for i in range(3) :
for j in range(3) :
if (not board[i][j]) :
return True
return False
def evaluate(b, bot, opponent) :
# Checking for Rows for X or O victory.
for row in range(3) :
if (b[row][0] == b[row][1] and b[row][1] == b[row][2]) :
if (b[row][0] == bot) :
return 10
elif (b[row][0] == opponent) :
return -10
# Checking for Columns for X or O victory.
for col in range(3) :
if (b[0][col] == b[1][col] and b[1][col] == b[2][col]) :
if (b[0][col] == bot) :
return 10
elif (b[0][col] == opponent) :
return -10
# Checking for Diagonals for X or O victory.
if (b[0][0] == b[1][1] and b[1][1] == b[2][2]) :
if (b[0][0] == bot) :
return 10
elif (b[0][0] == opponent) :
return -10
if (b[0][2] == b[1][1] and b[1][1] == b[2][0]) :
if (b[0][2] == bot) :
return 10
elif (b[0][2] == opponent) :
return -10
# Else if none of them have won then return 0
return 0
def minimax(board, depth, is_max, bot, opponent) :
score = evaluate(board, bot, opponent)
# If Maximizer has won the game return his/her
# evaluated score
if (score == 10) :
return score
# If Minimizer has won the game return his/her
# evaluated score
if (score == -10) :
return score
# If there are no more moves and no winner then
# it is a tie
if (isMovesLeft(board) == False) :
return 0
# If this maximizer's move
if (is_max) :
best = -1000
# Traverse all cells
for i in range(3) :
for j in range(3) :
# Check if cell is empty
if (not board[i][j]) :
# Make the move
board[i][j] = bot
# Call minimax recursively and choose
# the maximum value
best = max( best, minimax(board,
depth + 1,
not is_max, bot, opponent) )
# Undo the move
board[i][j] = ""
return best
# If this minimizer's move
else :
best = 1000
# Traverse all cells
for i in range(3) :
for j in range(3) :
# Check if cell is empty
if (not board[i][j]) :
# Make the move
board[i][j] = opponent
# Call minimax recursively and choose
# the minimum value
best = min(best, minimax(board, depth + 1, not is_max, bot, opponent))
# Undo the move
board[i][j] = ""
return best
# This will return the best possible move for the player
def find_best_move(board, bot, opponent, mark_count) :
best_val = -1000
best_move = (-1, -1)
board = [[box.text() for box in row] for row in board.values()]
if mark_count < 9:
if mark_count == 0:
i = choice([0, 2])
if i == 1:
j = choice([0, 1, 2])
else:
j = choice([0, 2])
return (i, j)
else:
for i in range(3) :
for j in range(3):
# Check if cell is empty
if not board[i][j]:
# Make the move
board[i][j] = bot
# compute evaluation function for this
# move.
move_val = minimax(board, 0, False, bot, opponent)
# Undo the move
board[i][j] = ""
# If the value of the current move is
# more than the best value, then update
# best/
if move_val > best_val:
best_move = (i, j)
best_val = move_val
return best_move
| [
"realityinaship@gmail.com"
] | realityinaship@gmail.com |
34c4d58dbc00a029cccf06bca3604352c7a3dc0b | 833e9e3b34b271aa2522471bd0b281b892adff78 | /backend/forms.py | 9f1014a729fa0d32ce2cc205096f506180fa41c4 | [] | no_license | emilte/case | b3fcd869468e093ec754980824c6b155f283caa7 | 35eadb05bdd224f845353a952c9aa18b03d95591 | refs/heads/master | 2021-06-27T13:19:32.550253 | 2019-11-24T23:21:36 | 2019-11-24T23:21:36 | 223,599,299 | 0 | 0 | null | 2021-03-19T08:42:52 | 2019-11-23T14:10:19 | JavaScript | UTF-8 | Python | false | false | 2,377 | py | from django import forms
from urllib import request
from captcha.fields import ReCaptchaField
from django.conf import settings
def between(x, a, b):
return x >= a and x <= b
class Info(forms.Form):
applicant = forms.CharField(initial="emil", required=True, widget=forms.HiddenInput)
name = forms.CharField(initial="Emil Telstad", required=True, min_length=2)
email = forms.EmailField(initial="emil.telstad@gmail.com", required=True)
phone = forms.IntegerField(initial="41325358", required=True)
areacode = forms.CharField(initial="7051", required=False, min_length=4, max_length=4)
comment = forms.CharField(required=False, widget=forms.Textarea)
captcha = ReCaptchaField(
public_key=settings.RECAPTCHA_PUBLIC_KEY,
private_key=settings.RECAPTCHA_PRIVATE_KEY,
)
required_css_class = 'required'
def __init__(self, *args, **kwargs):
super(type(self), self).__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs.update({'class': 'form-control'})
self.fields['name'].widget.attrs.update({'placeholder': 'Ola Nordmann'})
self.fields['email'].widget.attrs.update({'placeholder': 'navn@domene.no'})
self.fields['phone'].widget.attrs.update({'placeholder': '12345678'})
self.fields['areacode'].widget.attrs.update({'placeholder': '1234'})
def clean_phone(self):
data = self.cleaned_data['phone']
if between(data, 40000000, 49999999) or between(data, 90000000, 99999999):
return data
raise forms.ValidationError("Invalid Norwegian phone number")
def clean_areacode(self):
data = self.cleaned_data['areacode']
if not data: # Areacode is not required
return data
try: int(data)
except: raise forms.ValidationError("Areacodes contain only digits (0-9)")
if len(data) != 4:
raise forms.ValidationError("Norwegian areacodes contain exactly 4 digits")
resource = request.urlopen("https://www.bring.no/postnummerregister-ansi.txt")
encode = resource.headers.get_content_charset()
for line in resource:
line = line.decode(encode)
n = line.split('\t')[0]
if int(n) == int(data):
return data
raise forms.ValidationError("Areacode does not exist")
| [
"emil.telstad@gmail.com"
] | emil.telstad@gmail.com |
7914eab270311d6a94213bb0d0fa5edfa4c36fb0 | 863d32f9adc6890600a7a114574be66e80dc4ec7 | /models/seg_model.py | 0e3d6fddf9a0d4b5e475694ffe2eb863038fda1d | [] | no_license | dsl2009/dsl_instance | 9e60dc36a3106a9500a9486208533c2eb23578ae | ca299c16feaf58eadfd21f282bf681194b6c118f | refs/heads/master | 2020-04-24T15:18:08.246023 | 2019-07-26T08:38:19 | 2019-07-26T08:38:19 | 172,060,432 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,584 | py | from models import resnet
import torch
from torch import nn
from torch.nn import functional as F
from layer import renet
class SegModel(nn.Module):
def __init__(self):
super(SegModel, self).__init__()
self.cnn = resnet.resnet50(pretrained=False)
self.cov1 = nn.Sequential(
nn.Conv2d(2048, 512, kernel_size=1, stride=1,bias=False),
nn.BatchNorm2d(512),
nn.ReLU(),
)
self.cov2 = nn.Sequential(
nn.Conv2d(768, 256, kernel_size=3,padding=1, stride=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU()
)
self.cov3 = nn.Sequential(
nn.Conv2d(320, 64, kernel_size=3,padding=1, stride=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU()
)
self.seg = nn.Conv2d(64, 1, kernel_size=3,padding=1, stride=1, bias=False)
self.edge = nn.Conv2d(64, 1, kernel_size=3, padding=1, stride=1, bias=False)
def forward(self, img):
x1, x2, x3 = self.cnn(img)
x3 = self.cov1(x3)
x3_up = F.interpolate(x3,scale_factor=2, mode='bilinear')
x2 = torch.cat([x3_up, x2],dim =1)
x2 = self.cov2(x2)
x2_up = F.interpolate(x2,scale_factor=2, mode='bilinear')
x1 = torch.cat([x2_up, x1],dim =1)
x1 = self.cov3(x1)
x0 = F.interpolate(x1,scale_factor=2, mode='bilinear')
seg = self.seg(x0)
edge = self.edge(x0)
return seg,edge
if __name__ == '__main__':
x = torch.randn(2,3,256,256).cuda()
md = SegModel().cuda()
md(x)
| [
"dsl"
] | dsl |
87cb6e36d3ce8f25552e58055a81a96c81d016d0 | 9994911f0ff388c92c21ca8178eec2d3af57082d | /teamup/cli.py | 8379e8bc873e2b905aca6bd2f170758de61ca15c | [
"MIT"
] | permissive | BruceEckel/TeamUp | 2809b36b8946b51bf96fcc113ef24ef02508f3c9 | 23e29301b462c329ad17253b4d4fb7f56fb7881b | refs/heads/master | 2023-01-05T19:06:21.010258 | 2022-12-26T23:30:44 | 2022-12-26T23:30:44 | 127,565,232 | 7 | 1 | MIT | 2022-12-26T23:30:45 | 2018-03-31T19:42:07 | Python | UTF-8 | Python | false | false | 1,527 | py | # -*- coding: utf-8 -*-
"""
Combine people for group activities
"""
from pathlib import Path
import os, sys
import click
import webbrowser
from teamup.pairings import Pairings
from teamup.PersistentLoopCounter import PersistentLoopCounter
attendees = Path("Attendees.txt")
html = Path() / "html"
@click.group()
@click.version_option()
def main():
"""
Generates and displays all combinations of 2-person teams using a
round-robin algorithm. Requires an Attendees.txt file containing
one name per line. Remove the 'html' directory to restart.
"""
def display(index):
pairing = html / f"pairing{index}.html"
assert pairing.exists()
webbrowser.open_new_tab(pairing)
@main.command()
def current():
"""
Show current teams
"""
if not attendees.exists():
print("Attendees.txt not found")
sys.exit(1)
pairings = Pairings.from_file(Path("Attendees.txt"))
if not html.exists():
pairings.create_html_files()
PersistentLoopCounter.create(html, pairings.bound)
display(PersistentLoopCounter.get(html).index())
@main.command()
def next():
"""
Moves to next team grouping and shows
"""
if not html.exists():
print("No 'html' directory, first run 'teamup current'")
sys.exit(1)
display(PersistentLoopCounter.get(html).next())
# @main.command()
# def clean():
# """
# Erases the 'html' directory
# """
# if html.exists():
# html.unlink()
if __name__ == "__main__":
main()
| [
"mindviewinc@gmail.com"
] | mindviewinc@gmail.com |
a7f52a070ab9786932134e6185e25c4294abacda | bfc25f1ad7bfe061b57cfab82aba9d0af1453491 | /data/external/repositories_2to3/113677/KaggleBillionWordImputation-master/scripts/test_to_train.py | d6a8b8242d2e01d61592d440427057247ee7db57 | [
"MIT"
] | permissive | Keesiu/meta-kaggle | 77d134620ebce530d183467202cf45639d9c6ff2 | 87de739aba2399fd31072ee81b391f9b7a63f540 | refs/heads/master | 2020-03-28T00:23:10.584151 | 2018-12-20T19:09:50 | 2018-12-20T19:09:50 | 147,406,338 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 284 | py | #!/usr/bin/env python
'''Convert test file format to train file format'''
import sys
if __name__ == '__main__':
header = sys.stdin.readline()
for line in sys.stdin:
i, sentence = line.rstrip().split(',', 1)
print(sentence[1:-1].replace('""', '"')) | [
"keesiu.wong@gmail.com"
] | keesiu.wong@gmail.com |
c9aa9c599cdb6264bd9acab064e97e527515437f | 0a4d3723384ef0a6a858f01d79292ce73a46cd8b | /frontend/urls.py | 286bf72ee53476aac3e84eb4719abbef526f6fec | [] | no_license | albus12138/NKTC-Website-Django | f32594e7de7397b1e70ccaa6e0dafbd2ff2caaf6 | 3c96ae272f226b33927bbdd0b05057127824a6ef | refs/heads/master | 2021-01-23T16:26:51.251044 | 2015-08-06T08:28:37 | 2015-08-06T08:28:37 | 39,332,441 | 0 | 1 | null | 2015-08-06T08:28:37 | 2015-07-19T12:07:38 | JavaScript | UTF-8 | Python | false | false | 653 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from frontend.views import index, main_menu, secondary_menu, secondary_menu_all, search, content
urlpatterns = patterns('',
url(r'^$', index, name='index'),
url(r'^s/(?P<main>\w+)/$', main_menu, name="main_menu"),
url(r'^s/(?P<main>\w+)/(?P<secondary>\w+)/$', secondary_menu, name="secondary_menu"),
url(r'^a/(?P<main>\w+)/(?P<secondary>\w+)/$', secondary_menu_all, name="secondary_menu_all"),
url(r'^search/$', search, name="search"),
url(r'^s/(?P<main>\w+)/(?P<secondary>\w+)/(?P<id>\d+)/$', content, name="content")
) | [
"albus.zly@gmail.com"
] | albus.zly@gmail.com |
0bb8dade96e13574b8b889e8b669455156c204b5 | e3d756f8723dc133fc8ed8339ade09ed3fde4bfe | /src/0_CD/src/interpolate.py | 2e85244f686e5dbaed290eef016eaee049f4ab78 | [] | no_license | chomamat/fit-bp | 6efb89711a4070d6d6b0cbf0f9d4560af2b64a69 | ba8261ba07cd5c36683a30526126ccc0808caf03 | refs/heads/master | 2020-04-24T02:53:48.026649 | 2019-05-19T19:44:49 | 2019-05-19T19:44:49 | 171,653,155 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,926 | py | import getopt
import cv2 as cv
import numpy as np
import sys
import torch
import torch.nn as nn
from models.interpolation import Model
# Device for running computations
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Not computing gradients for better computationl performance
torch.set_grad_enabled(False)
# Parse script arguments
arg_weights = "data/interpolation85.pth"
arg_frame1 = "examples/interpolation/03_1.png"
arg_frame2 = "examples/interpolation/03_3.png"
arg_out = "examples/interpolation/out.png"
for opt, arg in getopt.getopt(sys.argv[1:], '', [ param[2:] + '=' for param in sys.argv[1::2] ])[0]:
if opt == '--model' and arg != '': arg_weights = arg
if opt == '--first' and arg != '': arg_frame1 = arg
if opt == '--second' and arg != '': arg_frame2 = arg
if opt == '--out' and arg != '': arg_out = arg
#######################################
def interpolate(arg_frame1, arg_frame2, arg_out):
# Read input images and check dimensions
img1 = cv.imread(arg_frame1, cv.IMREAD_GRAYSCALE).astype('float32') / 255.
img2 = cv.imread(arg_frame2, cv.IMREAD_GRAYSCALE).astype('float32') / 255.
assert img1.shape == img2.shape
shape = img1.shape
img1 = img1.reshape((1,1,shape[0],shape[1]))
img2 = img2.reshape((1,1,shape[0],shape[1]))
# Create input tensor and compute output tensor
tensor_in = torch.tensor( np.concatenate((img1,img2),axis=1) ).to(device)
tensor_out = model(tensor_in)
# Save output image from the output tensor
img_out = (tensor_out[0,0].cpu().detach().numpy() * 255).astype('int')
cv.imwrite(arg_out, img_out)
#######################################
# Create model for interpolation
model = Model().to(device)
model.load_state_dict(torch.load(arg_weights, map_location=device))
model.eval()
#######################################
if __name__ == '__main__':
interpolate(arg_frame1, arg_frame2, arg_out) | [
"chomamat@fit.cvut.cz"
] | chomamat@fit.cvut.cz |
98d57a8478c682b8842dbf0da010110c3fcd6a8c | 90e10e5fe73272557b01bc600d3b0f1121b0ce0e | /worldbuildr/schema.py | 6a6350b487e09c3ac9177321e61102c1d591cc2a | [] | no_license | nanderv/worldbuildr | e18809599bfdc573e398cb35b65caca528f4a552 | 3c69ef51408350c9b215996d16ac4f63837785c2 | refs/heads/master | 2020-03-30T02:01:44.498920 | 2018-09-29T10:13:01 | 2018-09-29T10:13:01 | 150,608,695 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 223 | py | import when.schema
import graphene
from graphene_django.debug import DjangoDebug
import who.schema
class Query(when.schema.Query, who.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)
| [
"nander@nander.net"
] | nander@nander.net |
1c5daec5e4fda16f1120b32e7f9d688b02254b60 | 85a9ffeccb64f6159adbd164ff98edf4ac315e33 | /pysnmp-with-texts/IB-DHCPONE-MIB.py | aea222e97e72ae77fa4c45e1500e93446cf69240 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | agustinhenze/mibs.snmplabs.com | 5d7d5d4da84424c5f5a1ed2752f5043ae00019fb | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | refs/heads/master | 2020-12-26T12:41:41.132395 | 2019-08-16T15:51:41 | 2019-08-16T15:53:57 | 237,512,469 | 0 | 0 | Apache-2.0 | 2020-01-31T20:41:36 | 2020-01-31T20:41:35 | null | UTF-8 | Python | false | false | 11,349 | py | #
# PySNMP MIB module IB-DHCPONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IB-DHCPONE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:50:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint")
IbString, IbIpAddr, ibDHCPOne = mibBuilder.importSymbols("IB-SMI-MIB", "IbString", "IbIpAddr", "ibDHCPOne")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, enterprises, Gauge32, ModuleIdentity, IpAddress, Integer32, Counter32, ObjectIdentity, TimeTicks, MibIdentifier, Unsigned32, iso, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "enterprises", "Gauge32", "ModuleIdentity", "IpAddress", "Integer32", "Counter32", "ObjectIdentity", "TimeTicks", "MibIdentifier", "Unsigned32", "iso", "Counter64")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
ibDhcpModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1))
ibDhcpModule.setRevisions(('2010-03-23 00:00', '2008-02-14 00:00', '2005-01-10 00:00', '2004-05-21 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ibDhcpModule.setRevisionsDescriptions(('Fixed smilint errors', 'change ibDHCPSubnetPercentUsed syntax', 'Added copyright', 'Creation of the MIB file',))
if mibBuilder.loadTexts: ibDhcpModule.setLastUpdated('201003230000Z')
if mibBuilder.loadTexts: ibDhcpModule.setOrganization('Infoblox')
if mibBuilder.loadTexts: ibDhcpModule.setContactInfo('See IB-SMI-MIB for information.')
if mibBuilder.loadTexts: ibDhcpModule.setDescription('This file defines the Infoblox DHCP One MIB.')
ibDHCPSubnetTable = MibTable((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1), )
if mibBuilder.loadTexts: ibDHCPSubnetTable.setStatus('current')
if mibBuilder.loadTexts: ibDHCPSubnetTable.setDescription('A table of DHCP Subnet statistics.')
ibDHCPSubnetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1), ).setIndexNames((0, "IB-DHCPONE-MIB", "ibDHCPSubnetNetworkAddress"))
if mibBuilder.loadTexts: ibDHCPSubnetEntry.setStatus('current')
if mibBuilder.loadTexts: ibDHCPSubnetEntry.setDescription('A conceptual row of the ibDHCPSubnetEntry containing info about a particular network using DHCP.')
ibDHCPSubnetNetworkAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 1), IbIpAddr()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPSubnetNetworkAddress.setStatus('current')
if mibBuilder.loadTexts: ibDHCPSubnetNetworkAddress.setDescription('DHCP Subnet in IpAddress format. A subnetwork may have many ranges for lease.')
ibDHCPSubnetNetworkMask = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 2), IbIpAddr()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPSubnetNetworkMask.setStatus('current')
if mibBuilder.loadTexts: ibDHCPSubnetNetworkMask.setDescription('DHCP Subnet mask in IpAddress format.')
ibDHCPSubnetPercentUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPSubnetPercentUsed.setStatus('current')
if mibBuilder.loadTexts: ibDHCPSubnetPercentUsed.setDescription('Percentage of dynamic DHCP address for subnet leased out at this time. Fixed addresses are always counted as leased for this calcuation if the fixed addresses are within ranges of leases.')
ibDHCPStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3))
ibDhcpTotalNoOfDiscovers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfDiscovers.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfDiscovers.setDescription('This variable indicates the number of discovery messages received')
ibDhcpTotalNoOfRequests = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfRequests.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfRequests.setDescription('This variable indicates the number of requests received')
ibDhcpTotalNoOfReleases = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfReleases.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfReleases.setDescription('This variable indicates the number of releases received')
ibDhcpTotalNoOfOffers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfOffers.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfOffers.setDescription('This variable indicates the number of offers sent')
ibDhcpTotalNoOfAcks = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfAcks.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfAcks.setDescription('This variable indicates the number of acks sent')
ibDhcpTotalNoOfNacks = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfNacks.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfNacks.setDescription('This variable indicates the number of nacks sent')
ibDhcpTotalNoOfDeclines = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfDeclines.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfDeclines.setDescription('This variable indicates the number of declines received')
ibDhcpTotalNoOfInforms = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfInforms.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfInforms.setDescription('This variable indicates the number of informs received')
ibDhcpTotalNoOfOthers = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 3, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpTotalNoOfOthers.setStatus('current')
if mibBuilder.loadTexts: ibDhcpTotalNoOfOthers.setDescription('This variable indicates the number of other messages received')
ibDhcpDeferredQueueSize = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDhcpDeferredQueueSize.setStatus('current')
if mibBuilder.loadTexts: ibDhcpDeferredQueueSize.setDescription('The size of deferred dynamic DNS update queue')
ibDHCPDDNSStats = MibIdentifier((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5))
ibDHCPDDNSAvgLatency5 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 1), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency5.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency5.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 5 minutes')
ibDHCPDDNSAvgLatency15 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 2), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency15.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency15.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 15 minutes')
ibDHCPDDNSAvgLatency60 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 3), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency60.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency60.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 60 minutes')
ibDHCPDDNSAvgLatency1440 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency1440.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSAvgLatency1440.setDescription('Average Latencies (in microseconds) for DHCPD dynamic DNS updates during the last 1 day')
ibDHCPDDNSTimeoutCount5 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount5.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount5.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 5 minutes')
ibDHCPDDNSTimeoutCount15 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount15.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount15.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 15 minutes')
ibDHCPDDNSTimeoutCount60 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 7), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount60.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount60.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 60 minutes')
ibDHCPDDNSTimeoutCount1440 = MibScalar((1, 3, 6, 1, 4, 1, 7779, 3, 1, 1, 4, 1, 5, 8), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount1440.setStatus('current')
if mibBuilder.loadTexts: ibDHCPDDNSTimeoutCount1440.setDescription('The number of timeout DHCPD dynamic DDNS updates during the last 1 day')
mibBuilder.exportSymbols("IB-DHCPONE-MIB", ibDhcpTotalNoOfAcks=ibDhcpTotalNoOfAcks, ibDhcpTotalNoOfOthers=ibDhcpTotalNoOfOthers, ibDHCPSubnetNetworkAddress=ibDHCPSubnetNetworkAddress, ibDHCPDDNSAvgLatency5=ibDHCPDDNSAvgLatency5, ibDhcpTotalNoOfReleases=ibDhcpTotalNoOfReleases, ibDhcpTotalNoOfInforms=ibDhcpTotalNoOfInforms, ibDHCPDDNSTimeoutCount5=ibDHCPDDNSTimeoutCount5, ibDhcpTotalNoOfOffers=ibDhcpTotalNoOfOffers, ibDhcpTotalNoOfRequests=ibDhcpTotalNoOfRequests, ibDHCPSubnetTable=ibDHCPSubnetTable, ibDHCPStatistics=ibDHCPStatistics, ibDHCPDDNSAvgLatency60=ibDHCPDDNSAvgLatency60, ibDhcpModule=ibDhcpModule, ibDhcpTotalNoOfDiscovers=ibDhcpTotalNoOfDiscovers, ibDHCPDDNSTimeoutCount60=ibDHCPDDNSTimeoutCount60, ibDHCPDDNSAvgLatency15=ibDHCPDDNSAvgLatency15, ibDHCPDDNSTimeoutCount15=ibDHCPDDNSTimeoutCount15, ibDHCPDDNSStats=ibDHCPDDNSStats, ibDhcpTotalNoOfDeclines=ibDhcpTotalNoOfDeclines, ibDHCPSubnetNetworkMask=ibDHCPSubnetNetworkMask, ibDhcpTotalNoOfNacks=ibDhcpTotalNoOfNacks, ibDHCPSubnetEntry=ibDHCPSubnetEntry, ibDHCPSubnetPercentUsed=ibDHCPSubnetPercentUsed, ibDhcpDeferredQueueSize=ibDhcpDeferredQueueSize, PYSNMP_MODULE_ID=ibDhcpModule, ibDHCPDDNSTimeoutCount1440=ibDHCPDDNSTimeoutCount1440, ibDHCPDDNSAvgLatency1440=ibDHCPDDNSAvgLatency1440)
| [
"dcwangmit01@gmail.com"
] | dcwangmit01@gmail.com |
34b242e509f466f320688594ae1b456377f19fc0 | 3cd5de408139f0be09bf58ba406043819aca1d2c | /program1.py | 8500ead54844d796387e618284300bc569f77521 | [] | no_license | nadgabriel/first_repo | 79417e8ae9c73a00a7cd4ef0da836c109149761b | 500ea88fbd6da9c7cb60e363a9e733b9d5a6cb35 | refs/heads/master | 2023-04-01T14:08:43.941135 | 2020-12-23T22:30:25 | 2020-12-23T22:30:25 | 271,045,527 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 820 | py | # Do premennej mozme ulozit hocijaky datovy typ
pocet_jablk=2
pocet_hrusiek=3.4
number_of_windows=10
print("pocet_jabl = ", pocet_jablk)
# Premenna je case sensitive cize tieto dve premenne su rozdielne
cars=1
Cars=2
# Premennu mozme definovat aj niekolko krat
jablka=4
jablka=3
# Nazvy premennych mozu pozostavat len z malych a velkych pismen anglickej abecedy a podtrzniku _
toto_je_premenna = 4
# Vzdy pouzivajte nazvy ktore popisuju obsah premennej
pocet_byvalych_frajeriek = 12
# Medzi rovnasa premenou a cislom moze byt lubovolny pocet medzier. Ja odporucam nedavat ziadnu
pocet_zubov=32
pocet_zubov = 32
pocet_zubov = 32
print("pocet_zubov= ", pocet_zubov)
# Miso odporuca pouzivat anglicke nazvy premennych. Ked budete programovat pre firmy kazdy bude pouzivat anglicke nazvy
number_of_limbs=2 | [
"nadgabriell@gmail.com"
] | nadgabriell@gmail.com |
d49733bfac92a4f491e624790358f0aa6cb9d05f | a65cdc270f7c900c8f0dce75c88f4eb23bfcd856 | /tryzero.py | 77cf02d8b20fd5a1942b87b1b5e7e16c09235699 | [] | no_license | noufila/python-programs | a31ff0916d987f8307f809c12c44d11989245a0a | 8ddfeeb0aae757bdf4e269cb28b55271f3888726 | refs/heads/master | 2020-03-28T01:25:00.730879 | 2018-09-11T10:37:19 | 2018-09-11T10:37:19 | 147,503,389 | 0 | 0 | null | 2018-09-11T10:37:20 | 2018-09-05T10:51:57 | Python | UTF-8 | Python | false | false | 187 | py | try:
n=int(input("enter a number"))
n1=int(input("enter a number"))
print(n/n1)
except ZeroDivisionError as err:
print("second number cannot be zero")
print(err) | [
"noreply@github.com"
] | noreply@github.com |
44f3dee156facd70866135a80c736611e2656831 | ce88c0222e5c770ecfc4e05bf61c55371e8d9a92 | /termext/abs_kw_pair.py | fdbe8a9e205b722f7db84f8d23657b3267f917af | [] | no_license | melsk125/ner | 31683f83fc6343a49421ae3879f5aae80c601267 | 77d9ccad029f1d5d9c916f5d3d73a7132a6e411a | refs/heads/master | 2021-01-10T21:59:30.940959 | 2012-04-01T08:44:33 | 2012-04-01T08:44:33 | 2,889,299 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,862 | py | import lib
import sys
import re
from optparse import OptionParser
from nltk import word_tokenize
optionParser = OptionParser()
options, args = optionParser.parse_args()
if len(args) == 0:
raw = sys.stdin.read()
else:
f = open(args[0])
raw = f.read()
lines = lib.get_dat_sgml(raw)
"""
Assume the input is in the format
<Abstract text> <Count of keyword> <Keyword 1> ... <Keyword n>
Output
<Token> <Tag (BIO)> (If Tag==B <Abstract number> <Keyword number>)
"""
sys.stderr.write(str(len(lines)) + " entries\n")
for i in range(len(lines)):
if i % 100 == 0:
sys.stderr.write(str(i) + "/" + str(len(lines)) + "\n")
line = dict(lines[i])
if 'EKYWD' in line and 'EABST' in line:
abstract = line['EABST']
keywords = re.split('\t', line['EKYWD'])
abstract = word_tokenize(abstract)
output = []
keywords = [word_tokenize(keyword) for keyword in keywords]
j = 0
while j < len(abstract):
found = False
for k in range(len(keywords)):
keyword = keywords[k]
keyword_len = len(keyword)
if keyword_len > 0 and keyword == abstract[j:j+keyword_len]:
output.append((keyword[0], "B", k+1))
print keyword[0] + "\tB\t" + str(i+1) + "\t" + str(k+1)
for l in keyword[1:]:
output.append((l, "I", k+1))
print l + "\tI\t" + str(i+1) + "\t" + str(k+1)
found = True
j += keyword_len
if found:
break
if j >= len(abstract):
break
output.append((abstract[j], "O", 0))
print abstract[j] + "\tO\t" + str(i+1) + "\t0"
j += 1
sys.stderr.write("Finished\n")
| [
"mel.sk125@gmail.com"
] | mel.sk125@gmail.com |
da6a4ecd79cdde4a64fed17365c2700d3e0e3243 | b801f7f8258660ab5e186aa64108f9a1e481c785 | /eithne.py | ac1437d6922c8f5dfbb3580b43d10ed6519d4137 | [] | no_license | aureoares/eithne | 8ab9c094c6bf49861e86fda9f6a23b2a4e5bf844 | 4d8020753a272d283b7e14c6ae9b5129853dd17f | refs/heads/master | 2021-01-22T06:58:46.730744 | 2010-04-06T18:07:29 | 2010-04-06T18:07:29 | 37,327,704 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,772 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
#import optparse
import pickle
#import BeautifulSoup
import MySQLdb
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
import ansley
def loadConf(conf_file):
"""Carga la configuración de un fichero y la guarda en un diccionario."""
configuration = {} # Diccionario que contendrá la configuración.
conf = ConfigParser.ConfigParser()
try:
conf.readfp(file(conf_file))
except:
print "Eithne: no se pudo leer el fichero de configuración '%s' ." % conf_file
return
configuration['server_addr'] = conf.get('SERVER', 'Address'.lower())
try:
configuration['server_port'] = conf.getint('SERVER','Port'.lower())
except:
print "Catherine: valor incorrecto para el puerto del servidor, se usará el 8000."
configuration['server_port'] = 8000
# Configuración para la conexión con la base de datos.
configuration['dbserver'] = conf.get('DATABASE', 'Server'.lower())
configuration['db'] = conf.get('DATABASE', 'Database'.lower())
configuration['dbuser'] = conf.get('DATABASE', 'User')
configuration['dbpasswd'] = conf.get('DATABASE', 'Passwd')
return configuration
class MiManejador(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handler para el servidor HTTP.
Implementa los métodos PUT y GET adaptados a la aplicación."""
def do_PUT(self):
"""El método PUT recoge una cadena empaquetada mediante pickle,
recupera el objeto con la información del equipo y la almacena
en la base de datos."""
print 'Conectado PUT '+str(self.client_address)
self.send_response(200, 'OK')
self.end_headers()
self.request.close()
database = str(self.client_address[0])
print 'Recogiendo datos...'
computer_pickled = str(self.rfile.read())
computer_object = pickle.loads(computer_pickled)
traductor = ansley.Ansley(computer_object)
print 'Introduciendo datos en la Base de Datos...'
traductor.ListToDb(configuration['dbuser'], configuration['dbpasswd'], configuration['db'], configuration['dbserver'], configuration['network_id'])
#traductor.printNodes()
#traductor.printNodeProperties(1)
print 'Petición finalizada.'
def do_GET(self):
"""El método GET recibe un path de la forma /red/equipo y
devuelve el informe XML correspondiente."""
print 'Conectado GET '+str(self.client_address)
self.send_response(200, 'OK')
self.end_headers()
try:
network_id = self.path.split('/')[1]
computer_id = self.path.split('/')[2]
except:
self.wfile.write('Ruta incorrecta.')
self.request.close()
return
# Conectamos con la base de datos.
try:
connection = MySQLdb.connect(user=configuration['dbuser'], passwd=configuration['dbpasswd'], db=configuration['db'], host=configuration['dbserver'])
except:
print "Eithne: No se pudo conectar con la base de datos: %s." % self.database
return
cursor = connection.cursor()
cursor.execute('''select IDMem from MEMBERS where Computer=%s and Network=%s''', (computer_id, network_id))
if(cursor.rowcount == 0):
self.wfile.write('El equipo no existe o no pertenece a la red.')
self.request.close()
return
computer = []
traductor = ansley.Ansley(computer)
traductor.DbToList(configuration['dbuser'], configuration['dbpasswd'], configuration['db'], configuration['dbserver'], computer_id)
document = traductor.ListToXml()
pretty_document = document.prettify()
pretty_document = '<?xml version="1.0" standalone="yes" ?>'+pretty_document
self.wfile.write(pretty_document)
self.request.close()
class ThreadingHTTPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer, BaseHTTPServer.HTTPServer):
pass
if __name__ == "__main__":
config_file='/etc/eithne/eithne.conf'
configuration = loadConf(config_file)
# Conectamos con la base de datos.
try:
connection = MySQLdb.connect(user=configuration['dbuser'], passwd=configuration['dbpasswd'], db=configuration['db'], host=configuration['dbserver'])
except:
print "Eithne: No se pudo conectar con la base de datos: %s." % configuration['db']
exit()
cursor = connection.cursor()
cursor.execute('''set character_set_client = utf8''')
cursor.execute('''set character_set_results = utf8''')
# Pedimos los datos de la red.
network_name = raw_input("Introduzca un nombre para identificar la red: ")
# Comprobamos si la red existe en la base de datos.
# Si ya existe, preguntamos si sustituirla o escoger otro nombre.
net_ok = 'n'
while(net_ok != 'y'):
cursor.execute('''select IDNet from NETWORKS where Name like %s''', (network_name,))
if(cursor.rowcount > 0):
row = cursor.fetchone()
net_id = row[0]
print "La red %s ya existe en la base de datos." % network_name
net_ok = raw_input("¿Sustituir? (y/n/a): ") # yes / no / add
if(net_ok == 'y'):
print "Eliminando la red anterior..."
# Busco los equipos de la red.
cursor.execute('''select Computer from MEMBERS where Network=%s''', (net_id,))
computers = cursor.fetchall()
# Por cada equipo busco los dispositivos que tiene.
for computer in computers:
cursor.execute('''select IDDev from DEVICES where Computer=%s''', (computer[0],))
devices = cursor.fetchall()
# Por cada dispositivo elimino sus propiedades.
for device in devices:
cursor.execute('''delete from PROPERTIES where Device=%s''', (device[0],))
# Elimino el dispositivo
cursor.execute('''delete from DEVICES where Computer=%s''', (computer[0],))
# Elimino la relación entre el equipo y la red.
cursor.execute('''delete from MEMBERS where Computer=%s and Network=%s''', (computer[0],net_id))
# Elimino el equipo.
cursor.execute('''delete from COMPUTERS where IDCom=%s''', (computer[0],))
# Elimino la red.
cursor.execute('''delete from NETWORKS where IDNet=%s''', (net_id,))
connection.commit()
else:
if(net_ok == 'a'):
net_ok = 'y'
else:
network_name = raw_input("Introduzca un nombre para identificar la red: ")
else:
net_ok = 'y'
network_desc = raw_input("Descripción de la red: ")
network_addr = raw_input("Dirección IP de la red: ")
network_mask = raw_input("Máscara de red: ")
print "Creando la nueva red..."
cursor.execute('''insert into NETWORKS (Name, Description, IP, Netmask, Parent) values (%s,%s,%s,%s,NULL)''', (network_name, network_desc, network_addr, network_mask))
configuration['network_id'] = cursor.lastrowid
connection.commit()
Clase_Servidor = ThreadingHTTPServer
Clase_Manejador = MiManejador
Dir_Servidor = (configuration['server_addr'], configuration['server_port'])
httpd = Clase_Servidor(Dir_Servidor, Clase_Manejador)
print "Iniciando servidor HTTP (%s:%s) ID: %s." % (configuration['server_addr'], configuration['server_port'], configuration['network_id'])
httpd.serve_forever()
| [
"?ureo Ares@localhost"
] | ?ureo Ares@localhost |
2665b0d21ad75e4516c94f4328876d29cfbd5752 | 5c52589d28b48539eacf034bb3eaf2ab7efbed58 | /venv/Scripts/pip-script.py | eef5a04da23847758712b0c627c4d6c93ac05638 | [] | no_license | ShaeLin983/pythonTestProject | 9a96844d69b23af6779c88afdac5273e8ca83f36 | 788de2be7696028552dd9316d74de2ab77363d53 | refs/heads/master | 2020-06-09T17:03:33.331876 | 2019-07-01T13:10:32 | 2019-07-01T13:10:32 | 193,473,556 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | #!f:\PycharmProjects\pythonTestProject\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip'
__requires__ = 'pip==19.0.3'
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==19.0.3', 'console_scripts', 'pip')()
)
| [
"linx0220@163.com"
] | linx0220@163.com |
6e99c540a9920a214daca8c0db37c178bf0617b8 | 6a2a0ba0b3bb304fe8c844474f874619dd5b7df4 | /week1/ex8.py | 247891629a29d1b0bf731d0d4d7d07e8d5f97038 | [] | no_license | pbenipal61/iot-data-analysis | 583e1491c0819fd10c7e07b31d93c5ef11f37d57 | 7e2f3ed4b85f83cf6bc9e3ccf1d8b250ead0e995 | refs/heads/master | 2022-12-15T07:00:25.305896 | 2020-09-17T21:18:04 | 2020-09-17T21:18:04 | 291,765,540 | 0 | 0 | null | 2020-09-17T21:18:05 | 2020-08-31T16:20:14 | Python | UTF-8 | Python | false | false | 88 | py | import numpy as np
matrix = np.reshape(np.arange(100, 200, 10), (5, 2) )
print(matrix) | [
"t8sipr00@students.oamk.fi"
] | t8sipr00@students.oamk.fi |
70dea9681850a7d8176cc8fc66d927d5f1513732 | d9b48edd175aadbacf47c94872217b652e3a0add | /cvxpy/reductions/cone2cone/approximations.py | d4d8bff936acd93d4cb10a9c3aa978eb58ae6b55 | [
"Apache-2.0"
] | permissive | Fage2016/cvxpy | 106149f5f9a1b9bb957f41ecdca72194c4d065c3 | 2a23c109e49577d8da4b97bbf6c866400da105c4 | refs/heads/master | 2023-08-03T21:28:48.143370 | 2023-03-08T20:53:07 | 2023-03-08T20:53:07 | 86,796,794 | 0 | 0 | Apache-2.0 | 2023-03-18T04:56:08 | 2017-03-31T08:31:20 | C++ | UTF-8 | Python | false | false | 7,058 | py | """
Copyright 2022 the CVXPY developers
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.
"""
from typing import List, Tuple
import numpy as np
import cvxpy as cp
from cvxpy.atoms.affine.upper_tri import upper_tri
from cvxpy.constraints.constraint import Constraint
from cvxpy.constraints.exponential import (ExpCone, OpRelEntrConeQuad,
RelEntrConeQuad,)
from cvxpy.constraints.zero import Zero
from cvxpy.expressions.variable import Variable
from cvxpy.reductions.canonicalization import Canonicalization
from cvxpy.reductions.dcp2cone.canonicalizers.von_neumann_entr_canon import (
von_neumann_entr_canon,)
APPROX_CONES = {
RelEntrConeQuad: {cp.SOC},
OpRelEntrConeQuad: {cp.PSD}
}
def gauss_legendre(n):
"""
Helper function for returning the weights and nodes for an
n-point Gauss-Legendre quadrature on [0, 1]
"""
beta = 0.5/np.sqrt(np.ones(n-1)-(2*np.arange(1, n, dtype=float))**(-2))
T = np.diag(beta, 1) + np.diag(beta, -1)
D, V = np.linalg.eigh(T)
x = D
x, i = np.sort(x), np.argsort(x)
w = 2 * (np.array([V[0][k] for k in i]))**2
x = (x + 1)/2
w = w/2
return w, x
def rotated_quad_cone(X: cp.Expression, y: cp.Expression, z: cp.Expression):
"""
For each i, enforce a constraint that
(X[i, :], y[i], z[i])
belongs to the rotated quadratic cone
{ (x, y, z) : || x ||^2 <= y z, 0 <= (y, z) }
This implementation doesn't enforce (x, y) >= 0! That should be imposed by the calling function.
"""
m = y.size
assert z.size == m
assert X.shape[0] == m
if len(X.shape) < 2:
X = cp.reshape(X, (m, 1))
#####################################
# Comments from quad_over_lin_canon:
# quad_over_lin := sum_{i} x^2_{i} / y
# t = Variable(1,) is the epigraph variable.
# Becomes a constraint
# SOC(t=y + t, X=[y - t, 2*x])
####################################
soc_X_col0 = cp.reshape(y - z, (m, 1))
soc_X = cp.hstack((soc_X_col0, 2*X))
soc_t = y + z
con = cp.SOC(t=soc_t, X=soc_X, axis=1)
return con
def RelEntrConeQuad_canon(con: RelEntrConeQuad, args) -> Tuple[Constraint, List[Constraint]]:
"""
Use linear and SOC constraints to approximately enforce
con.x * log(con.x / con.y) <= con.z.
We rely on an SOC characterization of 2-by-2 PSD matrices.
Namely, a matrix
[ a, b ]
[ b, c ]
is PSD if and only if (a, c) >= 0 and a*c >= b**2.
That system of constraints can be expressed as
a >= quad_over_lin(b, c).
Note: constraint canonicalization in CVXPY uses a return format
(lead_con, con_list) where lead_con is a Constraint that might be
used in dual variable recovery and con_list consists of extra
Constraint objects as needed.
"""
k, m = con.k, con.m
x, y = con.x, con.y
n = x.size
# Z has been declared as so to allow for proper vectorization
Z = Variable(shape=(k+1, n))
w, t = gauss_legendre(m)
T = Variable(shape=(m, n))
lead_con = Zero(w @ T + con.z/2**k)
constrs = [Zero(Z[0] - y)]
for i in range(k):
# The following matrix needs to be PSD.
# [Z[i] , Z[i+1]]
# [Z[i+1], x ]
# The below recipe for imposing a 2x2 matrix as PSD follows from Pg-35, Ex 2.6
# of Boyd's convex optimization. Where the constraint simply becomes a
# rotated quadratic cone, see `dcp2cone/quad_over_lin_canon.py` for the very similar
# scalar case
epi = Z[i, :]
stackedZ = Z[i+1, :]
cons = rotated_quad_cone(stackedZ, epi, x)
constrs.append(cons)
constrs.extend([epi >= 0, x >= 0])
for i in range(m):
off_diag = -(t[i]**0.5) * T[i, :]
# The following matrix needs to be PSD.
# [ Z[k] - x - T[i] , off_diag ]
# [ off_diag , x - t[i]*T[i] ]
epi = (Z[k, :] - x - T[i, :])
cons = rotated_quad_cone(off_diag, epi, x-t[i]*T[i, :])
constrs.append(cons)
constrs.extend([epi >= 0, x-t[i]*T[i, :] >= 0])
return lead_con, constrs
def OpRelEntrConeQuad_canon(con: OpRelEntrConeQuad, args) -> Tuple[Constraint, List[Constraint]]:
k, m = con.k, con.m
X, Y = con.X, con.Y
assert X.is_real()
assert Y.is_real()
assert con.Z.is_real()
Zs = {i: Variable(shape=X.shape, symmetric=True) for i in range(k+1)}
Ts = {i: Variable(shape=X.shape, symmetric=True) for i in range(m+1)}
constrs = [Zero(Zs[0] - Y)]
if not X.is_symmetric():
ut = upper_tri(X)
lt = upper_tri(X.T)
constrs.append(ut == lt)
if not Y.is_symmetric():
ut = upper_tri(Y)
lt = upper_tri(Y.T)
constrs.append(ut == lt)
if not con.Z.is_symmetric():
ut = upper_tri(con.Z)
lt = upper_tri(con.Z.T)
constrs.append(ut == lt)
w, t = gauss_legendre(m)
lead_con = Zero(cp.sum([w[i] * Ts[i] for i in range(m)]) + con.Z/2**k)
for i in range(k):
# [Z[i] , Z[i+1]]
# [Z[i+1], x ]
constrs.append(cp.bmat([[Zs[i], Zs[i+1]], [Zs[i+1].T, X]]) >> 0)
for i in range(m):
off_diag = -(t[i]**0.5) * Ts[i]
# The following matrix needs to be PSD.
# [ Z[k] - x - T[i] , off_diag ]
# [ off_diag , x - t[i]*T[i] ]
constrs.append(cp.bmat([[Zs[k] - X - Ts[i], off_diag], [off_diag.T, X-t[i]*Ts[i]]]) >> 0)
return lead_con, constrs
def von_neumann_entr_QuadApprox(expr, args):
m, k = expr.quad_approx[0], expr.quad_approx[1]
epi, initial_cons = von_neumann_entr_canon(expr, args)
cons = []
for con in initial_cons:
if isinstance(con, ExpCone): # should only hit this once.
qa_con = con.as_quad_approx(m, k)
qa_con_canon_lead, qa_con_canon = RelEntrConeQuad_canon(
qa_con, None)
cons.append(qa_con_canon_lead)
cons.extend(qa_con_canon)
else:
cons.append(con)
return epi, cons
def von_neumann_entr_canon_dispatch(expr, args):
if expr.quad_approx:
return von_neumann_entr_QuadApprox(expr, args)
else:
return von_neumann_entr_canon(expr, args)
class QuadApprox(Canonicalization):
CANON_METHODS = {
RelEntrConeQuad: RelEntrConeQuad_canon,
OpRelEntrConeQuad: OpRelEntrConeQuad_canon
}
def __init__(self, problem=None) -> None:
super(QuadApprox, self).__init__(
problem=problem, canon_methods=QuadApprox.CANON_METHODS)
| [
"noreply@github.com"
] | noreply@github.com |
482dcaf3edc7af83efcf3fa4d13ebaf71dfa5d7b | e9e6ce520a2abae5e13363b47fbd6e9ebfc6c73f | /descriptions/three_pi_description_copy/scripts/move.py | ab89d306bb17e85d91a935f83254f8d8ee76dcd8 | [] | no_license | Lizzylizard/ReinforcementLearningByElisabeth | 755b5fff13f06f3f452e12a7eb6b48722e3bf3c2 | 10d612d454864028462e85d5349d4440833a3797 | refs/heads/main | 2022-12-29T07:52:47.828097 | 2020-10-16T13:04:07 | 2020-10-16T13:04:07 | 304,057,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,818 | py | #!/usr/bin/env python
import rospy
#from /home/elisabeth/catkin_ws/src/ROS_Packages/my_msgs.msg import VelJoint
from my_msgs.msg import VelJoint
def move():
# Starts a new node
rospy.init_node('move_three_pi', anonymous=True)
velocity_publisher = rospy.Publisher('/cmd_vel', VelJoint, queue_size=10)
vel_msg = VelJoint()
#Receiveing the user's input
print("Let's move your robot")
speed = float(input("Input your speed:"))
distance = float(input("Type your distance:"))
isForward = bool(input("Foward?: "))#True or False
#Checking if the movement is forward or backwards
if(isForward):
vel_msg.left_vel = abs(speed)
vel_msg.right_vel = abs(speed)
else:
vel_msg.left_vel = -abs(speed)
vel_msg.right_vel = -abs(speed)
#Since we are moving just in x-axis
'''vel_msg.linear.y = 0
vel_msg.linear.z = 0
vel_msg.angular.x = 0
vel_msg.angular.y = 0
vel_msg.angular.z = 0'''
while not rospy.is_shutdown():
#Setting the current time for distance calculus
t0 = rospy.Time.now().to_sec()
current_distance = 0
#Loop to move the turtle in an specified distance
while(current_distance < distance):
#Publish the velocity
velocity_publisher.publish(vel_msg)
#Takes actual time to velocity calculus
t1=rospy.Time.now().to_sec()
#Calculates distancePoseStamped
current_distance= speed*(t1-t0)
#After the loop, stops the robot
vel_msg.left_vel = float(0)
vel_msg.right_vel = float(0)
#Force the robot to stop
velocity_publisher.publish(vel_msg)
if __name__ == '__main__':
try:
#Testing our function
move()
except rospy.ROSInterruptException: pass | [
"elisabeth.milde@informatik.hs-fulda.de"
] | elisabeth.milde@informatik.hs-fulda.de |
667fbc214431aa1477babf4a3224675a2d8da21f | 63e3d4bfd14b1bc7eb0fdb735312dfa23210051e | /credentials.py | aeba98bbb4d23c799c98f05cc2981ff77b91febc | [] | no_license | Arcadonauts/BES-2018 | 1ec7331c4882603acdafa261a5c92de8d768fa42 | c73dc15e7178ea565cde24702ac69611e31324cc | refs/heads/master | 2023-02-21T03:48:34.418590 | 2022-01-08T05:15:42 | 2022-01-08T05:15:42 | 128,519,979 | 0 | 0 | null | 2023-02-02T03:47:29 | 2018-04-07T10:59:09 | JavaScript | UTF-8 | Python | false | false | 1,127 | py | from twitter import OAuth
from oauth2client.file import Storage
yieldcurve = OAuth(
token = "952297957788971008-kecr8AFjWcsTPMoXfsmmbnp7gbldcX2",
token_secret = "GMEDO1ZJEbPuI2LWSd1b7Kk95NymnreYQ6xrR7KdT7yXB",
#owner = "DailyYieldCurve",
#owner_id = "952297957788971008",
consumer_key = "DOWlrAasc9EE55AdBu273lqOu",
consumer_secret = "vw7LdB54TghtBLHNjS7E7GEUz7I05zhIQonOvnpSocMvmRKvtY"
)
tweemail = OAuth(
token = "959943269743554560-Yfvjnh9VyExbApCajMBfA2YMBADPb1h",
token_secret = "CyQRXxj4NWoJQawxKceUYmK3bXsvA9wGMYF55R7WS4tEU",
#owner = "DailyYieldCurve",
#owner_id = "952297957788971008",
consumer_key = "Zv1xXykj2ERarXluzWBQxhnWc",
consumer_secret = "RyRjeq4gXc0Ab3Ir6t03korCv6CPUw1TfF8n7qxcbV67ZjGjDI"
)
x = 'C:\\Users\\Nick\\Documents\\GitHub\\BES-2018\\credentials.py'
if __file__ == x or __file__ == (x+'c'):
home = 'C:/Users/Nick/Documents/GitHub/BES-2018/'
else:
home = '/home/NickFegley/mysite/'
json = home + 'tweetmail.json'
fegleyapi = Storage(json).get()
if not fegleyapi: # If at first you don't succeed...
fegleyapi = Storage(json).get() | [
"fegleynick@gmail.com"
] | fegleynick@gmail.com |
ad42586e96c02a379336285a2bc1b60cb0230dec | 5e6d8b9989247801718dd1f10009f0f7f54c1eb4 | /sdk/python/pulumi_azure_native/containerinstance/v20180401/container_group.py | 393f32a489204ca350e64cfea46921dc0a2db827 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | vivimouret29/pulumi-azure-native | d238a8f91688c9bf09d745a7280b9bf2dd6d44e0 | 1cbd988bcb2aa75a83e220cb5abeb805d6484fce | refs/heads/master | 2023-08-26T05:50:40.560691 | 2021-10-21T09:25:07 | 2021-10-21T09:25:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 21,452 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['ContainerGroupArgs', 'ContainerGroup']
@pulumi.input_type
class ContainerGroupArgs:
def __init__(__self__, *,
containers: pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]],
os_type: pulumi.Input[Union[str, 'OperatingSystemTypes']],
resource_group_name: pulumi.Input[str],
container_group_name: Optional[pulumi.Input[str]] = None,
image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]] = None,
ip_address: Optional[pulumi.Input['IpAddressArgs']] = None,
location: Optional[pulumi.Input[str]] = None,
restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
volumes: Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]] = None):
"""
The set of arguments for constructing a ContainerGroup resource.
:param pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]] containers: The containers within the container group.
:param pulumi.Input[Union[str, 'OperatingSystemTypes']] os_type: The operating system type required by the containers in the container group.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[str] container_group_name: The name of the container group.
:param pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]] image_registry_credentials: The image registry credentials by which the container group is created from.
:param pulumi.Input['IpAddressArgs'] ip_address: The IP address type of the container group.
:param pulumi.Input[str] location: The resource location.
:param pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']] restart_policy: Restart policy for all containers within the container group.
- `Always` Always restart
- `OnFailure` Restart on failure
- `Never` Never restart
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The resource tags.
:param pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]] volumes: The list of volumes that can be mounted by containers in this container group.
"""
pulumi.set(__self__, "containers", containers)
pulumi.set(__self__, "os_type", os_type)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if container_group_name is not None:
pulumi.set(__self__, "container_group_name", container_group_name)
if image_registry_credentials is not None:
pulumi.set(__self__, "image_registry_credentials", image_registry_credentials)
if ip_address is not None:
pulumi.set(__self__, "ip_address", ip_address)
if location is not None:
pulumi.set(__self__, "location", location)
if restart_policy is not None:
pulumi.set(__self__, "restart_policy", restart_policy)
if tags is not None:
pulumi.set(__self__, "tags", tags)
if volumes is not None:
pulumi.set(__self__, "volumes", volumes)
@property
@pulumi.getter
def containers(self) -> pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]]:
"""
The containers within the container group.
"""
return pulumi.get(self, "containers")
@containers.setter
def containers(self, value: pulumi.Input[Sequence[pulumi.Input['ContainerArgs']]]):
pulumi.set(self, "containers", value)
@property
@pulumi.getter(name="osType")
def os_type(self) -> pulumi.Input[Union[str, 'OperatingSystemTypes']]:
"""
The operating system type required by the containers in the container group.
"""
return pulumi.get(self, "os_type")
@os_type.setter
def os_type(self, value: pulumi.Input[Union[str, 'OperatingSystemTypes']]):
pulumi.set(self, "os_type", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="containerGroupName")
def container_group_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the container group.
"""
return pulumi.get(self, "container_group_name")
@container_group_name.setter
def container_group_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "container_group_name", value)
@property
@pulumi.getter(name="imageRegistryCredentials")
def image_registry_credentials(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]]:
"""
The image registry credentials by which the container group is created from.
"""
return pulumi.get(self, "image_registry_credentials")
@image_registry_credentials.setter
def image_registry_credentials(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ImageRegistryCredentialArgs']]]]):
pulumi.set(self, "image_registry_credentials", value)
@property
@pulumi.getter(name="ipAddress")
def ip_address(self) -> Optional[pulumi.Input['IpAddressArgs']]:
"""
The IP address type of the container group.
"""
return pulumi.get(self, "ip_address")
@ip_address.setter
def ip_address(self, value: Optional[pulumi.Input['IpAddressArgs']]):
pulumi.set(self, "ip_address", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
The resource location.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="restartPolicy")
def restart_policy(self) -> Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]]:
"""
Restart policy for all containers within the container group.
- `Always` Always restart
- `OnFailure` Restart on failure
- `Never` Never restart
"""
return pulumi.get(self, "restart_policy")
@restart_policy.setter
def restart_policy(self, value: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]]):
pulumi.set(self, "restart_policy", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
The resource tags.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
@property
@pulumi.getter
def volumes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]]:
"""
The list of volumes that can be mounted by containers in this container group.
"""
return pulumi.get(self, "volumes")
@volumes.setter
def volumes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['VolumeArgs']]]]):
pulumi.set(self, "volumes", value)
class ContainerGroup(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
container_group_name: Optional[pulumi.Input[str]] = None,
containers: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]]] = None,
image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]]] = None,
ip_address: Optional[pulumi.Input[pulumi.InputType['IpAddressArgs']]] = None,
location: Optional[pulumi.Input[str]] = None,
os_type: Optional[pulumi.Input[Union[str, 'OperatingSystemTypes']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
volumes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]]] = None,
__props__=None):
"""
A container group.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] container_group_name: The name of the container group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]] containers: The containers within the container group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]] image_registry_credentials: The image registry credentials by which the container group is created from.
:param pulumi.Input[pulumi.InputType['IpAddressArgs']] ip_address: The IP address type of the container group.
:param pulumi.Input[str] location: The resource location.
:param pulumi.Input[Union[str, 'OperatingSystemTypes']] os_type: The operating system type required by the containers in the container group.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']] restart_policy: Restart policy for all containers within the container group.
- `Always` Always restart
- `OnFailure` Restart on failure
- `Never` Never restart
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The resource tags.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]] volumes: The list of volumes that can be mounted by containers in this container group.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: ContainerGroupArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
A container group.
:param str resource_name: The name of the resource.
:param ContainerGroupArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ContainerGroupArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
container_group_name: Optional[pulumi.Input[str]] = None,
containers: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerArgs']]]]] = None,
image_registry_credentials: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageRegistryCredentialArgs']]]]] = None,
ip_address: Optional[pulumi.Input[pulumi.InputType['IpAddressArgs']]] = None,
location: Optional[pulumi.Input[str]] = None,
os_type: Optional[pulumi.Input[Union[str, 'OperatingSystemTypes']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
restart_policy: Optional[pulumi.Input[Union[str, 'ContainerGroupRestartPolicy']]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
volumes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeArgs']]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ContainerGroupArgs.__new__(ContainerGroupArgs)
__props__.__dict__["container_group_name"] = container_group_name
if containers is None and not opts.urn:
raise TypeError("Missing required property 'containers'")
__props__.__dict__["containers"] = containers
__props__.__dict__["image_registry_credentials"] = image_registry_credentials
__props__.__dict__["ip_address"] = ip_address
__props__.__dict__["location"] = location
if os_type is None and not opts.urn:
raise TypeError("Missing required property 'os_type'")
__props__.__dict__["os_type"] = os_type
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["restart_policy"] = restart_policy
__props__.__dict__["tags"] = tags
__props__.__dict__["volumes"] = volumes
__props__.__dict__["instance_view"] = None
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:containerinstance/v20180401:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20170801preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20170801preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20171001preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20171001preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20171201preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20171201preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180201preview:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180201preview:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180601:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180601:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20180901:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20180901:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20181001:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20181001:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20191201:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20191201:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20201101:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20201101:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210301:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210301:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210701:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210701:ContainerGroup"), pulumi.Alias(type_="azure-native:containerinstance/v20210901:ContainerGroup"), pulumi.Alias(type_="azure-nextgen:containerinstance/v20210901:ContainerGroup")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ContainerGroup, __self__).__init__(
'azure-native:containerinstance/v20180401:ContainerGroup',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'ContainerGroup':
"""
Get an existing ContainerGroup resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = ContainerGroupArgs.__new__(ContainerGroupArgs)
__props__.__dict__["containers"] = None
__props__.__dict__["image_registry_credentials"] = None
__props__.__dict__["instance_view"] = None
__props__.__dict__["ip_address"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["os_type"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["restart_policy"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["type"] = None
__props__.__dict__["volumes"] = None
return ContainerGroup(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def containers(self) -> pulumi.Output[Sequence['outputs.ContainerResponse']]:
"""
The containers within the container group.
"""
return pulumi.get(self, "containers")
@property
@pulumi.getter(name="imageRegistryCredentials")
def image_registry_credentials(self) -> pulumi.Output[Optional[Sequence['outputs.ImageRegistryCredentialResponse']]]:
"""
The image registry credentials by which the container group is created from.
"""
return pulumi.get(self, "image_registry_credentials")
@property
@pulumi.getter(name="instanceView")
def instance_view(self) -> pulumi.Output['outputs.ContainerGroupResponseInstanceView']:
"""
The instance view of the container group. Only valid in response.
"""
return pulumi.get(self, "instance_view")
@property
@pulumi.getter(name="ipAddress")
def ip_address(self) -> pulumi.Output[Optional['outputs.IpAddressResponse']]:
"""
The IP address type of the container group.
"""
return pulumi.get(self, "ip_address")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
The resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="osType")
def os_type(self) -> pulumi.Output[str]:
"""
The operating system type required by the containers in the container group.
"""
return pulumi.get(self, "os_type")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
The provisioning state of the container group. This only appears in the response.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="restartPolicy")
def restart_policy(self) -> pulumi.Output[Optional[str]]:
"""
Restart policy for all containers within the container group.
- `Always` Always restart
- `OnFailure` Restart on failure
- `Never` Never restart
"""
return pulumi.get(self, "restart_policy")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
The resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter
def volumes(self) -> pulumi.Output[Optional[Sequence['outputs.VolumeResponse']]]:
"""
The list of volumes that can be mounted by containers in this container group.
"""
return pulumi.get(self, "volumes")
| [
"noreply@github.com"
] | noreply@github.com |
4f6302572228b7efcecdd72f4d4e5d237a66da92 | a8577e7ad1652458de236b85636069a1ca0c9c96 | /oscn/parse/docket_report.py | 88017f3e596727cda11a3d9842e190147e4cbcc4 | [
"MIT"
] | permissive | codefortulsa/oscn | 596678649b9e5e0db58ad6ad7313cfcd90b907b0 | 012f721127849ff24f3f8b3c17c640c388e82591 | refs/heads/main | 2023-02-11T15:11:59.651899 | 2023-01-26T23:16:05 | 2023-01-26T23:16:05 | 140,227,962 | 11 | 10 | MIT | 2022-12-26T21:31:55 | 2018-07-09T03:42:54 | Python | UTF-8 | Python | false | false | 890 | py | import urllib.parse as urlparse
from bs4 import BeautifulSoup
def cases(oscn_html):
case_list = []
soup = BeautifulSoup(oscn_html, "html.parser")
case_tables = soup.findAll("table", "clspg")
for case in case_tables:
case_link = case.find("a")
parsed = urlparse.urlparse(case_link["href"])
db = urlparse.parse_qs(parsed.query)["db"][0]
cn = case_link.text
case_index = f"{db}-{cn}"
case_list.append(case_index)
return case_list
setattr(cases, "target", ["Docket"])
setattr(cases, "_default_value", [])
def tables(oscn_html):
case_list = []
soup = BeautifulSoup(oscn_html, "html.parser")
case_tables = soup.findAll("table", "clspg")
for case in case_tables:
case_list.append(case.get_text)
return case_list
setattr(tables, "target", ["Docket"])
setattr(tables, "_default_value", [])
| [
"johnadungan@gmail.com"
] | johnadungan@gmail.com |
15974039e082f50a6ca79584bc79968741955199 | dbdc26d866057457f2e511bd881148faf2996643 | /old/refers/_search_word_old.py | e17cdb015856eb428308920e267259d06a14fd47 | [] | no_license | yzyDavid/furigana | 2dc3376e8779ea3cfed57b6fdb4f6d31ffe68df4 | cc72db866d539687532808d69d6be5ac1a95443e | refs/heads/master | 2021-01-10T00:58:37.260389 | 2018-04-04T06:16:03 | 2018-04-04T06:16:03 | 51,136,928 | 0 | 1 | null | 2018-04-04T06:16:04 | 2016-02-05T09:14:27 | Python | UTF-8 | Python | false | false | 1,856 | py | # -*- coding:utf-8 -*-
# import urllib.request as ur
# import codecs
import requests
import re
DEBUG = False
BASIC_URL = r'http://dict.hjenglish.com/jp/jc/'
# def search_word(word):
# basic_url = r'http://dict.hjenglish.com/jp/jc/'
# search_url = basic_url + word
# #search_url = search_url.encode('ascii')
# fp = ur.urlopen(search_url)
# html_str = fp.read().decode('utf-8')
# print(html_str)
def search_word(word):
search_url = BASIC_URL + word
r = requests.get(search_url)
content_str = r.content.decode('utf-8')
content_str = re.sub('\n', '', content_str)
content_str = ''.join(content_str.split())
if DEBUG:
'''
print(search_url)
print(r.url)
print(content_str)
print(r.encoding)
'''
with open('out.txt', 'w', encoding='utf-8') as fp:
fp.write(content_str)
if DEBUG:
with open('../../res/html_part.txt', encoding='utf-8') as fpsaved:
content_str = fpsaved.readline()
kana = ''
# re1_str = r'([/u2E80-/u9FFF]+)'
re1_str = '假名">【([/u2E80-/u9FFF]+)】<'
re1_str = 'title="假名">【(.*?)】<'
# re1_str = r'<span id="kana_1" class="trs_jp bold" title="假名">【(\w+)】</span>'
re2_str = '<span id="kana_1" class="trs_jp bold" title="假名"><font color="red">【(\S+)】</font></span>'
m1 = re.search(re1_str, content_str)
c1 = re.compile(re1_str, re.MULTILINE)
res1 = c1.search(content_str)
m2 = re.search(re2_str, content_str)
print(type(m1))
print(type(res1))
print(c1.flags)
print(re.findall(re1_str, content_str))
print(res1.groups())
print(m1.group(0))
print(m1.start(1))
print(m1.groups())
# print(m2.group(1))
'''
[/u2E80-/u9FFF]+
'''
| [
"yzyDavid@qq.com"
] | yzyDavid@qq.com |
485d3cc56b43af702b13d75f3c85981c119aa6fc | f8908de51fdee29875c7720efb3ef1584328086b | /tools/RemywikiSonglistScraper.py | 491726b3a629c4ad4878e48d975681e731ccc1ae | [
"MIT"
] | permissive | cyberkitsune/DDRGenie | 634e2e24323022181ed39a541d6594db958bcb16 | 6d2a78c84e33049c1541d761744da0868f23e0bb | refs/heads/master | 2022-08-07T09:52:17.850326 | 2022-07-25T04:16:21 | 2022-07-25T04:16:21 | 241,182,285 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,093 | py | import sys, requests
import wikitextparser as wtp
base_uri = 'https://remywiki.com'
query = '/api.php?action=query&prop=revisions&titles=%s&formatversion=2&redirects=1&rvprop=content&rvslots=*&format=json'
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: RemywikiSonglistScraper.py [Page_Name]")
exit(1)
page = sys.argv[1]
page = page.replace(' ','_')
print(page)
final_uri = "%s%s" % (base_uri, query % page)
r = requests.get(final_uri)
if r.status_code != 200:
print("Failure getting URI...")
exit(1)
j = r.json()
content = j['query']['pages'][0]['revisions'][0]['slots']['main']['content']
songs = []
parsed = wtp.parse(content)
lists = parsed.get_lists()
for list in lists:
for item in list.items:
# Weird hack to make sure we're the only newline in town
songs.append("%s\n" % wtp.remove_markup(item).strip('\n').lstrip())
with open("%s.txt" % page, 'w', encoding='utf-8') as f:
f.writelines(songs)
print("Output: ", "%s.txt" % page)
| [
"cyberkitsune09@gmail.com"
] | cyberkitsune09@gmail.com |
6bb0bb620a727e137539fa2541dcdc9c70c36bb4 | c9bc95759aef6c068a9fbb170c40c255b2f4e451 | /plugin/CutsceneSkipper.py | c85430b6ee289a25d0abf2093ca399f891c71bd7 | [] | no_license | lumptyd/FFxivPythonTriggerPlus | 52847420d866414024330bf8ff074fea65f6b239 | d7d783f7f4412f4c2fa965d12f74585010d12e09 | refs/heads/master | 2023-06-06T00:55:59.194873 | 2021-06-23T18:46:20 | 2021-06-23T18:46:20 | 379,401,467 | 0 | 0 | null | 2021-06-22T21:27:03 | 2021-06-22T21:10:01 | null | UTF-8 | Python | false | false | 2,865 | py | from FFxivPythonTrigger import PluginBase
import logging
"""
patch code to skip cutscene in some zone
command: @cutscene
format: /e @cutscene [p(patch)/d(dispatch)]
"""
nop = b"\x90\x90"
pattern = b"\x8B\xD7\x48\x8B\x08\x4C\x8B\x01"
command="@cutscene"
class CutsceneSkipper(PluginBase):
name = "Cutscene Skipper"
def plugin_onload(self):
self.original_0 = None
self.original_1 = None
self.scanAddress = self.FPT.api.MemoryHandler.pattern_scan_main_module(pattern)
self.FPT.log("found scan address at %s"%hex(self.scanAddress),logging.DEBUG)
self.FPT.api.command.register(command, self.process_command)
# self.FPT.register_event("log_event", self.process_command)
def process_command(self, args):
self.FPT.api.Magic.echo_msg(self._process_command(args))
def _process_command(self, arg):
try:
if arg[0] == "patch" or arg[0] == "p":
return "patch success" if self.patch() else "invalid patch"
elif arg[0] == "dispatch" or arg[0] == "d":
return "dispatch success" if self.dispatch() else "invalid dispatch"
else:
return "unknown arguments {}".format(arg[0])
except Exception as e:
return str(e)
def patch(self):
if self.scanAddress is None:
raise Exception("address scan not found")
original_0 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x11, 2)
original_1 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x2c, 2)
if original_0 == nop and original_1 == nop:
raise Exception("already patched")
self.original_0 = original_0
self.original_1 = original_1
self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x11, nop, len(nop))
self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x2c, nop, len(nop))
return True
def dispatch(self):
if self.scanAddress is None:
raise Exception("address scan not found")
original_0 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x11, 2)
original_1 = self.FPT.api.MemoryHandler.read_bytes(self.scanAddress + 0x2c, 2)
if original_0 != nop or original_1 != nop:
raise Exception("not patched")
if self.original_0 is None:
raise Exception("original data not found")
self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x11, self.original_0, len(nop))
self.FPT.api.MemoryHandler.write_bytes(self.scanAddress + 0x2c, self.original_1, len(nop))
self.original_0 = None
self.original_1 = None
return True
def plugin_onunload(self):
self.FPT.api.command.unregister(command)
try:
self.dispatch()
except:
pass
| [
"hhh"
] | hhh |
051eb317acccff8a7d27506a3e72e3c1e18d19f3 | ebce276eb1e7391fd33ce3b6488846c9907b889e | /mymodule_demo.py | 77859133138abb9e4d3670598557130e5212f278 | [] | no_license | junlongsun/PythonDemo | 9630eec7ff3de5ee92ae2d2f00906a9155e7c4bb | 086d72ae3228756fd3155ba1a3f1128be534c317 | refs/heads/master | 2016-08-06T06:07:46.951234 | 2015-08-29T19:02:52 | 2015-08-29T19:02:52 | 41,603,994 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 140 | py | #!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
dir(mymodule)
mymodule.sayhi()
print 'Version', mymodule.version
| [
"junlong.sun@colorado.edu"
] | junlong.sun@colorado.edu |
6180214e717d6e06e85875f87e397b17f6826576 | d61711ceb3c505067956b37be08cf9edab2ee4d4 | /I0320014_Soal2_Tugas4.py | 7916dee501d70ba0813698ae9479a45c38c7d618 | [] | no_license | audreyalexandra/Audrey-Alexandra_I0320014_Wildan_Tugas4 | de8b4debb0a66be097360bf530c0fc4e41c13b82 | 46fc9966a42c4e0305c86e79bdd37843e5b7912f | refs/heads/main | 2023-03-15T05:02:07.011153 | 2021-03-27T01:34:01 | 2021-03-27T01:34:01 | 351,607,836 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 164 | py | bil1 = int(input("Masukan Bilangan bulat pertama : "))
bil2 = int(input("Masukan Bilangan bulat kedua : "))
print("Hasil %d // %d = %d" % (bil1, bil2, bil1//bil2)) | [
"audreyalexandra18@gmail.com"
] | audreyalexandra18@gmail.com |
4271d8331175e5148e8949a67e93f8ab2c93e395 | 8a3cc7cee5da2cfc69270feb502e71a52ebe7684 | /MinMax & Alphabeta/game_agent.py | 3d65c7087bdcaaab87a1284fcdf6485d3a1c0e29 | [] | no_license | LearnedVector/AI-Foundation | 1ff6287cee2c92e8f9ead03b106431307ea64c07 | f191feb10ca47d5281c8002ee990228723ab850f | refs/heads/master | 2021-07-13T19:43:25.282277 | 2017-10-16T01:33:55 | 2017-10-16T01:33:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,501 | py | import random
class SearchTimeout(Exception):
"""Subclass base exception for code clarity. """
pass
def center_score(game, player):
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
w, h = game.width / 2., game.height / 2.
y, x = game.get_player_location(player)
return float((h - y)**2 + (w - x)**2)
def improved_score(game, player):
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = len(game.get_legal_moves(player))
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(own_moves - opp_moves)
def open_move(game, player):
if game.is_loser(player):
return float("inf")
if game.is_winner(player):
return float("inf")
return float(len(game.get_legal_moves(player)))
def weighted_improved_score(game, player):
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
w1 = game.move_count
own_moves = len(game.get_legal_moves(player))
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(w1*own_moves - opp_moves)
def custom_score(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
This should be the best heuristic function for your project submission.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
return center_score(game, player)*open_move(game, player)
def custom_score_2(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
return weighted_improved_score(game, player)
def custom_score_3(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
return open_move(game, player)*improved_score(game, player)
class IsolationPlayer:
"""Base class for minimax and alphabeta agents -- this class is never
constructed or tested directly.
******************** DO NOT MODIFY THIS CLASS ********************
Parameters
----------
search_depth : int (optional)
A strictly positive integer (i.e., 1, 2, 3,...) for the number of
layers in the game tree to explore for fixed-depth search. (i.e., a
depth of one (1) would only explore the immediate sucessors of the
current state.)
score_fn : callable (optional)
A function to use for heuristic evaluation of game states.
timeout : float (optional)
Time remaining (in milliseconds) when search is aborted. Should be a
positive value large enough to allow the function to return before the
timer expires.
"""
def __init__(self, search_depth=3, score_fn=custom_score, timeout=10.):
self.search_depth = search_depth
self.score = score_fn
self.time_left = None
self.TIMER_THRESHOLD = timeout
class MinimaxPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using depth-limited minimax
search. You must finish and test this player to make sure it properly uses
minimax to return a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
************** YOU DO NOT NEED TO MODIFY THIS FUNCTION *************
For fixed-depth search, this function simply wraps the call to the
minimax method, but this method provides a common interface for all
Isolation agents, and you will replace it in the AlphaBetaPlayer with
iterative deepening search.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# Initialize the best move so that this function returns something
# in case the search fails due to timeout
best_move = (-1, -1)
try:
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
return self.minimax(game, self.search_depth)
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move from the last completed search iteration
return best_move
def minimax(self, game, depth):
"""Implement depth-limited minimax search algorithm as described in
the lectures.
This should be a modified version of MINIMAX-DECISION in the AIMA text.
https://github.com/aimacode/aima-pseudocode/blob/master/md/Minimax-Decision.md
**********************************************************************
You MAY add additional methods to this class, or define helper
functions to implement the required functionality.
**********************************************************************
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
Notes
-----
(1) You MUST use the `self.score()` method for board evaluation
to pass the project tests; you cannot call any other evaluation
function directly.
(2) If you use any helper functions (e.g., as shown in the AIMA
pseudocode) then you must copy the timer check into the top of
each helper function or else your agent will timeout during
testing.
"""
def terminal_state(legal_moves, depth):
if not legal_moves or depth <= 0:
return True
return False
def min_value(game, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if terminal_state(legal_moves, depth):
return self.score(game, game._inactive_player)
min_val = float("inf")
for coordinates in legal_moves:
min_val = min(min_val,
max_value(game.forecast_move(coordinates), depth - 1))
return min_val
def max_value(game, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if terminal_state(legal_moves, depth):
return self.score(game, game._active_player)
max_val = float("-inf")
for coordinates in legal_moves:
max_val = max(max_val,
min_value(game.forecast_move(coordinates), depth - 1))
return max_val
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if terminal_state(legal_moves, depth):
return (-1, -1)
return max(legal_moves,
key=lambda m: min_value(game.forecast_move(m), depth - 1))
class AlphaBetaPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using iterative deepening minimax
search with alpha-beta pruning. You must finish and test this player to
make sure it returns a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
Modify the get_move() method from the MinimaxPlayer class to implement
iterative deepening search instead of fixed-depth search.
**********************************************************************
NOTE: If time_left() < 0 when this function returns, the agent will
forfeit the game due to timeout. You must return _before_ the
timer reaches 0.
**********************************************************************
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# Initialize the best move so that this function returns something
# in case the search fails due to timeout
best_move = (-1, -1)
try:
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
depth = 0
while True:
best_move = self.alphabeta(game, depth)
self.search_depth = depth
depth += 1
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move from the last completed search iteration
return best_move
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")):
"""Implement depth-limited minimax search with alpha-beta pruning as
described in the lectures.
This should be a modified version of ALPHA-BETA-SEARCH in the AIMA text
https://github.com/aimacode/aima-pseudocode/blob/master/md/Alpha-Beta-Search.md
**********************************************************************
You MAY add additional methods to this class, or define helper
functions to implement the required functionality.
**********************************************************************
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
Notes
-----
(1) You MUST use the `self.score()` method for board evaluation
to pass the project tests; you cannot call any other evaluation
function directly.
(2) If you use any helper functions (e.g., as shown in the AIMA
pseudocode) then you must copy the timer check into the top of
each helper function or else your agent will timeout during
testing.
"""
def terminal_state(legal_moves, depth):
if not legal_moves or depth <= 0:
return True
return False
def min_value(game, depth, alpha, beta):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if terminal_state(legal_moves, depth):
return self.score(game, game._inactive_player)
min_val = float("inf")
for coordinates in legal_moves:
min_val = min(min_val,
max_value(
game.forecast_move(coordinates),
depth - 1,
alpha,
beta))
if min_val <= alpha:
return min_val
beta = min(beta, min_val)
return min_val
def max_value(game, depth, alpha, beta):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if terminal_state(legal_moves, depth):
return self.score(game, game._active_player)
max_val = float("-inf")
for coordinates in legal_moves:
max_val = max(max_val,
min_value(
game.forecast_move(coordinates),
depth - 1,
alpha,
beta))
if max_val >= beta:
return max_val
alpha = max(alpha, max_val)
return max_val
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if len(legal_moves) == 0:
return (-1. -1)
move = (-1, -1)
for coordinates in legal_moves:
val = min_value(game.forecast_move(coordinates),
depth -1,
alpha,
beta)
if val > alpha:
alpha = val
move = coordinates
return move
| [
"ppnguyen91@gmail.com"
] | ppnguyen91@gmail.com |
d614a2dc512cfe4f235594be6aaf24e0db8ac8fd | bc8b9ca228fb90ce3e0aefd53b135cdd68329caa | /telethon/events/chataction.py | 2927c8d0f0b65e052e3609fbb2fae46a45097883 | [
"MIT"
] | permissive | huangdehui2013/Telethon | 1147ce9acba4db087efa39514a7cab6276becb92 | dd954b8fbd1957844c8e241183764c3ced7698a9 | refs/heads/master | 2020-03-16T18:49:25.989083 | 2018-05-10T07:44:25 | 2018-05-10T07:44:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,657 | py | from .common import EventBuilder, EventCommon, name_inner_event
from .. import utils
from ..tl import types, functions
@name_inner_event
class ChatAction(EventBuilder):
"""
Represents an action in a chat (such as user joined, left, or new pin).
"""
def build(self, update):
if isinstance(update, types.UpdateChannelPinnedMessage) and update.id == 0:
# Telegram does not always send
# UpdateChannelPinnedMessage for new pins
# but always for unpin, with update.id = 0
event = ChatAction.Event(types.PeerChannel(update.channel_id),
unpin=True)
elif isinstance(update, types.UpdateChatParticipantAdd):
event = ChatAction.Event(types.PeerChat(update.chat_id),
added_by=update.inviter_id or True,
users=update.user_id)
elif isinstance(update, types.UpdateChatParticipantDelete):
event = ChatAction.Event(types.PeerChat(update.chat_id),
kicked_by=True,
users=update.user_id)
elif (isinstance(update, (
types.UpdateNewMessage, types.UpdateNewChannelMessage))
and isinstance(update.message, types.MessageService)):
msg = update.message
action = update.message.action
if isinstance(action, types.MessageActionChatJoinedByLink):
event = ChatAction.Event(msg,
added_by=True,
users=msg.from_id)
elif isinstance(action, types.MessageActionChatAddUser):
event = ChatAction.Event(msg,
added_by=msg.from_id or True,
users=action.users)
elif isinstance(action, types.MessageActionChatDeleteUser):
event = ChatAction.Event(msg,
kicked_by=msg.from_id or True,
users=action.user_id)
elif isinstance(action, types.MessageActionChatCreate):
event = ChatAction.Event(msg,
users=action.users,
created=True,
new_title=action.title)
elif isinstance(action, types.MessageActionChannelCreate):
event = ChatAction.Event(msg,
created=True,
users=msg.from_id,
new_title=action.title)
elif isinstance(action, types.MessageActionChatEditTitle):
event = ChatAction.Event(msg,
users=msg.from_id,
new_title=action.title)
elif isinstance(action, types.MessageActionChatEditPhoto):
event = ChatAction.Event(msg,
users=msg.from_id,
new_photo=action.photo)
elif isinstance(action, types.MessageActionChatDeletePhoto):
event = ChatAction.Event(msg,
users=msg.from_id,
new_photo=True)
elif isinstance(action, types.MessageActionPinMessage):
# Telegram always sends this service message for new pins
event = ChatAction.Event(msg,
users=msg.from_id,
new_pin=msg.reply_to_msg_id)
else:
return
else:
return
event._entities = update._entities
return self._filter_event(event)
class Event(EventCommon):
"""
Represents the event of a new chat action.
Members:
action_message (`MessageAction <https://lonamiwebs.github.io/Telethon/types/message_action.html>`_):
The message invoked by this Chat Action.
new_pin (`bool`):
``True`` if there is a new pin.
new_photo (`bool`):
``True`` if there's a new chat photo (or it was removed).
photo (:tl:`Photo`, optional):
The new photo (or ``None`` if it was removed).
user_added (`bool`):
``True`` if the user was added by some other.
user_joined (`bool`):
``True`` if the user joined on their own.
user_left (`bool`):
``True`` if the user left on their own.
user_kicked (`bool`):
``True`` if the user was kicked by some other.
created (`bool`, optional):
``True`` if this chat was just created.
new_title (`str`, optional):
The new title string for the chat, if applicable.
unpin (`bool`):
``True`` if the existing pin gets unpinned.
"""
def __init__(self, where, new_pin=None, new_photo=None,
added_by=None, kicked_by=None, created=None,
users=None, new_title=None, unpin=None):
if isinstance(where, types.MessageService):
self.action_message = where
where = where.to_id
else:
self.action_message = None
super().__init__(chat_peer=where, msg_id=new_pin)
self.new_pin = isinstance(new_pin, int)
self._pinned_message = new_pin
self.new_photo = new_photo is not None
self.photo = \
new_photo if isinstance(new_photo, types.Photo) else None
self._added_by = None
self._kicked_by = None
self.user_added, self.user_joined, self.user_left,\
self.user_kicked, self.unpin = (False, False, False, False, False)
if added_by is True:
self.user_joined = True
elif added_by:
self.user_added = True
self._added_by = added_by
if kicked_by is True:
self.user_left = True
elif kicked_by:
self.user_kicked = True
self._kicked_by = kicked_by
self.created = bool(created)
self._user_peers = users if isinstance(users, list) else [users]
self._users = None
self._input_users = None
self.new_title = new_title
self.unpin = unpin
def respond(self, *args, **kwargs):
"""
Responds to the chat action message (not as a reply).
Shorthand for ``client.send_message(event.chat, ...)``.
"""
return self._client.send_message(self.input_chat, *args, **kwargs)
def reply(self, *args, **kwargs):
"""
Replies to the chat action message (as a reply). Shorthand for
``client.send_message(event.chat, ..., reply_to=event.message.id)``.
Has the same effect as ``.respond()`` if there is no message.
"""
if not self.action_message:
return self.respond(*args, **kwargs)
kwargs['reply_to'] = self.action_message.id
return self._client.send_message(self.input_chat, *args, **kwargs)
def delete(self, *args, **kwargs):
"""
Deletes the chat action message. You're responsible for checking
whether you have the permission to do so, or to except the error
otherwise. This is a shorthand for
``client.delete_messages(event.chat, event.message, ...)``.
Does nothing if no message action triggered this event.
"""
if self.action_message:
return self._client.delete_messages(self.input_chat,
[self.action_message],
*args, **kwargs)
@property
def pinned_message(self):
"""
If ``new_pin`` is ``True``, this returns the (:tl:`Message`)
object that was pinned.
"""
if self._pinned_message == 0:
return None
if isinstance(self._pinned_message, int) and self.input_chat:
r = self._client(functions.channels.GetMessagesRequest(
self._input_chat, [self._pinned_message]
))
try:
self._pinned_message = next(
x for x in r.messages
if isinstance(x, types.Message)
and x.id == self._pinned_message
)
except StopIteration:
pass
if isinstance(self._pinned_message, types.Message):
return self._pinned_message
@property
def added_by(self):
"""
The user who added ``users``, if applicable (``None`` otherwise).
"""
if self._added_by and not isinstance(self._added_by, types.User):
self._added_by =\
self._entities.get(utils.get_peer_id(self._added_by))
if not self._added_by:
self._added_by = self._client.get_entity(self._added_by)
return self._added_by
@property
def kicked_by(self):
"""
The user who kicked ``users``, if applicable (``None`` otherwise).
"""
if self._kicked_by and not isinstance(self._kicked_by, types.User):
self._kicked_by =\
self._entities.get(utils.get_peer_id(self._kicked_by))
if not self._kicked_by:
self._kicked_by = self._client.get_entity(self._kicked_by)
return self._kicked_by
@property
def user(self):
"""
The first user that takes part in this action (e.g. joined).
Might be ``None`` if the information can't be retrieved or
there is no user taking part.
"""
if self.users:
return self._users[0]
@property
def input_user(self):
"""
Input version of the ``self.user`` property.
"""
if self.input_users:
return self._input_users[0]
@property
def user_id(self):
"""
Returns the marked signed ID of the first user, if any.
"""
if self._user_peers:
return utils.get_peer_id(self._user_peers[0])
@property
def users(self):
"""
A list of users that take part in this action (e.g. joined).
Might be empty if the information can't be retrieved or there
are no users taking part.
"""
if not self._user_peers:
return []
if self._users is None:
have, missing = [], []
for peer in self._user_peers:
user = self._entities.get(utils.get_peer_id(peer))
if user:
have.append(user)
else:
missing.append(peer)
try:
missing = self._client.get_entity(missing)
except (TypeError, ValueError):
missing = []
self._users = have + missing
return self._users
@property
def input_users(self):
"""
Input version of the ``self.users`` property.
"""
if self._input_users is None and self._user_peers:
self._input_users = []
for peer in self._user_peers:
try:
self._input_users.append(self._client.get_input_entity(
peer
))
except (TypeError, ValueError):
pass
return self._input_users
@property
def user_ids(self):
"""
Returns the marked signed ID of the users, if any.
"""
if self._user_peers:
return [utils.get_peer_id(u) for u in self._user_peers]
| [
"totufals@hotmail.com"
] | totufals@hotmail.com |
29b762ec133fdade4911774d3363521b2f7f9ba4 | 3a5c7d812fac93b4a2543a36a07149f864d4ed0b | /Hmm/hmm_new/2H.py | 59a37551d7613858f64e6cebb22695e8f0e26a66 | [
"MIT"
] | permissive | MrAlexLemon/GeneratorOfPoems | d54a17476cd3cc581f0bcc03865d5adb7e1063df | 467f798153fed967c9c5994c9a796b90d565f597 | refs/heads/master | 2020-04-23T08:36:43.411172 | 2019-02-16T19:30:45 | 2019-02-16T19:30:45 | 171,042,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,861 | py |
from HMM import unsupervised_HMM
from Utility import Utility
import re
import copy
def unsupervised_learning(n_states, n_iters):
'''
Trains an HMM using supervised learning on the file 'ron.txt' and
prints the results.
Arguments:
n_states: Number of hidden states that the HMM should have.
'''
genres, genre_map, rhyming = Utility.load_shakespeare_hidden_stripped_poems()
# Train the HMM.
HMM = unsupervised_HMM(genres, n_states, n_iters)
# Print the transition matrix.
print("Transition Matrix:")
print('#' * 70)
for i in range(len(HMM.A)):
print(''.join("{:<12.3e}".format(HMM.A[i][j]) for j in range(len(HMM.A[i]))))
print('')
print('')
# Print the observation matrix.
print("Observation Matrix: ")
print('#' * 70)
for i in range(len(HMM.O)):
print(''.join("{:<12.3e}".format(HMM.O[i][j]) for j in range(len(HMM.O[i]))))
print('')
print('')
return HMM, genre_map, rhyming
def syllables(word):
'''
This function counts number of syllables in a word
'''
count = 0
vowels = 'aeiouy'
word = word.lower().strip(".:;?!")
if word[0] in vowels:
count +=1
for index in range(1,len(word)):
if word[index] in vowels and word[index-1] not in vowels:
count +=1
if word.endswith('e'):
count -= 1
if word.endswith('le'):
count+=1
if count == 0:
count +=1
return count
def sylco(word) :
word = word.lower()
# exception_add are words that need extra syllables
# exception_del are words that need less syllables
exception_add = ['serious','crucial']
exception_del = ['fortunately','unfortunately']
co_one = ['cool','coach','coat','coal','count','coin','coarse','coup','coif','cook','coign','coiffe','coof','court']
co_two = ['coapt','coed','coinci']
pre_one = ['preach']
syls = 0 #added syllable number
disc = 0 #discarded syllable number
#1) if letters < 3 : return 1
if len(word) <= 3 :
syls = 1
return syls
#2) if doesn't end with "ted" or "tes" or "ses" or "ied" or "ies", discard "es" and "ed" at the end.
# if it has only 1 vowel or 1 set of consecutive vowels, discard. (like "speed", "fled" etc.)
if word[-2:] == "es" or word[-2:] == "ed" :
doubleAndtripple_1 = len(re.findall(r'[eaoui][eaoui]',word))
if doubleAndtripple_1 > 1 or len(re.findall(r'[eaoui][^eaoui]',word)) > 1 :
if word[-3:] == "ted" or word[-3:] == "tes" or word[-3:] == "ses" or word[-3:] == "ied" or word[-3:] == "ies" :
pass
else :
disc+=1
#3) discard trailing "e", except where ending is "le"
le_except = ['whole','mobile','pole','male','female','hale','pale','tale','sale','aisle','whale','while']
if word[-1:] == "e" :
if word[-2:] == "le" and word not in le_except :
pass
else :
disc+=1
#4) check if consecutive vowels exists, triplets or pairs, count them as one.
doubleAndtripple = len(re.findall(r'[eaoui][eaoui]',word))
tripple = len(re.findall(r'[eaoui][eaoui][eaoui]',word))
disc+=doubleAndtripple + tripple
#5) count remaining vowels in word.
numVowels = len(re.findall(r'[eaoui]',word))
#6) add one if starts with "mc"
if word[:2] == "mc" :
syls+=1
#7) add one if ends with "y" but is not surrouned by vowel
if word[-1:] == "y" and word[-2] not in "aeoui" :
syls +=1
#8) add one if "y" is surrounded by non-vowels and is not in the last word.
for i,j in enumerate(word) :
if j == "y" :
if (i != 0) and (i != len(word)-1) :
if word[i-1] not in "aeoui" and word[i+1] not in "aeoui" :
syls+=1
#9) if starts with "tri-" or "bi-" and is followed by a vowel, add one.
if word[:3] == "tri" and word[3] in "aeoui" :
syls+=1
if word[:2] == "bi" and word[2] in "aeoui" :
syls+=1
#10) if ends with "-ian", should be counted as two syllables, except for "-tian" and "-cian"
if word[-3:] == "ian" :
#and (word[-4:] != "cian" or word[-4:] != "tian") :
if word[-4:] == "cian" or word[-4:] == "tian" :
pass
else :
syls+=1
#11) if starts with "co-" and is followed by a vowel, check if exists in the double syllable dictionary, if not, check if in single dictionary and act accordingly.
if word[:2] == "co" and word[2] in 'eaoui' :
if word[:4] in co_two or word[:5] in co_two or word[:6] in co_two :
syls+=1
elif word[:4] in co_one or word[:5] in co_one or word[:6] in co_one :
pass
else :
syls+=1
#12) if starts with "pre-" and is followed by a vowel, check if exists in the double syllable dictionary, if not, check if in single dictionary and act accordingly.
if word[:3] == "pre" and word[3] in 'eaoui' :
if word[:6] in pre_one :
pass
else :
syls+=1
#13) check for "-n't" and cross match with dictionary to add syllable.
negative = ["doesn't", "isn't", "shouldn't", "couldn't","wouldn't"]
if word[-3:] == "n't" :
if word in negative :
syls+=1
else :
pass
#14) Handling the exceptional words.
if word in exception_del :
disc+=1
if word in exception_add :
syls+=1
# calculate the output
return numVowels - disc + syls
if __name__ == '__main__':
print('')
print('')
print('#' * 70)
print("{:^70}".format("Running Code For Question 2H"))
print('#' * 70)
print('')
print('')
HMM, mapping, rhyming = unsupervised_learning(8,100)
inv_map = {v: k for k, v in mapping.items()}
numLines = 0
count = 0
topN = 15
# Find the top 10 words associated with each state
toPrint = [0. for i in range(topN)]
for i, row in enumerate(HMM.O):
# Need to map probability to word, not just index to word, because of sorting
d = {row[i]: inv_map[i] for i in range(len(row))}
probs = sorted(row)
for j, p in enumerate(probs[-topN:]):
toPrint[j] = d[p]
print(i, toPrint)
while numLines != 14:
numSyllables = 0
currentLine = (HMM.generate_emission(8))
currentNumberLine = copy.deepcopy(currentLine)
for i in range(len(currentLine)):
currentLine[i] = inv_map[int(currentLine[i])]
currentLine[0] = currentLine[0][0].upper() + currentLine[0][1:]
for i in currentLine:
if syllables(i) == sylco(i):
numSyllables += syllables(i)
if numSyllables == 10:
print (" ". join(currentLine))
print()
numLines += 1
for i in range(1):
print()
lst =[]
lst2 = []
count = 0
while (count < 7):
flag = 0
numSyllables = 0
numSyllables2 = 0
currentLine = (HMM.generate_emission(8))
currentLine2 = (HMM.generate_emission(8))
lastNum1 = currentLine[-1]
lastNum2 = currentLine2[-1]
if (lastNum1 == lastNum2):
continue
for i in rhyming:
if lastNum1 in i and lastNum2 in i:
flag = 1
break
if flag == 0:
continue
for i in range(len(currentLine)):
currentLine[i] = inv_map[int(currentLine[i])]
currentLine2[i] = inv_map[int(currentLine2[i])]
currentLine[0] = currentLine[0][0].upper() + currentLine[0][1:]
currentLine2[0] = currentLine2[0][0].upper() + currentLine2[0][1:]
for i in range(len(currentLine)):
if syllables(currentLine[i]) == sylco(currentLine[i]) and syllables(currentLine2[i]) == sylco(currentLine2[i]):
numSyllables += syllables(currentLine[i])
numSyllables2 += syllables(currentLine2[i])
if numSyllables == 10 and numSyllables2 == 10:
lst.append(" ". join(currentLine))
lst2.append(" ". join(currentLine2))
count += 1
assert(len(lst) == 7)
print(lst[0])
print(lst[1])
print(lst2[0])
print(lst2[1])
print(lst[2])
print(lst[3])
print(lst2[2])
print(lst2[3])
print(lst[4])
print(lst[5])
print(lst2[4])
print(lst2[5])
print(lst[6])
print(lst2[6])
| [
"lileynuk@gmail.com"
] | lileynuk@gmail.com |
9770331cc4ed8b9caba652786a87ec8aced75466 | e94c7bd97d8b8b3b2945d357521bd346e66d5d75 | /test/lmp/script/gen_txt/test_signature.py | 1a75301a671acbdfbd9ac9ea870cb204b57d9bc1 | [
"Beerware"
] | permissive | ProFatXuanAll/language-model-playground | 4d34eacdc9536c57746d6325d71ebad0d329080e | ec4442a0cee988a4412fb90b757c87749b70282b | refs/heads/main | 2023-02-19T16:21:06.926421 | 2022-09-25T13:35:01 | 2022-09-25T13:35:01 | 202,471,099 | 11 | 26 | NOASSERTION | 2023-02-16T06:39:40 | 2019-08-15T03:57:23 | Python | UTF-8 | Python | false | false | 1,040 | py | """Test :py:mod:`lmp.script.gen_txt` signatures."""
import argparse
import inspect
from inspect import Parameter, Signature
from typing import List
import lmp.script.gen_txt
def test_module_method() -> None:
"""Ensure module methods' signatures."""
assert hasattr(lmp.script.gen_txt, 'parse_args')
assert inspect.isfunction(lmp.script.gen_txt.parse_args)
assert inspect.signature(lmp.script.gen_txt.parse_args) == Signature(
parameters=[
Parameter(
annotation=List[str],
default=Parameter.empty,
kind=Parameter.POSITIONAL_OR_KEYWORD,
name='argv',
),
],
return_annotation=argparse.Namespace,
)
assert hasattr(lmp.script.gen_txt, 'main')
assert inspect.isfunction(lmp.script.gen_txt.main)
assert inspect.signature(lmp.script.gen_txt.main) == Signature(
parameters=[
Parameter(
annotation=List[str],
default=Parameter.empty,
kind=Parameter.POSITIONAL_OR_KEYWORD,
name='argv',
),
],
return_annotation=None,
)
| [
"ProFatXuanAll@gmail.com"
] | ProFatXuanAll@gmail.com |
fb2ac13cd6ae9f98927d9133160b287216fab5b2 | 2d7c21a793c8080a090ce8c9f05df38f6477c7c7 | /creator/referral_tokens/apps.py | 1e50dca4c827c703ff396ac486c4cdb4d6185f08 | [
"Apache-2.0"
] | permissive | kids-first/kf-api-study-creator | c40e0a8a514fd52a857e9a588635ef76d16d5bc7 | ba62b369e6464259ea92dbb9ba49876513f37fba | refs/heads/master | 2023-08-17T01:09:38.789364 | 2023-08-15T14:06:29 | 2023-08-15T14:06:29 | 149,347,812 | 3 | 0 | Apache-2.0 | 2023-09-08T15:33:40 | 2018-09-18T20:25:38 | Python | UTF-8 | Python | false | false | 104 | py | from django.apps import AppConfig
class ReferralTokensConfig(AppConfig):
name = "referral_tokens"
| [
"xzhu.fg@gmail.com"
] | xzhu.fg@gmail.com |
a66207933164a09184cfbafd8103be05a5840217 | 204833b06d6b62a66cf60c966835d0876f84432e | /Constants.py | ee09c1a8cfc4c6f068b2057c868b723727983bbc | [] | no_license | dariodematties/Dirichlet | d03a9067bcedd882f9e3421dc5a35c592da0c360 | 7a69ea351e64110b699290268379b6ef2fc86e4b | refs/heads/master | 2018-11-10T11:02:49.439077 | 2018-08-21T17:37:26 | 2018-08-21T17:37:26 | 109,689,246 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 32 | py | ENABLE_RANDOM_BEHAVIOUR = True;
| [
"dariodematties@yahoo.com.ar"
] | dariodematties@yahoo.com.ar |
e578ca55d3417235a395630d3703b4a15be034e3 | 0d16ed8dffd7b951abd66bf895c254749ed8195a | /Lab4_Data_Structure__And_Iternation/List_questions/Three_largest_Four_smallest.py | d88b064b48df1c3232635c99c3140107e8c2ceb9 | [] | no_license | sanjiv576/LabExercises | 1cfea292e5b94537722b2caca42f350ab8fc7ab8 | ef5adb4fbcff28162fe9e3e80782172b93127b33 | refs/heads/master | 2023-07-22T08:13:04.771784 | 2021-08-17T12:23:21 | 2021-08-17T12:23:21 | 372,397,796 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 275 | py | # Write a Python program to get the largest number from a list.
# Write a Python program to get the smallest number from a list.
ThreeFour = [23,11,5,12,4]
print(max(ThreeFour)) # max() gives the largest number of the list
print(min(ThreeFour)) # min() gives the smallest | [
"83968516+sanjiv576@users.noreply.github.com"
] | 83968516+sanjiv576@users.noreply.github.com |
16c9a46a2c9d733a15e6609b93e0c2dda7c13452 | 12a6a68913fa5772973af9b2b2c4c90bc0656a57 | /assignment03/mdp-simulator/ai982-mdp/utilities.py | 5ec736a82ac011e00107bc86d94110542ff535c6 | [] | no_license | homasms/AI_projects | 42b944166617f76a106edcafe7d940dd240be0b1 | c66c2e6c7e1965e6579b9ed849b7d6415c6e5e9a | refs/heads/master | 2023-06-01T05:03:27.160197 | 2021-06-10T14:28:36 | 2021-06-10T14:28:36 | 276,040,644 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,036 | py | import enum
class Actions(enum.Enum):
N = 1
W = 2
S = 3
E = 4
EXIT = 5
def initialize_world_parameters(world_type):
if world_type == 'smallWorld':
return (3, 3), {(0, 2): 1, (1, 2): -1}
if world_type == 'largeWorld':
return (10, 10), {(0, 9): 1, (1, 9): -1}
else:
raise Exception("Wrong Entry.")
def initialize_mdp_parameters(width, height, exit_locations):
v_states = [[0 for i in range(0, width)] for j in range(height)] # Current step's V*(s) grid.
pre_v_states = [[0 for i in range(0, width)] for j in range(height)] # Last step's V*(s) grid.
policy = [[Actions.N for i in range(0, width)] for j in range(height)] # Current step's policy gird.
for exit_state, exit_reward in exit_locations.items():
exit_x, exit_y = exit_state
v_states[exit_x][exit_y] = exit_reward
pre_v_states[exit_x][exit_y] = exit_reward
policy[exit_x][exit_y] = Actions.EXIT
return v_states, pre_v_states, policy
| [
"homasemsarha@yahoo.com"
] | homasemsarha@yahoo.com |
36e937ed9a02e89828503fe4075624dadcde6ed4 | bf3bc3abdb7b2660c02bc1375ba146461b188364 | /modules/loto/loto.py | 7328f3cabee6872a53226de8c3ab6bb8d672bf29 | [] | no_license | JeremyMet/matrix_bot | 39a3d942ad091f49445b5e5bcd8600175c919b8f | be76fb8276d031dc796ce3c329c871ec8854c30b | refs/heads/master | 2023-05-13T00:36:39.384341 | 2021-05-01T19:44:03 | 2021-05-01T19:44:03 | 143,750,633 | 0 | 0 | null | 2023-05-01T22:16:13 | 2018-08-06T15:49:40 | Python | UTF-8 | Python | false | false | 7,150 | py | import json;
import random;
import datetime;
from collections import namedtuple;
import os.path
import pickle
Draw_Time = namedtuple("Draw_Time", "hour minute");
class loto(object):
pt_table = {} ;
pt_table[0] = 0 ;
pt_table[1] = 1 ;
pt_table[2] = 5 ;
pt_table[3] = 75 ;
pt_table[4] = 3400 ;
pt_table[5] = 800000 ;
pt_table[6] = 10000000 ;
def __init__(self, hour=0, minute=0, scoreboard_file="./modules/loto/scoreboard_file.dic", \
dailybet_file="./modules/loto/dailybet_file.dic", log_file = "./modules/loto/log.dic", nb_numbers=49, combination_length=6):
self.scoreboard_file = scoreboard_file;
self.dailybet_file = dailybet_file;
self.log_file = log_file;
self.nb_numbers = nb_numbers;
self.combination_length = combination_length;
self.scoreboard = {} ;
self.dailybet = {} ;
# On initialise au jour précédent ; typiquement si on lance le script le 1er juin et que l'on souhaite un tirage à 22h
# on initialise "le tirage précédent" (fictif, il n'a pas eu lieu) le 31 mai à 22h ; le module loto_bot.py (le "wrapper de cette classe")
# vérifie toutes les secondes s'il y a eu 24h écoulés entre la date datetime.now() et la date du tirage précédent. Ainsi, même si l'on lance le script
# à 21h45 un premier juin, en utilisant le tirage "fictif" (celui de 31 mai à 22h), nous aurons bien à tirage à 22h, le 1er juin.
self.draw_time = Draw_Time(hour, minute);
if os.path.isfile(self.log_file):
with open(self.log_file, "rb") as pickle_file:
self.log = pickle.load(pickle_file);
else:
tmp_datetime = datetime.datetime.now();
self.log = {} ;
self.log["last_draw"] = datetime.datetime(year=tmp_datetime.year, month = tmp_datetime.month, \
day = tmp_datetime.day, hour = self.draw_time.hour, minute = self.draw_time.minute)-datetime.timedelta(days=1) ;
self.load_previous_state();
random.seed(datetime.datetime.now()); # Seed initialisation
def set_scoreboard_file(self, scoreboard_file):
self.scoreboard_file = scoreboard_file;
def set_log_file(self, log_file):
self.log_file = log_file;
def set_dailybet_file(self, dailybet_file):
self.dailybet_file = dailybet_file;
# def set_draw_time(self, hour, minute):
# self.draw_time = Draw_Time(hour, minute);
def get_draw_time(self):
return self.draw_time;
def get_log(self):
return self.log;
def load_previous_state(self):
if os.path.isfile(self.scoreboard_file):
with open(self.scoreboard_file, "rb") as pickle_file:
self.scoreboard = pickle.load(pickle_file);
if os.path.isfile(self.dailybet_file):
with open(self.dailybet_file, "rb") as pickle_file:
self.dailybet = pickle.load(pickle_file);
if os.path.isfile(self.log_file):
with open(self.log_file, "rb") as pickle_file:
self.log = pickle.load(pickle_file);
def save_current_state(self):
with open(self.scoreboard_file, "wb") as pickle_file:
pickle.dump(self.scoreboard, pickle_file);
with open(self.dailybet_file, "wb") as pickle_file:
pickle.dump(self.dailybet, pickle_file);
with open(self.log_file, "wb") as pickle_file:
pickle.dump(self.log, pickle_file);
def draw(self):
self.current_result = set();
while(len(self.current_result) < self.combination_length):
rd = random.randint(1, self.nb_numbers);
self.current_result.add(rd);
tmp_datetime = datetime.datetime.now();
self.log["last_draw"] = datetime.datetime(year=tmp_datetime.year, month = tmp_datetime.month, day = tmp_datetime.day, hour = self.draw_time.hour, minute = self.draw_time.minute) ;
#self.current_result = {1,2,3,8,33,2}; # todo remove!
def check_result(self):
self.draw(); # tirage
ret = "\U0001F3B2 Le tirage du {} est {}. \nBravo à".format(datetime.datetime.today().strftime('%d-%m-%Y'), self.current_result);
is_there_a_winner = False;
for key, value in self.dailybet.items():
tmp_nb_pt = len(self.current_result & value);
nb_pt = loto.pt_table[tmp_nb_pt];
if nb_pt > 0:
is_there_a_winner = True;
ret += "\n\t- {} avec {} point(s) ({} nombre(s) correct(s))".format(key.capitalize(), nb_pt, tmp_nb_pt)
if key in self.scoreboard.keys(): # on ajoute quand même les participants avec zero point.
self.scoreboard[key] += nb_pt;
else:
self.scoreboard[key] = nb_pt;
self.dailybet = {} ; # réinitialisation des paris ;)
if is_there_a_winner:
return ret;
else:
return "\U0001F3B2 Pas de vainqueurs aujourd'hui ({}) !\nLe tirage était le suivant : {}.".format(datetime.datetime.today().strftime('%d-%m-%Y'), self.current_result);
def bet(self, sender, proposition):
# check if proposition is well-formed
proposition = proposition.replace(" ", "");
if (proposition[0] != "(" or proposition[-1] != ")"):
return "";
proposition = proposition[1:-1];
proposition_array = proposition.split(",");
for i in proposition_array:
if not(i.isnumeric()):
return "" # On ne traite pas ce cas
if (len(proposition_array) != self.combination_length):
return "\U0001F3B2 La combinaison doit être de longueur {}.".format(self.combination_length);
proposition_array = [(int(i) if (int(i) <= self.nb_numbers) else 0) for i in proposition_array];
if (0 in proposition_array):
return "\U0001F3B2 Les valeurs doivent être comprises entre 1 et {}.".format(self.nb_numbers);
proposition_set = set(proposition_array);
if (len(proposition_set) != self.combination_length):
return "\U0001F3B2 Les propositions ne doivent pas contenir deux fois le même nombre."
# proposition is well-formed,
self.dailybet[sender] = proposition_set;
return "\U0001F3B2 La proposition {} de {} a bien été prise en compte.".format(self.dailybet[sender], sender.capitalize());
def get_dailybet(self):
ret = "\U0001F3B2 Joueurs Participants - Grille";
for key, value in self.dailybet.items():
ret = "{}\n\t- {}: {} ".format(ret, key.capitalize(), value);
return ret;
#todo mettre dans l'ordre croissant
def get_scoreboard(self):
medals_array = ["\U0001F947", "\U0001f948", "\U0001f949"] ;
ret = "\U0001F3B2 Tableau des Scores :";
cpt = 0 ;
for key_value in sorted(self.scoreboard.items(), key=lambda x: x[1], reverse=True):
ret = "{}\n\t- {}: {}".format(ret, key_value[0].capitalize(), key_value[1]);
if cpt < 3:
ret+= (" ({})".format(medals_array[cpt]));
cpt+=1;
return ret;
| [
"metairie.jeremy@gmail.com"
] | metairie.jeremy@gmail.com |
8dcb22ca5cfbfea727ccfbf086dcd7217f807a28 | e5487abf1270a8b14f003c444b199483c6d825d2 | /Code/lambda/skill_env/bin/rst2s5.py | 28d30c28e7838663dfad221a9f679ae1e398e04c | [] | no_license | tmoessing/Coin-Collector | 8828c789da2fa7a46fbfc741487d1a6dc533c7c8 | c5e9dccee6ed393c81db7350bdab89111033ac33 | refs/heads/master | 2020-11-26T01:23:03.131189 | 2019-12-18T21:02:07 | 2019-12-18T21:02:07 | 223,520,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 685 | py | #!c:\users\tmoes\appdata\local\programs\python\python36\python.exe
# $Id: rst2s5.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: Chris Liechti <cliechti@gmx.net>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing HTML slides using
the S5 template system.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates S5 (X)HTML slideshow documents from standalone '
'reStructuredText sources. ' + default_description)
publish_cmdline(writer_name='s5', description=description)
| [
"tmoessing@gmail.com"
] | tmoessing@gmail.com |
6388a2abfd90b416b71fb102e7f2bdc93ad8f6ca | 23da742e7b7fd998f499abda3d26d4a8689f681f | /split_list.py | 3b3f52e747e063226bbd99bd7574ca6f7c7cdadf | [
"Apache-2.0"
] | permissive | JustDoItGit/daily_utils | 57c25f7beb57f887d69e1244ecac518e0f357d63 | 503937f284bca021e10a11d846dfae2fcae808d8 | refs/heads/master | 2023-01-22T04:34:31.114116 | 2020-12-04T05:28:30 | 2020-12-04T05:28:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 656 | py | def split_list(ls, num):
"""
拆分list
:param ls: 带截取的列表 [0, 1, 2, 3, 4, 5, 6]
:param num: 除最后一个列表之外其他列表长度 3
:return: 所有拆分的列表 [[0, 1, 2], [3, 4, 5], [6]]
"""
a = len(ls)
if a <= num:
return [ls]
quotient = a // num # 商
remainder = a % num # 余数
res_split = []
for i in range(quotient):
res_split.append(ls[num * i: num * (i + 1)])
if remainder != 0:
res_split.append(ls[num * quotient: num * quotient + remainder])
# 方法2
# res_split = [ls[i:i + num] for i in range(0, len(ls), num)]
return res_split
| [
"noreply@github.com"
] | noreply@github.com |
68b259649181c54eea9faebc337711ab016af534 | 5c4289608693609de3d755674cba53b77cbc4c69 | /Python_Study/2课堂练习/Python基础班/06_名片管理系统/cards_main.py | 32a8e9caa251e2f2c3000e3de1f3a1e6e5ad5bcf | [
"Apache-2.0"
] | permissive | vipliujunjie/HouseCore | 95892e632f840f22715d08467d6610195d562261 | e9fa5ebc048cbede7823ac59a011a554bddf8674 | refs/heads/master | 2021-02-05T13:09:43.962224 | 2020-02-28T14:46:26 | 2020-02-28T14:46:26 | 243,783,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,298 | py | #! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
import cards_tools
# 无限循环 由用户决定什么时候退出循环
while True:
# TODO(刘俊杰) 显示功能菜单
cards_tools.show_menu()
action_str = input("请输入希望执行的操作:")
print("您选择的操作是【%s】" % action_str)
# [1,2,3] 针对名片的操作
if action_str in ["1", "2", "3"]: # 判断在指定列表内
# 新增名片
if action_str == "1":
cards_tools.new_card()
# pass
# 显示全部
if action_str == "2":
cards_tools.show_all()
# pass
# 查询名片
if action_str == "3":
cards_tools.search_card()
# pass
# pass
# 0 退出系统
elif action_str == "0":
# 如果在开发程序时,不希望立刻编写分支内部的代码
# 可以使用 pass 关键字,表示一个占位符,能够保证程序的代码结构正确!
# 程序运行时,pass 关键字不会执行任何的操作
print("\n欢迎再次使用【名片管理系统】")
break
# pass
# 输入其他内容提示用户错误
else:
print("您输入的不正确,请从新选择")
| [
"1520997065@qq.com"
] | 1520997065@qq.com |
202bff332bc7441a918f1a1ed187ec533a4b32cf | 04bae28a2eefc1db77097a94af558d3df6a1e713 | /20191009/Deblur_GAN/deblurgan/losses.py | c5c6dfc84d0af0c2ed18a1f853911c052d194acb | [] | no_license | Armida220/DIPHomeWork | 8fc56df852fdedf26ef852ca2cc62f7be4067005 | 1753c1ad9783aba8a5402c98421d1126d5081aaf | refs/heads/master | 2020-11-26T06:10:24.752413 | 2019-10-31T08:11:08 | 2019-10-31T08:11:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,208 | py | import keras.backend as K
from keras.applications.vgg16 import VGG16
from keras.models import Model
import numpy as np
# Note the image_shape must be multiple of patch_shape
# image_shape = (256, 256, 3)
image_shape = (1024, 1024, 3)
def l1_loss(y_true, y_pred):
return K.mean(K.abs(y_pred - y_true))
def perceptual_loss_100(y_true, y_pred):
return 100 * perceptual_loss(y_true, y_pred)
def perceptual_loss(y_true, y_pred):
vgg = VGG16(include_top=False, weights='imagenet', input_shape=image_shape)
loss_model = Model(inputs=vgg.input, outputs=vgg.get_layer('block3_conv3').output)
loss_model.trainable = False
return K.mean(K.square(loss_model(y_true) - loss_model(y_pred)))
def wasserstein_loss(y_true, y_pred):
return K.mean(y_true*y_pred)
def gradient_penalty_loss(self, y_true, y_pred, averaged_samples):
gradients = K.gradients(y_pred, averaged_samples)[0]
gradients_sqr = K.square(gradients)
gradients_sqr_sum = K.sum(gradients_sqr,
axis=np.arange(1, len(gradients_sqr.shape)))
gradient_l2_norm = K.sqrt(gradients_sqr_sum)
gradient_penalty = K.square(1 - gradient_l2_norm)
return K.mean(gradient_penalty)
| [
"754037927@qq.com"
] | 754037927@qq.com |
468ec6b362681d9a3018b5f0182ef31622ef30b1 | 1b0a729f6e20c542a6370785a49c181c0675e334 | /main.py | 35fb3f77ad0ea393411e9e0c57d85315d85bd310 | [] | no_license | fans656/mint-dev | 68125c4b41ab64b20d54a2b19e8bf0179dc4636b | 408f6f055670b15a3f3ee9c9ec086b1090cce372 | refs/heads/master | 2021-05-04T11:43:44.740116 | 2016-09-07T13:43:44 | 2016-09-07T13:43:44 | 45,515,119 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 239 | py | from mint import *
from mint.protocols.test import Retransmit
a, b, c = Host(), Host(), Host()
s = Switch()
link(a, s.tips[0], 1)
link(b, s.tips[1], 2)
#link(c, s.tips[2], 3)
a += Retransmit()
a.send('hi')
#b.send('me').at(5)
start()
| [
"fans656@yahoo.com"
] | fans656@yahoo.com |
1ad67f537ad7c367ceee20cd2b88f9124ff2566a | 6971681df75216216f4b0a196b49077361ed6829 | /src/olympia/migrations/335-perms-locales.py | 6e210baccd4f36e7d0b22701cea1f573819fb9dc | [
"CC-BY-3.0",
"CC-BY-NC-4.0",
"CC-BY-4.0",
"CC-BY-ND-3.0",
"CC-BY-NC-ND-3.0",
"CC-BY-SA-3.0",
"CC-BY-NC-3.0",
"CC-BY-NC-ND-4.0",
"CC-BY-NC-SA-3.0"
] | permissive | piyushmittal25/addons-server | fb6eafc2c1239608c435e3afc7a6bd3db3e38e77 | 1527d1542f0e025940b7b370bf98350869737e2f | refs/heads/master | 2020-03-18T21:44:06.420678 | 2018-05-29T11:08:31 | 2018-05-29T11:08:31 | 130,405,465 | 0 | 0 | BSD-3-Clause | 2018-04-23T10:56:40 | 2018-04-20T19:29:28 | Python | UTF-8 | Python | false | false | 1,140 | py | from django.conf import settings
from access.models import Group, GroupUser
LANGS = sorted(list(
set(settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES) -
set(['en-US'])))
def run():
Group.objects.create(pk=50006, name='Senior Localizers',
rules='Locales:Edit')
for idx, locale in enumerate(LANGS):
pk = 50007 + idx
name = '%s Localizers' % locale
rules = 'Locale.%s:Edit,L10nTools:View' % locale
group = Group.objects.create(pk=pk, name=name, rules=rules)
print 'New group created: (%d) %s' % (pk, name)
try:
old_group = Group.objects.get(pk__lt=50000, name=name)
except Group.DoesNotExist:
print 'Old group not found: %s' % name
continue
# Rename old groups so they are distinguisable.
old_group.update(name=old_group.name + ' (OLD)')
# Migrate users to new group.
cnt = 0
for user in old_group.users.all():
cnt += 1
GroupUser.objects.create(group=group, user=user)
print 'Migrated %d users to new group (%s)' % (cnt, name)
| [
"chudson@mozilla.com"
] | chudson@mozilla.com |
dc2c1061b024a7d9902210c6ee216bf9908e7be1 | 1511bc3e1dac288855e0757f199e5f505afb8e6c | /Senior(2018-2019)/Python/Chapter 4/P4.3-B.py | 42a71b3597b3d64dcf32077b45bf2392ed09c958 | [] | no_license | jakelorah/highschoolprojects | a629fa36cc662c908371ad800b53bbdb2cc8390f | dfe8eec9894338933ce4eb46f180d7eeadd7e4d3 | refs/heads/main | 2023-02-26T03:01:55.570156 | 2021-01-31T19:05:41 | 2021-01-31T19:05:41 | 308,147,867 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 267 | py | #Name: Jake Lorah
#Date: 10/18/2018
#Program Number: P4.3-B
#Program Description: This program prints every second letter of the string.
#B:
string = input("Please enter a string: ")
n = len(string)
for n in range (1, n, 2) :
print(string [n])
| [
"jlorah@highpoint.edu"
] | jlorah@highpoint.edu |
42e1c516f36f4fbc2863cfbb85713138553946f4 | e62ade72c9808b806a523a73908fa1032b10f9fc | /AlgorithmPrograms/InsertionSort.py | 42bdf35e24078997b64c895332640f2b507087c1 | [] | no_license | manjumugali/Python_Programs | 40b0b77586cc20d1f77b6035cdc67f62b5e9955e | 06934cb8037594dd4269f8c2fee3d301c27f624f | refs/heads/master | 2020-04-17T06:54:55.571579 | 2019-02-13T04:37:25 | 2019-02-13T04:37:25 | 166,344,863 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 981 | py | """
******************************************************************************
* Purpose: Reads in strings from standard input and prints them in sorted order.Uses insertion sort.
*
* @author: Manjunath Mugali
* @version: 3.7
* @since: 16-01-2019
*
******************************************************************************
"""
import re
from Utility import UtilityTest
c1 = UtilityTest.TestFunctional()
class InsertionSort:
try:
print("Enter The String")
str1 = input() # read The String
onlystr = re.sub('[^A-Za-z]+', ' ', str1) # Remove The All Special Characters
word = onlystr.split() # It splits the Given Sentence into Words(by Space)
print("Before Sorting:")
print(word)
print("After Sorting:")
sort = c1.insertionSort(word) # Invoking function it takes One arguments As list
print(sort)
except ValueError:
print("...........oops Something Went Wrong.........") | [
"manjumugali111@gmail.com"
] | manjumugali111@gmail.com |
6557c40afa926f83bc0721834c9ee2d158e8fd46 | 0d0988d2afeba6539ab3802f0cac9a25ff862076 | /metodosConjuntosSTR.py | f42cea1cbd2300014f65169bbb193579f1ddd1e4 | [] | no_license | alexisflores99/Repo-for-Python | a5e967c17c0938dc5a8e91db2a6ea7302e2cd109 | d4339edcee3d2b1f57129df8059eb32c41ce4864 | refs/heads/master | 2023-04-18T18:43:06.864806 | 2021-05-02T04:05:41 | 2021-05-02T04:05:41 | 363,562,129 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 480 | py | # set_conjunto1 = set({1,2,3,4})
# set_conjunto1.add(5)
# print(set_conjunto1)
#************************************
# set_conjunto = set({1.0, "Auto", True})
# otro_conjunto = set_conjunto.copy()
# set_conjunto == otro_conjunto
# print(otro_conjunto)
#************************************
# paquete = set({"Hola",2 ,3 ,4 })
# paquete.discard("Hola")
# print(paquete)
#************************************
paquete = set({"Hola" ,2, 3, 4})
paquete.remove("Hola")
print(paquete)
| [
"hector.flores6@unmsm.edu.pe"
] | hector.flores6@unmsm.edu.pe |
6affbb678c0509cdb3dd5674c2edb67dd98dcb75 | e53d920751b86ae09a16913c7531a806c334265f | /mmdet3d/ops/furthest_point_sample/points_sampler.py | 9a3bd2ae42d625cc19355492246d4967a8e96b92 | [
"Apache-2.0"
] | permissive | destinyls/mmdetection3d | e959e4a1a9316b385cec73a654bc8a016cb43a02 | f2247c2471dbb429512353b3f0802f839655dd16 | refs/heads/master | 2023-03-20T21:12:32.105859 | 2023-01-24T01:45:12 | 2023-01-24T01:45:12 | 279,744,471 | 1 | 1 | Apache-2.0 | 2020-07-15T02:42:54 | 2020-07-15T02:42:53 | null | UTF-8 | Python | false | false | 5,373 | py | import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
from .utils import calc_square_dist
def get_sampler_type(sampler_type):
"""Get the type and mode of points sampler.
Args:
sampler_type (str): The type of points sampler.
The valid value are "D-FPS", "F-FPS", or "FS".
Returns:
class: Points sampler type.
"""
if sampler_type == 'D-FPS':
sampler = DFPS_Sampler
elif sampler_type == 'F-FPS':
sampler = FFPS_Sampler
elif sampler_type == 'FS':
sampler = FS_Sampler
else:
raise ValueError('Only "sampler_type" of "D-FPS", "F-FPS", or "FS"'
f' are supported, got {sampler_type}')
return sampler
class Points_Sampler(nn.Module):
"""Points sampling.
Args:
num_point (list[int]): Number of sample points.
fps_mod_list (list[str]: Type of FPS method, valid mod
['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS'].
F-FPS: using feature distances for FPS.
D-FPS: using Euclidean distances of points for FPS.
FS: using F-FPS and D-FPS simultaneously.
fps_sample_range_list (list[int]): Range of points to apply FPS.
Default: [-1].
"""
def __init__(self,
num_point: List[int],
fps_mod_list: List[str] = ['D-FPS'],
fps_sample_range_list: List[int] = [-1]):
super(Points_Sampler, self).__init__()
# FPS would be applied to different fps_mod in the list,
# so the length of the num_point should be equal to
# fps_mod_list and fps_sample_range_list.
assert len(num_point) == len(fps_mod_list) == len(
fps_sample_range_list)
self.num_point = num_point
self.fps_sample_range_list = fps_sample_range_list
self.samplers = nn.ModuleList()
for fps_mod in fps_mod_list:
self.samplers.append(get_sampler_type(fps_mod)())
self.fp16_enabled = False
@force_fp32()
def forward(self, points_xyz, features):
"""forward.
Args:
points_xyz (Tensor): (B, N, 3) xyz coordinates of the features.
features (Tensor): (B, C, N) Descriptors of the features.
Return:
Tensor: (B, npoint, sample_num) Indices of sampled points.
"""
indices = []
last_fps_end_index = 0
for fps_sample_range, sampler, npoint in zip(
self.fps_sample_range_list, self.samplers, self.num_point):
assert fps_sample_range < points_xyz.shape[1]
if fps_sample_range == -1:
sample_points_xyz = points_xyz[:, last_fps_end_index:]
sample_features = features[:, :, last_fps_end_index:] if \
features is not None else None
else:
sample_points_xyz = \
points_xyz[:, last_fps_end_index:fps_sample_range]
sample_features = \
features[:, :, last_fps_end_index:fps_sample_range] if \
features is not None else None
fps_idx = sampler(sample_points_xyz.contiguous(), sample_features,
npoint)
indices.append(fps_idx + last_fps_end_index)
last_fps_end_index += fps_sample_range
indices = torch.cat(indices, dim=1)
return indices
class DFPS_Sampler(nn.Module):
"""DFPS_Sampling.
Using Euclidean distances of points for FPS.
"""
def __init__(self):
super(DFPS_Sampler, self).__init__()
def forward(self, points, features, npoint):
"""Sampling points with D-FPS."""
fps_idx = furthest_point_sample(points.contiguous(), npoint)
return fps_idx
class FFPS_Sampler(nn.Module):
"""FFPS_Sampler.
Using feature distances for FPS.
"""
def __init__(self):
super(FFPS_Sampler, self).__init__()
def forward(self, points, features, npoint):
"""Sampling points with F-FPS."""
assert features is not None, \
'feature input to FFPS_Sampler should not be None'
features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2)
features_dist = calc_square_dist(
features_for_fps, features_for_fps, norm=False)
fps_idx = furthest_point_sample_with_dist(features_dist, npoint)
return fps_idx
class FS_Sampler(nn.Module):
"""FS_Sampling.
Using F-FPS and D-FPS simultaneously.
"""
def __init__(self):
super(FS_Sampler, self).__init__()
def forward(self, points, features, npoint):
"""Sampling points with FS_Sampling."""
assert features is not None, \
'feature input to FS_Sampler should not be None'
features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2)
features_dist = calc_square_dist(
features_for_fps, features_for_fps, norm=False)
fps_idx_ffps = furthest_point_sample_with_dist(features_dist, npoint)
fps_idx_dfps = furthest_point_sample(points, npoint)
fps_idx = torch.cat([fps_idx_ffps, fps_idx_dfps], dim=1)
return fps_idx
| [
"noreply@github.com"
] | noreply@github.com |
9e6666d6b99be4eaa286ee65de5946bc52dde225 | d7016f69993570a1c55974582cda899ff70907ec | /sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_managed_instance_vulnerability_assessments_operations.py | b81f57346b44a5fb1b5e3a63d654f6f168e9144d | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | kurtzeborn/azure-sdk-for-python | 51ca636ad26ca51bc0c9e6865332781787e6f882 | b23e71b289c71f179b9cf9b8c75b1922833a542a | refs/heads/main | 2023-03-21T14:19:50.299852 | 2023-02-15T13:30:47 | 2023-02-15T13:30:47 | 157,927,277 | 0 | 0 | MIT | 2022-07-19T08:05:23 | 2018-11-16T22:15:30 | Python | UTF-8 | Python | false | false | 21,802 | py | # pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import sys
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._managed_instance_vulnerability_assessments_operations import (
build_create_or_update_request,
build_delete_request,
build_get_request,
build_list_by_instance_request,
)
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class ManagedInstanceVulnerabilityAssessmentsOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.sql.aio.SqlManagementClient`'s
:attr:`managed_instance_vulnerability_assessments` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace_async
async def get(
self,
resource_group_name: str,
managed_instance_name: str,
vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName],
**kwargs: Any
) -> _models.ManagedInstanceVulnerabilityAssessment:
"""Gets the managed instance's vulnerability assessment.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessment is defined. Required.
:type managed_instance_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceVulnerabilityAssessment or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2020-11-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2020-11-01-preview")
)
cls: ClsType[_models.ManagedInstanceVulnerabilityAssessment] = kwargs.pop("cls", None)
request = build_get_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
vulnerability_assessment_name=vulnerability_assessment_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}"
}
@overload
async def create_or_update(
self,
resource_group_name: str,
managed_instance_name: str,
vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName],
parameters: _models.ManagedInstanceVulnerabilityAssessment,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ManagedInstanceVulnerabilityAssessment:
"""Creates or updates the managed instance's vulnerability assessment. Learn more about setting
SQL vulnerability assessment with managed identity -
https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessment is defined. Required.
:type managed_instance_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param parameters: The requested resource. Required.
:type parameters: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceVulnerabilityAssessment or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def create_or_update(
self,
resource_group_name: str,
managed_instance_name: str,
vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName],
parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> _models.ManagedInstanceVulnerabilityAssessment:
"""Creates or updates the managed instance's vulnerability assessment. Learn more about setting
SQL vulnerability assessment with managed identity -
https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessment is defined. Required.
:type managed_instance_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param parameters: The requested resource. Required.
:type parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceVulnerabilityAssessment or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def create_or_update(
self,
resource_group_name: str,
managed_instance_name: str,
vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName],
parameters: Union[_models.ManagedInstanceVulnerabilityAssessment, IO],
**kwargs: Any
) -> _models.ManagedInstanceVulnerabilityAssessment:
"""Creates or updates the managed instance's vulnerability assessment. Learn more about setting
SQL vulnerability assessment with managed identity -
https://docs.microsoft.com/azure/azure-sql/database/sql-database-vulnerability-assessment-storage.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessment is defined. Required.
:type managed_instance_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param parameters: The requested resource. Is either a model type or a IO type. Required.
:type parameters: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ManagedInstanceVulnerabilityAssessment or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2020-11-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2020-11-01-preview")
)
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ManagedInstanceVulnerabilityAssessment] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(parameters, (IO, bytes)):
_content = parameters
else:
_json = self._serialize.body(parameters, "ManagedInstanceVulnerabilityAssessment")
request = build_create_or_update_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
vulnerability_assessment_name=vulnerability_assessment_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self.create_or_update.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessment", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
return deserialized # type: ignore
create_or_update.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}"
}
@distributed_trace_async
async def delete( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
managed_instance_name: str,
vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName],
**kwargs: Any
) -> None:
"""Removes the managed instance's vulnerability assessment.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessment is defined. Required.
:type managed_instance_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None or the result of cls(response)
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2020-11-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2020-11-01-preview")
)
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
vulnerability_assessment_name=vulnerability_assessment_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.delete.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}"
}
@distributed_trace
def list_by_instance(
self, resource_group_name: str, managed_instance_name: str, **kwargs: Any
) -> AsyncIterable["_models.ManagedInstanceVulnerabilityAssessment"]:
"""Gets the managed instance's vulnerability assessment policies.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param managed_instance_name: The name of the managed instance for which the vulnerability
assessments is defined. Required.
:type managed_instance_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ManagedInstanceVulnerabilityAssessment or the
result of cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.ManagedInstanceVulnerabilityAssessment]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2020-11-01-preview"] = kwargs.pop(
"api_version", _params.pop("api-version", "2020-11-01-preview")
)
cls: ClsType[_models.ManagedInstanceVulnerabilityAssessmentListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_instance_request(
resource_group_name=resource_group_name,
managed_instance_name=managed_instance_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_instance.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = HttpRequest("GET", next_link)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ManagedInstanceVulnerabilityAssessmentListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_instance.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/vulnerabilityAssessments"
}
| [
"noreply@github.com"
] | noreply@github.com |
78f30f4848d93d075ba4bebcbc215dde6d0351fd | f777be3ca7cfe3c4ac24a1f962ea4c4d4e0aada3 | /testing.py | b672b936e7b0c0fe9bbfe3fdaf65b82198dabdb3 | [] | no_license | rogelio08/text_based_story | ab7419865b34c6c1b47f87fc768a02eddcc5c2ea | e7c646335ead1cf552e382dff3025157b4540ecf | refs/heads/master | 2023-07-02T03:49:46.080875 | 2021-08-08T05:07:09 | 2021-08-08T05:07:09 | 393,861,497 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,411 | py | import sys
import time
#I changed this
a = 2
b = 0.2 # slower time between characters getting spaced out
c = 0.08 # quicker time between characters getting printed
def intro():
print("\n")
time.sleep(a)
string_1 = '"Very well, remember to answer truthfully... Or don\'t, either way you\'ll provide valuable data"\n'
for character in string_1:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print("With that the voice leaves you and the lights turn off for a moment\nWhen they turn on again you find a table has appeared")
time.sleep(a)
print("On the table you see a key on end of the table and a hammer on the other\nThe voice chimes in again")
s = '"Please choose the item that has most value to you..."\n'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print()
first_path = input("which item do you pick? (key = 1 / hammer = 2): ")
if first_path == '1':
print()
path1()
elif first_path == '2':
print()
path2()
else:
print("Unknown path detected")
def path1():
time.sleep(a)
print("\nDespite how strange and unnerving the situation is, you decided that perhaps the key might be important for something down the line.")
time.sleep(a)
print("You rationalize that there has to be some kind of logic as to why you're here and what's the meaning behind all this.")
time.sleep(a)
print("After picking up the key the lights turn off and the voice speaks up.")
s = '"Interesting choice, you have no idea where you are or if that key even fits anywhere yet you still chose it?"'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
s2 = '"Let us find out whether your choice will be the key to freedom or the key to your death."'
for character in s2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(b)
time.sleep(1)
print()
print("When the lights turn on again the table is gone, but now the room includes two doors.\n")
time.sleep(a)
print("The first door appears to have seen better days, mots of its color has faded while several cracks could be seen in the wood.")
time.sleep(a)
print("The second door leaves you stunned, you recognize the door as the same one on the front of your home!")
door_choice = input("\nWhich door do you use the key on? (1/2): ")
if door_choice == "1":
print()
path1_1()
elif door_choice == '2':
print()
path1_2()
def path1_1():
print("\nWhile the familiar door is calling out to you, you realize that such an obvious choice must be a trap. So going against all your instincts for survival you hesitantely unlock the worn down door and head inside.")
time.sleep(a)
print("After exiting the concrete prison you find yourself somewhere damp, dark, and cold. Using your hands to feel around you deduce that you must be in some sort of cave.")
time.sleep(a)
print("Realizing that the door is no longer behind you and left with no other options you decide to feel your way to what is hopefully an exit.")
time.sleep(a)
print("After wandering around in the dark you notice small beams of light that eventually lead to an opening in the cave, and before you know you're outside in a forest.")
time.sleep(a)
print("Out in the distance you notice smoke from a what could be a campfire but at the same time you have no idea if you've actually escaped or not.")
time.sleep(a)
print("Armed with the determination to survive, you venture towards the smoke.")
def path1_2():
print("\nNot wanting to spend another moment in the room you rush over to the familiar door and check to see if they key works.")
time.sleep(a)
print("By some miracle the key fits and you're able to open the door\nRushing through the door you find yourself in your own living room, and breathing a sigh of relief.")
time.sleep(a)
print("Things however, are not as they seem. You begin to notice that your home is eerily quiet, with no traces of your family anywhere.")
time.sleep(a)
print("As you search through your home your fears and only confirmed, none of your family members are anywhere!\nDesperate for answers you go back through the front door but are shocked by the result.")
time.sleep(a)
print("Instead of making it back to the isolated room your find yourself in your neighborhood, only there's no neighbors in sight. Moreover the normally busy interstate freeway you live next to is unusually quiet.")
time.sleep(a)
print("While trying to process what's happening you realize that if the door was in fact the one to your home how did they key you picked up unlock it if you've never seen a key like it?")
time.sleep(a)
print("Trying to remain optimistic, you figure there has to be someone around. And so you you go off in search of survivors that don't exist, forever wandering the hollow shell of the world you once knew.")
def path2():
time.sleep(a)
print("\nGiven the situation you're in, you can't rule out the possibility that this is all some kind of twisted game. Thus you reason that it's in your best interest to have some kind of weapon.")
time.sleep(a)
print("Besides, who knows if the key is meant to throw you off from choosing a multi-purpose tool? Not to mention you could theoretically open any lock using the hammer if you're smart about it.")
time.sleep(a)
print("Feeling satisfied you pick up the hammer, soon after the lights turn off and the voice could be heard again.\n")
s = '"What an interesting choice, while it\'s clever to be cautious in your position choosing what could be considered a weapon does seem rather barbaric. Though that\'s nothing new to humans."'
for character in s:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
s2 = '"You made a bold choice, let\'s find out whether you have the dexterity to justify such an option."'
for character in s2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(c)
time.sleep(1)
print()
print("Soon the lights turn on and you notice the table and key is gone but you're not interested in that. What has your attention now is the 500 pound apex preadator that occupies the room with.")
time.sleep(a)
print("With a low growl, the spontaneous bear is sizng you up. It's at this moment when your adrenaline kicks in and you're given a few breif seconds to form a plan of attack.")
time.sleep(a)
print("You narrow down to your options to two choices: 1) Use your adrenaline to take on the bear in a battle to the death or 2) Throw the hammer towards the one lightbulb in the room and use the darkness to hide and wait it out.")
bear_choice = input("\nHow do you go about dealing with the bear? (1/2): ")
if bear_choice == '1':
print()
path2_1()
else:
print()
path2_2()
def path2_1():
print("\nDespite feeling panicked and afraid for your life you decide to muster up all the courage you have and challenge the bear for the right to live.")
time.sleep(a)
print("With a war cry you rush the bear ad the bear responds with a roar of its own and stands on two feet in order to strike you down.")
time.sleep(a)
print("Seeing this you fling yourself to the right in order to dodge the potentially fatal blow and as the bear crashes its paws down and turns to face you, you get in a lucky swing and manage to strike the bear near it's eye.")
time.sleep(a)
print("With a roar of pain the bear backs off. You can't believe it, you just might be able to pull this off! Is what you were thinking before you realized that you didn't completely dodge the first attack.")
time.sleep(a)
print("Looking down you realize you see an unsightly slash on the left side of your abdomen and while attempting to stop the bleeding the last of your adrenaline fades as the bear recovers.")
time.sleep(a)
print("Your last thoughts as you see the bear closing in for the finishing move were about how people who don't consider bears as apex predators have never fought one.")
def path2_2():
print("\nUnderstanding the fact that under the laws of nature no human could ever beat a grown bear with just a hammer in an enclosed space you decide to use your higher level intelligence to your advantage.")
time.sleep(a)
print("As the bear prepares to attack your quickly throw your hammer at the dim lightbulb hanging from the ceiling, shattering it and engulfing the room in darkness.")
time.sleep(a)
print("At first your gamble seems to pay off as the bear's roars turn from aggressive to confused at the lack of vision.\nAs you hide in the corner of the now dark room a terrifying thought hits you.")
time.sleep(a)
print("Not only are you in a small room but bears don't exactly have to rely on sight alone. Sure enough, the bear begins to compose itself and soon begins sniffing the air.")
time.sleep(a)
print("You could only cower in horror and wait for your inevitable death as you curse your own lack of foresight")
print()
print()
print(" #######################")
print(" # #")
print(" # Title Card #")
print(" # #")
print(" #######################")
print()
print()
time.sleep(a)
print("You find yourself in a dim, concrete room with only a single lightbulb hanging from the ceiling")
time.sleep(a)
print("Before you are able to asses your surroundings a monotone voice could be heard")
time.sleep(a)
print()
start_game = input("Would you like to start the game? (Y/N): ")
if start_game == 'n' or start_game == 'N':
print("Understood, subject #[REDACTED] does not wish to participate in the experiment. Bringing in the next subject...")
elif start_game == 'y' or start_game == 'Y':
intro()
else:
print("Answer does not compute, try again") | [
"noreply@github.com"
] | noreply@github.com |
2f42da8393cd536ef56b1a0bef15efe947177b66 | d83118503614bb83ad8edb72dda7f449a1226f8b | /src/dprj/platinumegg/app/cabaret/views/mgr/model_edit/trade_shop.py | d402834b28b5ad1f8056bc5d4ec9eec808d29ae6 | [] | no_license | hitandaway100/caba | 686fe4390e182e158cd9714c90024a082deb8c69 | 492bf477ac00c380f2b2758c86b46aa7e58bbad9 | refs/heads/master | 2021-08-23T05:59:28.910129 | 2017-12-03T19:03:15 | 2017-12-03T19:03:15 | 112,512,044 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,156 | py | # -*- coding: utf-8 -*-
from platinumegg.app.cabaret.views.mgr.model_edit import AdminModelEditHandler,\
AppModelForm, ModelEditValidError, AppModelChoiceField
from defines import Defines
from platinumegg.app.cabaret.util.api import BackendApi
from platinumegg.app.cabaret.models.TradeShop import TradeShopMaster, TradeShopItemMaster
from platinumegg.app.cabaret.models.Schedule import ScheduleMaster
class Handler(AdminModelEditHandler):
"""マスターデータの操作.
"""
class Form(AppModelForm):
class Meta:
model = TradeShopMaster
exclude = (
Defines.MASTER_EDITTIME_COLUMN,
)
schedule = AppModelChoiceField(ScheduleMaster, required=False, label=u'期間')
def setting_property(self):
self.MODEL_LABEL = u'トレードショップ'
def valid_insert(self, master):
self.__valid_master(master)
def valid_update(self, master):
self.__valid_master(master)
def __valid_master(self, master):
model_mgr = self.getModelMgr()
self.__check_schedule(model_mgr, master)
self.__check_trade_shop_item_masetr_ids(model_mgr, master)
model_mgr.write_all()
def __check_schedule(self, model_mgr, master):
model = model_mgr.get_model(ScheduleMaster, master.schedule)
if model is None:
raise ModelEditValidError(u'スケジュールに、存在しないIDが指定されています.id=%d' % master.id)
def __check_trade_shop_item_masetr_ids(self, model_mgr, master):
if not isinstance(master.trade_shop_item_master_ids, (list)):
raise ModelEditValidError(u'trade_shop_item_master_idsのJsonが壊れています.id=%d' % master.id)
for trade_shop_item_master_id in master.trade_shop_item_master_ids:
model = model_mgr.get_model(TradeShopItemMaster, trade_shop_item_master_id)
if model is None:
raise ModelEditValidError(u'trade_shop_item_master_idsで指定されているidがTradeShopItemMasterに存在しません.id=%d' % master.id)
def main(request):
return Handler.run(request) | [
"shangye@mail.com"
] | shangye@mail.com |
ace388a41b74682d643ef7c6c7176d8cf1f6b831 | 3a5d8cdc7ac14c389fd9426f3f39c3b1dc906dda | /nautobot/extras/tests/test_jobs.py | e04668889b1dffc9a3853d2e190027a5f793514f | [
"Apache-2.0"
] | permissive | nammie-punshine/nautobot | f3cdb9d269c37a74706c105d237b883650f10465 | d6227b211ad89f25233a8791937cd75092421c8a | refs/heads/main | 2023-03-08T10:51:29.437859 | 2021-02-24T20:44:32 | 2021-02-24T20:44:32 | 342,080,836 | 0 | 0 | Apache-2.0 | 2021-02-25T01:01:36 | 2021-02-25T01:01:36 | null | UTF-8 | Python | false | false | 1,970 | py | import os
import uuid
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from nautobot.extras.choices import JobResultStatusChoices
from nautobot.extras.jobs import get_job, run_job
from nautobot.extras.models import JobResult
from nautobot.utilities.testing import TestCase
class JobTest(TestCase):
"""
Test basic jobs to ensure importing works.
"""
def test_job_pass(self):
"""
Job test with pass result.
"""
with self.settings(JOBS_ROOT=os.path.join(settings.BASE_DIR, "extras/tests/dummy_jobs")):
module = "test_pass"
name = "TestPass"
job_class = get_job(f"local/{module}/{name}")
job_content_type = ContentType.objects.get(app_label="extras", model="job")
job_result = JobResult.objects.create(
name=job_class.class_path,
obj_type=job_content_type,
user=None,
job_id=uuid.uuid4(),
)
run_job(data={}, request=None, commit=False, job_result=job_result)
self.assertEqual(job_result.status, JobResultStatusChoices.STATUS_COMPLETED)
def test_job_fail(self):
"""
Job test with fail result.
"""
with self.settings(JOBS_ROOT=os.path.join(settings.BASE_DIR, "extras/tests/dummy_jobs")):
module = "test_fail"
name = "TestFail"
job_class = get_job(f"local/{module}/{name}")
job_content_type = ContentType.objects.get(app_label="extras", model="job")
job_result = JobResult.objects.create(
name=job_class.class_path,
obj_type=job_content_type,
user=None,
job_id=uuid.uuid4(),
)
run_job(data={}, request=None, commit=False, job_result=job_result)
self.assertEqual(job_result.status, JobResultStatusChoices.STATUS_ERRORED)
| [
"lampwins@gmail.com"
] | lampwins@gmail.com |
40d836471602038f8e490438807b48014491d9e2 | df97d5b25d40b54e0714ed9c0a6dd7a579011e2e | /mikadocms/flikr_grabber.py | 966050a532ec3be0269d2f1bc60375d21d2ae39b | [] | no_license | mikadosoftware/mikadoCMS | 90ac1910b06f32bc3e808d1df656ba38a30e781c | 7bb1ca4f66b74d4529a601540e1bf469f44d3b01 | refs/heads/master | 2021-01-17T00:20:34.489198 | 2018-06-13T15:27:53 | 2018-06-13T15:27:53 | 8,103,422 | 0 | 0 | null | 2013-05-03T23:07:59 | 2013-02-08T23:27:27 | JavaScript | UTF-8 | Python | false | false | 2,740 | py | #!/usr/bin/env python
#! -*- coding: utf-8 -*-
### Copyright Paul Brian 2013
# This program is licensed, without under the terms of the
# GNU General Public License version 2 (or later). Please see
# LICENSE.txt for details
###
"""
:author: paul@mikadosoftware.com <Paul Brian>
Flikr.com provides a useful outlet for using photographs on
a website with minimal cost, and importantly, fuss.
1. visit http://www.flickr.com/search/advanced/
Search for a photo (by tag / text) but click "creative commons"
and "commercial" use.
2. Find the right photo URL
3. run ``python flickr_grabber.py <URL>``
4. I will grab the page and make a best guess as to the original photo
URL
5.
"""
import requests
from bs4 import BeautifulSoup
import sys
from bookmaker import lib
import conf
from optparse import OptionParser
import logging
import webbrowser
import urllib
import os
class myError(Exception):
pass
#########
PHOTO_STORE = "./photos"
testurl = "http://www.flickr.com/photos/comedynose/4230176889/"
def extract_photo_url(url):
r = requests.get(url)
soup = BeautifulSoup(r.text)
likelicandidate = soup.find(property='og:image')
resultstr = """
From page %s
We have likely candidate of
%s
or these:
"""
resultstr = resultstr % (url, str(likelicandidate))
for imgtag in soup.find_all("img"):
resultstr += str(imgtag)
return (likelicandidate, resultstr)
def get_photo(url):
"""
"""
tgt = os.path.join(PHOTO_STORE, os.path.basename(url))
urllib.urlretrieve(url, tgt)
#########
def parse_args():
parser = OptionParser()
parser.add_option("--config", dest="confpath",
help="path to ini file")
parser.add_option("--flikrpage", dest="flikrpage",
help="url to embedded photo")
parser.add_option("--flikrphoto", dest="flikrphoto",
help="url to stadnalone photo (mutually xlusive with glikrpage")
(options, args) = parser.parse_args()
return (options, args)
def main(opts, args):
"""
"""
if opts.confpath:
confd = conf.get_config(opts.confpath)
lgr.debug(pprint.pformat(confd))
else:
confd = {}
if opts.flikrpage:
likelicandidate, resultstr = extract_photo_url(opts.flikrpage)
print likelicandidate
print resultstr
if opts.flikrphoto:
get_photo(opts.flikrphoto)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
opts, args = parse_args()
try:
main(opts, args)
except Exception, e:
print "We can trap a lot up here"
raise e
| [
"paul@mikadosoftware.com"
] | paul@mikadosoftware.com |
5accaca4d79de6e89aeddb67971165259bec460b | 7a866c210bba93fa33e02305e221338541d6ec9b | /Direction JOL/Timed JOL/Output/Merged/EX2_conf_plots.py | 912af24af1f000dedf77b86d611584c4bba457a1 | [] | no_license | npm27/Spring-2019-Projects | afbb6d3816e097b58f7d5032bc8d7563536a232a | 52e0c1c4dc3de2e0399e5391dd2c8aff56754c1c | refs/heads/master | 2021-12-20T01:01:11.218779 | 2021-12-08T14:49:18 | 2021-12-08T14:49:18 | 168,214,407 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,075 | py | ##set up
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dat = pd.read_csv("Delayed conf.csv") #JUST NEED TO ADD DATA
dat['diff'] = dat['Upper'].sub(dat['Lower'])
dat['diff2'] = dat['diff'].div(2)
##make subsets
datF = dat[dat['Direction'] == 'F']
datB = dat[dat['Direction'] == 'B']
datS = dat[dat['Direction'] == 'S']
datU = dat[dat['Direction'] == 'U']
##set up the initial plot
fig = plt.figure()
fig.set_size_inches(11,8)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
dot_line = np.arange(100)
major_ticks = np.arange(0, 101, 20)
fig.text(0.5, 0.04, 'JOL Rating', ha='center', fontsize=18)
fig.text(0.04, 0.5, '% Correct Recall', va='center', rotation='vertical', fontsize=18)
##forward
x1 = datF.JOL_Bin.values
y1 = datF.Average.values
ax1.plot(dot_line, 'k--')
ax1.plot(x1, y1, marker = '.', color = 'k')
ax1.set_xticks(major_ticks)
ax1.set_yticks(major_ticks)
ax1.set_title("Forward", fontsize = 16)
ax1.errorbar(x1, y1, yerr=(datF['diff2']), fmt='none', c= 'k', capsize=5)
##backward
x2 = datB.JOL_Bin.values
y2 = datB.Average.values
ax2.plot(dot_line, 'k--')
ax2.plot(x2, y2, marker = '.', color = 'k')
ax2.set_xticks(major_ticks)
ax2.set_yticks(major_ticks)
ax2.set_title("Backward", fontsize = 16)
ax2.errorbar(x2, y2, yerr=(datB['diff2']), fmt='none', c= 'k', capsize=5)
##symmetrical
x3 = datS.JOL_Bin.values
y3 = datS.Average.values
ax3.plot(dot_line, 'k--')
ax3.plot(x3, y3, marker = '.', color = 'k')
ax3.set_xticks(major_ticks)
ax3.set_yticks(major_ticks)
ax3.set_title("Symmetrical", fontsize = 16)
ax3.errorbar(x3, y3, yerr=(datS['diff2']), fmt='none', c= 'k', capsize=5)
##unrelated
x4 = datU.JOL_Bin.values
y4 = datU.Average.values
ax4.plot(dot_line, 'k--')
ax4.plot(x4, y4, marker = '.', color = 'k')
ax4.set_xticks(major_ticks)
ax4.set_yticks(major_ticks)
ax4.set_title("Unrelated", fontsize = 16)
ax4.errorbar(x4, y4, yerr=(datU['diff2']), fmt='none', c= 'k', capsize=5)
##save figure
#fig.savefig('Plot2_smoothed.png')
| [
"35810320+npm27@users.noreply.github.com"
] | 35810320+npm27@users.noreply.github.com |
6316d5bbf61b883c8a1230ade79e25d1b8b68ce4 | 8b4521c046779bee7f0499d73e183851f198af14 | /server.py | b5d0f09fbb907e26b62a438d288a204612cc22b5 | [] | no_license | sugrospi/RPSLS | 80fa53a88f1531af03809716c44f10a937a125e4 | 1c50c9b3019dcc8f244f6ae2d1cba87d409bbd56 | refs/heads/master | 2023-07-24T15:21:35.423381 | 2021-09-07T15:13:47 | 2021-09-07T15:13:47 | 403,999,856 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,475 | py | import socket
from _thread import *
import pickle
from game import Game
server = "IP_ADDRESS"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for a connection, Server Started")
connected = set()
games = {}
idCount = 0
def threaded_client(conn, p, gameId):
global idCount
conn.send(str.encode(str(p)))
reply = ""
while True:
try:
data = conn.recv(4096).decode()
if gameId in games:
game = games[gameId]
if not data:
break
else:
if data == "reset":
game.resetWent()
elif data != "get":
game.play(p, data)
conn.sendall(pickle.dumps(game))
else:
break
except:
break
print("Lost connection")
try:
del games[gameId]
print("Closing Game", gameId)
except:
pass
idCount -= 1
conn.close()
while True:
conn, addr = s.accept()
print("Connected to:", addr)
idCount += 1
p = 0
gameId = (idCount - 1)//2
if idCount % 2 == 1:
games[gameId] = Game(gameId)
print("Creating a new game...")
else:
games[gameId].ready = True
p = 1
start_new_thread(threaded_client, (conn, p, gameId))
| [
"s.shaggypi@gmail.com"
] | s.shaggypi@gmail.com |
47b2fcaa1e74c97b42be077420a4335f38b24f8d | a7ff1ba9437204454c6b8639e99b007393c64118 | /synapse/tools/aha/enroll.py | a643a485268842bbc531afab92dd9b5e8bf84112 | [
"Apache-2.0"
] | permissive | vishalbelsare/synapse | 67013933db31ac71a4074b08a46b129774f63e47 | a418b1354b2f94e32644ede612c271a6c362ccae | refs/heads/master | 2023-09-01T10:45:34.439767 | 2022-05-13T21:07:20 | 2022-05-13T21:07:20 | 164,022,574 | 0 | 0 | Apache-2.0 | 2022-05-15T07:45:07 | 2019-01-03T21:01:32 | Python | UTF-8 | Python | false | false | 2,609 | py | import os
import sys
import asyncio
import argparse
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.output as s_output
import synapse.lib.certdir as s_certdir
descr = '''
Use a one-time use key to initialize your AHA user enrivonment.
Examples:
python -m synapse.tools.aha.register tcp://aha.loop.vertex.link:27272/b751e6c3e6fc2dad7a28d67e315e1874
'''
async def main(argv, outp=s_output.stdout):
pars = argparse.ArgumentParser(prog='provision', description=descr)
pars.add_argument('onceurl', help='The one-time use AHA user enrollment URL.')
opts = pars.parse_args(argv)
async with s_telepath.withTeleEnv():
certpath = s_common.getSynDir('certs')
yamlpath = s_common.getSynPath('telepath.yaml')
teleyaml = s_common.yamlload(yamlpath)
if teleyaml is None:
teleyaml = {}
teleyaml.setdefault('version', 1)
teleyaml.setdefault('aha:servers', ())
s_common.gendir(certpath)
certdir = s_certdir.CertDir(path=certpath)
async with await s_telepath.openurl(opts.onceurl) as prov:
userinfo = await prov.getUserInfo()
ahaurls = userinfo.get('aha:urls')
ahauser = userinfo.get('aha:user')
ahanetw = userinfo.get('aha:network')
username = f'{ahauser}@{ahanetw}'
capath = certdir.getCaCertPath(ahanetw)
if capath is not None:
os.path.unlink(capath)
byts = await prov.getCaCert()
capath = certdir.saveCaCertByts(byts)
outp.printf(f'Saved CA certificate: {capath}')
keypath = certdir.getUserKeyPath(username)
if keypath is not None:
os.path.unlink(keypath)
crtpath = certdir.getUserCertPath(username)
if crtpath is not None:
os.path.unlink(keypath)
xcsr = certdir.genUserCsr(username)
byts = await prov.signUserCsr(xcsr)
crtpath = certdir.saveUserCertByts(byts)
outp.printf(f'Saved user certificate: {crtpath}')
ahaurls = s_telepath.modurl(ahaurls, user=ahauser)
if ahaurls not in teleyaml.get('aha:servers'):
outp.printf('Updating known AHA servers')
servers = list(teleyaml.get('aha:servers'))
servers.append(ahaurls)
teleyaml['aha:servers'] = servers
s_common.yamlsave(teleyaml, yamlpath)
if __name__ == '__main__': # pragma: no cover
sys.exit(asyncio.run(main(sys.argv[1:])))
| [
"noreply@github.com"
] | noreply@github.com |
07ed4b9273137675fff9b21384eac1a28eb95b43 | 137524b533472fd4b2752078e0a6d7f4c0fcf2d7 | /tasksLab1/task2/TaskC.py | fcb64df58dd9a0784cd9d4db227026f85e35aa2e | [] | no_license | blazejmichal/inteligencja-obliczeniowa | 8666869c227006fdae5dc1ab3a1b549c1db91548 | 4ffef53cddd82711d559eafd5c9d47e09c0e048d | refs/heads/master | 2023-02-17T05:42:43.522395 | 2021-01-17T16:09:34 | 2021-01-17T16:09:34 | 319,463,135 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 595 | py | import matplotlib.pyplot as plt
import csv
class Task2c:
def __init__(self):
pass
@staticmethod
def execute():
x = []
y = []
with open('miasta.csv') as csvfile:
reader = csv.DictReader(csvfile)
for column in reader:
x.append(column['Rok'])
y.append(column['Gdansk'])
plt.plot(x, y, 'r', label='Krzywa wykresu')
plt.xlabel('Lata')
plt.ylabel('Liczba ludnosci [w tys.]')
plt.title('Ludnosc w miastach Polski (Gdansk)')
plt.legend()
plt.show()
| [
"Blazej@DESKTOP-P8SE49K"
] | Blazej@DESKTOP-P8SE49K |
a006f031a6bef10a643b1366ee30edb96ede4562 | 7e40fdb15a67e3b53162bbcd2b1f091805837d9f | /article/migrations/0006_auto__add_newslettermain.py | ee4e4c7d24923010ed32341a3a741fa9e7bb03f5 | [] | no_license | brentcappello/newsdub | 79a5eecd92dcaf44aa07314eedbc7d5183683689 | cdfc6619cc8b89bc224100e913cb85378d0d8cea | refs/heads/master | 2016-09-01T20:53:07.784968 | 2012-11-15T02:53:41 | 2012-11-15T02:53:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,992 | py | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'NewsletterMain'
db.create_table('article_newslettermain', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
('description', self.gf('django.db.models.fields.TextField')()),
('created_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('status', self.gf('django.db.models.fields.IntegerField')(default=2)),
))
db.send_create_signal('article', ['NewsletterMain'])
# Adding M2M table for field newsletters_main on 'Newsletter'
db.create_table('article_newsletter_newsletters_main', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('newsletter', models.ForeignKey(orm['article.newsletter'], null=False)),
('newslettermain', models.ForeignKey(orm['article.newslettermain'], null=False))
))
db.create_unique('article_newsletter_newsletters_main', ['newsletter_id', 'newslettermain_id'])
def backwards(self, orm):
# Deleting model 'NewsletterMain'
db.delete_table('article_newslettermain')
# Removing M2M table for field newsletters_main on 'Newsletter'
db.delete_table('article_newsletter_newsletters_main')
models = {
'article.newsletter': {
'Meta': {'ordering': "('-publish',)", 'object_name': 'Newsletter'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'description': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'newsletters_main': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['article.NewsletterMain']", 'symmetrical': 'False'}),
'publish': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'article.newslettermain': {
'Meta': {'object_name': 'NewsletterMain'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'description': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'article.post': {
'Meta': {'ordering': "('-publish',)", 'object_name': 'Post'},
'allow_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'added_posts'", 'to': "orm['auth.User']"}),
'body': ('django.db.models.fields.TextField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'newsletters': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['article.Newsletter']", 'symmetrical': 'False'}),
'publish': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'tease': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'taggit.tag': {
'Meta': {'object_name': 'Tag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
},
'taggit.taggeditem': {
'Meta': {'object_name': 'TaggedItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"})
}
}
complete_apps = ['article'] | [
"brent@gmail"
] | brent@gmail |
b3cffcaaac0bef8d65f8fdbae1aa31e4b48f15ed | 2a1b8a671aceda6bc446f8ce26400aa84fa444a6 | /Packs/FiltersAndTransformers/Scripts/JoinIfSingleElementOnly/JoinIfSingleElementOnly.py | c91e49454d83bdef53b8f6eeabbd9dcc16b073fc | [
"MIT"
] | permissive | demisto/content | 6d4722d46f0ff0beea2748e9f7de585bf91a78b4 | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | refs/heads/master | 2023-09-04T00:02:25.618032 | 2023-09-03T21:56:22 | 2023-09-03T21:56:22 | 60,525,392 | 1,023 | 1,921 | MIT | 2023-09-14T20:55:24 | 2016-06-06T12:17:02 | Python | UTF-8 | Python | false | false | 466 | py | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
def return_first_element_if_single(value):
res = value
if isinstance(value, list):
if len(value) == 1:
res = value[0]
return res
def main(): # pragma: no cover
value = demisto.args()["value"]
res = return_first_element_if_single(value)
demisto.results(res)
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
| [
"noreply@github.com"
] | noreply@github.com |
17edec3a0cbd5397bc360dc2289f7aa23fef2f2b | 02122ec38633c178ced34d8a027addc919b4c200 | /Nutrients/api/urls.py | 757826e0b86fe90b0ab82e9e332d35f5dd0ee419 | [] | no_license | SIBU99/serverCVKM | 07907b3c416892bcc432b9317506927112750a93 | 8182f2274216016a15a2a98ea5a31d7e05222ed5 | refs/heads/master | 2023-01-12T10:19:54.966211 | 2020-11-10T08:33:41 | 2020-11-10T08:33:41 | 311,407,784 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 182 | py | from django.urls import path
from .views import NutrientExamination
urlpatterns = [
path("nutrient-examination/", NutrientExamination.as_view(), name="nutrient-examination"),
]
| [
"kumarmishra678@gmail.com"
] | kumarmishra678@gmail.com |
230c05c7d30324adcb69a3442767523215dea7ec | a56252fda5c9e42eff04792c6e16e413ad51ba1a | /resources/usr/local/lib/python2.7/dist-packages/sklearn/metrics/cluster/supervised.py | 31d1a45b74047c04f16b5e95a5fec55fca7b256f | [
"Apache-2.0"
] | permissive | edawson/parliament2 | 4231e692565dbecf99d09148e75c00750e6797c4 | 2632aa3484ef64c9539c4885026b705b737f6d1e | refs/heads/master | 2021-06-21T23:13:29.482239 | 2020-12-07T21:10:08 | 2020-12-07T21:10:08 | 150,246,745 | 0 | 0 | Apache-2.0 | 2019-09-11T03:22:55 | 2018-09-25T10:21:03 | Python | UTF-8 | Python | false | false | 26,696 | py | """Utilities to evaluate the clustering performance of models
Functions named as *_score return a scalar value to maximize: the higher the
better.
"""
# Authors: Olivier Grisel <olivier.grisel@ensta.org>
# Wei LI <kuantkid@gmail.com>
# Diego Molla <dmolla-aliod@gmail.com>
# License: BSD 3 clause
from math import log
from scipy.misc import comb
from scipy.sparse import coo_matrix
import numpy as np
from ...utils.fixes import unique
from .expected_mutual_info_fast import expected_mutual_information
def comb2(n):
# the exact version is faster for k == 2: use it by default globally in
# this module instead of the float approximate variant
return comb(n, 2, exact=1)
def check_clusterings(labels_true, labels_pred):
"""Check that the two clusterings matching 1D integer arrays"""
labels_true = np.asarray(labels_true)
labels_pred = np.asarray(labels_pred)
# input checks
if labels_true.ndim != 1:
raise ValueError(
"labels_true must be 1D: shape is %r" % (labels_true.shape,))
if labels_pred.ndim != 1:
raise ValueError(
"labels_pred must be 1D: shape is %r" % (labels_pred.shape,))
if labels_true.shape != labels_pred.shape:
raise ValueError(
"labels_true and labels_pred must have same size, got %d and %d"
% (labels_true.shape[0], labels_pred.shape[0]))
return labels_true, labels_pred
def contingency_matrix(labels_true, labels_pred, eps=None):
"""Build a contengency matrix describing the relationship between labels.
Parameters
----------
labels_true : int array, shape = [n_samples]
Ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
Cluster labels to evaluate
eps: None or float
If a float, that value is added to all values in the contingency
matrix. This helps to stop NaN propagation.
If ``None``, nothing is adjusted.
Returns
-------
contingency: array, shape=[n_classes_true, n_classes_pred]
Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in
true class :math:`i` and in predicted class :math:`j`. If
``eps is None``, the dtype of this array will be integer. If ``eps`` is
given, the dtype will be float.
"""
classes, class_idx = unique(labels_true, return_inverse=True)
clusters, cluster_idx = unique(labels_pred, return_inverse=True)
n_classes = classes.shape[0]
n_clusters = clusters.shape[0]
# Using coo_matrix to accelerate simple histogram calculation,
# i.e. bins are consecutive integers
# Currently, coo_matrix is faster than histogram2d for simple cases
contingency = coo_matrix((np.ones(class_idx.shape[0]),
(class_idx, cluster_idx)),
shape=(n_classes, n_clusters),
dtype=np.int).toarray()
if eps is not None:
# don't use += as contingency is integer
contingency = contingency + eps
return contingency
# clustering measures
def adjusted_rand_score(labels_true, labels_pred):
"""Rand index adjusted for chance
The Rand Index computes a similarity measure between two clusterings
by considering all pairs of samples and counting pairs that are
assigned in the same or different clusters in the predicted and
true clusterings.
The raw RI score is then "adjusted for chance" into the ARI score
using the following scheme::
ARI = (RI - Expected_RI) / (max(RI) - Expected_RI)
The adjusted Rand index is thus ensured to have a value close to
0.0 for random labeling independently of the number of clusters and
samples and exactly 1.0 when the clusterings are identical (up to
a permutation).
ARI is a symmetric measure::
adjusted_rand_score(a, b) == adjusted_rand_score(b, a)
Parameters
----------
labels_true : int array, shape = [n_samples]
Ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
Cluster labels to evaluate
Returns
-------
ari: float
Similarity score between -1.0 and 1.0. Random labelings have an ARI
close to 0.0. 1.0 stands for perfect match.
Examples
--------
Perfectly maching labelings have a score of 1 even
>>> from sklearn.metrics.cluster import adjusted_rand_score
>>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1])
1.0
>>> adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Labelings that assign all classes members to the same clusters
are complete be not always pure, hence penalized::
>>> adjusted_rand_score([0, 0, 1, 2], [0, 0, 1, 1]) # doctest: +ELLIPSIS
0.57...
ARI is symmetric, so labelings that have pure clusters with members
coming from the same classes but unnecessary splits are penalized::
>>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 2]) # doctest: +ELLIPSIS
0.57...
If classes members are completely split across different clusters, the
assignment is totally incomplete, hence the ARI is very low::
>>> adjusted_rand_score([0, 0, 0, 0], [0, 1, 2, 3])
0.0
References
----------
.. [Hubert1985] `L. Hubert and P. Arabie, Comparing Partitions,
Journal of Classification 1985`
http://www.springerlink.com/content/x64124718341j1j0/
.. [wk] http://en.wikipedia.org/wiki/Rand_index#Adjusted_Rand_index
See also
--------
adjusted_mutual_info_score: Adjusted Mutual Information
"""
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
n_samples = labels_true.shape[0]
classes = np.unique(labels_true)
clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split;
# or trivial clustering where each document is assigned a unique cluster.
# These are perfect matches hence return 1.0.
if (classes.shape[0] == clusters.shape[0] == 1
or classes.shape[0] == clusters.shape[0] == 0
or classes.shape[0] == clusters.shape[0] == len(labels_true)):
return 1.0
contingency = contingency_matrix(labels_true, labels_pred)
# Compute the ARI using the contingency data
sum_comb_c = sum(comb2(n_c) for n_c in contingency.sum(axis=1))
sum_comb_k = sum(comb2(n_k) for n_k in contingency.sum(axis=0))
sum_comb = sum(comb2(n_ij) for n_ij in contingency.flatten())
prod_comb = (sum_comb_c * sum_comb_k) / float(comb(n_samples, 2))
mean_comb = (sum_comb_k + sum_comb_c) / 2.
return ((sum_comb - prod_comb) / (mean_comb - prod_comb))
def homogeneity_completeness_v_measure(labels_true, labels_pred):
"""Compute the homogeneity and completeness and V-Measure scores at once
Those metrics are based on normalized conditional entropy measures of
the clustering labeling to evaluate given the knowledge of a Ground
Truth class labels of the same samples.
A clustering result satisfies homogeneity if all of its clusters
contain only data points which are members of a single class.
A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.
Both scores have positive values between 0.0 and 1.0, larger values
being desirable.
Those 3 metrics are independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score values in any way.
V-Measure is furthermore symmetric: swapping ``labels_true`` and
``label_pred`` will give the same score. This does not hold for
homogeneity and completeness.
Parameters
----------
labels_true : int array, shape = [n_samples]
ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
cluster labels to evaluate
Returns
-------
homogeneity: float
score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling
completeness: float
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling
v_measure: float
harmonic mean of the first two
See also
--------
homogeneity_score
completeness_score
v_measure_score
"""
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
if len(labels_true) == 0:
return 1.0, 1.0, 1.0
entropy_C = entropy(labels_true)
entropy_K = entropy(labels_pred)
MI = mutual_info_score(labels_true, labels_pred)
homogeneity = MI / (entropy_C) if entropy_C else 1.0
completeness = MI / (entropy_K) if entropy_K else 1.0
if homogeneity + completeness == 0.0:
v_measure_score = 0.0
else:
v_measure_score = (2.0 * homogeneity * completeness
/ (homogeneity + completeness))
return homogeneity, completeness, v_measure_score
def homogeneity_score(labels_true, labels_pred):
"""Homogeneity metric of a cluster labeling given a ground truth
A clustering result satisfies homogeneity if all of its clusters
contain only data points which are members of a single class.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`completeness_score` which will be different in
general.
Parameters
----------
labels_true : int array, shape = [n_samples]
ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
cluster labels to evaluate
Returns
-------
homogeneity: float
score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling
References
----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
conditional entropy-based external cluster evaluation measure
<http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_
See also
--------
completeness_score
v_measure_score
Examples
--------
Perfect labelings are homogeneous::
>>> from sklearn.metrics.cluster import homogeneity_score
>>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Non-perfect labelings that further split classes into more clusters can be
perfectly homogeneous::
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2]))
... # doctest: +ELLIPSIS
1.0...
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3]))
... # doctest: +ELLIPSIS
1.0...
Clusters that include samples from different classes do not make for an
homogeneous labeling::
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1]))
... # doctest: +ELLIPSIS
0.0...
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0]))
... # doctest: +ELLIPSIS
0.0...
"""
return homogeneity_completeness_v_measure(labels_true, labels_pred)[0]
def completeness_score(labels_true, labels_pred):
"""Completeness metric of a cluster labeling given a ground truth
A clustering result satisfies completeness if all the data points
that are members of a given class are elements of the same cluster.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred``
will return the :func:`homogeneity_score` which will be different in
general.
Parameters
----------
labels_true : int array, shape = [n_samples]
ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
cluster labels to evaluate
Returns
-------
completeness: float
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling
References
----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
conditional entropy-based external cluster evaluation measure
<http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_
See also
--------
homogeneity_score
v_measure_score
Examples
--------
Perfect labelings are complete::
>>> from sklearn.metrics.cluster import completeness_score
>>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Non-perfect labelings that assign all classes members to the same clusters
are still complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0]))
1.0
>>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1]))
1.0
If classes members are split across different clusters, the
assignment cannot be complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1]))
0.0
>>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3]))
0.0
"""
return homogeneity_completeness_v_measure(labels_true, labels_pred)[1]
def v_measure_score(labels_true, labels_pred):
"""V-measure cluster labeling given a ground truth.
This score is identical to :func:`normalized_mutual_info_score`.
The V-measure is the harmonic mean between homogeneity and completeness::
v = 2 * (homogeneity * completeness) / (homogeneity + completeness)
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Parameters
----------
labels_true : int array, shape = [n_samples]
ground truth class labels to be used as a reference
labels_pred : array, shape = [n_samples]
cluster labels to evaluate
Returns
-------
v_measure: float
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling
References
----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A
conditional entropy-based external cluster evaluation measure
<http://acl.ldc.upenn.edu/D/D07/D07-1043.pdf>`_
See also
--------
homogeneity_score
completeness_score
Examples
--------
Perfect labelings are both homogeneous and complete, hence have score 1.0::
>>> from sklearn.metrics.cluster import v_measure_score
>>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1])
1.0
>>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
Labelings that assign all classes members to the same clusters
are complete be not homogeneous, hence penalized::
>>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1]))
... # doctest: +ELLIPSIS
0.8...
>>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1]))
... # doctest: +ELLIPSIS
0.66...
Labelings that have pure clusters with members coming from the same
classes are homogeneous but un-necessary splits harms completeness
and thus penalize V-measure as well::
>>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2]))
... # doctest: +ELLIPSIS
0.8...
>>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3]))
... # doctest: +ELLIPSIS
0.66...
If classes members are completely split across different clusters,
the assignment is totally incomplete, hence the V-Measure is null::
>>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3]))
... # doctest: +ELLIPSIS
0.0...
Clusters that include samples from totally different classes totally
destroy the homogeneity of the labeling, hence::
>>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0]))
... # doctest: +ELLIPSIS
0.0...
"""
return homogeneity_completeness_v_measure(labels_true, labels_pred)[2]
def mutual_info_score(labels_true, labels_pred, contingency=None):
"""Mutual Information between two clusterings
The Mutual Information is a measure of the similarity between two labels of
the same data. Where :math:`P(i)` is the probability of a random sample
occurring in cluster :math:`U_i` and :math:`P'(j)` is the probability of a
random sample occurring in cluster :math:`V_j`, the Mutual Information
between clusterings :math:`U` and :math:`V` is given as:
.. math::
MI(U,V)=\sum_{i=1}^R \sum_{j=1}^C P(i,j)\log\\frac{P(i,j)}{P(i)P'(j)}
This is equal to the Kullback-Leibler divergence of the joint distribution
with the product distribution of the marginals.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : array, shape = [n_samples]
A clustering of the data into disjoint subsets.
contingency: None or array, shape = [n_classes_true, n_classes_pred]
A contingency matrix given by the :func:`contingency_matrix` function.
If value is ``None``, it will be computed, otherwise the given value is
used, with ``labels_true`` and ``labels_pred`` ignored.
Returns
-------
mi: float
Mutual information, a non-negative value
See also
--------
adjusted_mutual_info_score: Adjusted against chance Mutual Information
normalized_mutual_info_score: Normalized Mutual Information
"""
if contingency is None:
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
contingency = contingency_matrix(labels_true, labels_pred)
contingency = np.array(contingency, dtype='float')
contingency_sum = np.sum(contingency)
pi = np.sum(contingency, axis=1)
pj = np.sum(contingency, axis=0)
outer = np.outer(pi, pj)
nnz = contingency != 0.0
# normalized contingency
contingency_nm = contingency[nnz]
log_contingency_nm = np.log(contingency_nm)
contingency_nm /= contingency_sum
# log(a / b) should be calculated as log(a) - log(b) for
# possible loss of precision
log_outer = -np.log(outer[nnz]) + log(pi.sum()) + log(pj.sum())
mi = (contingency_nm * (log_contingency_nm - log(contingency_sum))
+ contingency_nm * log_outer)
return mi.sum()
def adjusted_mutual_info_score(labels_true, labels_pred):
"""Adjusted Mutual Information between two clusterings
Adjusted Mutual Information (AMI) is an adjustment of the Mutual
Information (MI) score to account for chance. It accounts for the fact that
the MI is generally higher for two clusterings with a larger number of
clusters, regardless of whether there is actually more information shared.
For two clusterings :math:`U` and :math:`V`, the AMI is given as::
AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [max(H(U), H(V)) - E(MI(U, V))]
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Be mindful that this function is an order of magnitude slower than other
metrics, such as the Adjusted Rand Index.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : array, shape = [n_samples]
A clustering of the data into disjoint subsets.
Returns
-------
ami: float
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling
See also
--------
adjusted_rand_score: Adjusted Rand Index
mutual_information_score: Mutual Information (not adjusted for chance)
Examples
--------
Perfect labelings are both homogeneous and complete, hence have
score 1.0::
>>> from sklearn.metrics.cluster import adjusted_mutual_info_score
>>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1])
1.0
>>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
If classes members are completely split across different clusters,
the assignment is totally in-complete, hence the AMI is null::
>>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3])
0.0
References
----------
.. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for
Clusterings Comparison: Variants, Properties, Normalization and
Correction for Chance, JMLR
<http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_
.. [2] `Wikipedia entry for the Adjusted Mutual Information
<http://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_
"""
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
n_samples = labels_true.shape[0]
classes = np.unique(labels_true)
clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split.
# This is a perfect match hence return 1.0.
if (classes.shape[0] == clusters.shape[0] == 1
or classes.shape[0] == clusters.shape[0] == 0):
return 1.0
contingency = contingency_matrix(labels_true, labels_pred)
contingency = np.array(contingency, dtype='float')
# Calculate the MI for the two clusterings
mi = mutual_info_score(labels_true, labels_pred,
contingency=contingency)
# Calculate the expected value for the mutual information
emi = expected_mutual_information(contingency, n_samples)
# Calculate entropy for each labeling
h_true, h_pred = entropy(labels_true), entropy(labels_pred)
ami = (mi - emi) / (max(h_true, h_pred) - emi)
return ami
def normalized_mutual_info_score(labels_true, labels_pred):
"""Normalized Mutual Information between two clusterings
Normalized Mutual Information (NMI) is an normalization of the Mutual
Information (MI) score to scale the results between 0 (no mutual
information) and 1 (perfect correlation). In this function, mutual
information is normalized by ``sqrt(H(labels_true) * H(labels_pred))``
This measure is not adjusted for chance. Therefore
:func:`adjusted_mustual_info_score` might be preferred.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : array, shape = [n_samples]
A clustering of the data into disjoint subsets.
Returns
-------
nmi: float
score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling
See also
--------
adjusted_rand_score: Adjusted Rand Index
adjusted_mutual_info_score: Adjusted Mutual Information (adjusted
against chance)
Examples
--------
Perfect labelings are both homogeneous and complete, hence have
score 1.0::
>>> from sklearn.metrics.cluster import normalized_mutual_info_score
>>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1])
1.0
>>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0])
1.0
If classes members are completely split across different clusters,
the assignment is totally in-complete, hence the NMI is null::
>>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3])
0.0
"""
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
classes = np.unique(labels_true)
clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split.
# This is a perfect match hence return 1.0.
if (classes.shape[0] == clusters.shape[0] == 1
or classes.shape[0] == clusters.shape[0] == 0):
return 1.0
contingency = contingency_matrix(labels_true, labels_pred)
contingency = np.array(contingency, dtype='float')
# Calculate the MI for the two clusterings
mi = mutual_info_score(labels_true, labels_pred,
contingency=contingency)
# Calculate the expected value for the mutual information
# Calculate entropy for each labeling
h_true, h_pred = entropy(labels_true), entropy(labels_pred)
nmi = mi / max(np.sqrt(h_true * h_pred), 1e-10)
return nmi
def entropy(labels):
"""Calculates the entropy for a labeling."""
if len(labels) == 0:
return 1.0
label_idx = unique(labels, return_inverse=True)[1]
pi = np.bincount(label_idx).astype(np.float)
pi = pi[pi > 0]
pi_sum = np.sum(pi)
# log(a / b) should be calculated as log(a) - log(b) for
# possible loss of precision
return -np.sum((pi / pi_sum) * (np.log(pi) - log(pi_sum)))
| [
"szarate@dnanexus.com"
] | szarate@dnanexus.com |
0829499a37fc13ac636386433fe887068436789a | b8ab0e1ac2634741a05e5fef583585b597a6cdcf | /wsltools/utils/faker/providers/date_time/fil_PH/__init__.py | 42a736439193745ecd672678cc198a9d48ef49e4 | [
"MIT"
] | permissive | Symbo1/wsltools | be99716eac93bfc270a5ef0e47769290827fc0c4 | 0b6e536fc85c707a1c81f0296c4e91ca835396a1 | refs/heads/master | 2022-11-06T16:07:50.645753 | 2020-06-30T13:08:00 | 2020-06-30T13:08:00 | 256,140,035 | 425 | 34 | MIT | 2020-04-16T14:10:45 | 2020-04-16T07:22:21 | Python | UTF-8 | Python | false | false | 829 | py | from .. import Provider as DateTimeProvider
class Provider(DateTimeProvider):
"""Provider for datetimes for fil_PH locale"""
DAY_NAMES = {
'0': 'Linggo',
'1': 'Lunes',
'2': 'Martes',
'3': 'Miyerkules',
'4': 'Huwebes',
'5': 'Biyernes',
'6': 'Sabado',
}
MONTH_NAMES = {
'01': 'Enero',
'02': 'Pebrero',
'03': 'Marso',
'04': 'Abril',
'05': 'Mayo',
'06': 'Hunyo',
'07': 'Hulyo',
'08': 'Agosto',
'09': 'Setyembre',
'10': 'Oktubre',
'11': 'Nobyembre',
'12': 'Disyembre',
}
def day_of_week(self):
day = self.date('%w')
return self.DAY_NAMES[day]
def month_name(self):
month = self.month()
return self.MONTH_NAMES[month]
| [
"tr3jer@gmail.com"
] | tr3jer@gmail.com |
b27a50e038b03e30c82265c12688de6cc9a21df9 | 0ac34d1fad3ed7e18b3803a25878a8e3d74a259e | /messages_app/forms.py | 39b210591b39588f92dd76cf69d3813ca820b149 | [] | no_license | predictnonprofit/PredictME-WebApplication | b20a35a3ca9fcd0f8349cca83a75576afe96841c | 557864cf9b98188478b9661cba23477d3e16ff85 | refs/heads/main | 2023-08-12T12:01:53.865143 | 2021-10-06T18:40:01 | 2021-10-06T18:40:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | # -*- coding: utf-8 -*-#
from django.forms import ModelForm
from .models import MemberMessages
class MemberMessagesForm(ModelForm):
class Meta:
model = MemberMessages
fields = ('sender', 'subject', "other_subject", "attachment", 'message', "reply")
| [
"ibm_luq95@yahoo.com"
] | ibm_luq95@yahoo.com |
26d03fcefa5d70539bb6d822b5978722de681a0c | a9e578a66a4706dedf83838ec3288adb893e57fd | /src/impute.py | e82f2af49047a8a2aa131493f61070eb732b20a6 | [] | no_license | jgondin/predict-water-pump-failure | 4e741c9385717c9f802e7ccc5fbc1c5032b81129 | 73d7664fb6b0ab605b6b3d6605ede256a56024fa | refs/heads/master | 2020-12-25T17:16:36.944533 | 2016-07-09T22:53:14 | 2016-07-09T22:53:14 | 62,754,230 | 1 | 0 | null | 2016-07-06T21:22:52 | 2016-07-06T21:22:52 | null | UTF-8 | Python | false | false | 13,041 | py | import pandas as pd
#import matplotlib.pyplot as plt
#import statsmodels.api as sm
#import seaborn as sbrn
import numpy as np
#import re
#import trainetime
import pickle
#from collections import OrderedDict
#import sklearn
def imputeTrain(trn):
"""
Input: Training dataset
Output: Returns copy of imputed training set; and a reference map (nested dictionary)
Function takes in a trainaset for the "water pump failure" driventraina.org competition
and returns a list of two items:
1. A training dataframe that contains imputed columns, namely:
- gps_height
- population
- latitude
- longitude
- construction_year
*Note: An exception will be thrown if any one of these columns are missing
*Note: Columns do not need to contain 'NaN' values. The function will replace
zeroes with NaNs as well as erroneous lat, long values
*Note: Uses a heirarchical geographically nearest neighbors mean measure
2. A nested dictionary in the following format that contains trained imputed values for
each variable above, by a heirarchical geography. The intent is to use this nested
dictionary to inform unseen test observations during prediction.
"""
train = trn.copy()
imputeCols = ['gps_height','population','latitude','longitude','construction_year', 'subvillage','ward','lga','region_code']
imputeMap = {'population':{'subvillage':{},'ward':{},'lga':{},'region_code':{}},
'gps_height':{'subvillage':{},'ward':{},'lga':{},'region_code':{}},
'construction_year':{'subvillage':{},'ward':{},'lga':{},'region_code':{}},
'latitude':{'subvillage':{},'ward':{},'lga':{},'region_code':{}},
'longitude':{'subvillage':{},'ward':{},'lga':{},'region_code':{}} }
exception = 'Missing Columns! Please make sure all of the following columns are in your training frame: \n'+str(imputeCols)
if not set(imputeCols) < set(list(train.columns)):
raise Exception(exception)
#replace continuous predictor missing values (0s) with NaN
train.population.replace({0:np.nan,1:np.nan,2:np.nan}, inplace=True)
train.gps_height.replace({0:np.nan}, inplace=True)
train['construction_year']=train['construction_year'].astype('int64')
train.loc[train.construction_year==0,['construction_year']]=np.nan
#replace lat/long outliers with NaN; replace in plce won't work for multiple columns
train.loc[((train.longitude==0)&(train.latitude==-2.000000e-08)),['latitude','longitude']]=train.loc[((train.longitude==0)&(train.latitude==-2.000000e-08)),['latitude','longitude']].replace({'latitude':{-2.000000e-08:np.nan}, 'longitude':{0.0:np.nan}}, regex=False)
#now, impute NaNs with the mean of hierarchical geographies going from nearest to farthest:
#sub-village > ward > lga > region_code
#population
#first, store location mean per location unit
imputeMap=generateMap('subvillage','population',train,imputeMap)
train.population.fillna(train.groupby(['subvillage'])['population'].transform('mean'), inplace=True)
imputeMap=generateMap('ward','population',train,imputeMap)
train.population.fillna(train.groupby(['ward'])['population'].transform('mean'), inplace=True)
imputeMap=generateMap('lga','population',train,imputeMap)
train.population.fillna(train.groupby(['lga'])['population'].transform('mean'), inplace=True)
imputeMap=generateMap('region_code','population',train,imputeMap)
train.population.fillna(train.groupby(['region_code'])['population'].transform('mean'), inplace=True)
#gps_height (do the same thing)
imputeMap=generateMap('subvillage','gps_height',train,imputeMap)
train.gps_height.fillna(train.groupby(['subvillage'])['gps_height'].transform('mean'), inplace=True)
imputeMap=generateMap('ward','gps_height',train,imputeMap)
train.gps_height.fillna(train.groupby(['ward'])['gps_height'].transform('mean'), inplace=True)
imputeMap=generateMap('lga','gps_height',train,imputeMap)
train.gps_height.fillna(train.groupby(['lga'])['gps_height'].transform('mean'), inplace=True)
imputeMap=generateMap('region_code','gps_height',train,imputeMap)
train.gps_height.fillna(train.groupby(['region_code'])['gps_height'].transform('mean'), inplace=True)
#construction_year (same! just set construction year back to int64 at the end)
imputeMap=generateMap('subvillage','construction_year',train,imputeMap)
train.construction_year.fillna(train.groupby(['subvillage'])['construction_year'].transform('mean'), inplace=True)
imputeMap=generateMap('ward','construction_year',train,imputeMap)
train.construction_year.fillna(train.groupby(['ward'])['construction_year'].transform('mean'), inplace=True)
imputeMap=generateMap('lga','construction_year',train,imputeMap)
train.construction_year.fillna(train.groupby(['lga'])['construction_year'].transform('mean'), inplace=True)
imputeMap=generateMap('region_code','construction_year',train,imputeMap)
train.construction_year.fillna(train.groupby(['region_code'])['construction_year'].transform('mean'), inplace=True)
train['construction_year']=train.construction_year.astype('int64') #set to int! or we'll have too many
#same for lats and longs
imputeMap=generateMap('subvillage','latitude',train,imputeMap)
train.latitude.fillna(train.groupby(['subvillage'])['latitude'].transform('mean'), inplace=True)
imputeMap=generateMap('ward','latitude',train,imputeMap)
train.latitude.fillna(train.groupby(['ward'])['latitude'].transform('mean'), inplace=True)
imputeMap=generateMap('lga','latitude',train,imputeMap)
train.latitude.fillna(train.groupby(['lga'])['latitude'].transform('mean'), inplace=True)
imputeMap=generateMap('region_code','latitude',train,imputeMap)
train.latitude.fillna(train.groupby(['region_code'])['latitude'].transform('mean'), inplace=True)
#long
imputeMap=generateMap('subvillage','longitude',train,imputeMap)
train.longitude.fillna(train.groupby(['subvillage'])['longitude'].transform('mean'), inplace=True)
imputeMap=generateMap('ward','longitude',train,imputeMap)
train.longitude.fillna(train.groupby(['ward'])['longitude'].transform('mean'), inplace=True)
imputeMap=generateMap('lga','longitude',train,imputeMap)
train.longitude.fillna(train.groupby(['lga'])['longitude'].transform('mean'), inplace=True)
imputeMap=generateMap('region_code','longitude',train,imputeMap)
train.longitude.fillna(train.groupby(['region_code'])['longitude'].transform('mean'), inplace=True)
return train, imputeMap
def generateMap(geog, col, train, imputeMap):
"""helps the imputeTrain function out by storing the means of each location breakdown
for that column in the nested dictionary"""
grpdf = train.groupby(train[geog])[col].mean().reset_index()
grpdf = grpdf.loc[~grpdf[col].isnull()]
grpdf.set_index(grpdf.iloc[:,0], inplace=True)
grpdf.drop(geog, inplace=True, axis=1)
#insert into nested dict
imputeMap[col][geog].update(grpdf.iloc[:,0].to_dict())
return imputeMap
def fillTest(tst, imputeMap):
"""
Inputs: Test dataframe, reference map nested dictionary
Outputs: Copy of Test dataframe with filled in trained values.
uses a passed in reference map that contains trained means by geographical
nearness for numerics
- gps_height
- population
- latitude
- longitude
- construction_year.
Function returns the passed in test dataframe with any missing values filled
in according to the reference map.
*Note: if input dataframe is sorted in any order the order will be lost as
missing values are removed, filled in, and appended back to the dataframe.
Simply re-sort if original order is desired.
"""
test_imp=tst.copy()
imputeCols = ['gps_height','population','latitude','longitude','construction_year', 'subvillage','ward','lga','region_code']
exception = 'Missing Columns! Please make sure all of the following columns are in your test frame: \n'+str(imputeCols)
numCols = ['gps_height','population','latitude','longitude','construction_year']
if not set(imputeCols) < set(list(test_imp.columns)):
raise Exception(exception)
geogHierarch = np.array(['subvillage','ward','lga','region_code'])
#replace continuous predictor missing values (0s) with NaN
test_imp.population.replace({0:np.nan, 1:np.nan, 2:np.nan}, inplace=True)
test_imp.gps_height.replace({0:np.nan}, inplace=True)
test_imp['construction_year']=test_imp['construction_year'].astype('int64')
test_imp.loc[test_imp.construction_year==0,['construction_year']]=np.nan
#replace lat/long outliers with NaN; replace in plce won't work for multiple columns
test_imp.loc[((test_imp.longitude==0)&(test_imp.latitude==-2.000000e-08)),['latitude','longitude']]=test_imp.loc[((test_imp.longitude==0)&(test_imp.latitude==-2.000000e-08)),['latitude','longitude']].replace({'latitude':{-2.000000e-08:np.nan}, 'longitude':{0.0:np.nan}}, regex=False)
#BACKUP IMPUTE STRATEGY: NOT USING REFERENCE MAP
"""
test.gps_height.fillna(test.groupby(['subvillage'])['gps_height'].transform('mean'), inplace=True)
test.gps_height.fillna(test.groupby(['ward'])['gps_height'].transform('mean'), inplace=True)
test.gps_height.fillna(test.groupby(['lga'])['gps_height'].transform('mean'), inplace=True)
test.gps_height.fillna(test.groupby(['region_code'])['gps_height'].transform('mean'), inplace=True)
test.population.fillna(test.groupby(['subvillage'])['population'].transform('mean'), inplace=True)
test.population.fillna(test.groupby(['ward'])['population'].transform('mean'), inplace=True)
test.population.fillna(test.groupby(['lga'])['population'].transform('mean'), inplace=True)
test.populationr.fillna(test.groupby(['region_code'])['population'].transform('mean'), inplace=True)
test.construction_year.fillna(test.groupby(['subvillage'])['construction_year'].transform('mean'), inplace=True)
test.construction_year.fillna(test.groupby(['ward'])['construction_year'].transform('mean'), inplace=True)
test.construction_year.fillna(test.groupby(['lga'])['construction_year'].transform('mean'), inplace=True)
test.construction_year.fillna(test.groupby(['region_code'])['construction_year'].transform('mean'), inplace=True)
test.latitude.fillna(test.groupby(['subvillage'])['latitude'].transform('mean'), inplace=True)
test.latitude.fillna(test.groupby(['ward'])['latitude'].transform('mean'), inplace=True)
test.latitude.fillna(test.groupby(['lga'])['latitude'].transform('mean'), inplace=True)
test.latitude.fillna(test.groupby(['region_code'])['latitude'].transform('mean'), inplace=True)
test.longitude.fillna(test.groupby(['subvillage'])['longitude'].transform('mean'), inplace=True)
test.longitude.fillna(test.groupby(['ward'])['longitude'].transform('mean'), inplace=True)
test.longitude.fillna(test.groupby(['lga'])['longitude'].transform('mean'), inplace=True)
test.longitude.fillna(test.groupby(['region_code'])['longitude'].transform('mean'), inplace=True)
"""
df_id = test_imp[['id']]
test = test_imp
for col in numCols:
if test[col].isnull().sum():
#subset ad remove from test frame col specific nulls (will append filled values later)
test_sub = test[test[col].isnull()]
test = test[~test[col].isnull()]
#fill in missing values by tiered geography
test_filled = test_sub[~test_sub[col].isnull()] #empty at first
for geog in geogHierarch:
#get col and geog specific reference map
refdf = extractMap(imputeMap, col, geog)
#now merge col and geog missing values in test with ref map
test_sub=pd.merge(test_sub, refdf, how='left', on=geog)
test_sub[col+'_x']=test_sub[col+'_y']
test_sub.drop(col+'_y', axis=1, inplace=True)
test_sub=test_sub.rename(columns={col+'_x':col}) #remove _x
#get all non NaNs from test_sub
test_filled = pd.concat([test_filled,test_sub[~test_sub[col].isnull()]], axis=0)
test_sub = test_sub[test_sub[col].isnull()]
if test_sub.shape[0]==0:
break
#merge filled set and any remaining (could not fill) back to Test
test = pd.concat([test, test_filled, test_sub], axis=0, ignore_index=True)
#make sure construction year is an integer col
test['construction_year']=test['construction_year'].astype('int64')
df_merge = pd.merge(df_id, test, on='id')
return df_merge
def extractMap(imap, col, geog):
"""
Extract impute column and geography specific values from trained reference map.
Returns a reference dataframe, with columns col, geog.
"""
#extract col and geog specific values from reference map as dataframe
mapdf = pd.DataFrame()
mapdf = mapdf.from_dict(imap[col][geog],orient='index')
mapdf[geog]=mapdf.index
mapdf.columns=[col,geog]
return mapdf
| [
"ashirwad08@yahoo.com"
] | ashirwad08@yahoo.com |
a56825bd2f75c83393aad08f9a63136c9a6cd561 | 393f30495e9cecebd6f8950d51b10c0817ed7d28 | /venv/task2_10.py | ad6a65bf495eaffc67787979cd14e929bce47380 | [] | no_license | Skornel/NNGASU_Domrachev_Python | 8f741d99a9b689e4c09a739ff42b0648da0cf24c | 9a996925ca6729178b7a439025508aad72d633ae | refs/heads/master | 2020-12-19T15:36:24.546269 | 2020-04-13T15:48:24 | 2020-04-13T15:48:24 | 235,776,259 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 596 | py | s=[]
for i in range(4):
b=[]
print("Введите данные ",i+1," списка")
for row in range(4):
print("Вводи ",row+1," элемент ",i+1," списка ")
b.append(input())
s.append(b)
print(s)
maximum=0
minimum=1000
for i in range(len(s)):
for j in range(len(s[i])):
if int(s[i][j])>int(maximum):
maximum=s[i][j]
if int(s[i][j])<int(minimum):
minimum=s[i][j]
print("Максимальное число:", maximum, "Минимальное: ", minimum, " Разность: ",int(maximum)-int(minimum)) | [
"Suslova2907@gmail.com"
] | Suslova2907@gmail.com |
8d80bf9946e1f8e66795f476eeb0e9382bf7ca7d | 0c70dcec22a090e70b1f20613ea6e0a64fd9a037 | /GPS卫星位置的计算/venv/Lib/site-packages/pandas/core/arrays/boolean.py | 071e1ce42914a78c713b3948405141a7734c0ce1 | [
"MIT"
] | permissive | payiz-asj/Gis | 82c1096d830878f62c7a0d5dfb6630d4e4744764 | 3d315fed93e2ab850b836ddfd7a67f5618969d10 | refs/heads/main | 2023-06-27T15:25:17.301154 | 2021-08-03T10:02:58 | 2021-08-03T10:02:58 | 392,269,853 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 25,132 | py | import numbers
from typing import TYPE_CHECKING, List, Tuple, Type, Union
import warnings
import numpy as np
from pandas._libs import lib, missing as libmissing
from pandas._typing import ArrayLike
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.core.dtypes.common import (
is_bool_dtype,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_integer_dtype,
is_list_like,
is_numeric_dtype,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import isna
from pandas.core import ops
from .masked import BaseMaskedArray, BaseMaskedDtype
if TYPE_CHECKING:
import pyarrow # noqa: F401
@register_extension_dtype
class BooleanDtype(BaseMaskedDtype):
"""
Extension dtype for boolean data.
.. versionadded:: 1.0.0
.. warning::
BooleanDtype is considered experimental. The implementation and
parts of the API may change without warning.
Attributes
----------
None
Methods
-------
None
Examples
--------
>>> pd.BooleanDtype()
BooleanDtype
"""
name = "boolean"
@property
def type(self) -> Type[np.bool_]:
return np.bool_
@property
def kind(self) -> str:
return "b"
@property
def numpy_dtype(self) -> np.dtype:
return np.dtype("bool")
@classmethod
def construct_array_type(cls) -> Type["BooleanArray"]:
"""
Return the array type associated with this dtype.
Returns
-------
type
"""
return BooleanArray
def __repr__(self) -> str:
return "BooleanDtype"
@property
def _is_boolean(self) -> bool:
return True
@property
def _is_numeric(self) -> bool:
return True
def __from_arrow__(
self, array: Union["pyarrow.Array", "pyarrow.ChunkedArray"]
) -> "BooleanArray":
"""
Construct BooleanArray from pyarrow Array/ChunkedArray.
"""
import pyarrow # noqa: F811
if isinstance(array, pyarrow.Array):
chunks = [array]
else:
# pyarrow.ChunkedArray
chunks = array.chunks
results = []
for arr in chunks:
# TODO should optimize this without going through object array
bool_arr = BooleanArray._from_sequence(np.array(arr))
results.append(bool_arr)
return BooleanArray._concat_same_type(results)
def coerce_to_array(
values, mask=None, copy: bool = False
) -> Tuple[np.ndarray, np.ndarray]:
"""
Coerce the input values array to numpy arrays with a mask.
Parameters
----------
values : 1D list-like
mask : bool 1D array, optional
copy : bool, default False
if True, copy the input
Returns
-------
tuple of (values, mask)
"""
if isinstance(values, BooleanArray):
if mask is not None:
raise ValueError("cannot pass mask for BooleanArray input")
values, mask = values._data, values._mask
if copy:
values = values.copy()
mask = mask.copy()
return values, mask
mask_values = None
if isinstance(values, np.ndarray) and values.dtype == np.bool_:
if copy:
values = values.copy()
elif isinstance(values, np.ndarray) and is_numeric_dtype(values.dtype):
mask_values = isna(values)
values_bool = np.zeros(len(values), dtype=bool)
values_bool[~mask_values] = values[~mask_values].astype(bool)
if not np.all(
values_bool[~mask_values].astype(values.dtype) == values[~mask_values]
):
raise TypeError("Need to pass bool-like values")
values = values_bool
else:
values_object = np.asarray(values, dtype=object)
inferred_dtype = lib.infer_dtype(values_object, skipna=True)
integer_like = ("floating", "integer", "mixed-integer-float")
if inferred_dtype not in ("boolean", "empty") + integer_like:
raise TypeError("Need to pass bool-like values")
mask_values = isna(values_object)
values = np.zeros(len(values), dtype=bool)
values[~mask_values] = values_object[~mask_values].astype(bool)
# if the values were integer-like, validate it were actually 0/1's
if inferred_dtype in integer_like:
if not np.all(
values[~mask_values].astype(float)
== values_object[~mask_values].astype(float)
):
raise TypeError("Need to pass bool-like values")
if mask is None and mask_values is None:
mask = np.zeros(len(values), dtype=bool)
elif mask is None:
mask = mask_values
else:
if isinstance(mask, np.ndarray) and mask.dtype == np.bool_:
if mask_values is not None:
mask = mask | mask_values
else:
if copy:
mask = mask.copy()
else:
mask = np.array(mask, dtype=bool)
if mask_values is not None:
mask = mask | mask_values
if not values.ndim == 1:
raise ValueError("values must be a 1D list-like")
if not mask.ndim == 1:
raise ValueError("mask must be a 1D list-like")
return values, mask
class BooleanArray(BaseMaskedArray):
"""
Array of boolean (True/False) data with missing values.
This is a pandas Extension array for boolean data, under the hood
represented by 2 numpy arrays: a boolean array with the data and
a boolean array with the mask (True indicating missing).
BooleanArray implements Kleene logic (sometimes called three-value
logic) for logical operations. See :ref:`boolean.kleene` for more.
To construct an BooleanArray from generic array-like input, use
:func:`pandas.array` specifying ``dtype="boolean"`` (see examples
below).
.. versionadded:: 1.0.0
.. warning::
BooleanArray is considered experimental. The implementation and
parts of the API may change without warning.
Parameters
----------
values : numpy.ndarray
A 1-d boolean-dtype array with the data.
mask : numpy.ndarray
A 1-d boolean-dtype array indicating missing values (True
indicates missing).
copy : bool, default False
Whether to copy the `values` and `mask` arrays.
Attributes
----------
None
Methods
-------
None
Returns
-------
BooleanArray
Examples
--------
Create an BooleanArray with :func:`pandas.array`:
>>> pd.array([True, False, None], dtype="boolean")
<BooleanArray>
[True, False, <NA>]
Length: 3, dtype: boolean
"""
# The value used to fill '_data' to avoid upcasting
_internal_fill_value = False
def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False):
if not (isinstance(values, np.ndarray) and values.dtype == np.bool_):
raise TypeError(
"values should be boolean numpy array. Use "
"the 'pd.array' function instead"
)
self._dtype = BooleanDtype()
super().__init__(values, mask, copy=copy)
@property
def dtype(self) -> BooleanDtype:
return self._dtype
@classmethod
def _from_sequence(cls, scalars, dtype=None, copy: bool = False) -> "BooleanArray":
if dtype:
assert dtype == "boolean"
values, mask = coerce_to_array(scalars, copy=copy)
return BooleanArray(values, mask)
@classmethod
def _from_sequence_of_strings(
cls, strings: List[str], dtype=None, copy: bool = False
) -> "BooleanArray":
def map_string(s):
if isna(s):
return s
elif s in ["True", "TRUE", "true", "1", "1.0"]:
return True
elif s in ["False", "FALSE", "false", "0", "0.0"]:
return False
else:
raise ValueError(f"{s} cannot be cast to bool")
scalars = [map_string(x) for x in strings]
return cls._from_sequence(scalars, dtype, copy)
_HANDLED_TYPES = (np.ndarray, numbers.Number, bool, np.bool_)
def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs):
# For BooleanArray inputs, we apply the ufunc to ._data
# and mask the result.
if method == "reduce":
# Not clear how to handle missing values in reductions. Raise.
raise NotImplementedError("The 'reduce' method is not supported.")
out = kwargs.get("out", ())
for x in inputs + out:
if not isinstance(x, self._HANDLED_TYPES + (BooleanArray,)):
return NotImplemented
# for binary ops, use our custom dunder methods
result = ops.maybe_dispatch_ufunc_to_dunder_op(
self, ufunc, method, *inputs, **kwargs
)
if result is not NotImplemented:
return result
mask = np.zeros(len(self), dtype=bool)
inputs2 = []
for x in inputs:
if isinstance(x, BooleanArray):
mask |= x._mask
inputs2.append(x._data)
else:
inputs2.append(x)
def reconstruct(x):
# we don't worry about scalar `x` here, since we
# raise for reduce up above.
if is_bool_dtype(x.dtype):
m = mask.copy()
return BooleanArray(x, m)
else:
x[mask] = np.nan
return x
result = getattr(ufunc, method)(*inputs2, **kwargs)
if isinstance(result, tuple):
tuple(reconstruct(x) for x in result)
else:
return reconstruct(result)
def _coerce_to_array(self, value) -> Tuple[np.ndarray, np.ndarray]:
return coerce_to_array(value)
def astype(self, dtype, copy: bool = True) -> ArrayLike:
"""
Cast to a NumPy array or ExtensionArray with 'dtype'.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
ndarray or ExtensionArray
NumPy ndarray, BooleanArray or IntegerArray with 'dtype' for its dtype.
Raises
------
TypeError
if incompatible type with an BooleanDtype, equivalent of same_kind
casting
"""
from pandas.core.arrays.string_ import StringDtype
dtype = pandas_dtype(dtype)
if isinstance(dtype, BooleanDtype):
values, mask = coerce_to_array(self, copy=copy)
return BooleanArray(values, mask, copy=False)
elif isinstance(dtype, StringDtype):
return dtype.construct_array_type()._from_sequence(self, copy=False)
if is_bool_dtype(dtype):
# astype_nansafe converts np.nan to True
if self._hasna:
raise ValueError("cannot convert float NaN to bool")
else:
return self._data.astype(dtype, copy=copy)
if is_extension_array_dtype(dtype) and is_integer_dtype(dtype):
from pandas.core.arrays import IntegerArray
return IntegerArray(
self._data.astype(dtype.numpy_dtype), self._mask.copy(), copy=False
)
# for integer, error if there are missing values
if is_integer_dtype(dtype):
if self._hasna:
raise ValueError("cannot convert NA to integer")
# for float dtype, ensure we use np.nan before casting (numpy cannot
# deal with pd.NA)
na_value = self._na_value
if is_float_dtype(dtype):
na_value = np.nan
# coerce
return self.to_numpy(dtype=dtype, na_value=na_value, copy=False)
def _values_for_argsort(self) -> np.ndarray:
"""
Return values for sorting.
Returns
-------
ndarray
The transformed values should maintain the ordering between values
within the array.
See Also
--------
ExtensionArray.argsort
"""
data = self._data.copy()
data[self._mask] = -1
return data
def any(self, skipna: bool = True, **kwargs):
"""
Return whether any element is True.
Returns False unless there is at least one element that is True.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be False, as for an empty array.
If `skipna` is False, the result will still be True if there is
at least one element that is True, otherwise NA will be returned
if there are NA's present.
**kwargs : any, default None
Additional keywords have no effect but might be accepted for
compatibility with NumPy.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
numpy.any : Numpy version of this method.
BooleanArray.all : Return whether all elements are True.
Examples
--------
The result indicates whether any element is True (and by default
skips NAs):
>>> pd.array([True, False, True]).any()
True
>>> pd.array([True, False, pd.NA]).any()
True
>>> pd.array([False, False, pd.NA]).any()
False
>>> pd.array([], dtype="boolean").any()
False
>>> pd.array([pd.NA], dtype="boolean").any()
False
With ``skipna=False``, the result can be NA if this is logically
required (whether ``pd.NA`` is True or False influences the result):
>>> pd.array([True, False, pd.NA]).any(skipna=False)
True
>>> pd.array([False, False, pd.NA]).any(skipna=False)
<NA>
"""
kwargs.pop("axis", None)
nv.validate_any((), kwargs)
values = self._data.copy()
np.putmask(values, self._mask, False)
result = values.any()
if skipna:
return result
else:
if result or len(self) == 0 or not self._mask.any():
return result
else:
return self.dtype.na_value
def all(self, skipna: bool = True, **kwargs):
"""
Return whether all elements are True.
Returns True unless there is at least one element that is False.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be True, as for an empty array.
If `skipna` is False, the result will still be False if there is
at least one element that is False, otherwise NA will be returned
if there are NA's present.
**kwargs : any, default None
Additional keywords have no effect but might be accepted for
compatibility with NumPy.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
numpy.all : Numpy version of this method.
BooleanArray.any : Return whether any element is True.
Examples
--------
The result indicates whether any element is True (and by default
skips NAs):
>>> pd.array([True, True, pd.NA]).all()
True
>>> pd.array([True, False, pd.NA]).all()
False
>>> pd.array([], dtype="boolean").all()
True
>>> pd.array([pd.NA], dtype="boolean").all()
True
With ``skipna=False``, the result can be NA if this is logically
required (whether ``pd.NA`` is True or False influences the result):
>>> pd.array([True, True, pd.NA]).all(skipna=False)
<NA>
>>> pd.array([True, False, pd.NA]).all(skipna=False)
False
"""
kwargs.pop("axis", None)
nv.validate_all((), kwargs)
values = self._data.copy()
np.putmask(values, self._mask, True)
result = values.all()
if skipna:
return result
else:
if not result or len(self) == 0 or not self._mask.any():
return result
else:
return self.dtype.na_value
@classmethod
def _create_logical_method(cls, op):
def logical_method(self, other):
if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
# Rely on pandas to unbox and dispatch to us.
return NotImplemented
assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"}
other = lib.item_from_zerodim(other)
other_is_booleanarray = isinstance(other, BooleanArray)
other_is_scalar = lib.is_scalar(other)
mask = None
if other_is_booleanarray:
other, mask = other._data, other._mask
elif is_list_like(other):
other = np.asarray(other, dtype="bool")
if other.ndim > 1:
raise NotImplementedError(
"can only perform ops with 1-d structures"
)
other, mask = coerce_to_array(other, copy=False)
elif isinstance(other, np.bool_):
other = other.item()
if other_is_scalar and not (other is libmissing.NA or lib.is_bool(other)):
raise TypeError(
"'other' should be pandas.NA or a bool. "
f"Got {type(other).__name__} instead."
)
if not other_is_scalar and len(self) != len(other):
raise ValueError("Lengths must match to compare")
if op.__name__ in {"or_", "ror_"}:
result, mask = ops.kleene_or(self._data, other, self._mask, mask)
elif op.__name__ in {"and_", "rand_"}:
result, mask = ops.kleene_and(self._data, other, self._mask, mask)
elif op.__name__ in {"xor", "rxor"}:
result, mask = ops.kleene_xor(self._data, other, self._mask, mask)
return BooleanArray(result, mask)
name = f"__{op.__name__}__"
return set_function_name(logical_method, name, cls)
@classmethod
def _create_comparison_method(cls, op):
def cmp_method(self, other):
from pandas.arrays import IntegerArray
if isinstance(
other, (ABCDataFrame, ABCSeries, ABCIndexClass, IntegerArray)
):
# Rely on pandas to unbox and dispatch to us.
return NotImplemented
other = lib.item_from_zerodim(other)
mask = None
if isinstance(other, BooleanArray):
other, mask = other._data, other._mask
elif is_list_like(other):
other = np.asarray(other)
if other.ndim > 1:
raise NotImplementedError(
"can only perform ops with 1-d structures"
)
if len(self) != len(other):
raise ValueError("Lengths must match to compare")
if other is libmissing.NA:
# numpy does not handle pd.NA well as "other" scalar (it returns
# a scalar False instead of an array)
result = np.zeros_like(self._data)
mask = np.ones_like(self._data)
else:
# numpy will show a DeprecationWarning on invalid elementwise
# comparisons, this will raise in the future
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
with np.errstate(all="ignore"):
result = op(self._data, other)
# nans propagate
if mask is None:
mask = self._mask.copy()
else:
mask = self._mask | mask
return BooleanArray(result, mask, copy=False)
name = f"__{op.__name__}"
return set_function_name(cmp_method, name, cls)
def _reduce(self, name: str, skipna: bool = True, **kwargs):
if name in {"any", "all"}:
return getattr(self, name)(skipna=skipna, **kwargs)
return super()._reduce(name, skipna, **kwargs)
def _maybe_mask_result(self, result, mask, other, op_name: str):
"""
Parameters
----------
result : array-like
mask : array-like bool
other : scalar or array-like
op_name : str
"""
# if we have a float operand we are by-definition
# a float result
# or our op is a divide
if (is_float_dtype(other) or is_float(other)) or (
op_name in ["rtruediv", "truediv"]
):
result[mask] = np.nan
return result
if is_bool_dtype(result):
return BooleanArray(result, mask, copy=False)
elif is_integer_dtype(result):
from pandas.core.arrays import IntegerArray
return IntegerArray(result, mask, copy=False)
else:
result[mask] = np.nan
return result
@classmethod
def _create_arithmetic_method(cls, op):
op_name = op.__name__
def boolean_arithmetic_method(self, other):
if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
# Rely on pandas to unbox and dispatch to us.
return NotImplemented
other = lib.item_from_zerodim(other)
mask = None
if isinstance(other, BooleanArray):
other, mask = other._data, other._mask
elif is_list_like(other):
other = np.asarray(other)
if other.ndim > 1:
raise NotImplementedError(
"can only perform ops with 1-d structures"
)
if len(self) != len(other):
raise ValueError("Lengths must match")
# nans propagate
if mask is None:
mask = self._mask
if other is libmissing.NA:
mask |= True
else:
mask = self._mask | mask
if other is libmissing.NA:
# if other is NA, the result will be all NA and we can't run the
# actual op, so we need to choose the resulting dtype manually
if op_name in {"floordiv", "rfloordiv", "mod", "rmod", "pow", "rpow"}:
dtype = "int8"
else:
dtype = "bool"
result = np.zeros(len(self._data), dtype=dtype)
else:
with np.errstate(all="ignore"):
result = op(self._data, other)
# divmod returns a tuple
if op_name == "divmod":
div, mod = result
return (
self._maybe_mask_result(div, mask, other, "floordiv"),
self._maybe_mask_result(mod, mask, other, "mod"),
)
return self._maybe_mask_result(result, mask, other, op_name)
name = f"__{op_name}__"
return set_function_name(boolean_arithmetic_method, name, cls)
BooleanArray._add_logical_ops()
BooleanArray._add_comparison_ops()
BooleanArray._add_arithmetic_ops()
| [
"1778029840@qq.com"
] | 1778029840@qq.com |
40830d2e202a0447d24f36b58b901c90eba955bd | d1e3399db6973d639082bd24865bc0df538c0d8d | /ricommender_backend/settings.py | a51b80864b9dc2f358ec683a497db12f165cc5bd | [
"MIT"
] | permissive | reeechart/ricommender | a0c505f8eab6b7c381a41b919d3f5c3da02f61a2 | c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a | refs/heads/master | 2020-04-22T12:13:35.198868 | 2019-05-12T16:42:25 | 2019-05-12T16:42:25 | 170,365,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,359 | py | """
Django settings for ricommender_backend project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('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',
'rest_framework',
'ricommender_backend.authentication',
'ricommender_backend.musicstreamer',
]
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 = 'ricommender_backend.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 = 'ricommender_backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': os.environ.get('DATABASE_NAME'),
},
}
# Password validation
# https://docs.djangoproject.com/en/2.1/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',
},
]
# Django REST Framework
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
}
# Internationalization
# https://docs.djangoproject.com/en/2.1/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/2.1/howto/static-files/
STATIC_URL = '/static/'
| [
"ferdinandusrichard@yahoo.co.id"
] | ferdinandusrichard@yahoo.co.id |
5dfb79becde51feb01c67400ff548446d6963775 | 0cb38adedbe3a5192076de420e1aa0fd10ae3311 | /return_merchandise_authorizations/admin.py | 213dea63a59221b56ba699e6a457f59ff5076d67 | [] | no_license | fogcitymarathoner/rma | 73ada816b98f068b6c00b2e1fcf39461259453fa | 133d6026f99820d0702f0578b8a3b4574671f888 | refs/heads/master | 2021-01-11T00:32:47.797673 | 2016-10-10T18:34:54 | 2016-10-10T18:35:11 | 70,516,821 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 756 | py | from django.contrib import admin
from return_merchandise_authorizations.models import Rma
from return_merchandise_authorizations.models import Item
from return_merchandise_authorizations.models import RmaAttachment
class ItemInline(admin.TabularInline):
model = Item
class AttachInline(admin.TabularInline):
model = RmaAttachment
class RmaAdmin(admin.ModelAdmin):
list_display = ('date', 'customer', 'case_number', 'reference_number', 'address')
search_fields = ('case_number', 'reference_number', 'address', 'issue')
inlines = [
ItemInline,
AttachInline
]
#
admin.site.register(Rma, RmaAdmin)
class ItemAdmin(admin.ModelAdmin):
list_display = ('note', 'quantity')
#
admin.site.register(Item, ItemAdmin) | [
"marc@fogtest.com"
] | marc@fogtest.com |
9265eec49a0e583e02e5cb8418f517c93695b206 | be25988b4b92e16144315b3f3a45bb31c9036d87 | /FinalProject.py | a4cc0cff617ba3e9e95bdafd188cff1566c19015 | [] | no_license | cormag128/Python_Checkers | c658cd3ce9bbc03e770df6faed5ec1acb83326e1 | 4068b25a54d195a223c7bf73dfc4d4e18ac6c1cb | refs/heads/master | 2021-01-19T21:23:50.391239 | 2017-05-03T00:58:52 | 2017-05-03T00:58:52 | 88,652,979 | 1 | 0 | null | 2017-04-30T19:49:40 | 2017-04-18T17:38:32 | Python | UTF-8 | Python | false | false | 6,292 | py | # Final Project: Checkers AI
# Written by Thomas Walters and Trevor Jenkins
# The purpose of this project is to demonstrate a complex state-based
# program using heuristic programming to create a Checkers AI capable of
# beating a human in checkershttps://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04https://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04https://askubuntu.com/questions/827005/how-to-install-eric-6-on-ubuntu-16-04.
# Import random module for use later in program.
import random
# Class to output different errors that could be encountered during game.
class Errors:
NotValid = "The space entered is not a valid move."
ShortMove = "Move must start at current position and finish at another square."
WrongPiece = "Player must move their own piece."
OccupiedSpace = "Player must move to an empty space."
MoveTooLong = "Player must move exactly two spaces."
BackwardMove = "Only king can move backward."
MustJump = ("Player must jump opponent in this move, and must do multiple jumps"
"if they are possible.")
KingPiece = "Move terminates immediately if piece enters king's row."
JumpMove = "If a move starts with a jump, only jumps can be performed."
InvalidCapture = "Player can only capture opponent's pieces."
InvalidMove = "Please move to an adjacent empty space, or jump the opponent."
# Class to populate and print board.
class Board():
board = [" " * 8 for i in range(8)]
error = Errors
def __init__(self, width, height):
self.width = width
self.height = height
def __repr__(self):
print(self.board)
#function to place pieces on the board, stri is the name of the pieces
def placepieces(self, stri):
#if we want to place white pieces but on bottom 3 rows, use letters array for distinguishing
#checkers pieces
wnum = 0;
bnum = 0;
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m']
if stri == "W":
i = self.height - 3
j = 0
while i < self.height:
j = 0
while j < self.width:
if i % 2 == 0:
if j % 2 == 1:
if wnum < 10:
self.board[i][j] = "W%s" % letters[wnum]
wnum += 1
else:
self.board[i][j] = "W%s" % letters[wnum]
wnum += 1
else:
pass
else:
if j % 2 == 1:
pass
else:
if wnum < 10:
self.board[i][j] = "W%s" % letters[wnum]
wnum += 1
else:
self.board[i][j] = "W%s" % letters[wnum]
wnum += 1
j += 1
i += 1
#else we want the black pieces, but on top 3 rows
else:
i = 0
j = 0
while i < 3:
j = 0
while j < self.width:
if i % 2 == 0:
if j % 2 == 1:
if bnum < 10:
self.board[i][j] = "B%s" % letters[bnum]
bnum += 1
else:
self.board[i][j] = "B%s" % letters[bnum]
bnum += 1
else:
pass
else:
if j % 2 == 1:
pass
else:
if bnum < 10:
self.board[i][j] = "B%s" % letters[bnum]
bnum += 1
else:
self.board[i][j] = "B%s" % letters[bnum]
bnum += 1
j += 1
i += 1
def setup(self):
#slashes used as a placeholder for empty spaces
self.board = [["//" for m in range(8)] for k in range(8)]
# place white team checkers
self.placepieces("W")
#place black team checkers
self.placepieces("B")
#print the board itself out, also prints out piece names etc.
def printboard(self):
i = 0
while i < self.height:
j = 0
print "---------------------------------------"
while j < self.width:
print "|%s|" % (self.board[i][j]),
j += 1
print ""
i += 1
print "---------------------------------------"
def move(self,str,move):
#find the location of the checker we are looking for, could be a function
#that returns to a checkers class with wval, hval, and str for variables?
i = 0
j = 0
wval = 0
hval = 0
while i < self.height:
j = 0;
while j < self.width:
if self.board[i][j] == str:
hval = i
wval = j
j += 1
i += 1
#white movement could be split into functions still needs checking for edges
# needs to handle kings/queens, and no jump handling, jump function could
# be made and replace the occupied space errors where a jump is possible
if(str.startswith("W")):
#moving up and to the right
if move == 9:
if self.board[hval - 1][wval + 1] == "//":
self.board[hval - 1][wval + 1] = self.board[hval][wval]
self.board[hval][wval] = "//"
board.printboard()
#error handling
else:
print ("%s") % (self.error.OccupiedSpace)
# moving up and to the left
elif move == 7:
if self.board[hval - 1][wval - 1] == "//":
self.board[hval - 1][wval - 1] = self.board[hval][wval]
self.board[hval][wval] = "//"
board.printboard()
# error handling
else:
print ("%s") % (self.error.OccupiedSpace)
# error handling for other moves
elif move == 1:
print ("%s") % (self.error.BackwardMove)
elif move == 3:
print ("%s") % (self.error.BackwardMove)
else:
print ("%s") % (self.error.InvalidMove)
#black movement could be split into functions, still needs checking for edges
# needs to handle kings/queens, and no jump handling, jump function could
# be made and replace the occupied space errors where a jump is possible
elif (str.startswith("B")):
# moving down and to the left
if move == 1:
if self.board[hval + 1][wval - 1] == "//":
self.board[hval + 1][wval - 1] = self.board[hval][wval]
self.board[hval][wval] = "//"
board.printboard()
#error handling
else:
print ("%s") % (self.error.OccupiedSpace)
# moving down and to the right
elif move == 3:
if self.board[hval + 1][wval + 1] == "//":
self.board[hval + 1][wval + 1] = self.board[hval][wval]
self.board[hval][wval] = "//"
board.printboard()
# error handling
else:
print ("%s") % (self.error.OccupiedSpace)
# error handling
elif move == 7:
print ("%s") % (self.error.BackwardMove)
elif move == 9:
print ("%s") % (self.error.BackwardMove)
else:
print ("%s") % (self.error.InvalidMove)
#start of main function area
#build a board that is 8x8, place checkers and print it out
board = Board(8, 8)
board.setup()
board.printboard()
| [
"noreply@github.com"
] | noreply@github.com |
b1cbde3a104f2e0b81d5ab63350c31dd2307980a | 0a4432a13600e025937af3b2554ae048321a50bb | /sphinx/conf.py | e717ad87e5ed58f5acf5bbcd3588642b18e4451a | [
"Apache-2.0"
] | permissive | PourroyJean/ProgrammingNote | 343c6a7fa3324b85cb7ed88e1bb794599d645c80 | 33fc7e64b3e5f44d1acde266df280f944d56674b | refs/heads/master | 2023-01-08T17:52:39.833582 | 2020-06-09T08:09:08 | 2020-06-09T08:09:08 | 87,910,140 | 2 | 0 | Apache-2.0 | 2022-12-27T15:01:06 | 2017-04-11T08:35:30 | Jupyter Notebook | UTF-8 | Python | false | false | 4,880 | py | # -*- coding: utf-8 -*-
#
# Notes Jean documentation build configuration file, created by
# sphinx-quickstart on Fri May 12 14:54:18 2017.
#
# 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.
# 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('.'))
# -- 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 = ['sphinxjp.themes.revealjs']
html_theme = 'revealjs'
html_use_index = False
# 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 = ['.txt', '.md']
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Notes Jean'
copyright = u'2017, Jean Pourroy'
author = u'Jean Pourroy'
# 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'
# The full version, including alpha/beta/rc tags.
release = u'1'
# 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 = 'fr'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# 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 = 'alabaster'
# 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']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'NotesJeandoc'
# -- 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, 'NotesJean.tex', u'Notes Jean Documentation',
u'Jean Pourroy', '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, 'notesjean', u'Notes Jean 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, 'NotesJean', u'Notes Jean Documentation',
author, 'NotesJean', 'One line description of project.',
'Miscellaneous'),
]
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
| [
"jean@Nano-ubuntu-VM.ielbyy3bjwuuredtcfjnooi3gd.ax.internal.cloudapp.net"
] | jean@Nano-ubuntu-VM.ielbyy3bjwuuredtcfjnooi3gd.ax.internal.cloudapp.net |
659788c034719b344f80307e0abf95f56aae99d2 | d16f2636a1157fde2eda16064b89dc6299d6c1fa | /main.py | 67691a8900c0347a4823718220af8a4e5fbfb262 | [] | no_license | razer89/Calculator | a762dd200074c7bd143fe087bf3752b92777f5c1 | cd2477c641f9f1ae08f72aea5f93bc5854dc240b | refs/heads/main | 2023-07-04T04:09:32.166568 | 2021-08-10T13:36:09 | 2021-08-10T13:36:09 | 382,019,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 318 | py | num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
action = str(input("Choose action: Add(a), Sub(s), Mult(m) Div(d) ->"))
print("The result is ",end="")
if action == "a":
print(num1+num2)
elif action == "s":
print(num1-num2)
elif action == "m":
print(num1*num2)
else:
print(num1/num2) | [
"49878506+razer89@users.noreply.github.com"
] | 49878506+razer89@users.noreply.github.com |
9e0d2453761f2903b984c6806664e6a9cfb0d256 | acac3cf012920dc027ee4343a2e27f02338b342f | /pattern_matcher/dto/project_dto.py | 0f5eca12d949e8f11e254de62cc59310aa4eb2a3 | [] | no_license | HYUNMIN-KIM/flask_start | ff60592d27cdc510402b6b18f7c8642db929de44 | 8897e00dd29e5f7b3db5d1cec6d597a8edb2980e | refs/heads/master | 2023-01-19T01:32:27.202743 | 2020-11-18T03:52:17 | 2020-11-18T03:52:17 | 291,651,373 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 625 | py | """
Project 전체에 대한 DTO
사이즈가 매우 큼
지식관리및학습서버와 대화작업서버간의 데이터 교환을 위해 사용됨
"""
from pattern_matcher.dto import triggering_pattern_dto
class ProjectDTO:
def __int__(self):
self.triggering_pattern_dto_list = triggering_pattern_dto()
# getter
@property
def triggering_pattern_dto_list(self):
return self.triggering_pattern_dto_list
@triggering_pattern_dto_list.setter
def triggering_pattern_dto_list(self, triggering_pattern_dto_list):
self.triggering_pattern_dto_list = triggering_pattern_dto_list
| [
"hogay88@wisenut.co.kr"
] | hogay88@wisenut.co.kr |
2e2f74124954a3985bfb08d9d40e0bc56bc5fff2 | 6e373b40393fb56be4437c37b9bfd218841333a8 | /Level_6/Lecture_9/enroll/forms.py | a24e95e08208751aa12e95e489b7e6bdfa3638eb | [] | no_license | mahto4you/Django-Framework | 6e56ac21fc76b6d0352f004a5969f9d4331defe4 | ee38453d9eceea93e2c5f3cb6895eb0dce24dc2b | refs/heads/master | 2023-01-22T01:39:21.734613 | 2020-12-04T03:01:17 | 2020-12-04T03:01:17 | 318,383,854 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 659 | py | from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class SignUpForm(UserCreationForm):
password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email']
labels ={'email':'Email'}
class EditUserProfileForm(UserChangeForm):
password = None
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login', 'is_active']
labels = {'email':'Email'} | [
"mahto4you@gmail.com"
] | mahto4you@gmail.com |
ce174f06a5f69d56fb0614a1766754e87ea39d0d | 0a983eebf91ad9a4342c8be92e1223b5d6ac28e1 | /setup.py | 13acd1717a2d8232655e0886d603d21d4dc7db71 | [
"MIT"
] | permissive | davidkwast/db_tools | 7bb1c6eeb01be81863e33edc38c60df8b31785b9 | 6881a3ce1d5bfb8634e01fc797d5e1dec6cd4891 | refs/heads/master | 2020-03-26T06:03:43.874788 | 2018-09-04T23:16:18 | 2018-09-04T23:16:18 | 144,587,472 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 306 | py | from setuptools import setup
setup(name='db_tools',
version='0.0',
description='Python database tools',
url='https://github.com/davidkwast/db_tools',
author='David Kwast',
author_email='david@kwast.me',
license='MIT',
packages=['db_tools'],
zip_safe=False)
| [
"david@kwast.me"
] | david@kwast.me |
bb69649a492b5bb2e5ee249630dca2d8b04e8c78 | 8f1996c1b5a0211474c7fa287be7dc20a517f5f0 | /batch/batch/cloud/driver.py | 96349e4c4d578c9209d5ffabef4590256096a62d | [
"MIT"
] | permissive | johnc1231/hail | 9568d6effe05e68dcc7bf398cb32df11bec061be | 3dcaa0e31c297e8452ebfcbeda5db859cd3f6dc7 | refs/heads/main | 2022-04-27T10:51:09.554544 | 2022-02-08T20:05:49 | 2022-02-08T20:05:49 | 78,463,138 | 0 | 0 | MIT | 2022-03-01T15:55:25 | 2017-01-09T19:52:45 | Python | UTF-8 | Python | false | false | 936 | py | from hailtop import aiotools
from gear import Database
from gear.cloud_config import get_global_config
from ..inst_coll_config import InstanceCollectionConfigs
from ..driver.driver import CloudDriver
from .azure.driver.driver import AzureDriver
from .gcp.driver.driver import GCPDriver
async def get_cloud_driver(
app,
db: Database,
machine_name_prefix: str,
namespace: str,
inst_coll_configs: InstanceCollectionConfigs,
credentials_file: str,
task_manager: aiotools.BackgroundTaskManager,
) -> CloudDriver:
cloud = get_global_config()['cloud']
if cloud == 'azure':
return await AzureDriver.create(
app, db, machine_name_prefix, namespace, inst_coll_configs, credentials_file, task_manager
)
assert cloud == 'gcp', cloud
return await GCPDriver.create(
app, db, machine_name_prefix, namespace, inst_coll_configs, credentials_file, task_manager
)
| [
"noreply@github.com"
] | noreply@github.com |
c9982973398a7bada2df68e8686fc6deee8ab7a5 | 3251eb404404da4f2cd49d7a77baf67c928453a2 | /src/membership/migrations/0003_coordinator_coordinator_image.py | 469ac79a801237f480cb16c68c332d19318926e5 | [
"MIT"
] | permissive | gatortechuf/gatortechuf.com | 6575abd26ce1382cfcb6255a28e1d202910c86ba | 8d0ad5f0772a42113c41bf454e96c2fa2c22d1f3 | refs/heads/master | 2020-05-22T06:49:09.580887 | 2018-02-03T17:42:02 | 2018-02-03T17:42:02 | 61,415,657 | 2 | 0 | MIT | 2018-02-03T17:42:03 | 2016-06-18T03:47:11 | Python | UTF-8 | Python | false | false | 489 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-28 18:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('membership', '0002_leader_leader_image'),
]
operations = [
migrations.AddField(
model_name='coordinator',
name='coordinator_image',
field=models.ImageField(blank=True, upload_to='membership'),
),
]
| [
"ryandsheppard95@gmail.com"
] | ryandsheppard95@gmail.com |
7796231c8f937912e9ccd9dd1399da035526bee6 | 55c0254b9889235844ca2fcfa5b80e6aedeb4841 | /Book_app/wsgi.py | ea116599419347d50d5b310f5c940541109e1334 | [] | no_license | AKSHAY-KR99/book_project | a75761a40c544fe4ad38ebcdd01b9d524e5f8ea8 | 019b316ec97395ac080be86333d7902b7c590271 | refs/heads/master | 2023-05-30T05:09:12.888518 | 2021-06-15T11:03:47 | 2021-06-15T11:03:47 | 377,130,492 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | """
WSGI config for Book_app 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Book_app.settings')
application = get_wsgi_application()
| [
"ashayakr4@gmail.com"
] | ashayakr4@gmail.com |
2ffa30e97c07a6799d516290ff2c899a4253a39e | eff8f2e795566c7aad10e9e3e7b0ffcafcc19145 | /Set_difference().py | 727190aca895eb0eb82fe4954ad9530732eca9d6 | [] | no_license | Siddu02june/HackerRank-Sets | b27aa2f3679a6f3324d4daa3c5dffe28f08ebed7 | a5a3b56d1bfbdd8b58b2df246e397000deaddbf6 | refs/heads/main | 2023-05-31T08:10:31.756639 | 2021-06-14T09:24:10 | 2021-06-14T09:24:10 | 376,763,510 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 269 | py | #Set_difference()
E = int(input())
English = list(input().split()[:E])
F = int(input())
French = list(input().split()[:F])
print(len(set(English)-set(French)))
'''
Input (stdin)
9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8
Your Output (stdout)
4
Expected Output
4
'''
| [
"noreply@github.com"
] | noreply@github.com |
abb8c70131d77c3c5abbae2840f52ba202b21851 | fb56624f35821c0714b516c30831953da8f8d131 | /run_fm_exp/scripts/select_params_ps.py | 6067d585576b36567a88aa013e419cab74d70423 | [] | no_license | jyhsia5174/pos-bias-exp-code | b27e31f6604420afae4aa4f2c9e6161ae7705bc4 | 913a00e6707482fd2122ec2c957e0dc8ebc3e7cc | refs/heads/master | 2022-12-26T20:09:50.893942 | 2020-10-05T07:23:04 | 2020-10-05T07:23:04 | 222,909,534 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,266 | py | import os, sys
root = sys.argv[1]
flag = 1 if sys.argv[2] == 'auc' else 0
log_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith('log')]
records = {}
for lp in log_paths:
records[lp] = [0., 1000., 0.] # iter, min_logloss, max_auc
with open(lp) as f:
for i, line in enumerate(f):
if i < 2:
continue
line = line.strip().split(' ')
line = [s for s in line if s != '']
iter_num = float(line[0])
logloss = float(line[-2])
auc = float(line[-1])
if flag:
if auc > records[lp][-1]:
records[lp][0] = iter_num
records[lp][1] = logloss
records[lp][2] = auc
else:
if logloss < records[lp][1]:
records[lp][0] = iter_num
records[lp][1] = logloss
records[lp][2] = auc
if flag:
params = sorted(records.items(), key=lambda x: x[-1][-1], reverse=flag)[0]
else:
params = sorted(records.items(), key=lambda x: x[-1][-2], reverse=flag)[0]
print(params[0].split('/')[-1].split('.')[0], params[0].split('/')[-1].split('.')[2], int(params[1][0]), params[1][1], params[1][2],)
| [
"d08944012@ntu.edu.tw"
] | d08944012@ntu.edu.tw |
d2d8d1a76517bf0cbfed79f32e7b7f96acb604a2 | a7a8e79ba13962d792d9aa1ee758f095083044b9 | /gened.py | 6eedddca46433cccfb8e35171c9c33fc5f66edd9 | [] | no_license | vannjo02/Gen_eds | 96744091a8f08504fe68739ecee5e8b7b1b17b4a | 5fda16f2531e38358fdfadadf890037c4ad56fe5 | refs/heads/master | 2021-01-20T09:55:02.222524 | 2017-05-04T19:15:36 | 2017-05-04T19:15:36 | 90,300,687 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,804 | py | from flask import Flask, render_template, request
import psycopg2
from flask_bootstrap import Bootstrap
import os
app = Flask(__name__)
Bootstrap(app)
conn = psycopg2.connect(os.environ['DATABASE_URL'])
print('READY')
@app.route('/')
def index():
reqlst = ["Human Expression—Primary Texts", "Intercultural", "Historical", "Natural World—Nonlab", "Religion", "Human Expression", "Skills", "Human Behavior", "Human Behavior—Social Science Methods", "Quantitative", "Natural World—Lab", "Biblical Studies", "Wellness"]
cur=conn.cursor()
cur.execute("select number, title, count(requirement.description) as count from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) group by number, title order by count desc limit 5")
res=cur.fetchall()
print(res)
return render_template('index.html', reqs=reqlst, res = res)
@app.route('/requirement/')
def requirement():
reqs=tuple(request.args.getlist('option'))
cur=conn.cursor()
cur.execute("select number, title from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where requirement.description in %s group by number, title having count(requirement.description) >= %s", (reqs, len(reqs)))
res=cur.fetchall()
print(res)
return render_template('requirement.html', courses=res, reqs = reqs)
@app.route('/course/<crs>')
def course(crs):
cur = conn.cursor()
cur.execute("select requirement.description from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where course.number = %s", (crs,))
res = cur.fetchall()
print(res)
cur.execute("select title, course.description from course where course.number = %s", (crs,))
info = cur.fetchall()[0]
print(info)
return render_template('course.html', course = res, info = info, crs = crs)
@app.route('/search/')
def search():
query = tuple(request.args.getlist('input'))[0].title()
search= "%" + query + "%"
cur = conn.cursor()
cur.execute("select number, title from course where course.title like %s", (search,))
search = cur.fetchall()
print("Results", search)
fulfills = []
for course in search:
cur.execute("select requirement.description from course join course_requirement on (course.id = course_requirement.course) join requirement on (requirement.id = course_requirement.requirement) where course.number = %s", (course[0],))
tmp = []
for req in cur.fetchall():
tmp.append(req[0])
fulfills.append(tmp)
print("Reqs list", fulfills)
return render_template('search.html', search = search, lst = fulfills, query = query)
if __name__ == '__main__':
app.run(debug='True')
| [
"vannjo02@luther.edu"
] | vannjo02@luther.edu |
6249e0ffb60185954c5323d646f6ee5e4b97a4cc | 2be8a9f06d4003d12c0a727fb83d284c31a53050 | /HoudiniHotBox17.0/lib/PastFbx.py | a984bb3fb35778efa1d77ea747bb869b4f43016f | [] | no_license | LiuLiangFx/SmileHotBOX | 7551d9578b2defe612950cb8e3bffdb85024cede | 8bd8eac69b3c2a9824b9aa4488ca77789bea8d85 | refs/heads/master | 2021-01-01T10:22:26.959731 | 2020-02-09T03:16:32 | 2020-02-09T03:16:32 | 239,236,801 | 0 | 0 | null | 2020-02-09T02:47:18 | 2020-02-09T02:47:18 | null | UTF-8 | Python | false | false | 3,133 | py | import hou
class PastFbx:
def __init__(self):
pass
def checkNode(self,node, name,temp1 =0):
for childrenNode in node.parent().children():
if childrenNode.name() == name:
temp1 =childrenNode
return temp1
def checkInput(self,qian,hou1,temp=0):
if hou1.inputs() ==():
pass
else:
for node in hou1.inputs():
if node == qian:
temp =hou1
else:
temp =0
return temp
def creatNode(self,node,temp ):
for mergeName in temp:
serachNode = self.checkNode(node, mergeName)
if serachNode :
houNode = self.checkInput(node, serachNode )
if houNode ==0:
serachNode.setInput(100,node)
node = serachNode
else:
node = houNode
else:
merge = node.createOutputNode("merge",mergeName)
node = merge
def run(self):
plane = hou.ui.paneTabOfType(hou.paneTabType.NetworkEditor)
pos = plane.selectPosition()
pos1 = pos
node = plane.currentNode()
fl1=open('list.txt', 'r')
a= len( fl1.readlines())
check = 0
fl1.close()
for index in range(a):
pos[0] +=1
try:
null = node.createNode("object_merge")
except:
b = node.parent()
null =b.createNode("object_merge")
null.setPosition(pos)
fl1=open('list.txt', 'r')
path = fl1.readlines()[index][0:-1]
allPath= path.split("++")
null.parm("objpath1").set(allPath[0])
null.parm("xformtype").set("local")
attNode = null.createOutputNode("attribcreate")
attNode.parm("name1").set("shop_materialpath")
attNode.parm("type1").set("index")
attNode.parm("string1").set("/shop/"+ allPath[-1])
attNode.parm("class1").set("primitive")
catchNode = attNode.createOutputNode("catche_tool_1.0.1")
catchNode.bypass(1)
currentNode =catchNode
self.creatNode(currentNode,allPath[1:-1] )
comping =int((index*1.0/(a-1))*100 )
fl1.close()
print "CreatNode for " + null.name()+","+" Comping: " + str(comping)+"%"
print "\nCopy node success!!!!"
| [
"change52092@yahoo.com"
] | change52092@yahoo.com |
d86790151df1e4863c98a6064062d24f7876ecb4 | 192cc298bc78889873fc932041c543bdc7b54bbb | /Cashier program.py | 05d4371d74c7fd8262e8a02db5d9de3ddfc59112 | [] | no_license | winter4w/Cashier-Program | 01af06ccbd9d06fa509861e9a57094ad8ed100d6 | 8126ae412d7de21e95a415b5242508cb6d9df126 | refs/heads/master | 2020-09-22T16:41:06.845507 | 2019-12-02T06:59:42 | 2019-12-02T06:59:42 | 225,275,559 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,397 | py |
import os
import time
import sys
import math
class Cashier():
def getDollars(self, a):
dol = int(math.floor(a))
return dol
def getQuarters(self, a):
qua = int(math.floor(a / .25))
return qua
def getDimes(self, a):
dim = int(math.floor(a / .10))
return dim
def getNickels(self, a):
nic = int(math.floor(a / .05))
return nic
def getPennies(self, a):
pen = int(a / .01 +.1)
return pen
def newChange(self, a, coin_value , numberofcoins):
return a - coin_value * numberofcoins
myChange = Cashier()
while True:
print("")
print("Enter the amount due in dollars and cents: ")
amountDue = float(raw_input("$"))
print("")
amountReceived = float(raw_input("Enter the amount received: $"))
print("")
change = amountReceived - amountDue
if amountDue > amountReceived:
print("The customer has payed less than the cost")
else:
dolSolve = myChange.getDollars(change)
change = myChange.newChange(change, 1, dolSolve)
quaSolve = myChange.getQuarters(change)
change = myChange.newChange(change, .25, quaSolve)
dimSolve = myChange.getDimes(change)
change = myChange.newChange(change, .10, dimSolve)
nicSolve = myChange.getNickels(change)
change = myChange.newChange(change, .05, nicSolve)
penSolve = myChange.getPennies(change)
print("Give the customer")
print(str(dolSolve) + " Dollars")
print(str(quaSolve) + " Quarters")
print(str(dimSolve) + " Dimes")
print(str(nicSolve) + " Nickels")
print(str(penSolve) + " Pennies")
print("")
choiceQuit = raw_input ("If you will like to quit this program type 'quit' otherwise press enter:")
os.system('cls')
if choiceQuit == "quit":
break
else:
True
os.system('cls')
print("The Program is now closeing!")
print ("5")
time.sleep(1)
os.system('cls')
print("The Program is now closeing!")
print ("4")
time.sleep(1)
os.system('cls')
print("The Program is now closeing!")
print ("3")
time.sleep(1)
os.system('cls')
print("The Program is now closeing!")
print ("2")
time.sleep(1)
os.system('cls')
print("The Program is now closeing!")
print ("1")
sys.exit()
| [
"winter4w@users.noreply.github.com"
] | winter4w@users.noreply.github.com |
65e87e100e5ca37ed1bf10f7336709b79e1b9140 | b558b4348ff88bb670bf1a318d3c22d48ebf5627 | /src/manage.py | 7325504ca062609d3ef47b1c19939d4ae8762ec9 | [] | no_license | rnjane/Flight-Booking-API | 540fe63d47a6ac622633b8560603ce34600857e2 | 05f974c1f6b3dafe18b7cdc417f11f314271625b | refs/heads/develop | 2022-12-10T13:21:57.567096 | 2019-02-04T11:06:11 | 2019-02-04T11:06:11 | 162,910,819 | 0 | 0 | null | 2022-12-08T01:34:12 | 2018-12-23T17:26:58 | Python | UTF-8 | Python | false | false | 546 | py | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookingproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| [
"robert.njane@andela.com"
] | robert.njane@andela.com |
50b929b62405be6ed8aacd6a49a420bd9ba63219 | 23ac56d6e024a69ae9f6f9e471ddefd71c9f0243 | /reverse_list.py | 3ce059eb10cf84065d68099596ca3be2bda56c8f | [] | no_license | erenat77/data_structure_in_Python | c70538f2c510b5525b230f84f7b455a0524d7313 | 216b173ab27cbbd3440c783efbd671be47645457 | refs/heads/master | 2020-08-11T10:16:48.352675 | 2019-11-05T01:03:07 | 2019-11-05T01:03:07 | 214,548,248 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 169 | py | l = [1,2,5,4,8,9,87,9,9,6,4,5]
# recursive solution
def rev(l):
if len(l)<=1 : return l
else: return [l[-1]] + rev(l[:-1])
rev(l)
#easy solution
print(l[::-1])
| [
"noreply@github.com"
] | noreply@github.com |
9ffedfdbb5aa841be3b526cd48ec2b1a4d37799e | 459e0f34dfbc818763edf153152711a11c2efbe3 | /pythonscript/billing.py | 65cc9ddd17973536698c22abf0b14a204bd7a018 | [] | no_license | tariqcoupa/experiments | 15523c7f60edcb3078169fb9f407915f859ef91d | 3323add34d66ebc76d91124c7358abd639d9317a | refs/heads/master | 2021-04-05T23:52:21.718538 | 2018-03-03T12:31:49 | 2018-03-03T12:31:49 | 124,418,067 | 0 | 0 | null | 2018-03-08T16:26:12 | 2018-03-08T16:26:12 | null | UTF-8 | Python | false | false | 566 | py | #!/usr/bin/python
import SoftLayer
import json
import sys
client = SoftLayer.Client(username='prod.tariq', api_key='53c53cba25872849417fcc1794f9acdeb91c6680f597ddf76488aa4e4d999e51')
object_mask = "mask[id]"
object_mask2 = """mask[hostname,billingItem.nextInvoiceTotalRecurringAmount]"""
user_info = client['Account'].getHardware(mask=object_mask)
mgr = SoftLayer.HardwareManager(client)
for json_dict in user_info:
for key,value in json_dict.iteritems():
hardware_info = mgr.get_hardware(hardware_id=value,mask=object_mask2)
print hardware_info
| [
"tarsidd@gmail.com"
] | tarsidd@gmail.com |
a3b8ebb9edc3184f04b98b58d25d2ad29b4d644c | 3b21c2a5422dc2b900f65894849e7e2e765fc7cc | /CameraField.py | 8e4d25c66f759a3b7ebfd2a2dfdccca52657da95 | [] | no_license | mrbhjv/dft_python | 2c519dcdb5100511376c35db63c0248628fb9b3e | 480fffd81374f37f6a62c362fb551b2021772429 | refs/heads/master | 2020-04-24T09:04:28.412581 | 2011-07-21T12:23:47 | 2011-07-21T12:23:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,204 | py | import naoqi
from naoqi import ALProxy
import numpy
import DynamicField
import math_tools
class NaoCameraField(DynamicField.DynamicField):
"Camera field"
def __init__(self):
"Constructor"
DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]])
self._vision_proxy = ALProxy("ALVideoDevice", "nao.ini.rub.de", 9559)
self._gvm_name = "nao vision"
self._gvm_name = self._vision_proxy.subscribe(self._gvm_name, 0, 12, 30)
# switch off auto white balance
self._vision_proxy.setParam(12, 0)
# select the bottom camera
self._vision_proxy.setParam(18, 1)
self._name = "nao_camera_field"
def __del__(self):
self._gvm_name = self._vision_proxy.unsubscribe(self._gvm_name)
def _step_computation(self):
naoimage = self._vision_proxy.getImageRemote(self._gvm_name)
hsv_image = numpy.fromstring(naoimage[6], dtype=numpy.uint8)
hue = hsv_image[::3].reshape(120,160)
saturation = hsv_image[1::3].reshape(120,160)
hue = numpy.rot90(hue, 3)
saturation = numpy.rot90(saturation, 3)
sizes = self.get_input_dimension_sizes()
max_activation_level = 5.0
hue = math_tools.linear_interpolation_2d_custom(hue, [sizes[0], sizes[1]])
saturation = math_tools.linear_interpolation_2d_custom(saturation, [sizes[0], sizes[1]])
hue = numpy.round(hue * ((sizes[2] - 1)/255.)).astype(numpy.int)
saturation = saturation * (2 * max_activation_level / 255.) - max_activation_level
for i in range(sizes[0]):
for j in range(sizes[1]):
color = hue[i][j]
self._activation[i][j] = -max_activation_level
self._activation[i][j][color] = saturation[i][j]
self._activation[0,:,:] = -max_activation_level
self._activation[sizes[0]-1,:,:] = -max_activation_level
self._activation[:,0,:] = -max_activation_level
self._activation[:,sizes[1]-1,:] = -max_activation_level
self._output_buffer = self.compute_thresholded_activation(self._activation)
class GaussCameraField(DynamicField.DynamicField):
"Camera field"
def __init__(self):
"Constructor"
DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]])
self._activation += math_tools.gauss_3d([40,30,15], 9.0, [2.0,2.0,2.0], [10,20,0])
self._output_buffer = self.compute_thresholded_activation(self._activation)
def _step_computation(self):
pass
class DummyCameraField(DynamicField.DynamicField):
"Camera field"
def __init__(self):
"Constructor"
DynamicField.DynamicField.__init__(self, dimension_bounds = [[40],[30],[15]])
camera_field_file = open("snapshots/camera_field.txt", 'r')
activation = numpy.fromfile(camera_field_file, sep=', ')
camera_field_file.close()
activation = activation.reshape(160,120,50)
self._activation = math_tools.linear_interpolation_nd(activation, [40, 30, 15])
self._output_buffer = self.compute_thresholded_activation(self._activation)
def _step_computation(self):
pass
| [
"mathis.richter@ini.rub.de"
] | mathis.richter@ini.rub.de |
7e41be08a3a77a30cf7becf9259474bda1cdf940 | 6bde544edbda4291b8fd10533e3ec0cca4855a1f | /problem_2.py | ac9fd9e6bef2503460e546c4ca2608d9b641bf76 | [] | no_license | ekdeguzm/project_euler_problem_2 | 5d2ba3806a1679e188eee293ada334e53f5175bc | 6ba89ca7b181236d4c916bd31aeedbb2ceb8665a | refs/heads/main | 2023-08-24T23:50:26.581516 | 2021-09-29T06:57:09 | 2021-09-29T06:57:09 | 411,562,145 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 680 | py | # Probem 2 of Project Euler
# Python 3.9.5
# Even Fibonacci numbers
# Create Fibonacci list and even Fibonacci list
fib_list = []
even_fib_list = []
# Create Fibonacci sequence
def fibonacci(n):
a, b = 0, 1
for x in range(1, n):
a, b = b, a + b
return b
for i in range(1, 34):
fib_list.append(fibonacci(i))
# Print Fibonacci seq no more than 4,000,000
print(fib_list)
# Get the even values from fib_list and add it it into the even list
for value in fib_list:
if value % 2 == 0:
even_fib_list.append(value)
else:
None
print("Updated list", even_fib_list)
# Add values from even_fib_list together
print(sum(even_fib_list))
| [
"noreply@github.com"
] | noreply@github.com |
46e1519a37697b33c70c2f43ee6217c51755e86e | b169e1ac175f0acf5e48d58ce1acd04e6e4be158 | /utils/logfile_parser.py | 832d1045ea605bf6720390d8e3465002a8d2f63f | [] | no_license | bip5/osr_closed_set_all_you_need | 20ec1380190d3a1eb13eebdeeddabaff4f91b019 | 0e57845f6a4a64f6a01a31dec6911c5cb5bf3c5d | refs/heads/main | 2023-08-17T18:12:47.691043 | 2021-10-13T22:30:35 | 2021-10-13T22:30:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,967 | py | import re
import pandas as pd
import os
import numpy as np
from matplotlib import pyplot as plt
pd.options.display.width = 0
rx_dict = {
'model_dir': re.compile(r'model_dir=\'(.*?)\''),
'dataset': re.compile(r'dataset=\'(.*?)\''),
'loss': re.compile(r'loss=\'(.*?)\''),
'cs': re.compile(r'cs=(.*?),'),
'm': re.compile(r'rand_aug_m=([-+]?\d*)'),
'n': re.compile(r'rand_aug_n=([-+]?\d*)'),
'performance': re.compile("[-+]?\d*\.\d+|\d+"),
'split_idx': re.compile(r'split_idx=(\d)'),
'seed': re.compile(r'seed=(\d)'),
'runtime': re.compile(r'Total elapsed time \(h:m:s\): (.*?)\n'),
'label_smoothing': re.compile("label_smoothing=([-+]?\d*\.\d+|\d+)"),
'lr': re.compile(" lr=(\d*\.\d+|\d+)")
# 'oscr': re.compile("label_smoothing=([-+]?\d*\.\d+|\d+)")
}
save_root_dir = '/work/sagar/open_set_recognition/sweep_summary_files/ensemble_pkls'
def get_file(path):
file = []
with open(path, 'rt') as myfile:
for myline in myfile: # For each line, read to a string,
file.append(myline)
return file
def parse_arpl_out_file(path, rx_dict, root_dir=save_root_dir, save_name='test.pkl', save=True, verbose=True):
file = get_file(path=path)
models = []
for i, line in enumerate(file):
if line.find('Namespace') != -1:
model = {}
s = rx_dict['model_dir'].search(line).group(1)
exp_id = s[s.find("("):s.find(")") + 1]
model['exp_id'] = exp_id
model['M'] = rx_dict['m'].search(line).group(1)
model['N'] = rx_dict['n'].search(line).group(1)
model['split_idx'] = rx_dict['split_idx'].search(line).group(1)
model['seed'] = rx_dict['seed'].search(line).group(1)
model['dataset'] = rx_dict['dataset'].search(line).group(1)
model['loss'] = rx_dict['loss'].search(line).group(1)
model['cs'] = rx_dict['cs'].search(line).group(1)
model['lr'] = rx_dict['lr'].search(line).group(1)
if rx_dict['label_smoothing'].search(line) is not None:
model['label_smoothing'] = rx_dict['label_smoothing'].search(line).group(1)
if line.find('Finished') != -1:
line_ = file[i - 1]
perfs = rx_dict['performance'].findall(line_)[:3]
model['Acc'] = perfs[0]
model['AUROC'] = perfs[1]
model['OSCR'] = perfs[2]
model['runtime'] = rx_dict['runtime'].search(line).group(1)
models.append(model)
data = pd.DataFrame(models)
if verbose:
print(data)
if save:
save_path = os.path.join(root_dir, save_name)
data.to_pickle(save_path)
else:
return data
def parse_multiple_files(all_paths, rx_dict, root_dir=save_root_dir, save_name='test.pkl', verbose=True, save=False):
all_data = []
for path in all_paths:
data = parse_arpl_out_file(path, rx_dict, save=False, verbose=False)
data['fname'] = path.split('/')[-1]
all_data.append(data)
all_data = pd.concat(all_data)
save_path = os.path.join(root_dir, save_name)
if save:
all_data.to_pickle(save_path)
if verbose:
print(all_data)
return all_data
save_dir = '/work/sagar/open_set_recognition/sweep_summary_files/ensemble_pkls'
base_path = '/work/sagar/open_set_recognition/slurm_outputs/myLog-{}.out'
# base_path = '/work/sagar/open_set_recognition/dev_outputs/logfile_{}.out'
all_paths = [base_path.format(i) for i in [325905]]
# all_paths = [base_path.format(i) for i in [507, 508, 509, 510, 511]]
data = parse_multiple_files(all_paths, rx_dict, verbose=True, save=False, save_name='test.pkl')
print(f"Mean Acc: {np.mean(data['Acc'].values.astype('float')):.2f}")
print(f"Mean AUROC: {np.mean(data['AUROC'].values.astype('float')):.2f}")
print(f"Mean OSCR: {np.mean(data['OSCR'].values.astype('float')):.2f}")
print(len(data))
print(data['exp_id'].values) | [
"sagarvaze@dhcp24.robots.ox.ac.uk"
] | sagarvaze@dhcp24.robots.ox.ac.uk |
2f6e56a99087d6e94afa25eea1ce94be32f3127d | d906d1eb4f590deabb3c90ba9bb9dd6b11cabc55 | /web1/app.py | 8e1d00b00346a5d0c80c0b5615f4f791fec19f93 | [] | no_license | Lengoctruongson/lengoctruongson-fundametal-c4e21 | 83dfe671639faaf2bd2642f77b62df1c306db2f7 | 55affab6315f408f8c42a12b57775ec442a222f8 | refs/heads/master | 2020-03-26T20:02:56.120667 | 2018-10-09T16:41:34 | 2018-10-09T16:41:34 | 145,301,267 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,569 | py | #1. Creat a flask app
from flask import Flask, render_template
app = Flask(__name__)
ps = [
"Trong đầm gì đẹp bằng sen aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"Lá xanh bông trắng lại chen nhị vàngbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"Nhị vàng bông trắng lá xanh ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
]
#2. Creat router
@app.route("/")
def homepage():
return render_template("homepage.html",
title="Ca dao về sen",
posts=ps)
@app.route("/huy")
def huypage():
return "Hello Huy"
@app.route("/hello/<name>")
def hello(name):
return "Hello " + name
@app.route("/posts/<int:position>")
def post_detail(position):
if position < 0 or position >= len(ps):
return "Not found", 404
post = ps[position - 1]
return render_template("post_detail.html", post=post)
@app.route("/posts")
def posts():
shortened_ps = []
for post in ps:
shortened_ps.append(post[0:20])
return render_template("post_list.html", posts=shortened_ps)
# @app.route("/add/<number1>/<number2>")
# def add(number1,number2):
# add = str(int(number1) + int(number2))
# return add
@app.route("/add/<int:a>/<int:b>")
def add(a,b):
result = a+b
return str(result)
@app.route("/h1tag")
def h1tag():
return "<h1>Heading 1 - Bigggg</h1><p>Hom nay toi buon</p>"
#3. Run app
print("Running app")
if __name__ == "__main__":
app.run(debug=True) # listening | [
"leson1871995@hgamil.com"
] | leson1871995@hgamil.com |
835a35a0816d80e070b145914b614c4079752764 | 680d9e12f9916f68f84921e1b0328786454f2d50 | /cmd_line_sample.py | 3485a5f3ce5e52b1f0b411f971f00a44f69189b3 | [] | no_license | vkarpov15/hydra-injector-py | 24c791fd1bc3c90681b48f7515fc0e359fd14a94 | 3948b5056c4cf563db77c7172c6660daa7c62b19 | refs/heads/master | 2020-12-24T13:52:41.541934 | 2012-11-09T01:39:32 | 2012-11-09T01:39:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,353 | py | #
# cmd_line_sample.py
#
# Created on: November 3, 2012
# Author: Valeri Karpov
#
# An example usage of CommandLineInjector - a very general method for stripping
# padding from a sample file. While this is a somewhat trivial example, it
# highlights some of the more useful features of this library - managing object
# ("square") life cycle, wiring two methods / "circles" together, constructing
# squares from command line params, and a minimum of non-reusable boilerplate
#
from CommandLineInjector import *
import inspect
class FileReader:
inject = ["infile"]
def __init__(self, infile):
self.filename = infile
print infile
def initialize(self):
self.f = open(self.filename, "r")
def close(self):
self.f.close()
def getLines(self):
return self.f.readlines()
class FileWriter:
inject = ["outfile"]
def __init__(self, outfile):
self.filename = outfile
print outfile
def initialize(self):
self.f = open(self.filename, "w")
def close(self):
self.f.close()
def writeLine(self, line):
self.f.write("%s\n" % line)
def removePaddingFromFile(reader):
lines = reader.getLines()
newLines = [line.strip() for line in lines]
return newLines
def writeUnpaddedFile(writer, lines = "method:removePaddingFromFile"):
for line in lines:
writer.writeLine(line)
#### This is boilerplate
#### Sample run: python cmd_line_sample.py writeUnpaddedFile --f="../test" --outfile=../test2
class MyRunner:
def run(self, method, params):
return eval(method)(**params)
def getSpecs(self, method):
return inspect.getargspec(eval(method))
# Binding magic. Roughly translated:
# 1) Whenever a method or class asks for something called "reader", it means
# a FileReader where the constructor parameter "infile" is taken from
# command line parameter -f
# 2) Similar to above, "writer" is a FileWriter where all of its constructor
# parameters are taken from command line parameter with same name
# 3/4) Add the methods removePaddingFromFile and writeUnpaddedFile as callable
# methods from command line
# 5) Run using command line arguments using the runner from this scope
CommandLineInjector().addClass("reader", FileReader, { "infile" : "f" }).addClass("writer", FileWriter).addMethod("removePaddingFromFile").addMethod("writeUnpaddedFile").run(MyRunner())
| [
"valkar207@gmail.com"
] | valkar207@gmail.com |
0f6b34fbcc11d1d36e1186122b4196348d01de41 | 15d3a10db27128c06f84c30fa8d64b2e1c629fd9 | /express/express/api_exception.py | 50d8121033b83ac36e6070744f39d492bda13465 | [] | no_license | yiyuhao/exp | 7cba6650e3113ba05698f90a7baf75b680dd6435 | 866a90b2e6f0d113559b0674f514cdd56020f7d6 | refs/heads/master | 2020-03-19T20:20:04.799355 | 2018-07-15T14:55:24 | 2018-07-15T14:55:24 | 136,897,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 431 | py | # -*- coding: utf-8 -*
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response | [
"yiyuhao@mixadx.com"
] | yiyuhao@mixadx.com |
d7e5e857f01d9f595c4e22550aeb3ed978f814ef | f7378f4038882c3de627a7d1262790f649f5e89b | /dataset.py | 77564e166a38e75ee487cdf75078cb3d77632132 | [] | no_license | edui/imogiz-mobileunet | 176301a5238b0ab354b2fcf0a666c2820cbc165d | 49757428b9fc320211b417450f2e883d9d444225 | refs/heads/main | 2023-08-10T18:32:55.037061 | 2021-09-27T22:39:39 | 2021-09-27T22:39:39 | 408,748,322 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,710 | py | import random
import re
from glob import glob
import cv2
import numpy as np
import pandas as pd
from PIL import Image
import torch
from torch.utils.data import Dataset
import torchvision
from config import IMG_DIR
def _mask_to_img(mask_file):
img_file = re.sub('^{}/masks'.format(IMG_DIR),
'{}/images'.format(IMG_DIR), mask_file)
img_file = re.sub('\.ppm$', '.jpg', img_file)
return img_file
def _img_to_mask(img_file):
mask_file = re.sub('^{}/images'.format(IMG_DIR),
'{}/masks'.format(IMG_DIR), img_file)
# mask_file = re.sub('\.jpg$', '.ppm', mask_file)
return mask_file
def get_img_files_eval():
mask_files = sorted(glob('{}/masks/*.jpg'.format(IMG_DIR)))
return np.array([_mask_to_img(f) for f in mask_files])
def get_img_files():
mask_files = sorted(glob('{}/masks/*.jpg'.format(IMG_DIR)))
# mask_files = mask_files[:10000]
sorted_mask_files = []
# Sorting out
for msk in mask_files:
# Sort out black masks
msk_img = cv2.imread(msk)
if len(np.where(msk_img == 1)[0]) == 0:
continue
# Sort out night images
img_path = re.sub('^{}/masks'.format(IMG_DIR),
'{}/images'.format(IMG_DIR), msk)
img = cv2.imread(img_path)
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
higher_img = gray_image[0:120, :]
if np.average(higher_img) > 100:
# Day image, so append
sorted_mask_files.append(msk)
# return np.array([_mask_to_img(f) for f in mask_files])
return np.array([_mask_to_img(f) for f in sorted_mask_files])
class MaskDataset(Dataset):
def __init__(self, img_files, transform, mask_transform=None, mask_axis=0):
self.img_files = img_files
self.mask_files = [_img_to_mask(f) for f in img_files]
self.transform = transform
if mask_transform is None:
self.mask_transform = transform
else:
self.mask_transform = mask_transform
self.mask_axis = mask_axis
def __getitem__(self, idx):
img = cv2.imread(self.img_files[idx])
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
mask = cv2.imread(self.mask_files[idx])
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
mask = mask[:, :, self.mask_axis]
seed = random.randint(0, 2 ** 32)
# Apply transform to img
random.seed(seed)
img = Image.fromarray(img)
img = self.transform(img)
# Apply same transform to mask
random.seed(seed)
mask = Image.fromarray(mask)
mask = self.mask_transform(mask)
return img, mask
def __len__(self):
return len(self.img_files)
class MogizDataset(Dataset):
def __init__(self, ds_dir, ds_name, transform, mask_transform=None, mask_axis=0):
self.df = pd.read_csv(ds_dir + ds_name, header=None)
self.ds_dir = ds_dir
self.transform = transform
if mask_transform is None:
self.mask_transform = transform
else:
self.mask_transform = mask_transform
self.mask_axis = mask_axis
def __getitem__(self, idx):
image_name = self.df.iloc[idx, 0]
mask_name = self.df.iloc[idx, 1]
joint_name = self.df.iloc[idx, 2]
height = torch.from_numpy(
np.array([self.df.iloc[idx, 3]/100])).type(torch.FloatTensor)
weight = torch.from_numpy(
np.array([self.df.iloc[idx, 4]/100])).type(torch.FloatTensor)
img = cv2.imread(self.ds_dir + image_name)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
mask = cv2.imread(self.ds_dir + mask_name)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
mask = mask[:, :, self.mask_axis]
# For Heatmaps
#joint = np.load(self.ds_dir + joint_name).astype('int64')
#joint = torch.from_numpy(joint)
joint = height # not used
seed = random.randint(0, 2 ** 32)
# Apply transform to img
random.seed(seed)
img = Image.fromarray(img)
img = self.transform(img)
# Apply same transform to mask
random.seed(seed)
mask = Image.fromarray(mask)
mask = self.mask_transform(mask)
# return img, mask, height
return {'i': img, 'l': mask, 'j': joint, 'h': height, 'w': weight}
def __len__(self):
return len(self.df)
if __name__ == '__main__':
pass
#
# mask = cv2.imread('{}/masks/Aaron_Peirsol_0001.ppm'.format(IMG_DIR))
# mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
# mask = mask[:, :, 0]
# print(mask.shape)
# plt.imshow(mask)
# plt.show()
| [
"edui.bin@gmail.com"
] | edui.bin@gmail.com |
adcb107a99607a4473a99cbe4a62c8ecc5918f4d | f71118a9f24e09bba18d021f9c4a43a97dc4dead | /codes/scripts/make_gif_video.py | fc81e5647ff7ce75b5bb35f226bce946a93a1d56 | [
"Apache-2.0"
] | permissive | BlueAmulet/BasicSR | d7420fd9d7b73bf0cd90a3201d84393f262e63be | 7040913d8659a05af4c2428feb71c260efbf1e9c | refs/heads/lite | 2021-07-10T14:48:26.037589 | 2020-07-23T01:59:27 | 2020-07-23T01:59:27 | 196,041,187 | 19 | 9 | Apache-2.0 | 2020-09-01T17:39:00 | 2019-07-09T16:00:14 | Python | UTF-8 | Python | false | false | 3,311 | py | """
Add text to images, then make gif/video sequence from images.
Since the created gif has low quality with color issues, use this script to generate image with
text and then use `gifski`.
Call `ffmpeg` to make video.
"""
import os.path
import numpy as np
import cv2
crt_path = os.path.dirname(os.path.realpath(__file__))
# configurations
img_name_list = ['x1', 'x2', 'x3', 'x4', 'x5']
ext = '.png'
text_list = ['1', '2', '3', '4', '5']
h_start, h_len = 0, 576
w_start, w_len = 10, 352
enlarge_ratio = 1
txt_pos = (10, 50) # w, h
font_size = 1.5
font_thickness = 4
color = 'red'
duration = 0.8 # second
use_imageio = False # use imageio to make gif
make_video = False # make video using ffmpeg
is_crop = True
if h_start == 0 or w_start == 0:
is_crop = False # do not crop
img_name_list = [x + ext for x in img_name_list]
input_folder = os.path.join(crt_path, './ori')
save_folder = os.path.join(crt_path, './ori')
color_tb = {}
color_tb['yellow'] = (0, 255, 255)
color_tb['green'] = (0, 255, 0)
color_tb['red'] = (0, 0, 255)
color_tb['magenta'] = (255, 0, 255)
color_tb['matlab_blue'] = (189, 114, 0)
color_tb['matlab_orange'] = (25, 83, 217)
color_tb['matlab_yellow'] = (32, 177, 237)
color_tb['matlab_purple'] = (142, 47, 126)
color_tb['matlab_green'] = (48, 172, 119)
color_tb['matlab_liblue'] = (238, 190, 77)
color_tb['matlab_brown'] = (47, 20, 162)
color = color_tb[color]
img_list = []
# make temp dir
if not os.path.exists(save_folder):
os.makedirs(save_folder)
print('mkdir [{}] ...'.format(save_folder))
if make_video:
# tmp folder to save images for video
tmp_video_folder = os.path.join(crt_path, '_tmp_video')
if not os.path.exists(tmp_video_folder):
os.makedirs(tmp_video_folder)
idx = 0
for img_name, write_txt in zip(img_name_list, text_list):
img = cv2.imread(os.path.join(input_folder, img_name), cv2.IMREAD_UNCHANGED)
base_name = os.path.splitext(img_name)[0]
print(base_name)
# crop image
if is_crop:
print('Crop image ...')
if img.ndim == 2:
img = img[h_start:h_start + h_len, w_start:w_start + w_len]
elif img.ndim == 3:
img = img[h_start:h_start + h_len, w_start:w_start + w_len, :]
else:
raise ValueError('Wrong image dim [{:d}]'.format(img.ndim))
# enlarge img if necessary
if enlarge_ratio > 1:
H, W, _ = img.shape
img = cv2.resize(img, (W * enlarge_ratio, H * enlarge_ratio), \
interpolation=cv2.INTER_CUBIC)
# add text
font = cv2.FONT_HERSHEY_COMPLEX
cv2.putText(img, write_txt, txt_pos, font, font_size, color, font_thickness, cv2.LINE_AA)
cv2.imwrite(os.path.join(save_folder, base_name + '_text.png'), img)
if make_video:
idx += 1
cv2.imwrite(os.path.join(tmp_video_folder, '{:05d}.png'.format(idx)), img)
img = np.ascontiguousarray(img[:, :, [2, 1, 0]])
img_list.append(img)
if use_imageio:
import imageio
imageio.mimsave(os.path.join(save_folder, 'out.gif'), img_list, format='GIF', duration=duration)
if make_video:
os.system('ffmpeg -r {:f} -i {:s}/%05d.png -vcodec mpeg4 -y {:s}/movie.mp4'.format(
1 / duration, tmp_video_folder, save_folder))
if os.path.exists(tmp_video_folder):
os.system('rm -rf {}'.format(tmp_video_folder))
| [
"wxt1994@126.com"
] | wxt1994@126.com |
d9c4b8a7de6dbd3755b12d629a970ee4b0778798 | 49197a748adea1618a2cece7a1ae057006da090c | /jgodwin/micro/micro.py | f1132e04bc3d6e7e46ac6817121583f752dcc324 | [] | no_license | psava/cwp12 | 0bbb1f213c66737509280fc4b0ac5c53b52d017a | 3f47c1bf358caa5ebe608ab88fc12b85fd489220 | refs/heads/master | 2021-01-10T21:24:57.572992 | 2012-10-10T15:52:18 | 2012-10-10T15:52:18 | 2,213,082 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 17,263 | py | from rsf.cluster import *
import random,fdmod
def getpar():
par = {
###############################
# Model/Image dimensions
###############################
#'nx':501, 'ox':0, 'dx':0.002, 'lx':'x', 'ux':'km',
#'ny':151, 'oy':0, 'dy':0.002, 'ly':'y', 'uy':'km',
#'nz':351, 'oz':0, 'dz':0.002, 'lz':'z', 'uz':'km',
'nx':251, 'ox':0, 'dx':0.005, 'lx':'x', 'ux':'km',
'ny':75, 'oy':0, 'dy':0.005, 'ly':'y', 'uy':'km',
'nz':176, 'oz':0, 'dz':0.005, 'lz':'z', 'uz':'km',
###############################
# Wavelet parameters
###############################
'nt':4001, 'ot':0, 'dt':0.001, 'lt':'t', 'ut':'s',
'frq':45, # Peak frequency for Ricker wavelet
'kt':100, # Wavelet start position (wavelets are delayd for zero-phase)
###############################
# Modeling code parameters
###############################
'cfl': True,
'dabc':True, # Use absorbing boundary condition?
'nb':80, # How many cells for absorbing boundary?
'abcone':True, # Use additional ramp condition for boundaries? (Use default)
'dsou':False, # Use displacement source (acoustic-only)
'expl':False, # Use exploding reflector (acoustic-only)
'free':False, # Use free surface (generate multiples)
'jdata':1, # Interval between time-iterations before saving data at recv
'snap':True, # Save wavefield snapshots?
'verb':True, # Verbose output?
'jsnap':1, # Interval between time-iterations before saving wfld snapshot
'debug':False, # Debugging output (elastic-only)?
'nbell':5, # Size of interpolation for injection
'ssou':False, # Use stress-source (elastic-only)
'ompchunk':1, # OpenMP chunk size (use default)
'ompnth':2, # Number of OpenMP threads to use (4 works best)
###############################
# Thomsen parameters for models
###############################
'vp':1.5,
'ro':2.0,
###############################
# Miscellaneous parameters
###############################
'height':10,
'nht': 80,
'nhx': 40,
'nhz': 40,
}
fdmod.param(par)
par['nframe']=5
par['iframe']=4
# ------------------------------------------------------------
# End user parameters -- NO EDITS BELOW
# ------------------------------------------------------------
par['kz']=2./3.*par['nz']
return par
def windowreceivers(rr,groups,keys,par):
for group,gpars in groups.items():
nwin = gpars['nr']
owin = gpars['or']
dwin = gpars['dr']
Flow('rr-'+group,gpars['group'],'window n2=%d f2=%d j2=%d squeeze=n' % (nwin,owin,dwin))
Plot('rr-'+group,fdmod.rrplot('plotcol=%d plotfat=10' % gpars['color'],par))
Flow(rr,['rr-'+group for group in keys],
'cat axis=2 ${SOURCES[1:%d]}' % len(groups))
Plot(rr,['rr-'+group for group in keys],'Overlay')
def triangulate(image,tcube,noisy,clean,groups,keys,hypocenters,subgroups,snapshots,par):
ii = 0
Fork(nodes=1,time=3,ipn=1)
for group in keys:
gpars = groups[group]
nwin = gpars['nr']
Flow('da-'+group,noisy,
'''
window n1=%d f1=%d squeeze=n |
''' % (nwin,ii) +
'''put o1=%(oz)g d1=%(dz)g ''' % par)
Result('da-'+group+'_',clean,
'''
window n1=%d f1=%d squeeze=n |
''' % (nwin,ii) +
'''
put o1=0 d1=1 | transp |
wiggle poly=y pclip=99 title="" labelsz=6 labelfat=3 titlesz=12 titlefat=3
label2="\F2 trace\F3 " label1="\F2 time\F3"
''' )
Result('da-'+group,
'''put o1=0 d1=1 | transp |
wiggle poly=n pclip=100 title="" transp=%(transp)d labelsz=6 labelfat=3 titlesz=12 titlefat=3
yreverse=%(yreverse)d %(custom)s
label2="\F2 trace\F3 " label1="\F2 time\F3"
''' % gpars)
backproject('da-'+group,'rr-'+group,'vp-2d','ro-2d','_wa-'+group,par)
Flow('wa-%s'%group,'_wa-%s'%group,
'''
transp plane=23 | transp plane=12
''' % par)
Result('wa-%s' % group,'_wa-%s' % group,
'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=100',par))
for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]):
Plot('wa-%s-%d' % (group,i),'_wa-%s' % group,'window n3=1 f3=%d | ' % (i) + fdmod.cgrey('pclip=100',par))
Result('wa-%s-%d' % (group,i),['wa-%s-%d' % (group,i),'rr-2d'],'Overlay')
subgroupwflds = []
for sub in subgroups:
for j in range(0,nwin,sub):
if sub + j <= nwin:
Flow('da-%s-%d-%d' % (group,sub,j),'da-%s' % group,
'''
window n1=%d f1=%d squeeze=n
''' % (sub,j))
Flow('rr-%s-%d-%d' % (group,sub,j),'rr-%s' % group,
'''
window n2=%d f2=%d squeeze=n
''' % (sub,j))
else:
Flow('da-%s-%d-%d' % (group,sub,j),'da-%s' % group,
'''
window f1=%d squeeze=n
''' % (j))
Flow('rr-%s-%d-%d' % (group,sub,j),'rr-%s' % group,
'''
window f2=%d squeeze=n
''' % (j))
backproject('da-%s-%d-%d' % (group,sub,j),
'rr-%s-%d-%d' % (group,sub,j),
'vp-2d','ro-2d','_wa-%s-%d-%d' % (group,sub,j),par)
# Go from z-x-t to t-z-x
Flow('wa-%s-%d-%d'% (group,sub,j),'_wa-%s-%d-%d'%(group,sub,j),
'''
transp plane=23 | transp plane=12
''' % par)
Result('wa-%s-%d-%d' % (group,sub,j),'_wa-%s-%d-%d' % (group,sub,j),
'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=100',par))
subgroupwflds.append('_wa-%s-%d-%d' % (group,sub,j))
j = 0
for hypocenter in hypocenters:
xi = hypocenter[0]
zi = hypocenter[1]
ti = hypocenter[2]
Flow('hypo-%d-%s' % (j,group), '_wa-%s' % group,
'''
window min1=%(oz)f min2=%(ox)f n1=%(nz)d n2=%(nx)d |
''' % par +
'''
window n1=1 n2=1 f1=%d f2=%d
''' % (zi,xi))
for subgroupwfld in subgroupwflds:
subgrouphypo = subgroupwfld.replace('_wa','hypo-%d' % j)
Flow(subgrouphypo,subgroupwfld,
'''
window n1=1 n2=1 f1=%d f2=%d
''' % (zi,xi))
j+= 1
ii += nwin
Iterate()
Join()
for jhypo in range(len(hypocenters)):
Flow('hypo-%d' % jhypo, ['hypo-%d-%s' % (jhypo,group) for group in keys],
'''
cat axis=2 ${SOURCES[1:%d]}
''' % len(keys))
Result('hypo-%d' % jhypo, 'grey pclip=95')
#Save('hypo-%d' % jhypo)
for sub in subgroups:
subwflds = []
for group in keys:
for j in range(0,groups[group]['nr'],sub):
subwflds.append('hypo-%d-%s-%d-%d' % (jhypo,group,sub,j))
Flow('hypo-%d-%d' % (jhypo,sub), subwflds,
'''
cat axis=2 ${SOURCES[1:%d]}
''' % len(subwflds))
Result('hypo-%d-%d' % (jhypo,sub),'grey pclip=95')
#Save('hypo-%d-%d' % (jhypo,sub))
for sub in subgroups:
subwflds = ['wa-%s-%d-%d'% (group,sub,j) for group in keys for j in range(0,groups[group]['nr'],sub) ]
Flow(tcube+'-sem-%d' % sub,subwflds,
'''
semblance m=10 ${SOURCES[1:%d]} |
transp plane=12 | transp plane=23
''' % len(subwflds))
Flow(tcube+'-%d' % sub,subwflds,
'''
add mode=p ${SOURCES[1:%d]} |
transp plane=12 | transp plane=23
''' % len(subwflds))
Result(tcube+'-sem-%d'% sub,
'window f3=%d n3=%d j3=%d | ' %
(snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=99.9 gainpanel=a',par))
Result(tcube+'-%d' % sub,
'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=99.9 gainpanel=a',par))
Flow(image+'-%d' % sub,tcube+'-%d' % sub,'stack axis=3')
#Flow(image+'-sem-%d' % sub,tcube+'-sem-%d' % sub,'thr thr=0.4 mode="hard" | stack axis=3')
Flow(image+'-sem-%d' % sub,tcube+'-sem-%d' % sub,'stack axis=3')
Plot(image+'-sem-box-%d' % sub,image+'-sem-%d' % sub,
fdmod.cgrey('pclip=100 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par))
Plot(image+'-box-%d' % sub,image+'-%d' % sub,
fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par))
Plot(image+'-%d' % sub,fdmod.cgrey('pclip=99.98',par))
Result(image+'-%d' % sub,[image+'-%d' % sub,'ss-2d','box'],'Overlay')
Result('image-box-%d' % sub,[image+'-box'+'-%d' % sub,'ss-2d-box'],'Overlay')
Result('image-sem-box-%d' % sub,[image+'-sem-box-%d' % sub,'ss-2d-box'],'Overlay')
Flow(tcube+'-sem',['wa-%s' % group for group in keys],
'''
semblance m=10 ${SOURCES[1:%d]} |
transp plane=12 | transp plane=23
''' % len(keys))
Flow(tcube,['wa-%s'%group for group in keys],
'''
add mode=p ${SOURCES[1:%d]} |
transp plane=12 | transp plane=23
''' % len(keys))
Result(tcube,
'window f3=%d n3=%d j3=%d | ' %
(snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=100 gainpanel=a',par))
Result(tcube+'-sem',
'window f3=%d n3=%d j3=%d | ' %
(snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=100 gainpanel=a',par))
for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]):
Plot(tcube+'-%d' % i,tcube,'window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par))
Result(tcube+'-%d' % i , [tcube+'-%d' % i,'rr-2d'],'Overlay')
Plot(tcube+'-sem-%d' % i,tcube+'-sem','window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par))
Result(tcube+'-sem-%d' % i , [tcube+'-sem-%d' % i,'rr-2d'],'Overlay')
Flow(image,tcube,'stack axis=3')
#Flow(image+'-sem',tcube+'-sem','thr thr=0.4 mode="hard" | stack axis=3')
Flow(image+'-sem',tcube+'-sem','stack axis=3')
Plot(image+'-box',image,fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par))
Plot(image+'-sem-box',image+'-sem',fdmod.cgrey('pclip=99.98 min2=0.4 max2=0.9 min1=0.2 max1=0.4',par))
Plot(image,fdmod.cgrey('pclip=99.98',par))
Plot(image+'-sem',fdmod.cgrey('pclip=100',par))
Result(image,[image,'ss-2d','box'],'Overlay')
Result(image+'-sem',[image+'-sem','ss-2d','box'],'Overlay')
Result('image-box',[image+'-box','ss-2d-box'],'Overlay')
Result('image-sem-box',[image+'-sem-box','ss-2d-box'],'Overlay')
# ------------------------------------------------------------
# Setup functions for calling FD operators
# ------------------------------------------------------------
# These operations are usually hidden, but having them here is more
# transparent. All possible options are specified by the user.
def backproject(data,receivers,velocity,density,wavefieldname,par):
Flow(data+'-reversed',data,'sfreverse which=2 opt=i')
awefd(data+'-junk',wavefieldname,data+'-reversed',
velocity,density,
receivers,receivers, par)
def awefd(odat,owfl,idat,velo,dens,sou,rec,par):
# call the acoustic wave equation code
# see sfawe for a more detaile description of options
Flow([odat,owfl],[idat,velo,dens,sou,rec],
'''
awe
ompchunk=%(ompchunk)d ompnth=%(ompnth)d
snap=%(snap)d jsnap=%(jsnap)d
dabc=%(dabc)d nb=%(nb)d
dsou=%(dsou)d free=%(free)d
expl=%(expl)d jdata=%(jdata)d
cfl=%(cfl)d
fmax=%(frq)f
verb=%(verb)d
vel=${SOURCES[1]}
den=${SOURCES[2]}
sou=${SOURCES[3]}
rec=${SOURCES[4]}
wfl=${TARGETS[1]}
nqz=%(nz)d
nqx=%(nx)d
dqz=%(dz)f
dqx=%(dx)f
oqz=%(oz)f
oqx=%(ox)f
''' % par)
# ------------------------------------------------------------
def wavelet(waveletname,frequency,kt,par):
partemp = par.copy()
partemp['kt'] = kt
partemp['frequency'] = frequency
Flow(waveletname,None,
'''
spike nsp=1 mag=1 n1=%(nt)d d1=%(dt)g o1=%(ot)g k1=%(kt)d |
pad end1=%(nt)d |
ricker1 frequency=%(frequency)g |
window n1=%(nt)d |
scale axis=123 |
put label1=t | thr thr=0.001
''' % partemp)
# ------------------------------------------------------------
def makemicroseisms(ns,wav,sou,par):
sources = []
wavelets = []
r = random.Random()
r.seed(1234)
locations = []
for i in range(ns):
tag = '-%03d' % i
xi = r.randrange(100,150)
zi = r.randrange(50,60)
ti = r.randrange(par['nt']/4,3*par['nt']/4)
print 'Microseism %d %d %d %d' % (i,xi,zi,ti)
locations.append((xi,zi,ti))
xsou = par['ox']+par['dx']*xi
zsou = par['oz']+par['dz']*zi
fdmod.point(sou+tag,xsou,zsou,par)
wavelet(wav+tag,par['frq'],ti,par)
sources.append(sou+tag)
wavelets.append(wav+tag)
Flow(wav+'_',wavelets,'cat axis=2 ${SOURCES[1:%d]}' % ns)
Flow(sou,sources,'cat axis=2 ${SOURCES[1:%d]}' % ns)
Plot('ss-2d',fdmod.ssplot('symbol=+ symbolsz=7 plotfat=5',par))
Plot('ss-2d-box','ss-2d',
fdmod.ssplot('min1=0.4 max1=0.9 min2=0.2 max2=0.4 plotfat=5 symbol=+ symbolsz=9',par))
Flow( 'wava','wav_','add scale=10000000 | transp')
Result('wava','transp |' + fdmod.waveplot('',par))
# These are bad locations, no microseisms here.
locations.append((50,25,100))
locations.append((75,80,100))
return locations
# ------------------------------------------------------------
def model(rr,par):
Flow('zero-2d',None,
'''
spike nsp=1 mag=0.0
n1=%(nz)d o1=%(oz)g d1=%(dz)g
n2=%(nx)d o2=%(ox)g d2=%(dx)g |
put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s
''' % par)
Flow('vz-2d','zero-2d',
'''
spike nsp=5
nsp=5 k1=10,40,70,100,130 l1=39,69,99,129,%(nz)d mag=0.2,0.4,0.6,0.8,1.0
n1=%(nz)d o1=%(oz)g d1=%(dz)g
n2=%(nx)d o2=%(ox)g d2=%(dx)g |
put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s |
add add=%(vp)f
''' % par)
Flow('fault-2d','zero-2d',
'''
spike nsp=1 k1=40 mag=1.0 l1=%(nz)d k2=60 l2=%(nx)d p2=1
n1=%(nz)d o1=%(oz)g d1=%(dz)g
n2=%(nx)d o2=%(ox)g d2=%(dx)g |
put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s
''' % par)
Flow('const-2d','zero-2d',
'''
spike nsp=1 mag=1.0 k1=40 l1=%(nz)d k2=1 l2=59
n1=%(nz)d o1=%(oz)g d1=%(dz)g
n2=%(nx)d o2=%(ox)g d2=%(dx)g |
put label1=%(lz)s label2=%(lx)s unit1=%(uz)s unit2=%(ux)s
''' % par)
Flow('vp-2d','vz-2d','window')
Flow('ro-2d','zero-2d','math output="%(ro)g"' %par)
fdmod.makebox('box',0.2,0.4,0.4,0.9,par)
Plot('box',fdmod.bbplot('',par))
Plot('vp-2d',fdmod.cgrey('allpos=y pclip=100 bias=1.5 ',par))
Plot('ro-2d',fdmod.cgrey('bias=2. allpos=y',par))
Result('vp-2d','vp-2d ss-2d rr-2d box','Overlay')
Result('ro-2d','ro-2d ss-2d','Overlay')
def synthesize(data,rr,snapshots,par):
# 2D acoustic modeling
awefd(data,'wa-2d','wava','vp-2d','ro-2d','ss-2d',rr,par)
Result(data,'transp |' + fdmod.dgrey('',par))
for i in range(snapshots[0],snapshots[0]+snapshots[1]*snapshots[2],snapshots[2]):
Plot('wa-2d-%d' % i,'wa-2d','window n3=%d f3=%d | ' % (1,i) + fdmod.cgrey('pclip=99.9 gainpanel=a',par))
Result('wa-2d-%d' %i , ['wa-2d-%d' % i,rr],'Overlay')
def addnoise(noisy,data,scale,snapshots,par):
Flow(noisy,data, 'math output="0" | noise seed=123 | transp | bandpass flo=20 fhi=50 | transp | add scale=%f | add mode=a ${SOURCES[0]} | add scale=1e6' % scale)
Result(noisy,'transp | grey pclip=99.9')
backproject(noisy,'rr-2d','vp-2d','ro-2d','wa-%s'% noisy,par)
Result('wa-%s' % noisy,
'window f3=%d n3=%d j3=%d | ' % (snapshots[0],snapshots[1],snapshots[2]) +
fdmod.cgrey('pclip=100',par))
| [
"jgodwin@mines.edu"
] | jgodwin@mines.edu |
8cfa0564a630a016ac91663a5dbcade279afd639 | 144b54b91cbd541421c12df1074920c1bd635780 | /utils.py | 71aca180b475fef8fb48cacb903d2616b5893e9b | [
"MIT"
] | permissive | jajcayn/re_hippocampal_model | 777956b93476051202e10c908f419c69e9349c0e | 5dc984cec0591d27ed6dedf8e8e2ddd8e07b20c7 | refs/heads/main | 2023-04-19T05:29:14.064024 | 2021-04-21T09:37:45 | 2021-04-21T09:37:45 | 353,683,773 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,481 | py | """
Helper functions
"""
import logging
from functools import partial
from multiprocessing import Pool, cpu_count
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from tqdm import tqdm
def run_in_parallel(
partial_function,
iterable,
workers=cpu_count(),
length=None,
assert_ordered=False,
):
"""
Wrapper for running functions in parallel with tqdm bar.
:param partial_function: partial function to be evaluated
:type partial_function: :class:`_functools.partial`
:param iterable: iterable comprised of arguments to be fed to partial
function
:type iterable: iterable
:param workers: number of workers to be used
:type workers: int
:param length: Length of the iterable / generator.
:type length: int|None
:param assert_ordered: whether to assert order of results same as the
iterable (imap vs imap_unordered)
:type assert_ordered: bool
:return: list of values returned by partial function
:rtype: list
"""
total = length
if total is None:
try:
total = len(iterable)
except (TypeError, AttributeError):
pass
# wrap method in order to get original exception from a worker process
partial_function = partial(_worker_fn, fn=partial_function)
pool = Pool(workers)
imap_func = pool.imap_unordered if not assert_ordered else pool.imap
results = []
for result in tqdm(imap_func(partial_function, iterable), total=total):
results.append(result)
pool.close()
pool.join()
return results
def _worker_fn(item, fn):
"""
Wrapper for worker method in order to get original exception from
a worker process and to log correct exception stacktrace.
:param item: item from iterable
:param fn: partial function to be evaluated
:type fn: :class:`_functools.partial`
"""
try:
return fn(item)
except Exception as e:
logging.exception(e)
raise
class AnchoredHScaleBar(matplotlib.offsetbox.AnchoredOffsetbox):
"""
Creates horizontal scale bar in the matplotlib figures.
Taken from https://stackoverflow.com/a/43343934.
"""
def __init__(
self,
size=1,
extent=0.03,
label="",
loc=2,
ax=None,
pad=0.6,
borderpad=0.5,
ppad=0,
sep=4,
txtsize=16,
prop=None,
frameon=False,
linekw={},
**kwargs
):
if not ax:
ax = plt.gca()
trans = ax.get_xaxis_transform()
size_bar = matplotlib.offsetbox.AuxTransformBox(trans)
line = Line2D([0, size], [0, 0], **linekw)
vline1 = Line2D([0, 0], [-extent / 2.0, extent / 2.0], **linekw)
vline2 = Line2D([size, size], [-extent / 2.0, extent / 2.0], **linekw)
size_bar.add_artist(line)
size_bar.add_artist(vline1)
size_bar.add_artist(vline2)
txt = matplotlib.offsetbox.TextArea(
label, minimumdescent=False, textprops={"size": txtsize}
)
self.vpac = matplotlib.offsetbox.VPacker(
children=[size_bar, txt], align="center", pad=ppad, sep=sep
)
matplotlib.offsetbox.AnchoredOffsetbox.__init__(
self,
loc,
pad=pad,
borderpad=borderpad,
child=self.vpac,
prop=prop,
frameon=frameon,
**kwargs
)
| [
"nikola.jajcay@gmail.com"
] | nikola.jajcay@gmail.com |
3b2ebe81d2835ea42691bb7d5bff97c782a8bc00 | 59ac1d0f09ebfb527701031f3ab2cfbfb8055f51 | /soapsales/employees/migrations/0003_auto_20200902_1721.py | 0819efd6aafd9e48e4f311586f2596836d84ff10 | [] | no_license | DUMBALINYOLO/erpmanu | d4eb61b66cfa3704bd514b58580bdfec5639e3b0 | db979bafcc7481f60af467d1f48d0a81bbbfc1aa | refs/heads/master | 2023-04-28T13:07:45.593051 | 2021-05-12T09:30:23 | 2021-05-12T09:30:23 | 288,446,097 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 543 | py | # Generated by Django 3.0.7 on 2020-09-02 15:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('employees', '0002_auto_20200902_0038'),
]
operations = [
migrations.RenameField(
model_name='employee',
old_name='is_staff',
new_name='is_admin',
),
migrations.AlterField(
model_name='employee',
name='is_superuser',
field=models.BooleanField(default=False),
),
]
| [
"baridzimaximillem@gmail.com"
] | baridzimaximillem@gmail.com |
792a326fad5224ee15c058836faae17f70de5ca2 | 30174fca608e3fb20664acb27bcbf4fb037ca4f1 | /foodrider/migrations/0016_auto_20200825_1822.py | c9ea4a488536f8777a044fb183d9e084b689fa35 | [] | no_license | jabir15/foodrider | f32e88b8c9d612bace39cf475d6dfa41800c98d3 | 724828f39ddd05e612030dfea846a7a8b5b017a8 | refs/heads/master | 2023-04-16T17:54:58.326973 | 2021-05-02T10:07:51 | 2021-05-02T10:07:51 | 290,949,621 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 438 | py | # Generated by Django 3.1 on 2020-08-25 16:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foodrider', '0015_auto_20200825_1820'),
]
operations = [
migrations.AlterField(
model_name='menuitemoption',
name='discount_price',
field=models.DecimalField(decimal_places=2, default='0.00', max_digits=7),
),
]
| [
"jabir.hussain.aec@gmail.com"
] | jabir.hussain.aec@gmail.com |
3a3bf2a75f8238a4f8a98e775a43ea60086f6668 | 87521e0ce35095d06f8cd2e0890f8b73f9ec0511 | /training_window.py | 3a083317b9c5a9109bcbb974ec32216694347011 | [] | no_license | chamara96/voice-command-rnn | 20fa6446e44a72c78113528b598756b545c1529d | e6847af88e09e01ddf06f1d6cdd1b0835d30ba4f | refs/heads/main | 2023-01-02T12:12:28.542385 | 2020-11-01T06:52:28 | 2020-11-01T06:52:28 | 308,967,152 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,464 | py | import sys
from PIL import ImageTk, Image
import time
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
from tkinter import messagebox
import neural_network
import dataset_handling
def update_thread():
# global is_stop
time.sleep(5)
is_train_end = 0
while not is_train_end:
is_train_end = dataset_handling.end_train
# text = ""
w.Label_log.delete("1.0", tk.END)
if is_stop == 1:
break
curr_epoch, total_epoches = neural_network.check_curr_epoch()
w.TProgressbar1['value'] = int((curr_epoch) * 100 / total_epoches)
filename = "checkpoints/log.txt"
try:
with open(filename) as f:
text = f.read()
except IOError:
text = ""
w.Label_log.insert("1.0", text)
try:
img = Image.open("checkpoints/fig.jpg")
except IOError:
img = Image.open("classes/wait.png")
basewidth = 550
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
w.Label_plot['image'] = img
w.Label_plot.image = img
sys.stdout.flush()
print("Updated")
time.sleep(2)
messagebox.showinfo("Training", "Done..!")
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def btn_stop():
destroy_window()
sys.stdout.flush()
is_stop = 0
def btn_update_view():
curr_epoch, total_epoches = neural_network.check_curr_epoch()
w.TProgressbar1['value'] = int(curr_epoch * 100 / total_epoches)
filename = "checkpoints/log.txt"
try:
with open(filename) as f:
text = f.read()
except IOError:
text = ""
w.Label_log.insert("1.0", text)
try:
img = Image.open("checkpoints/fig.jpg")
except IOError:
img = Image.open("classes/wait.png")
basewidth = 550
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
w.Label_plot['image'] = img
w.Label_plot.image = img
sys.stdout.flush()
print("Updated")
# time.sleep(2)
def destroy_window():
global is_stop
is_stop=1
print("QQWWEERR")
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
sys.exit()
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
init(root, top)
root.mainloop()
w = None
def create_Toplevel1(rt, *args, **kwargs):
'''Starting point when module is imported by another module.
Correct form of call: 'create_Toplevel1(root, *args, **kwargs)' .'''
global w, w_win, root
#rt = root
root = rt
w = tk.Toplevel (root)
top = Toplevel1 (w)
init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("1245x656+220+79")
top.minsize(120, 1)
top.maxsize(2650, 1005)
top.resizable(0, 0)
top.title("Training Model")
top.configure(background="#d9d9d9")
self.Labelframe1 = tk.LabelFrame(top)
self.Labelframe1.place(x=20, y=40, height=600, width=600)
self.Labelframe1.configure(relief='groove')
self.Labelframe1.configure(foreground="black")
self.Labelframe1.configure(text='''Log''')
self.Labelframe1.configure(background="#d9d9d9")
self.Label_log=tk.Text(self.Labelframe1)
# self.Label_log = tk.Label(self.Labelframe1)
self.Label_log.place(x=20, y=30, height=551, width=564
, bordermode='ignore')
# self.Label_log.configure(anchor='nw')
self.Label_log.configure(background="#d9d9d9")
# self.Label_log.configure(disabledforeground="#a3a3a3")
self.Label_log.configure(foreground="#000000")
# self.Label_log.configure(text='''Label''')
self.Labelframe2 = tk.LabelFrame(top)
self.Labelframe2.place(x=630, y=40, height=600, width=600)
self.Labelframe2.configure(relief='groove')
self.Labelframe2.configure(foreground="black")
self.Labelframe2.configure(text='''Training Curves''')
self.Labelframe2.configure(background="#d9d9d9")
self.Label_plot = tk.Label(self.Labelframe2)
self.Label_plot.place(x=20, y=30, height=551, width=554
, bordermode='ignore')
self.Label_plot.configure(anchor='nw')
self.Label_plot.configure(background="#d9d9d9")
self.Label_plot.configure(disabledforeground="#a3a3a3")
self.Label_plot.configure(foreground="#000000")
self.Label_plot.configure(text='''Label''')
self.Button1 = tk.Button(top)
self.Button1.place(x=1100, y=10, height=34, width=127)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=btn_stop)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Stop''')
self.TProgressbar1 = ttk.Progressbar(top)
self.TProgressbar1.place(x=20, y=10, width=600, height=22)
self.TProgressbar1.configure(length="600")
self.TProgressbar1.configure(value="10")
# self.Button2 = tk.Button(top)
# self.Button2.place(x=980, y=10, height=34, width=117)
# self.Button2.configure(activebackground="#ececec")
# self.Button2.configure(activeforeground="#000000")
# self.Button2.configure(background="#d9d9d9")
# self.Button2.configure(command=btn_update_view)
# self.Button2.configure(disabledforeground="#a3a3a3")
# self.Button2.configure(foreground="#000000")
# self.Button2.configure(highlightbackground="#d9d9d9")
# self.Button2.configure(highlightcolor="black")
# self.Button2.configure(pady="0")
# self.Button2.configure(text='''Update View''')
if __name__ == '__main__':
vp_start_gui()
| [
"cmb.info96@gmail.com"
] | cmb.info96@gmail.com |
27ca4ceae6de9d605e2bfc5c1fee240d3f1fe145 | 10300363f12e5a6a0ea6a69d0a6d210174499d60 | /times.py | 746272f2b9f1a029c66f51b8e55c0ba5edea3241 | [] | no_license | nedbat/point_match | 2da5cc12bf3f3866b35ec71ea227a5d21760ca97 | a6c19ed1d206ec1ad02b13e15b8d761192b32593 | refs/heads/master | 2023-06-22T04:16:09.638622 | 2019-04-01T21:25:09 | 2019-04-01T21:25:09 | 100,109,656 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,068 | py | import random
import timeit
if 0:
TRIES = 10000
for z in range(7):
n = int(10**z)
stmt='random.randint(1, 999999) in d'
setup='import random; d = {{random.randint(1, 999999): 1 for _ in xrange({N:d})}}'.format(N=n)
total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES)
print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n))
if 0:
TRIES = 2000
for z in range(7):
n = int(10**z)
stmt='random.randint(1, 999999) in x'
setup='import random; x = [random.randint(1, 999999) for _ in xrange({N:d})]'.format(N=n)
total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES)
print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n))
if 1:
TRIES = 200
for z in range(7):
n = int(10**z)
stmt='sorted(x)'
setup='import random; x = [random.randint(1, 999999) for _ in xrange({N:d})]'.format(N=n)
total = timeit.timeit(stmt=stmt, setup=setup, number=TRIES)
print("{N:>9d}: {time:.7f}s".format(time=total/TRIES, N=n))
| [
"ned@nedbatchelder.com"
] | ned@nedbatchelder.com |
14d91c016f740d9564b17288e566a3efeee3fcfe | c77843e9d25458d4a848c41f7e88d942bcc0d7dc | /code/lib/nltk/eval.py | 4b8ca39cbde7a5dadf32d3b17f5fbde666b8c66e | [] | no_license | sethwoodworth/wikipedia-style-edits | 0cf99e9f184a8cafce8b8e3e92bbbd6dc0540659 | b660ac52ee2c901bc5358e2af2fa8be2d43f6a4c | refs/heads/master | 2021-01-22T03:12:54.954349 | 2008-10-15T21:32:23 | 2008-10-15T21:32:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,713 | py | # Natural Language Toolkit: Evaluation
#
# Copyright (C) 2004 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@csse.unimelb.edu.au>
# URL: <http://lib.nltk.sf.net>
# For license information, see LICENSE.TXT
"""
Utility functions for evaluating processing modules.
"""
import sets, math
from lib.nltk.chktype import chktype
def accuracy(reference, test):
"""
Given a list of reference values and a corresponding list of test
values, return the percentage of corresponding values that are
equal. In particular, return the percentage of indices
C{0<i<=len(test)} such that C{test[i] == reference[i]}.
@type reference: C{list}
@param reference: An ordered list of reference values.
@type test: C{list}
@param test: A list of values to compare against the corresponding
reference values.
@raise ValueError: If C{reference} and C{length} do not have the
same length.
"""
assert chktype(1, reference, [])
assert chktype(2, test, [])
if len(reference) != len(test):
raise ValueError("Lists must have the same length.")
num_correct = [1 for x,y in zip(reference, test) if x==y]
return float(len(num_correct)) / len(reference)
def precision(reference, test):
"""
Given a set of reference values and a set of test values, return
the percentage of test values that appear in the reference set.
In particular, return |C{reference}S{cap}C{test}|/|C{test}|.
If C{test} is empty, then return C{None}.
@type reference: C{Set}
@param reference: A set of reference values.
@type test: C{Set}
@param test: A set of values to compare against the reference set.
@rtype: C{float} or C{None}
"""
assert chktype(1, reference, sets.BaseSet)
assert chktype(2, test, sets.BaseSet)
if len(test) == 0:
return None
else:
return float(len(reference.intersection(test)))/len(test)
def recall(reference, test):
"""
Given a set of reference values and a set of test values, return
the percentage of reference values that appear in the test set.
In particular, return |C{reference}S{cap}C{test}|/|C{reference}|.
If C{reference} is empty, then return C{None}.
@type reference: C{Set}
@param reference: A set of reference values.
@type test: C{Set}
@param test: A set of values to compare against the reference set.
@rtype: C{float} or C{None}
"""
assert chktype(1, reference, sets.BaseSet)
assert chktype(2, test, sets.BaseSet)
if len(reference) == 0:
return None
else:
return float(len(reference.intersection(test)))/len(reference)
def f_measure(reference, test, alpha=0.5):
"""
Given a set of reference values and a set of test values, return
the f-measure of the test values, when compared against the
reference values. The f-measure is the harmonic mean of the
L{precision} and L{recall}, weighted by C{alpha}. In particular,
given the precision M{p} and recall M{r} defined by:
- M{p} = |C{reference}S{cap}C{test}|/|C{test}|
- M{r} = |C{reference}S{cap}C{test}|/|C{reference}|
The f-measure is:
- 1/(C{alpha}/M{p} + (1-C{alpha})/M{r})
If either C{reference} or C{test} is empty, then C{f_measure}
returns C{None}.
@type reference: C{Set}
@param reference: A set of reference values.
@type test: C{Set}
@param test: A set of values to compare against the reference set.
@rtype: C{float} or C{None}
"""
p = precision(reference, test)
r = recall(reference, test)
if p is None or r is None:
return None
if p == 0 or r == 0:
return 0
return 1.0/(alpha/p + (1-alpha)/r)
def log_likelihood(reference, test):
"""
Given a list of reference values and a corresponding list of test
probability distributions, return the average log likelihood of
the reference values, given the probability distributions.
@param reference: A list of reference values
@type reference: C{list}
@param test: A list of probability distributions over values to
compare against the corresponding reference values.
@type test: C{list} of L{ProbDist}
"""
if len(reference) != len(test):
raise ValueError("Lists must have the same length.")
# Return the average value of dist.logprob(val).
total_likelihood = sum([dist.logprob(val)
for (val, dist) in zip(reference, test)])
return total_likelihood/len(reference)
class ConfusionMatrix:
"""
The confusion matrix between a list of reference values and a
corresponding list of test values. Entry [M{r},M{t}] of this
matrix is a count of the number of times that the reference value
M{r} corresponds to the test value M{t}. E.g.:
>>> ref = 'DET NN VB DET JJ NN NN IN DET NN'.split()
>>> test = 'DET VB VB DET NN NN NN IN DET NN'.split()
>>> cm = ConfusionMatrix(ref, test)
>>> print cm['NN', 'NN']
3
Note that the diagonal entries (M{Ri}=M{Tj}) of this matrix
corresponds to correct values; and the off-diagonal entries
correspond to incorrect values.
"""
def __init__(self, reference, test):
"""
Construct a new confusion matrix from a list of reference
values and a corresponding list of test values.
@type reference: C{list}
@param reference: An ordered list of reference values.
@type test: C{list}
@param test: A list of values to compare against the
corresponding reference values.
@raise ValueError: If C{reference} and C{length} do not have
the same length.
"""
assert chktype(1, reference, [])
assert chktype(2, test, [])
if len(reference) != len(test):
raise ValueError('Lists must have the same length.')
# Get a list of all values.
values = dict([(val,1) for val in reference+test]).keys()
# Construct a value->index dictionary
indices = dict([(val,i) for (i,val) in enumerate(values)])
# Make a confusion matrix table.
confusion = [[0 for val in values] for val in values]
max_conf = 0 # Maximum confusion
for w,g in zip(reference, test):
confusion[indices[w]][indices[g]] += 1
max_conf = max(max_conf, confusion[indices[w]][indices[g]])
#: A list of all values in C{reference} or C{test}.
self._values = values
#: A dictionary mapping values in L{self._values} to their indices.
self._indices = indices
#: The confusion matrix itself (as a list of lists of counts).
self._confusion = confusion
#: The greatest count in L{self._confusion} (used for printing).
self._max_conf = 0
#: The total number of values in the confusion matrix.
self._total = len(reference)
#: The number of correct (on-diagonal) values in the matrix.
self._correct = sum([confusion[i][i] for i in range(len(values))])
def __getitem__(self, (li,lj)):
"""
@return: The number of times that value C{li} was expected and
value C{lj} was given.
@rtype: C{int}
"""
i = self._indices[li]
j = self._indices[lj]
return self._confusion[i][j]
def __repr__(self):
return '<ConfusionMatrix: %s/%s correct>' % (self._correct,
self._total)
def __str__(self):
return self.pp()
def pp(self, show_percents=False, values_in_chart=True):
"""
@return: A multi-line string representation of this confusion
matrix.
@todo: add marginals?
"""
confusion = self._confusion
if values_in_chart:
values = self._values
else:
values = range(len(self._values))
# Construct a format string for row values
valuelen = max([len(str(val)) for val in values])
value_format = '%' + `valuelen` + 's |'
# Construct a format string for matrix entries
if show_percents:
entrylen = 6
entry_format = '%5.1f%%'
else:
entrylen = len(`self._max_conf`)
entry_format = '%' + `entrylen` + 'd'
# Write the column values.
value_strings = [str(val) for val in values]
s = ''
for i in range(valuelen):
s += (' '*valuelen)+' |'
for val in value_strings:
if i >= valuelen-len(val):
s += val[i-valuelen+len(val)].rjust(entrylen+1)
else:
s += ' '*(entrylen+1)
s += ' |\n'
# Write a dividing line
s += '%s-+-%s+\n' % ('-'*valuelen, '-'*((entrylen+1)*len(values)))
# Write the entries.
for i in range(len(values)):
s += value_format % values[i]
for j in range(len(values)):
s += ' '
if show_percents:
s += entry_format % (100.0*confusion[i][j]/self._total)
else:
s += entry_format % confusion[i][j]
s += ' |\n'
# Write a dividing line
s += '%s-+-%s+\n' % ('-'*valuelen, '-'*((entrylen+1)*len(values)))
# Write a key
s += '(row = reference; col = test)\n'
if not values_in_chart:
s += 'Value key:\n'
for i, value in enumerate(self._values):
s += '%6d: %s\n' % (i, value)
return s
def key(self):
values = self._values
str = 'Value key:\n'
indexlen = len(`len(values)-1`)
key_format = ' %'+`indexlen`+'d: %s\n'
for i in range(len(values)):
str += key_format % (i, values[i])
return str
def demo():
print '-'*75
reference = 'DET NN VB DET JJ NN NN IN DET NN'.split()
test = 'DET VB VB DET NN NN NN IN DET NN'.split()
print 'Reference =', reference
print 'Test =', test
print 'Confusion matrix:'
print ConfusionMatrix(reference, test)
print 'Accuracy:', accuracy(reference, test)
print '-'*75
reference_set = sets.Set(reference)
test_set = sets.Set(test)
print 'Reference =', reference_set
print 'Test = ', test_set
print 'Precision:', precision(reference_set, test_set)
print ' Recall:', recall(reference_set, test_set)
print 'F-Measure:', f_measure(reference_set, test_set)
print '-'*75
if __name__ == '__main__':
demo()
| [
"asheesh@fe7ecb3d-170a-0410-af80-b42c727aa7d5"
] | asheesh@fe7ecb3d-170a-0410-af80-b42c727aa7d5 |
7e6dccde1c6ea2ba3cbd360b3009d30db942726a | b1e7481f8b5bf40c2547c95b1863e25b11b8ef78 | /Kai/python/modules/JetMETLogic.py | 9fdf533765af3ae52ed238853b1aaaeac74dfcea | [
"Apache-2.0"
] | permissive | NJManganelli/FourTopNAOD | 3df39fd62c0546cdbb1886b23e35ebdc1d3598ad | c86181ae02b1933be59d563c94e76d39b83e0c52 | refs/heads/master | 2022-12-22T22:33:58.697162 | 2022-12-17T01:19:36 | 2022-12-17T01:19:36 | 143,607,743 | 1 | 1 | Apache-2.0 | 2022-06-04T23:11:42 | 2018-08-05T11:40:42 | Python | UTF-8 | Python | false | false | 48,234 | py | from __future__ import division, print_function
import ROOT
import math
from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object
from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import Module
from PhysicsTools.NanoAODTools.postprocessing.tools import * #DeltaR, match collection methods
from FourTopNAOD.Kai.tools.toolbox import *
class JetMETLogic(Module):
def __init__(self, passLevel, era="2017", subera=None, isData=True, weightMagnitude=1, fillHists=False, btagging=['DeepJet', 'M'], MET=[45, 50], HT=[450,500], ZWidth=15, jetPtVar = "pt_nom", jetMVar = "mass_nom", verbose=False, probEvt=None, mode="Flag", debug=False):
# genEquivalentLuminosity=1, genXS=1, genNEvents=1, genSumWeights=1, era="2017", btagging=['DeepCSV','M'], lepPt=25, GenTop_LepSelection=None):
""" Jet, MET, HT logic that performs lepton cleaning and jet selection. Optionally can do b-tagging, but mode without this requirement can be enabled/disabled
passLevel is the level at which the module should trigger "True" to pass the event along to further modules. Available: 'all', 'baseline', 'selection'
Era is a string with the year of data taking or corresponding MC sample ("2017", "2018")
Subera is a string with the subera of data-taking, only for use in combination with isData=True and TriggerChannel ("B", "E", etc.)
isData is a boolean for when it's a data sample, as these are handled differently (trigger exclusivity and tier selection) from Monte Carlo.
TriggerChannel is a string with the trigger channel ("ElMu" for e-mu channel/dataset, regardless of which is higher pT, "El" for single-electron channel/dataset).
fillHists is a boolean for filling histograms.
Regarding data, internally there are 'tiers' associated with the trigger tuples. For MC, if the event fires any trigger from any tier, it should be accepted.
For data, given that events can be duplicated across data streams ('SingleMuon' and 'MuonEG'), triggers are divided into tiers.
The goal is to only select a data event from the highest available tier of triggers that it fires, and veto that event in appropriate
data streams when it corresponds to a lower trigger selection.
For example, let an event fire both a single muon trigger (tier 3) and a mu-mu trigger (tier 1), but not an e-mu trigger (tier 0). In the double muon dataset,
the event is selected because it fired the tier 1 trigger in the list (and not the tier 0 triggers). In the single muon dataset, the event is veto'd,
because it fired the tier 1 trigger as well as the tier 3. A different event that only fired the tier 3 trigger is appropriately picked up on the single muon
dataset, and while it may exist in the double muon dataset, it will only be becasue of a trigger that we have not checked for, and so we must not have picked it up
in that dataset"""
self.passLevel = passLevel
self.writeHistFile=True
self.fillHists = fillHists
if self.fillHists and not self.writeHistFile:
self.writeHistFile=True
self.verbose=verbose
self.probEvt = probEvt
self.isData = isData
self.weightMagnitude = weightMagnitude
self.btagging = btagging
self.era = era
if probEvt:
#self.probEvt = probEvt
print("Skipping events until event #{0:d} is found".format(probEvt))
self.verbose = True
#Bits for status flag checking
self.flagbits = {'isPrompt':0b000000000000001,
'isDecayedLeptonHadron':0b000000000000010,
'isTauDecayProduct':0b000000000000100,
'isPromptTauDecaypprProduct':0b000000000001000,
'isDirectTauDecayProduct':0b000000000010000,
'isDirectPromptTauDecayProduct':0b000000000100000,
'isDirectHadronDecayProduct':0b000000001000000,
'isHardProcess':0b000000010000000,
'fromHardProcess':0b000000100000000,
'isHardProcessTauDecayProduct':0b000001000000000,
'isDirectHardProcessTauDecayProduct':0b000010000000000,
'fromHardProcessBeforeFSR':0b000100000000000,
'isFirstCopy':0b001000000000000,
'isLastCopy':0b010000000000000,
'isLastCopyBeforeFSR':0b100000000000000
}
#Bits for Event Selection Variables
self.passbits = {'PV_minNDoF': 0b00000000000000000001,
'PV_maxAbsZ': 0b00000000000000000010,
'PV_maxRho': 0b00000000000000000100,
'MET_globalSuperTightHalo2016Filter': 0b00000000000000001000,
'MET_goodVertices': 0b00000000000000010000,
'MET_HBHENoiseFilter': 0b00000000000000100000,
'MET_HBHENoiseIsoFilter': 0b00000000000001000000,
'MET_EcalDeadCellTriggerPrimitiveFilter':0b00000000000010000000,
'MET_BadPFMuonFilter': 0b00000000000100000000,
'MET_ecalBadCalibFilterV2': 0b00000000001000000000,
'MET_pt': 0b00000000010000000000,
'unused1': 0b00000000100000000000,
'Lepton_ZWindow': 0b00000001000000000000,
'Jet_nJet25': 0b00000010000000000000,
'Jet_nJet20': 0b00000100000000000000,
'HT': 0b00001000000000000000,
'Jet_nBJet_2DCSV': 0b00010000000000000000,
'Jet_nBJet_2DJet': 0b00100000000000000000,
'unused2': 0b01000000000000000000,
'unused3': 0b10000000000000000000,
}
#bits for Object Selection Variables - Jets
self.jetbits = {'lepClean': 0b000000001,
'maxEta': 0b000000010,
'jetID': 0b000000100,
'pt25': 0b000001000,
'pt20': 0b000010000,
'unused': 0b000100000,
'DCSV': 0b001000000,
'DJET': 0b010000000,
'BTag_WP': 0b100000000
}
# Thresholds for Event and Jet levels
self.jet_threshold_bits = {}
self.jet_threshold_bits['baseline'] = self.jetbits['lepClean'] + self.jetbits['maxEta'] + self.jetbits['jetID'] + \
self.jetbits['pt20']
print("Baseline bits are {0:09b}".format(self.jet_threshold_bits['baseline']))
self.jet_threshold_bits['selection'] = self.jetbits['lepClean'] + self.jetbits['maxEta'] + self.jetbits['jetID'] + \
self.jetbits['pt20']
print("Selection bits are {0:09b}".format(self.jet_threshold_bits['selection']))
self.evt_threshold_bits = {}
# self.evt_threshold_bits['baseline'] = 0b00001100011111111111
# self.evt_threshold_bits['selection'] = 0b00001100011111111111
self.evt_threshold_bits['baseline'] = self.passbits['PV_minNDoF'] + self.passbits['PV_maxAbsZ'] +\
self.passbits['PV_maxRho'] + self.passbits['MET_globalSuperTightHalo2016Filter'] +\
self.passbits['MET_goodVertices'] + self.passbits['MET_HBHENoiseFilter'] + \
self.passbits['MET_HBHENoiseIsoFilter'] + \
self.passbits['MET_EcalDeadCellTriggerPrimitiveFilter'] + \
self.passbits['MET_BadPFMuonFilter'] + self.passbits['MET_ecalBadCalibFilterV2'] + \
self.passbits['MET_pt'] + self.passbits['Jet_nJet20'] + self.passbits['HT']
self.evt_threshold_bits['selection'] = self.passbits['PV_minNDoF'] + self.passbits['PV_maxAbsZ'] +\
self.passbits['PV_maxRho'] + self.passbits['MET_globalSuperTightHalo2016Filter'] +\
self.passbits['MET_goodVertices'] + self.passbits['MET_HBHENoiseFilter'] + \
self.passbits['MET_HBHENoiseIsoFilter'] + \
self.passbits['MET_EcalDeadCellTriggerPrimitiveFilter'] + \
self.passbits['MET_BadPFMuonFilter'] + self.passbits['MET_ecalBadCalibFilterV2'] + \
self.passbits['MET_pt'] + self.passbits['Jet_nJet20'] + self.passbits['HT']
#flags for MET filters
self.FlagsDict = {"2016" : { "isData" : ["globalSuperTightHalo2016Filter"],
"Common" : ["goodVertices",
"HBHENoiseFilter",
"HBHENoiseIsoFilter",
"EcalDeadCellTriggerPrimitiveFilter",
"BadPFMuonFilter"
],
"NotRecommended" : ["BadChargedCandidateFilter",
"eeBadScFilter"
]
},
"2017" : { "isData" : ["globalSuperTightHalo2016Filter"],
"Common" : ["goodVertices",
"HBHENoiseFilter",
"HBHENoiseIsoFilter",
"EcalDeadCellTriggerPrimitiveFilter",
"BadPFMuonFilter",
"ecalBadCalibFilterV2"
],
"NotRecommended" : ["BadChargedCandidateFilter",
"eeBadScFilter"
]
},
"2018" : { "isData" : ["globalSuperTightHalo2016Filter"],
"Common" : ["goodVertices",
"HBHENoiseFilter",
"HBHENoiseIsoFilter",
"EcalDeadCellTriggerPrimitiveFilter",
"BadPFMuonFilter",
"ecalBadCalibFilterV2"
],
"NotRecommended" : ["BadChargedCandidateFilter",
"eeBadScFilter"
]
}
}
self.Flags = self.FlagsDict[era]
#Btagging dictionary
#FIXMEFIXMEFIXME
self.bTagWorkingPointDict = {
'2016':{
'DeepCSV':{
'L': 0.2217,
'M': 0.6321,
'T': 0.8953,
'Var': 'btagDeepB'
},
'DeepJet':{
'L': 0.0614,
'M': 0.3093,
'T': 0.7221,
'Var': 'btagDeepFlavB'
}
},
'2017':{
'CSVv2':{
'L': 0.5803,
'M': 0.8838,
'T': 0.9693,
'Var': 'btagCSVV2'
},
'DeepCSV':{
'L': 0.1522,
'M': 0.4941,
'T': 0.8001,
'Var': 'btagDeepB'
},
'DeepJet':{
'L': 0.0521,
'M': 0.3033,
'T': 0.7489,
'Var': 'btagDeepFlavB'
}
},
'2018':{
'DeepCSV':{
'L': 0.1241,
'M': 0.4184,
'T': 0.7527,
'Var': 'btagDeepB'
},
'DeepJet':{
'L': 0.0494,
'M': 0.2770,
'T': 0.7264,
'Var': 'btagDeepFlavB'
}
}
}
#2016selection required !isFake(), nDegreesOfFreedom> 4 (strictly),|z| < 24 (in cm? fractions of acentimeter?), and rho =sqrt(PV.x**2 + PV.y**2)< 2
#Cuts are to use strictly less than and greater than, i.e. PV.ndof > minNDoF, not >=
self.PVCutDict = {
'2016':{
'minNDoF': 4,
'maxAbsZ': 24.0,
'maxRho': 2
},
'2017':{
'minNDoF': 4,
'maxAbsZ': 24.0,
'maxRho': 2
},
'2018':{
'minNDoF': 4,
'maxAbsZ': 24.0,
'maxRho': 2
}
}
self.PVCut = self.PVCutDict[era]
#Weight variations
if self.isData:
self.weightList = ["NONE"]
else:
# self.weightList = ["NONE", "EWo", "EWS", "PUo", "EP"]
self.weightList = ["NOM"]
#NOM will be XS weight * PU weight * L1Prefiring weight? No Lepton weights, yet
#BTagging method, algorithm name, and chosen selection working point
self.BTName = btagging[0]
self.BTMeth = self.bTagWorkingPointDict[era][btagging[0]]
self.BTWP = self.bTagWorkingPointDict[era][btagging[0]][btagging[1]]
self.BTAlg = self.bTagWorkingPointDict[era][btagging[0]]["Var"]
self.MET = MET
self.HT = HT
self.ZWidth = ZWidth
# self.invertZWindow = invertZWindow
# self.invertZWindowEarlyReturn = invertZWindowEarlyReturn
self.jetPtVar = jetPtVar
self.jetMVar = jetMVar
self.mode = mode
self.debug = debug
if self.verbose:
print("BTMeth " + str(self.BTMeth))
print("BTWP " + str(self.BTWP))
print("BTAlg " + str(self.BTAlg))
print("Minimum lepton Pt: " + str(self.lepPt))
print("Minimum MET[Baseline, Selection]: " + str(self.MET))
print("Minimum HT[Baseline, Selection]: " + str(self.HT))
print("Z Window Width for veto bit: " + str(self.ZWidth))
# print("Inverted Z window: " + str(self.invertZWindow))
# print("Inverted Z window early return: " + str(self.invertZWindowEarlyReturn))
#event counters
self.counter = 0
self.BitsBins = 20
self.BitsMin = 0
self.BitsMax = 20
def beginJob(self, histFile=None,histDirName=None):
if self.fillHists == False and self.writehistFile == False:
Module.beginJob(self, None, None)
else:
if histFile == None or histDirName == None:
raise RuntimeError("fillHists set to True, but no histFile or histDirName specified")
###Inherited from Module
prevdir = ROOT.gDirectory
self.histFile = histFile
self.histFile.cd()
self.dir = self.histFile.mkdir( histDirName + "_JetMETLogic")
prevdir.cd()
self.objs = []
# self.JetMETLogic_Freq = {}
# self.JetMETLogic_Correl = {}
self.JetMETLogic_FailBits = {}
self.JetMETLogic_FailFirst = {}
for lvl in ["baseline", "selection"]:
# self.JetMETLogic_Freq[lvl] = ROOT.TH1D("JetMETLogic_Freq_{}".format(lvl),
# "HLT Paths Fired and Vetoed at {} level (weightMagnitude={}); Type; Events".format(lvl, self.weightMagnitude),
# 1, 0, 0)
# self.JetMETLogic_Correl[lvl] = ROOT.TH2D("JetMETLogic_Correl_{}".format(lvl),
# "Fired HLT Path Correlations at {} level (weightMagnitude={}); Path; Path ".format(lvl, self.weightMagnitude),
# self.PathsBins, self.PathsMin, self.PathsMax, self.PathsBins, self.PathsMin, self.PathsMax)
self.JetMETLogic_FailBits[lvl] = ROOT.TH1D("JetMETLogic_FailBits_{}".format(lvl),
"Failed JetMETLogic selection (any bits) at {} level (weightMagnitude={}); Path; Least significant bit power".format(lvl, self.weightMagnitude),
self.BitsBins, self.BitsMin, self.BitsMax)
self.JetMETLogic_FailFirst[lvl] = ROOT.TH1D("JetMETLogic_FailFirst_{}".format(lvl),
"Failed JetMETLogic selection (power of least significant bit) at {} level (weightMagnitude={}); Path; Least significant bit power".format(lvl, self.weightMagnitude),
self.BitsBins, self.BitsMin, self.BitsMax)
for lvl in ["baseline", "selection"]:
# self.addObject(self.JetMETLogic_Freq[lvl])
# self.addObject(self.JetMETLogic_Correl[lvl])
self.addObject(self.JetMETLogic_FailBits[lvl])
self.addObject(self.JetMETLogic_FailFirst[lvl])
# #Initialize labels to keep consistent across all files (only for labeled histograms, since introduction of 'extra' events in the histo counters (despite 0 weight)
# for lvl in ["baseline", "selection"]:
# for bitPos in xrange(self.BitsMin, self.BitsMax):
# # self.JetMETLogic_Correl[lvl].Fill(trig.trigger + " (T{})".format(trig.tier), trig.trigger + " (T{})".format(trig.tier), 0.0)
# # self.JetMETLogic_FailBits[lvl].Fill(bitPos+1, 0, 0.0)
# # self.JetMETLogic_FailFirst[lvl].Fill(bitPos+1, 0, 0.0)
# # for cat in ["Vetoed", "Fired", "Neither"]:
# # self.JetMETLogic_Freq[lvl].Fill(cat, 0.0)
# def endJob(self):
# if hasattr(self, 'objs') and self.objs != None:
# prevdir = ROOT.gDirectory
# self.dir.cd()
# for obj in self.objs:
# obj.Write()
# prevdir.cd()
# if hasattr(self, 'histFile') and self.histFile != None:
# self.histFile.Close()
def beginFile(self, inputFile, outputFile, inputTree, wrappedOutputTree):
self.branchList = inputTree.GetListOfBranches()
if "Jet_{0:s}".format(self.jetPtVar) not in self.branchList:
print("Warning: expected branch Jet_{0:s} to be present, but it is not. If not added in a module preceding this one, there will be a crash.".format(self.jetPtVar))
if "Jet_{0:s}".format(self.jetMVar) not in self.branchList:
print("Warning: expected branch Jet_{0:s} to be present, but it is not. If not added in a module preceding this one, there will be a crash.".format(self.jetMVar))
self.out = wrappedOutputTree
self.varTuple = [('Jet_OSV_baseline', 'i', 'Passes JetMETLeptonLogic at baseline level', 'nJet'),
('Jet_OSV_selection', 'i', 'Passes JetMETLogic at selection level', 'nJet'),
('ESV_JetMETLogic_baseline', 'i', 'Passes JetMETLogic at event level baseline,'\
' bits correspond to levels of baseline in JetMETLogic', None),
('ESV_JetMETLogic_nJet_baseline', 'i', 'Number of jets passing baseline requirements', None),
('ESV_JetMETLogic_HT_baseline', 'D', 'Scalar sum of selected jets\' Pt', None),
('ESV_JetMETLogic_H_baseline', 'D', 'Scalar sum of selected jets\' P', None),
('ESV_JetMETLogic_HT2M_baseline', 'D', 'Scalar sum of selected jets\' Pt except 2 highest b-tagged if they are medium or tight', None),
('ESV_JetMETLogic_H2M_baseline', 'D', 'Scalar sum of selected jets\' P except 2 highest b-tagged if they are medium or tight', None),
('ESV_JetMETLogic_HTb_baseline', 'D', 'Scalar sum of Pt for medium and tight b-tagged jets', None),
('ESV_JetMETLogic_HTH_baseline', 'D', 'Hadronic centrality, HT/H', None),
('ESV_JetMETLogic_HTRat_baseline', 'D', 'Ratio of Pt for two highest b-tagged jets to HT', None),
('ESV_JetMETLogic_dRbb_baseline', 'D', 'DeltaR between the two highest b-tagged jets', None),
('ESV_JetMETLogic_DiLepMass_baseline', 'D', 'Invariant mass of same-flavour leptons (0 default)', None),
('ESV_JetMETLogic_selection', 'i', 'Passes JetMETLogic at event level selection,'\
' bits correspond to levels of selection in JetMETLogic', None),
('ESV_JetMETLogic_nJet_selection', 'i', 'Number of jets passing selection requirements', None),
('ESV_JetMETLogic_HT_selection', 'D', 'Scalar sum of selected jets\' Pt', None),
('ESV_JetMETLogic_H_selection', 'D', 'Scalar sum of selected jets\' P', None),
('ESV_JetMETLogic_HT2M_selection', 'D', 'Scalar sum of selected jets\' Pt except 2 highest b-tagged if they are medium or tight', None),
('ESV_JetMETLogic_H2M_selection', 'D', 'Scalar sum of selected jets\' P except 2 highest b-tagged if they are medium or tight', None),
('ESV_JetMETLogic_HTb_selection', 'D', 'Scalar sum of Pt for medium and tight b-tagged jets', None),
('ESV_JetMETLogic_HTH_selection', 'D', 'Hadronic centrality, HT/H', None),
('ESV_JetMETLogic_HTRat_selection', 'D', 'Ratio of Pt for two highest b-tagged jets to HT', None),
('ESV_JetMETLogic_dRbb_selection', 'D', 'DeltaR between the two highest b-tagged jets', None),
('ESV_JetMETLogic_DiLepMass_selection', 'D', 'Invariant mass of same-flavour leptons (0 default)', None),
]
self.deprecated = [('ESV_JetMETLogic_nJet', 'I', 'Number of jets passing selection requirements', None),
('ESV_JetMETLogic_nJetBTL', 'I', 'Number of jets passing selection requirements and loose b-tagged', None),
('ESV_JetMETLogic_nJetBTM', 'I', 'Number of jets passing selection requirements and medium b-tagged', None),
('ESV_JetMETLogic_nJetBTT', 'I', 'Number of jets passing selection requirements and tight b-tagged', None),
]
if self.mode == "Flag":
if not self.out:
raise RuntimeError("No Output file selected, cannot flag events for JetMETLogic module")
else:
for name, valType, valTitle, lVar in self.varTuple:
self.out.branch("{}".format(name), valType, lenVar=lVar, title=valTitle)
elif self.mode == "Pass" or self.mode == "Fail" or self.mode == "Plot":
pass
if self.isData:
self.XSweight = self.dataWeightFunc
elif "genWeight" not in self.branchList:
self.XSweight = self.backupWeightFunc
print("Warning in TriggerAndLeptonLogic: expected branch genWeight to be present, but it is not."\
"The weight magnitude indicated will be used, but the sign of the genWeight must be assumed positive!")
else:
self.XSweight = self.genWeightFunc
def analyze(self, event): #called by the eventloop per-event
"""process event, return True (go to next module) or False (fail, go to next event)"""
#Increment counter and skip events past the maxEventsToProcess, if larger than -1
self.counter +=1
# if -1 < self.maxEventsToProcess < self.counter:
# return False
# if self.probEvt:
# if event.event != self.probEvt:
# return False
###############################################
### Collections and Objects and isData check###
###############################################
#Bits for passing different cuts in the event, make final decision at the end, the loop is going to be slow anyway, thanks to PostProcessor
ESV_baseline = 0
ESV_selection = 0
PV = Object(event, "PV")
otherPV = Collection(event, "OtherPV")
SV = Collection(event, "SV")
electrons = Collection(event, "Electron")
muons = Collection(event, "Muon")
taus = Collection(event, "Tau")
jets = Collection(event, "Jet")
# fatjets = Collection(event, "FatJet")
# subjets = Collection(event, "SubJet")
weight = self.XSweight(event) # * PU weight, L1Prefiring weight, etc.
if not self.isData:
generator = Object(event, "Generator")
btagweight = Object(event, "btagWeight") #contains .CSVV2 and .DeepCSVB float weights
if self.era == "2017":
met = Object(event, "METFixEE2017")
else:
met = Object(event, "MET")
HLT = Object(event, "HLT")
Filters = Object(event, "Flag")
#Set up dictionary for all the weights to be used.
# theWeight = {}
#Begin weight calculations. Some won't work properly with cutflow, so they'll be running weights
# ["NONE", "EWo", "EWS", "PUo", "EP"]
btagSFs = {}
for jet in jets:
pass
# for WLweight in self.weightList:
# if WLweight == "NONE":
# theWeight[WLweight] = 1
# elif WLweight == "EWo":
# theWeight[WLweight] = math.copysign(self.evtWeightBase, generator.weight)
# elif WLweight == "EWS":
# theWeight[WLweight] = math.copysign(self.evtWeightAlt, generator.weight)
# elif WLweight == "GWo":
# theWeight[weight] = generator.weight
# elif weight == "PUo":
# theWeight[weight] = event.puWeight #puWeightUp, puWeightDown
# elif weight == "EP":
# theWeight[weight] = math.copysign(self.evtWeightBase, generator.weight)*event.puWeight
# else:
# theWeight[weight] = -1
# self.cutflow[weight].Fill("> preselection", theWeight[weight])
######################
### Primary Vertex ###
######################
#Require ndof > minNDoF, |z| < maxAbsZ, and rho < maxRho
# if PV.ndof <= self.PVCut['minNDoF'] or abs(PV.z) >= self.VPCut['maxAbsZ'] or math.sqrt(PV.x**2 + PV.y**2) >= self.PVCut['maxRho']:
# return False
if PV.ndof > self.PVCut['minNDoF']:
ESV_baseline += self.passbits['PV_minNDoF']
ESV_selection += self.passbits['PV_minNDoF']
if abs(PV.z) < self.PVCut['maxAbsZ']:
ESV_baseline += self.passbits['PV_maxAbsZ']
ESV_selection += self.passbits['PV_maxAbsZ']
if math.sqrt(PV.x**2 + PV.y**2) < self.PVCut['maxRho']:
ESV_baseline += self.passbits['PV_maxRho']
ESV_selection += self.passbits['PV_maxRho']
###########
### MET ###
###########
#Check additional flag(s) solely for Data
if self.isData:
passFilters = getattr(Filters, self.Flags["isData"][0])
if passFilters:
ESV_baseline += self.passbits['MET_globalSuperTightHalo2016Filter']
ESV_selection += self.passbits['MET_globalSuperTightHalo2016Filter']
else:
#Default to true for MC
ESV_baseline += self.passbits['MET_globalSuperTightHalo2016Filter']
ESV_selection += self.passbits['MET_globalSuperTightHalo2016Filter']
#Ensure MC and Data pass all recommended filters for 2017 and 2018
for fi, flag in enumerate(self.Flags["Common"]):
passFilters = getattr(Filters, flag)
if passFilters:
ESV_baseline += self.passbits['MET_{}'.format(flag)]
ESV_selection += self.passbits['MET_{}'.format(flag)]
if met.pt >= self.MET[0]: #baseline level
ESV_baseline += self.passbits['MET_pt']
if met.pt >= self.MET[1]: #selection level
ESV_selection += self.passbits['MET_pt']
# for weight in self.weightList:
# self.cutflow[weight].Fill("> MET > {0:d}".format(self.MET), theWeight[weight])
if not self.isData:
pass
# gens = Collection(event, "GenPart")
# genjets = Collection(event, "GenJet")
# genfatjets = Collection(event, "GenJetAK8")
# gensubjets = Collection(event, "SubGenJetAK8")
# genmet = Object(event, "GenMET")
#These two are grabbed earlier
# generator = Object(event, "Generator") #stored earlier for weights access
# btagweight = Object(event, "btagWeight") #contains .CSVV2 and .DeepCSVB float weights
#This doesn't exist yet
# LHEReweightingWeight = Collection(event, "LHEReweightingWeight")
#These might fail because some of the samples lack weights... axe them for now, check later when actually needed.
# LHE = Object(event, "LHE")
# PSWeights = Collection(event, "PSWeight")
# LHEWeight = getattr(event, "LHEWeight_originalXWGTUP")
# LHEScaleWeight = Collection(event, "LHEScaleWeight")
# LHEPdfWeight = Collection(event, "LHEPdfWeight")
#BIG Weights lesson learned: you cannot use Collection, and possibly, you cannot even assign the variable and iterate through it using indices or
#pythonic methods. Thus, to ge the 3rd LHEScaleWeight, should use 3rdLHEScaleWeight = getattr(event, "LHEScaleWeight")[2] instead, indexing after acquis.
muon_baseline = []
muon_selection = []
for idx, muon in enumerate(muons):
if muon.OSV_baseline > 0:
muon_baseline.append((idx, muon))
if muon.OSV_selection > 0:
muon_selection.append((idx, muon))
electron_baseline = []
electron_selection = []
for idx, electron in enumerate(electrons):
if electron.OSV_baseline > 0:
electron_baseline.append((idx, electron))
if electron.OSV_selection > 0:
electron_selection.append((idx, electron))
leptons_baseline = electron_baseline + muon_baseline
leptons_selection = electron_selection + muon_selection
if self.debug:
if self.passLevel == 'baseline':
if len(leptons_baseline) > 2:
print("Mayday!")
if leptons_baseline[0][1].charge * leptons_baseline[1][1].charge > 0:
print("Charging up!")
if self.passLevel == 'selection':
if len(leptons_selection) > 2:
print("Mayday!")
if leptons_selection[0][1].charge * leptons_selection[1][1].charge > 0:
print("Charging up!")
#passbit if outside the Z window in same-flavor event or all in different-flavor event
if (len(electron_baseline) > 1 or len(muon_baseline) > 1):
DiLepMass_baseline = (leptons_baseline[0][1].p4() + leptons_baseline[1][1].p4()).M()
if abs( DiLepMass_baseline - 91.0) > self.ZWidth:
ESV_baseline += self.passbits['Lepton_ZWindow']
else: #opposite-flavor
ESV_baseline += self.passbits['Lepton_ZWindow']
DiLepMass_baseline = -1
#Should see no difference in invariant mass except when a collection drops below length 1, given the TriggerAndLeptonLogic Module in LeptonLogic.py
if (len(electron_selection) > 1 or len(muon_selection) > 1):
DiLepMass_selection = (leptons_selection[0][1].p4() + leptons_selection[1][1].p4()).M()
if abs( DiLepMass_selection - 91.0) > self.ZWidth:
ESV_selection += self.passbits['Lepton_ZWindow']
else: #opposite-flavor
ESV_selection += self.passbits['Lepton_ZWindow']
DiLepMass_selection = -1
############
### Jets ###
###########
jetsToClean_selection = set([lep[1].jetIdx for lep in leptons_selection])
selJets_selection = []
selBTsortedJets_selection = []
jetbits_selection = [0]*len(jets)
jetsToClean_baseline = set([lep[1].jetIdx for lep in leptons_baseline])
selJets_baseline = []
selBTsortedJets_baseline = []
jetbits_baseline = [0]*len(jets)
selJets_bugged = []
for idx, jet in enumerate(jets):
if idx not in jetsToClean_baseline:
jetbits_baseline[idx] += self.jetbits['lepClean']
if abs(jet.eta) < 2.5:
jetbits_baseline[idx] += self.jetbits['maxEta']
if jet.jetId >= 2:
jetbits_baseline[idx] += self.jetbits['jetID']
if getattr(jet, self.jetPtVar) > 25:
jetbits_baseline[idx] += self.jetbits['pt25']
if getattr(jet, self.jetPtVar) > 20:
jetbits_baseline[idx] += self.jetbits['pt20']
if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepCSV']['Var']) > self.bTagWorkingPointDict[self.era]['DeepCSV']['L']:
jetbits_baseline[idx] += self.jetbits['DCSV']
if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepJet']['Var']) > self.bTagWorkingPointDict[self.era]['DeepJet']['L']:
jetbits_baseline[idx] += self.jetbits['DJET']
if getattr(jet, self.BTAlg) > self.BTWP:
jetbits_baseline[idx] += self.jetbits['BTag_WP']
if (jetbits_baseline[idx] & self.jet_threshold_bits['baseline']) >= self.jet_threshold_bits['baseline']:
selJets_baseline.append((idx, jet))
selBTsortedJets_baseline.append((idx, jet))
# #BTagging input disabled without highest bit! Use DeepJet Loose...
# if jetbits_baseline[idx] >= 0b010010111:
if idx not in jetsToClean_selection:
jetbits_selection[idx] += self.jetbits['lepClean']
if abs(jet.eta) < 2.5:
jetbits_selection[idx] += self.jetbits['maxEta']
if jet.jetId >= 2: #dropped to 2==Tight due to bug in 4==TightLepVeto ID regarding muon energy fractions
jetbits_selection[idx] += self.jetbits['jetID']
if getattr(jet, self.jetPtVar) > 25:
jetbits_selection[idx] += self.jetbits['pt25']
if getattr(jet, self.jetPtVar) > 20:
jetbits_selection[idx] += self.jetbits['pt20']
if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepCSV']['Var']) > self.bTagWorkingPointDict[self.era]['DeepCSV']['M']:
jetbits_selection[idx] += self.jetbits['DCSV']
if getattr(jet, self.bTagWorkingPointDict[self.era]['DeepJet']['Var']) > self.bTagWorkingPointDict[self.era]['DeepJet']['M']:
jetbits_selection[idx] += self.jetbits['DJET']
if getattr(jet, self.BTAlg) > self.BTWP:
jetbits_selection[idx] += self.jetbits['BTag_WP']
if (jetbits_selection[idx] & self.jet_threshold_bits['selection']) >= self.jet_threshold_bits['selection']:
selJets_selection.append((idx, jet))
selBTsortedJets_selection.append((idx, jet))
nJets_baseline = len(selJets_baseline)
nJets_selection = len(selJets_selection)
#BTagging algo used for sorting, still
selBTsortedJets_baseline.sort(key=lambda j : getattr(j[1], self.BTAlg), reverse=True)
selBTsortedJets_selection.sort(key=lambda j : getattr(j[1], self.BTAlg), reverse=True)
#B-tagged jets
# selBTLooseJets = [jetTup for jetTup in selBTsortedJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['L']]
# selBTMediumJets = [jetTup for jetTup in selBTLooseJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['M']]
# selBTTightJets = [jetTup for jetTup in selBTMediumJets if getattr(jetTup[1], self.BTAlg) > self.BTMeth['T']]
# selBTJets = [jetTup for jetTup in selBTsortedJets if getattr(jetTup[1], self.BTAlg) > self.BTWP]
# nJets = len(selJets)
# nBTLoose = len(selBTLooseJets)
# nBTMedium = len(selBTMediumJets)
# nBTTight = len(selBTTightJets)
# nBTSelected = len(selBTJets)
nJets25_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['pt25'] > 0)]
nBJetsDeepCSV_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['DCSV'] > 0)]
nBJetsDeepJet_baseline = [bits for bits in jetbits_baseline if (bits & self.jetbits['DJET'] > 0)]
#Just 3 jets in baseline
if nJets_baseline > 2:
ESV_baseline += self.passbits['Jet_nJet20']
if len(nJets25_baseline) > 2:
ESV_baseline += self.passbits['Jet_nJet25']
#Require 2 loose tagged jets
if len(nBJetsDeepCSV_baseline) > 1:
ESV_baseline += self.passbits['Jet_nBJet_2DCSV']
if len(nBJetsDeepJet_baseline) > 1:
ESV_baseline += self.passbits['Jet_nBJet_2DJet']
nJets25_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['pt25'] > 0)]
nBJetsDeepCSV_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['DCSV'] > 0)]
nBJetsDeepJet_selection = [bits for bits in jetbits_selection if (bits & self.jetbits['DJET'] > 0)]
#4 jets in selection
if nJets_selection > 3:
ESV_selection += self.passbits['Jet_nJet20']
if len(nJets25_selection) > 3:
ESV_selection += self.passbits['Jet_nJet25']
#Require 2 medium tagged jets
if len(nBJetsDeepCSV_selection) > 1:
ESV_selection += self.passbits['Jet_nBJet_2DCSV']
if len(nBJetsDeepJet_selection) > 1:
ESV_selection += self.passbits['Jet_nBJet_2DJet']
#HT and other calculations
HT_baseline = 0
H_baseline = 0
HT2M_baseline = 0
H2M_baseline = 0
HTb_baseline = 0
HTH_baseline = 0
HTRat_baseline = 0
dRbb_baseline = -1
for j, jet in selBTsortedJets_baseline:
HT_baseline += getattr(jet, self.jetPtVar)
jetP4_baseline = ROOT.TLorentzVector()
jetP4_baseline.SetPtEtaPhiM(getattr(jet, self.jetPtVar),
getattr(jet, "eta"),
getattr(jet, "phi"),
getattr(jet, self.jetMVar)
)
H_baseline += jetP4_baseline.P()
#Only use deepjet
if j > 1 and len(nBJetsDeepJet_baseline) > 1:
HT2M_baseline += getattr(jet, self.jetPtVar)
H2M_baseline += jetP4_baseline.P()
if jetbits_baseline[j] & self.jetbits['DJET']:
HTb_baseline += getattr(jet, self.jetPtVar)
if HT_baseline >= self.HT[0]:
ESV_baseline += self.passbits['HT']
if len(selBTsortedJets_baseline) > 3: #redundant, but only so long as 4 jet cut is in place
jet1_baseline = selBTsortedJets_baseline[0][1]
jet2_baseline = selBTsortedJets_baseline[1][1]
dRbb_baseline = deltaR(jet1_baseline, jet2_baseline)
HTRat_baseline = (jet1_baseline.pt + jet2_baseline.pt)/HT_baseline
HTH_baseline = HT_baseline/H_baseline
else:
dRbb_baseline = -1
HTRat_baseline = -0.1
HTH_baseline = -0.1
#HT and other calculations
HT_selection = 0
H_selection = 0
HT2M_selection = 0
H2M_selection = 0
HTb_selection = 0
HTH_selection = 0
HTRat_selection = 0
dRbb_selection = -1
for j, jet in selBTsortedJets_selection:
HT_selection += getattr(jet, self.jetPtVar)
jetP4_selection = ROOT.TLorentzVector()
jetP4_selection.SetPtEtaPhiM(getattr(jet, self.jetPtVar),
getattr(jet, "eta"),
getattr(jet, "phi"),
getattr(jet, self.jetMVar)
)
H_selection += jetP4_selection.P()
#Only use deepjet
if j > 1 and len(nBJetsDeepJet_selection) > 1:
HT2M_selection += getattr(jet, self.jetPtVar)
H2M_selection += jetP4_selection.P()
if jetbits_selection[j] & self.jetbits['DJET']:
HTb_selection += getattr(jet, self.jetPtVar)
if HT_selection >= self.HT[1]:
ESV_selection += self.passbits['HT']
if len(selBTsortedJets_selection) > 3: #redundant, but only so long as 4 jet cut is in place
jet1_selection = selBTsortedJets_selection[0][1]
jet2_selection = selBTsortedJets_selection[1][1]
dRbb_selection = deltaR(jet1_selection, jet2_selection)
HTRat_selection = (jet1_selection.pt + jet2_selection.pt)/HT_selection
HTH_selection = HT_selection/H_selection
else:
dRbb_selection = -1
HTRat_selection = -0.1
HTH_selection = -0.1
####################################
### Variables for branch filling ###
####################################
branchVals = {}
branchVals['Jet_OSV_baseline'] = jetbits_baseline
branchVals['Jet_OSV_selection'] = jetbits_selection
branchVals['ESV_JetMETLogic_baseline'] = ESV_baseline #Do a bit comparison at the end?
branchVals['ESV_JetMETLogic_selection'] = ESV_selection #do bit comparison at the end, but maybe still keep bits around...
branchVals['ESV_JetMETLogic_nJet_baseline'] = nJets_baseline
branchVals['ESV_JetMETLogic_nJet_selection'] = nJets_selection
# branchVals['ESV_JetMETLogic_nJetBTL'] = nBTLoose
# branchVals['ESV_JetMETLogic_nJetBTM'] = nBTMedium
# branchVals['ESV_JetMETLogic_nJetBTT'] = nBTTight
branchVals['ESV_JetMETLogic_HT_baseline'] = HT_baseline
branchVals['ESV_JetMETLogic_H_baseline'] = H_baseline
branchVals['ESV_JetMETLogic_HT2M_baseline'] = HT2M_baseline
branchVals['ESV_JetMETLogic_H2M_baseline'] = H2M_baseline
branchVals['ESV_JetMETLogic_HTb_baseline'] = HTb_baseline
branchVals['ESV_JetMETLogic_HTH_baseline'] = HTH_baseline
branchVals['ESV_JetMETLogic_HTRat_baseline'] = HTRat_baseline
branchVals['ESV_JetMETLogic_dRbb_baseline'] = dRbb_baseline
branchVals['ESV_JetMETLogic_DiLepMass_baseline'] = DiLepMass_baseline
branchVals['ESV_JetMETLogic_HT_selection'] = HT_selection
branchVals['ESV_JetMETLogic_H_selection'] = H_selection
branchVals['ESV_JetMETLogic_HT2M_selection'] = HT2M_selection
branchVals['ESV_JetMETLogic_H2M_selection'] = H2M_selection
branchVals['ESV_JetMETLogic_HTb_selection'] = HTb_selection
branchVals['ESV_JetMETLogic_HTH_selection'] = HTH_selection
branchVals['ESV_JetMETLogic_HTRat_selection'] = HTRat_selection
branchVals['ESV_JetMETLogic_dRbb_selection'] = dRbb_selection
branchVals['ESV_JetMETLogic_DiLepMass_selection'] = DiLepMass_selection
####################################
### Event pass values calculated ###
####################################
passVals = {}
passVals['ESV_JetMETLogic_pass_all'] = True
passVals['ESV_JetMETLogic_pass_baseline'] = ( (branchVals['ESV_JetMETLogic_baseline'] & self.evt_threshold_bits['baseline']) >= self.evt_threshold_bits['baseline'])
passVals['ESV_JetMETLogic_pass_selection'] = ( (branchVals['ESV_JetMETLogic_selection'] & self.evt_threshold_bits['selection']) >= self.evt_threshold_bits['selection'])
#######################
### Fill histograms ###
#######################
if self.fillHists:
for lvl in ["baseline", "selection"]:
if passVals['ESV_JetMETLogic_pass_{}'.format(lvl)]:
pass
else:
# self.addObject(self.JetMETLogic_Freq[lvl])
# self.addObject(self.JetMETLogic_Correl[lvl])
foundFirstFail = False
for bitPos, bitVal in enumerate(self.passbits.values()):
if (bitVal & self.evt_threshold_bits[lvl] == 0) or (bitVal & branchVals['ESV_JetMETLogic_{}'.format(lvl)] > 0):
#First skip values that aren't set in the evt_threshold, we can't fail on them, then additionally skip values that are passed in regard to those thresholds, using the comparison with bits in ESV_JetMETLogic_{lvl}
continue
#This is triggered when we have a bit that is in the threshold and was not met by the event, so it's a failure
self.JetMETLogic_FailBits[lvl].Fill(bitPos+1, weight)
if not foundFirstFail: self.JetMETLogic_FailFirst[lvl].Fill(bitPos+1, weight)
#And if we made it to this point, we skip filling any further bits in the second histo by flipping the flag below
foundFirstFail = True
##########################
### Write out branches ###
##########################
if self.out and self.mode == "Flag":
for name, valType, valTitle, lVar in self.varTuple:
self.out.fillBranch(name, branchVals[name])
return True
elif self.mode == "PassFail":
if passVals['ESV_JetMETLogic_pass_{}'.format(self.passLevel)]:
return True
else:
return False
elif self.mode == "Plot":
#Do something?
#Do pass through if plotting, make no assumptions about what should be done with the event
return True
else:
raise NotImplementedError("No method in place for JetMETLogic module in mode '{0}'".format(self.mode))
def genWeightFunc(self, event):
#Default value is currently useless, since the tree reader array tool raises an exception anyway
return math.copysign(self.weightMagnitude, getattr(event, "genWeight", 1))
def backupWeightFunc(self, event):
return self.weightMagnitude
def dataWeightFunc(self, event):
return 1
| [
"nmang001@ucr.edu"
] | nmang001@ucr.edu |
584b1e5c22490eed08ae277c45d9260ee70e2553 | 2c7bc4e4289e7146c9a9b0af836fe4069521737a | /第一阶段/基础/第10章 文件和异常/10.3 异常/10.3.9 决定报告哪些错误.py | 930fb4760e7056894619e2fdb20480984d046284 | [
"Apache-2.0"
] | permissive | kwhua/nihao- | e2da2502cff9e4b0b21770e02d971d7ec857c6fa | 0b69b0cda4f57831504d01b51bd2370f436db2b8 | refs/heads/master | 2022-12-19T04:23:49.757470 | 2020-09-24T07:53:35 | 2020-09-24T07:53:35 | 298,187,993 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 922 | py | '''
在什么情况下该向用户报告错误呢?在什么情况下又该在失败时一声不吭呢?如果用户知道
要分析哪些文件,他们希望在有文件没有文件等稀释出现一条消息,将其中的原因告诉他们.
如果客户只想看到结果,而不是要分析哪些文件,可能就需要在哪些文件不存在时告知他们.
向用户显示他不想看待的信息可能会降低程序的可用性.Python的错误处理结构让你能够细致地
控制与用户分享错误信息的程度,要分享多少信息由你决定.
编写得很好且经过详尽测试的代码不容易出现内部错误,入语法或逻辑错误,但只要程序依赖
于外部因素,如用户输入、存在指定的文件、有网络链接,就有可能出现异常。凭借经验可判断
该在程序的什么地方包含异常处理块,以及错误是该向用户提供多少相关的信息。
''' | [
"646013895@qq.com"
] | 646013895@qq.com |
9f9308863eec758d41777158b11d291e1b437a83 | 9b63ade6dd9c166b2e9dc363de94d6a02149bc69 | /app/core/migrations/0001_initial.py | dd8e72540712189dd4156237b574b3e1e3799370 | [
"MIT"
] | permissive | nafeesahyounis/recipe-app-api | 25244f7a12772a0281d99c03a0c6cf9b434ba849 | ff9f42de65d9b0185d9ab9fb565e4a881831cb15 | refs/heads/main | 2023-03-07T13:00:00.005410 | 2021-02-24T10:02:04 | 2021-02-24T10:02:04 | 338,332,277 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,709 | py | # Generated by Django 3.1.6 on 2021-02-23 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| [
"nafeesah.youniss@gmail.com"
] | nafeesah.youniss@gmail.com |
0769073e54f97a7b28ca46674614b73ce89d67c6 | 37906b41991719dff0590f9161f9b69af8d7e491 | /tensorflow/python/tpu/tensor_tracer.py | b9aec3f2e26e5272030fbfb380877f6d6a789d29 | [
"Apache-2.0"
] | permissive | nauman07/tensorflow | 7ae4277564bb596c0f8ba5d107a35d9505c3c2fb | f88cf68393e60525506a567e0081b8e2e6db409b | refs/heads/master | 2020-08-28T15:55:35.510154 | 2019-10-26T15:34:58 | 2019-10-26T15:39:08 | 217,742,698 | 3 | 0 | Apache-2.0 | 2019-10-26T17:11:10 | 2019-10-26T17:11:09 | null | UTF-8 | Python | false | false | 66,668 | py | # Copyright 2018 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.
# ========================================================================
"""A utility to trace tensor values on TPU."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path
import sys
import numpy as np
import six
from tensorflow.core.framework import summary_pb2
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_io
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import control_flow_util
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import summary_ops_v2 as summary
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import analytics
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary_iterator
from tensorflow.python.tpu import tensor_tracer_flags
from tensorflow.python.tpu import tensor_tracer_report
from tensorflow.python.tpu import tpu
from tensorflow.python.tpu.ops import tpu_ops
from tensorflow.python.training import training_util
_DEVICE_TYPE_TPU = 'tpu'
_DEVICE_TYPE_CPU = 'cpu'
_TRACE_MODE_PART_TENSOR_SIZE = 3
_REASON_OUTSIDE_OP_RANGE = 'not-traced-outside-op-range'
_REASON_UNSAFE_OP = 'not-traced-unsafe-op'
_REASON_WHILELOOP_OP = 'not-traced-special-whileloop-op'
_REASON_UNSAFE_SCALAR = 'not-traced-unsafe-scalar'
_REASON_SKIP_SCALAR = 'not-traced-scalar'
_REASON_LESS_INTERESTING_OP = 'not-traced-less-interesting-op'
_REASON_DEVICE_MISMATCH = 'not-traced-device-mismatch'
_REASON_DYNAMIC_SHAPE = 'not-traced-dynamic-shape'
_REASON_SCALAR_GET_TRACED = 'traced-scalar'
_REASON_TENSOR_GET_TRACED = 'traced-tensor'
_REASON_USER_INCLUDED = 'traced-user-included'
_REASON_USER_EXCLUDED = 'not-traced-user-excluded'
_REASON_NOT_EXECUTED = 'not-traced-not-in-exec-path'
_REASON_NON_NUMERIC_TENSOR = 'not-traced-non-numeric-tensor'
_REASON_FEEDS_WHILELOOP_OP = 'not-traced-feeds-special-whileloop-op'
_OUTPUT_STREAM_ESCAPE = 'file://'
_TENSOR_TRACER_COLLECTION = 'tensor_tracer_variables'
_TRACE_FILE_NAME = 'trace.all'
_COMPACT_TRACE_FILE_PREFIX = 'compact_trace.'
_COMPACT_TRACE_ENTRY_INIT_VALUE = -1.0
_TENSOR_TRACER_STORAGE = 'tensor_tracer_storage'
_TT_SNAPSHOT = 'tensor_tracer_snapshot'
_REPLICA_ID_TAG = '#replica-id: '
_TT_SUMMARY_NORM = tensor_tracer_flags.TT_SUMMARY_NORM
_TT_SUMMARY_MAX = tensor_tracer_flags.TT_SUMMARY_MAX
_TT_SUMMARY_MIN = tensor_tracer_flags.TT_SUMMARY_MIN
_TT_SUMMARY_MEAN = tensor_tracer_flags.TT_SUMMARY_MEAN
_TT_SUMMARY_VAR = tensor_tracer_flags.TT_SUMMARY_VAR
_TT_SUMMARY_SIZE = tensor_tracer_flags.TT_SUMMARY_SIZE
_TT_SUMMARY_TAG = 'tensor_tracer_summary'
_TT_TENSORBOARD_PLUGIN_NAME = 'tensor_tracer'
_TT_HOSTCALL_KEY = 'tensor_tracer_host_call'
_TT_EVENT_FILE_SUFFIX = '.tensor_tracer'
_TT_SUMMARY_MAX_QUEUE = 100
def op_priority(op_type):
"""Returns the priority of the op.
If the priority of the op is k, it will be traced if trace_level>=k.
Args:
op_type: String name of the operation type.
Returns:
Integer value corresponding the priority of the op.
"""
if op_type in ('Const', 'Shape', 'BroadcastGradientArgs', 'Range',
'VariableShape', 'Fill', 'OneHot'):
# Lowest priority ops, e.g., constant ops accross different steps,
# They will be traced only if trace_level>=7
return 7
if op_type in ('Identity', 'Cast', 'Reshape', 'ExpandDims', 'StopGradient',
'PreventGradient', 'Squeeze'):
# Operations without numerical effects.
# They will be only if trace_level>=6
return 6
if op_type in ('ConcatV2', 'Concat', 'StridedSlice', 'Slice', 'Pack', 'Tile'):
# Operations that merge or slice an input, will be traced if trace_level>=5
return 5
if op_type in ('Pad', 'RandomUniformInt', 'GreaterEqual'):
# Operations less likely to provide useful information,
# will be traced if trace_level>=4
return 4
if op_type in ('Sum', 'AddV2', 'Add', 'AddN', 'BiasAdd', 'CrossReplicaSum'):
# Add operations that are less likely create any issues, will be traced
# if trace_level>=3 (default=3)
return 3
if op_type in ('Neg', 'Sub'):
# Sub operations that are less likely create any issues, will be traced
# trace_level>=2
return 2
if op_type in ('Mul', 'Square', 'MatMul', 'RandomUniform', 'Select',
'Maximum', 'Mean', 'Variance'):
# Multiplication and some other operations, will be traced if trace_level>=1
return 1
return 0
def read_tensor_tracer_event_file(event_file):
"""Reads the event file written by tensor tracer.
Args:
event_file: Path to the event file that contains only tensor tracer events.
Returns:
An event dictionary in the form of
{step_number: {tensor_name: tensor_content}}
Raises:
ValueError: If an unexpected trace is found.
"""
event_dict = {}
for trace_event in summary_iterator.summary_iterator(event_file):
# First event is an event with file_version: "brain.Event:2"
if not trace_event.HasField('summary'):
continue
step = trace_event.step
if step not in event_dict:
event_dict[step] = {}
if len(trace_event.summary.value) != 1:
raise ValueError('Single step contains %d summary values,'
' expected 1.' % len(trace_event.summary.value))
tensor_value = trace_event.summary.value[0]
tensor_name = tensor_value.tag
real_shape = [d.size for d in tensor_value.tensor.tensor_shape.dim]
tensor_content = np.frombuffer(
tensor_value.tensor.tensor_content,
dtypes.DType(tensor_value.tensor.dtype).as_numpy_dtype()
).reshape(real_shape)
event_dict[step][tensor_name] = tensor_content
return event_dict
def tensor_tracepoint(tensor, checkpoint_name):
"""Adds a checkpoint with the given checkpoint name for the given tensor.
The tensor will be added to the list of tensors that will be traced by the
tensor tracer.
Args:
tensor: the tensor object for which the tracing is requested.
checkpoint_name: a string name for the checkpoint. This name has to be a
unique name if used within model comparison. The tensors that have the same
checkpoint identifier is compared in model comparison.
Returns:
The provided tensor.
"""
tensor.graph.get_collection(_TENSOR_TRACER_COLLECTION)
tensor.graph.add_to_collection(_TENSOR_TRACER_COLLECTION,
(tensor, checkpoint_name))
return tensor
def keras_layer_tracepoint(layer, checkpoint_name):
"""An interface for adding the tensor outputs of a keras layer.
Encapsulates tensor_tracepoint.
Args:
layer: A keras layer.
checkpoint_name: a string name for the checkpoint. This name has to be a
unique name if used within model comparison. The tensors that have the same
checkpoint identifier is compared in model comparison.
Returns:
The provided layer.
"""
try:
outputs = layer.output
if tensor_util.is_tensor(outputs):
tensor_tracepoint(outputs, '%s' % (checkpoint_name))
else:
idx = 0
for output_tensor in outputs:
if tensor_util.is_tensor(outputs):
tensor_tracepoint(output_tensor, '%s_%d' % (checkpoint_name, idx))
idx += 1
except AttributeError:
pass
except RuntimeError:
pass
return layer
def _trace_files_need_precreated(output_dir):
"""Return True if trace files must be pre-created by users."""
if not output_dir.startswith('/'):
return False
if len(output_dir) < 5:
return False
if output_dir[2] != 'n':
return False
if output_dir[3] != 's':
return False
if output_dir[1] != 'c':
return False
if output_dir[4] != '/':
return False
return True
class TensorTracer(object):
"""A software construct for tracing tensor values in a TF graph on TPU.
This utility is disabled by default. It can be enabled by setting
the TENSOR_TRACER_FLAGS env variable as:
export TENSOR_TRACER_FLAGS="--enable=1"
If it is enabled, it will trace the output tensor values of
selected Ops in the graph. It has two outputs: (1) the traces and (2)
a report. The traces are dumped to a specified local file on the TPU
host. The report is printed to the log.info of the TPU job.
By passing options via the env variable, users can change:
(1) the trace mode (e.g., detecting NaN/Inf, printing partial or
full tensor values)
(2) which Ops to be traced (via op.name or op.type)
(3) output trace file path.
"""
# The set of graphs that are rewritten by tensor tracer.
_traced_graphs = set()
@staticmethod
def is_enabled():
"""Returns True if TensorTracer is enabled."""
return tensor_tracer_flags.TTParameters().is_enabled()
@staticmethod
def check_device_type(device_type):
"""Checks if the given device type is valid."""
if device_type not in (_DEVICE_TYPE_TPU, _DEVICE_TYPE_CPU):
raise ValueError('Invalid device_type "%s"'%device_type)
@staticmethod
def check_trace_mode(device_type, trace_mode):
"""Checks if the given trace mode work on the given device type.
Args:
device_type: Device type, TPU, GPU, CPU.
trace_mode: Tensor tracer trace mode.
Raises:
ValueError: If the given trace mode is not supported for the device.
"""
if trace_mode in (tensor_tracer_flags.TRACE_MODE_SUMMARY,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY):
if device_type != _DEVICE_TYPE_TPU:
raise ValueError('Device_type "%s" is not yet supported for '
'trace mode "%s"' % (device_type, trace_mode))
@staticmethod
def loop_cond_op(op):
return op.type in ('LoopCond', 'RefLoopCond')
@staticmethod
def while_loop_op(op):
"""Returns true if op is one of the special ops of in a while loop.
Args:
op: A tf.Operation.
Returns:
True if the given op is one of [Switch, Merge, Enter, Exit,
NextIteration, LoopCond], which are all building blocks for TF while
loops.
"""
return (control_flow_util.IsLoopSwitch(op) or
control_flow_util.IsLoopMerge(op) or
control_flow_util.IsLoopEnter(op) or
control_flow_util.IsLoopExit(op) or
TensorTracer.loop_cond_op(op) or
op.type in ('RefNextIteration', 'NextIteration'))
@staticmethod
def unsafe_op(op):
"""Returns True if this op is not safe to be traced."""
if control_flow_util.IsInCond(op):
return True
# Reasons for not including following op types:
# Assign: cause incorrect result with CPU tracing.
if op.type == 'Assign':
return True
return False
@staticmethod
def device_mismatch(device_type, op):
if device_type == _DEVICE_TYPE_TPU:
# pylint: disable=protected-access
return tpu._TPU_REPLICATE_ATTR not in op.node_def.attr
# pylint: enable=protected-access
return False
@staticmethod
def unsafe_scalar_trace(op):
"""Return true if scalar output tensor from Op is not safe to be traced."""
# Tracing the following causes cycle in the graph on TPU.
if op.type in ('LoopCond', 'Enter', 'Merge', 'Const',
'Switch', 'Less', 'ReadVariableOp'):
return True
# Tracing the following will cause casting-issue
# with the norm tracing mode or other compilation issues on CPU.
if op.type in ('VarHandleOp', 'IteratorToStringHandle',
'IteratorGetNext', 'OneShotIterator',
'IteratorV2', 'MakeIterator',
'BatchDatasetV2', 'MapDataset',
'FixedLengthRecordDataset', 'TakeDataset', 'ZipDataset',
'Placeholder', 'PlaceholderWithDefault', 'StridedSlice'):
return True
return False
def _is_interesting_op(self, op):
"""Returns True if the given op is not an interesting one to be traced."""
# If flag is set to include less interesting ops, then include everything.
if self._parameters.include_less_interesting_ops:
return True
return op_priority(op.type) <= self._parameters.trace_level
@staticmethod
def reason(op_idx, details):
"""Returns reason why the Op at op_idx is traced or not."""
return '%d %s'%(op_idx, details)
def __init__(self):
"""Initializes a TensorTracer.
Sets the various member fields from the flags (if given) or the defaults.
"""
self._replica_id = None
self._tt_config = tensor_tracer_report.TensorTracerConfig()
self._parameters = tensor_tracer_flags.TTParameters()
self._included_op_full_names = set()
self._host_call_fn = {}
self._cache_variables = {}
def _get_all_cache_variables(self):
return self._cache_variables
def _create_or_get_tensor_values_cache(self, cache_name, graph=None,
shape=None, dtype=dtypes.float32):
"""Creates a variable as the cache to store intermediate tensor values.
Args:
cache_name: Name to be given to the cache (an instance of tf.variable).
graph: Tensorflow graph.
shape: A list of dimensions.
dtype: Data type of created cache.
Returns:
A ref to newly created or existing cache with the given dimensions.
Raises:
ValueError: If missing a parameter to create the cache.
"""
def _escape_namescopes(variable_name):
# TODO(deveci): This might cause name collisions as in "foo/bar/mytensor"
# and "foo_bar/mytensor".
return variable_name.replace('/', '_').replace(':', '_')
if cache_name not in self._cache_variables:
if graph is None:
raise ValueError('Graph must be provided at cache creation.')
if shape is None:
raise ValueError('shape must be provided at cache creation.')
graph = graph or ops.get_default_graph()
if dtype.is_integer:
init_val = int(_COMPACT_TRACE_ENTRY_INIT_VALUE)
else:
init_val = _COMPACT_TRACE_ENTRY_INIT_VALUE
# Create in proper graph and base name_scope.
with graph.as_default() as g, g.name_scope(None):
self._cache_variables[cache_name] = variable_scope.get_variable(
_TT_SNAPSHOT + '_' + _escape_namescopes(cache_name),
shape=shape, dtype=dtype,
initializer=init_ops.constant_initializer(init_val),
trainable=False,
use_resource=True,
collections=[_TENSOR_TRACER_STORAGE, ops.GraphKeys.LOCAL_VARIABLES])
return self._cache_variables[cache_name]
def _add_replica_id_to_graph(self):
"""Adds nodes for computing the replica ID to the graph."""
if self._tt_config.num_replicas:
with ops.control_dependencies(None):
# Uses None as dependency to run outside of TPU graph rewrites.
self._replica_id = tpu_ops.tpu_replicated_input(
list(range(self._tt_config.num_replicas)),
name='tt_replica_id')
else:
self._replica_id = 'unknown'
def _inside_op_range(self, idx):
"""Return True if the given index is inside the selected range."""
if idx < self._parameters.op_range[0]:
return False
return (self._parameters.op_range[1] < 0 or
idx <= self._parameters.op_range[1])
def _is_user_included_op(self, op):
"""Checks whether the op is included in the tensor tracer flags.
Args:
op: tf Operation
Returns:
True, if the op is included.
An op is included if:
- Its op name is given in included_opnames
- Its op type is given in included_optypes
- The op is at most _trace_ops_before_included hops before an included op
- The op is at most _trace_ops_after_included hops after an included op
"""
def _is_op_or_any_neighbor_included(op, check_before=0, check_after=0):
"""Helper function to check if op is included or not."""
if op.name in self._included_op_full_names:
return True
for opname_re in self._parameters.included_opname_re_list:
if opname_re.match(op.name):
self._included_op_full_names.add(op.name)
return True
for optype_re in self._parameters.included_optype_re_list:
if optype_re.match(op.type):
self._included_op_full_names.add(op.name)
return True
if check_after > 0:
for out_tensor in op.outputs:
for consumer in out_tensor.consumers():
if _is_op_or_any_neighbor_included(consumer, check_after - 1, 0):
self._included_op_full_names.add(op.name)
return True
if check_before > 0:
for input_tensor in op.inputs:
if _is_op_or_any_neighbor_included(input_tensor.op,
0,
check_before - 1):
self._included_op_full_names.add(op.name)
return True
return False
# check_after and check_before are swapped below, as below operation
# checks the distance from an arbitrary op to included ops.
return _is_op_or_any_neighbor_included(
op, self._parameters.trace_ops_after_included,
self._parameters.trace_ops_before_included)
def _is_user_excluded_op(self, op):
for opname_re in self._parameters.excluded_opname_re_list:
if opname_re.match(op.name):
return True
for optype_re in self._parameters.excluded_optype_re_list:
if optype_re.match(op.type):
return True
return False
def _signature_types(self):
"""Returns a dictionary holding the order of signatures in the cache for the selected trace mode."""
if self._parameters.trace_mode in set([
tensor_tracer_flags.TRACE_MODE_NAN_INF,
tensor_tracer_flags.TRACE_MODE_NORM,
tensor_tracer_flags.TRACE_MODE_MAX_ABS]):
return {self._parameters.trace_mode: 0}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
return self._parameters.summary_signatures
return {}
def _num_signature_dimensions(self):
return len(self._signature_types())
def _use_tensor_values_cache(self):
"""Returns True if immediate tensors should be first saved to a cache."""
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
# For summary tace mode only compact format is supported.
return True
if self._parameters.trace_mode not in set([
tensor_tracer_flags.TRACE_MODE_NAN_INF,
tensor_tracer_flags.TRACE_MODE_NORM,
tensor_tracer_flags.TRACE_MODE_MAX_ABS,
tensor_tracer_flags.TRACE_MODE_SUMMARY
]):
return False
if (self._parameters.trace_dir and
_trace_files_need_precreated(self._parameters.trace_dir)):
return True
return self._parameters.use_compact_trace
def _use_tensor_buffer(self):
"""Returns true if the whole tensor needs to be cached/buffered in memory."""
return (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)
def _save_tensor_value_to_cache_op(self, cache_idx, updates):
"""Returns an op that will save the given updates to an entry in the cache.
Args:
cache_idx: The cache index of the tensor within the cache.
updates: A dictionary of the signature updates.
Returns:
Cache update operation.
"""
# state_ops.scatter_update allows updates only along the first dimension.
# Make a compact array by concantating different signatures, and update
# them all together.
sorted_update = []
if self._num_signature_dimensions() > 1:
signature_indices = self._signature_types()
for _, val in sorted(updates.items(),
key=lambda item: signature_indices[item[0]]):
sorted_update.append(val)
updates = array_ops.stack(sorted_update, axis=0)
updates = array_ops.reshape(updates, [1,
self._num_signature_dimensions()])
else:
(_, val), = updates.items()
updates = array_ops.reshape(val, [1, self._num_signature_dimensions()])
indices = constant_op.constant([cache_idx])
cache = self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG)
return state_ops.scatter_update(cache, indices, updates).op
def _snapshot_tensor(self, tensor):
"""Creates a new tf.Variable and a new tf.Operation that assigns the value of the tensor to this variable.
Args:
tensor: tensor whose values will be stored in a new tf.Variable.
Returns:
An assignment operation.
"""
snapshot_variable = self._create_or_get_tensor_values_cache(
tensor.name, tensor.op.graph,
tensor.shape.as_list(), tensor.dtype)
return state_ops.assign(snapshot_variable, tensor).op
def _preprocess_traced_tensor(self, tensor):
"""Computes NAN/Norm/Max on TPUs before sending to CPU.
Args:
tensor: The tensor to be traced.
Returns:
A tensor that should be input to the trace_function.
Raises:
RuntimeError: If the trace mode is invalid.
"""
def _detect_nan_inf(tensor):
"""Trace function for detecting any NaN/Inf in the tensor."""
if tensor.dtype.is_floating:
mask = math_ops.reduce_any(
gen_math_ops.logical_or(
gen_math_ops.is_nan(tensor), gen_math_ops.is_inf(tensor)))
output_tensor = control_flow_ops.cond(
mask,
lambda: constant_op.constant([1.0]),
lambda: constant_op.constant([0.0]))
else:
output_tensor = constant_op.constant([0.0])
return output_tensor
def _compute_signature(tensor, tf_op, cast_to_f32=True):
if cast_to_f32:
tensor = math_ops.cast(tensor, dtypes.float32)
output_tensor = tf_op(tensor)
# Return type should be scalar. Set it if it does not have the
# information.
if not output_tensor.get_shape().is_fully_defined():
output_tensor = array_ops.reshape(output_tensor, [])
return output_tensor
def _show_size(tensor):
# In order to check the size of a tensor.
# Not all sizes are known at the compile time, also, different replicas
# sometimes get different sizes of tensors.
# Collect it here to be used in merging replica data.
tsize = _compute_signature(tensor, array_ops.size, cast_to_f32=False)
# Cast to float32, so that it can be placed into same cache with other
# signatures.
return math_ops.cast(tsize, dtypes.float32)
def _show_max(tensor, cast_to_f32=True):
# returns -inf for empty tensor
return _compute_signature(tensor, math_ops.reduce_max, cast_to_f32)
def _show_min(tensor, cast_to_f32=True):
# returns inf for empty tensor
return _compute_signature(tensor, math_ops.reduce_min, cast_to_f32)
def _show_norm(tensor, cast_to_f32=True):
# returns 0 for empty tensor
return _compute_signature(tensor, linalg_ops.norm, cast_to_f32)
def _show_mean_and_variance(tensor, cast_to_f32=True):
"""Returns the mean and variance of the given tensor."""
if cast_to_f32:
tensor = math_ops.cast(tensor, dtypes.float32)
# returns nan for empty tensor
mean, var = nn_impl.moments(array_ops.reshape(tensor, [-1]), axes=[0])
# The shape has to be 1. Set it if it does not have the information.
if not mean.get_shape().is_fully_defined():
mean = array_ops.reshape(mean, [])
if not var.get_shape().is_fully_defined():
var = array_ops.reshape(var, [])
return mean, var
def _show_max_abs(tensor):
tensor = math_ops.cast(tensor, dtypes.float32)
output_tensor = math_ops.reduce_max(math_ops.abs(tensor))
zero = constant_op.constant(0, dtypes.float32)
output_tensor = gen_math_ops.maximum(zero, output_tensor)
# The shape has to be 1. Set it if it does not have the information.
output_tensor = array_ops.reshape(output_tensor, [1])
return output_tensor
def _detect_inf_nan_producer(tensor):
"""Checks if the tensor is the first NaN/Inf tensor in the computation path."""
if tensor.op.inputs:
inp_check = [
_detect_nan_inf(inp_tensor) for inp_tensor in tensor.op.inputs
]
is_any_input_inf_nan = math_ops.add_n(inp_check)
else:
is_any_input_inf_nan = constant_op.constant(0, dtypes.bool)
is_current_tensor_inf_nan = _detect_nan_inf(tensor)
# An op is NaN/INF producer only when all inputs are nan/inf free (
# is_any_input_inf_nan = 0), and its output has nan/inf (
# is_current_tensor_inf_nan=1). Below will be 1 if op nan/inf is producer.
is_nan_producer = is_current_tensor_inf_nan - is_any_input_inf_nan
is_nan_producer = math_ops.reduce_any(is_nan_producer > 0)
return is_nan_producer
if (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_FULL_IF_NAN):
return {self._parameters.trace_mode: _detect_inf_nan_producer(tensor)}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NAN_INF:
return {self._parameters.trace_mode: _detect_nan_inf(tensor)}
if (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_PART_TENSOR):
return {self._parameters.trace_mode: tensor}
if (self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)):
return {self._parameters.trace_mode: tensor}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NORM:
return {self._parameters.trace_mode: array_ops.reshape(
_show_norm(tensor), [1])}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_MAX_ABS:
return {self._parameters.trace_mode: _show_max_abs(tensor)}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
tensor = math_ops.cast(tensor, dtypes.float32)
result_dict = {}
# Call mean and variance computation here to avoid adding the same nodes
# twice.
if (_TT_SUMMARY_MEAN in self._signature_types() or
_TT_SUMMARY_VAR in self._signature_types()):
mean, variance = _show_mean_and_variance(tensor, cast_to_f32=False)
for signature_name, _ in sorted(self._signature_types().items(),
key=lambda x: x[1]):
if signature_name == _TT_SUMMARY_NORM:
signature_result_tensor = _show_norm(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_MAX:
signature_result_tensor = _show_max(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_MIN:
signature_result_tensor = _show_min(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_SIZE:
signature_result_tensor = _show_size(tensor)
elif signature_name == _TT_SUMMARY_MEAN:
signature_result_tensor = mean
elif signature_name == _TT_SUMMARY_VAR:
signature_result_tensor = variance
else:
raise ValueError('Unknown signature type :%s.' % signature_name)
result_dict[signature_name] = signature_result_tensor
return result_dict
raise RuntimeError(
'Tensor trace fun for %s is not yet implemented'
% self._parameters.trace_mode)
def _make_tensor_trace_fun(self, tensor_name, tensor_trace_order):
"""Makes the tensor tracing function called by outside compilation.
Args:
tensor_name: name of the tensor being traced.
tensor_trace_order: TensorTraceOrder object holding tensorname to id map.
Returns:
A function to be passed as the first argument to outside compilation.
Raises:
RuntimeError: If the trace mode is invalid.
"""
def _print_tensor(tensor_name, num_elements, tensor, output_tensor):
"""Prints a tensor value to a file.
Args:
tensor_name: name of the tensor being traced.
num_elements: number of elements to print (-1 means print all).
tensor: the tensor needs to be returned.
output_tensor: the tensor needs to be printed.
Returns:
The same tensor passed via the "tensor" argument.
Raises:
ValueError: If tensor_name is not already in
self._tensorname_idx_map.
"""
if self._parameters.is_brief_mode():
if tensor_name not in tensor_trace_order.tensorname_idx_map:
raise ValueError(
'Tensor name %s is not in the tensorname_idx_map'%tensor_name)
msg = '%d'%self._tensorname_idx_map[tensor_name]
else:
msg = '"%s"'%tensor_name
if self._parameters.trace_dir:
output_path = os.path.join(self._parameters.trace_dir, _TRACE_FILE_NAME)
output_stream = _OUTPUT_STREAM_ESCAPE + output_path
else:
output_stream = sys.stderr
return logging_ops.print_v2(msg, array_ops.shape(output_tensor),
'@', self._replica_id,
'\n', output_tensor, '\n',
summarize=num_elements,
output_stream=output_stream)
def _show_part_tensor(tensor):
"""Trace function for printing part of the tensor."""
return _print_tensor(tensor_name, _TRACE_MODE_PART_TENSOR_SIZE,
tensor, tensor)
def _show_full_tensor(tensor):
"""Trace function for printing the entire tensor."""
return _print_tensor(tensor_name, -1, tensor, tensor)
def _show_full_tensors(tensor):
"""Prints the full tensor values for the tensors that are _trace_stack_size hops away from a given tensor."""
def _get_distance_k_tensors(k_before=0):
"""Returns the tensors that are at most k_before hops away from the tensor."""
if k_before < 0:
return []
visited_tensors = {tensor: 0}
visitor_queue = [tensor]
head = 0
while head < len(visitor_queue):
current_tensor = visitor_queue[head]
head += 1
distance = visited_tensors[current_tensor]
if distance == k_before:
break
for input_tensor in current_tensor.op.inputs:
if input_tensor in visited_tensors:
continue
visitor_queue.append(input_tensor)
visited_tensors[input_tensor] = distance + 1
return visitor_queue
tensors_to_print = _get_distance_k_tensors(
self._parameters.trace_stack_size)
print_ops = [_print_tensor(t.name, -1, t, t) for t in tensors_to_print]
with ops.control_dependencies(print_ops):
return constant_op.constant(True)
if (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_FULL_IF_NAN):
return _show_full_tensors
if (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_PART_TENSOR):
return _show_part_tensor
# The input tensor has a shape of "[1]" for TRACE_MODE_NAN_INF,
# TRACE_MODE_NORM, and TRACE_MODE_MAX_ABS, as related computations are
# performed within TPUs and only their results are transferred to CPU.
# Simply, print the full tensor for these trace modes.
if self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_NAN_INF,
tensor_tracer_flags.TRACE_MODE_NORM,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR,
tensor_tracer_flags.TRACE_MODE_MAX_ABS,
tensor_tracer_flags.TRACE_MODE_SUMMARY
):
return _show_full_tensor
raise RuntimeError('Tensor trace fun for %s is not yet implemented'
%self._parameters.trace_mode)
def _skip_op(self, op_id, op, ops_in_exec_path, report_handler):
"""Returns True if we should not trace Op.
Args:
op_id: Topological index of the op.
op: tf.Operation
ops_in_exec_path: Set of operations that are in the execution path.
report_handler: An instance of tensor_tracer_report.TTReportHandle.
Returns:
True if the op should not be traced, false otherwise.
"""
if TensorTracer.while_loop_op(op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_WHILELOOP_OP))
return True
if TensorTracer.unsafe_op(op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_UNSAFE_OP))
return True
if TensorTracer.device_mismatch(self._tt_config.device_type, op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_DEVICE_MISMATCH))
return True
if op not in ops_in_exec_path:
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_NOT_EXECUTED))
return True
if self._is_user_included_op(op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_USER_INCLUDED))
return False
if not self._inside_op_range(op_id):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_OUTSIDE_OP_RANGE))
return True
if not self._is_interesting_op(op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_LESS_INTERESTING_OP))
return True
if self._is_user_excluded_op(op):
report_handler.instrument_op(
op, TensorTracer.reason(op_id, _REASON_USER_EXCLUDED))
return True
return False
def _skip_tensor(self, op_id, out_tensor, report_handler):
"""Returns True if we should not trace out_tensor.
Args:
op_id: Topological index of the op producing tensor.
out_tensor: tf.Tensor
report_handler: An instance of tensor_tracer_report.TTReportHandle.
Returns:
True if the tensor should not be traced, false otherwise.
"""
# Skips a tensor if the tensor has a non-numeric type.
# Note: we cannot use check_ops.is_numeric_tensor(out_tensor)
# because it also excludes tensors with dtypes, bool, and
# float32_ref, which we actually want to trace.
non_numeric_tensor_types = set([dtypes.variant, dtypes.resource,
dtypes.string])
if out_tensor.dtype in non_numeric_tensor_types:
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_NON_NUMERIC_TENSOR))
return True
# Skip a tensor if it feeds a special while loop op.
if [consumer for consumer in out_tensor.consumers() if
TensorTracer.while_loop_op(consumer)]:
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_FEEDS_WHILELOOP_OP))
return True
if self._is_user_included_op(out_tensor.op):
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_USER_INCLUDED))
return False
if self._is_user_excluded_op(out_tensor.op):
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_USER_EXCLUDED))
return True
if not out_tensor.get_shape().is_fully_defined():
# If trace mode is nan-inf, norm or max, then the tensor will be reduced
# to a scalar before the outside compilation call.
if self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_NAN_INF,
tensor_tracer_flags.TRACE_MODE_NORM,
tensor_tracer_flags.TRACE_MODE_MAX_ABS,
tensor_tracer_flags.TRACE_MODE_SUMMARY
):
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_TENSOR_GET_TRACED))
return False
else:
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_DYNAMIC_SHAPE))
return True
rank = len(out_tensor.shape)
if rank < 1:
# scalar
if self._parameters.trace_scalar_ops:
if TensorTracer.unsafe_scalar_trace(out_tensor.op):
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_UNSAFE_SCALAR))
return True
else:
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_SCALAR_GET_TRACED))
return False
else:
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_SKIP_SCALAR))
return True
else:
# tensor
report_handler.instrument_tensor(
out_tensor, TensorTracer.reason(op_id, _REASON_TENSOR_GET_TRACED))
return False
def _filter_execution_path_operations(self, operations, fetches):
"""Returns the set of ops in the execution path to compute given fetches."""
# If no fetch provided, then return all operations.
if fetches is None:
return set(operations)
# Convert to list, if a single element is provided.
if not isinstance(fetches, (list, tuple)):
fetches = [fetches]
# If a tensor is given as fetch, convert it to op.
op_fetches = []
for fetch in fetches:
if isinstance(fetch, ops.Operation):
op_fetches.append(fetch)
elif isinstance(fetch, ops.Tensor):
op_fetches.append(fetch.op)
else:
raise RuntimeError('Given fetch:%s is neither a tensor nor an op.'
%fetch)
execution_path_operations = set(op_fetches)
traverse_stack = list(op_fetches)
while True:
if not traverse_stack:
break
head_op = traverse_stack.pop()
input_ops = [tensor_input.op for tensor_input in head_op.inputs]
input_ops.extend(head_op.control_inputs)
for input_op in input_ops:
if input_op not in execution_path_operations:
# Filter out loop condition operations, tracing them causes a cycle.
# Trace only the loop-body.
if TensorTracer.loop_cond_op(input_op):
continue
execution_path_operations.add(input_op)
traverse_stack.append(input_op)
return execution_path_operations
def _determine_and_instrument_traced_tensors(self, graph_order,
ops_in_exec_path,
tensor_trace_points,
report_handler):
"""Determines the tensors to trace and instruments the trace details.
Args:
graph_order: graph_order tuple containing graph (tf.graph), operations
(list of operations), op_to_idx (op id mapping), (tensors) list of
tensors, tensor_to_idx (tensor id mapping), contains_cycle (whether
there is a cycle in the graph), topological_order_or_cycle (list of ops
in topological order or list of ops creating a cycle).
ops_in_exec_path: Set of ops in the execution path.
tensor_trace_points: Collection of programatic tensor trace points.
report_handler: An instance of tensor_tracer_report.TTReportHandle.
Returns:
List of tensors to be traced.
"""
traced_tensors = []
checkpoint_operations = set([tensor.op
for (tensor, _) in tensor_trace_points])
for op_id, op in enumerate(graph_order.operations):
if checkpoint_operations and op not in checkpoint_operations:
continue
if self._skip_op(op_id, op, ops_in_exec_path, report_handler):
continue
for i in range(len(op.outputs)):
out_tensor = op.outputs[i]
if not self._skip_tensor(op_id, out_tensor, report_handler):
traced_tensors.append(out_tensor)
return traced_tensors
def _check_trace_files(self):
"""Checks if any requirements for trace files are satisfied."""
if not self._parameters.trace_dir:
# traces will be written to stderr. No need to check trace files.
return
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
# Output files are handled by tf.summary operations, no need to precreate
# them.
return
if _trace_files_need_precreated(self._parameters.trace_dir):
for replica_id in range(0, self._tt_config.num_replicas):
trace_file_path = os.path.join(
self._parameters.trace_dir,
_COMPACT_TRACE_FILE_PREFIX) + '%d'%replica_id
if not gfile.Exists(trace_file_path):
raise RuntimeError(
'%s must be pre-created with the '
'appropriate properties.'%trace_file_path)
else:
if not gfile.Exists(self._parameters.trace_dir):
gfile.MkDir(self._parameters.trace_dir)
if not gfile.Exists(self._parameters.trace_dir):
raise RuntimeError('Failed to create %s'%self._parameters.trace_dir)
def _determine_trace_and_create_report(self, graph, ops_in_exec_path):
"""Work needs to be done prior to TPU or CPU tracing.
Args:
graph: tf.graph
ops_in_exec_path: Set of operations in the execution path.
Returns:
An instance of tensor_tracer_report.TensorTraceOrder, containing list of
tensors to be traced with their topological order information.
"""
self._check_trace_files()
graph_order = tensor_tracer_report.sort_tensors_and_ops(graph)
tensor_trace_points = graph.get_collection(_TENSOR_TRACER_COLLECTION)
report_handler = tensor_tracer_report.TTReportHandle()
traced_tensors = self._determine_and_instrument_traced_tensors(
graph_order, ops_in_exec_path, tensor_trace_points, report_handler)
tensor_trace_order = tensor_tracer_report.TensorTraceOrder(graph_order,
traced_tensors)
num_signatures = self._num_signature_dimensions()
if num_signatures:
self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG,
graph,
[len(traced_tensors),
num_signatures])
if self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_SUMMARY,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY):
report_proto = report_handler.create_report_proto(self._tt_config,
self._parameters,
tensor_trace_order,
tensor_trace_points,
self._signature_types())
report_handler.write_report_proto(report_proto, self._parameters)
else:
report_handler.create_report(self._tt_config, self._parameters,
tensor_trace_order, tensor_trace_points)
return tensor_trace_order
def _create_host_call(self):
return self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_SUMMARY,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)
def _generate_flush_cache_op(self, num_replicas, on_tpu):
"""Generates an Op that will flush the cache to file.
Args:
num_replicas: total number of replicas.
on_tpu: if the graph is executed on TPU.
Returns:
The Op to flush the cache to file.
"""
def _flush_fun(cache, replica_id):
"""Flushes the cache to a file corresponding to replica_id."""
def _f(file_index):
"""Generates a func that flushes the cache to a file."""
def _print_cache():
"""Flushes the cache to a file."""
replica_str = ('%d' % file_index)
if self._parameters.trace_dir:
output_path = (os.path.join(self._parameters.trace_dir,
_COMPACT_TRACE_FILE_PREFIX)
+ replica_str)
output_stream = _OUTPUT_STREAM_ESCAPE + output_path
else:
output_stream = sys.stderr
new_step_line = _REPLICA_ID_TAG + replica_str
print_ops = []
for i in range(self._num_signature_dimensions()):
print_ops.append(logging_ops.print_v2(
new_step_line, '\n',
cache[:, i], '\n',
summarize=-1,
output_stream=output_stream))
with ops.control_dependencies(print_ops):
return constant_op.constant(0).op
return _print_cache
def _eq(file_index):
return math_ops.equal(replica_id, file_index)
flush_op_cases = {}
for i in range(num_replicas):
flush_op_cases[_eq(i)] = _f(i)
# Each replica needs to determine where to write their output.
# To do this, we check if replica_id is 0, then 1, ..., and then
# num_replicas - 1 statically; and return the corresponding static file
# name. We cannot simply set the file name in python, as replica_id is
# only known during tf runtime, and we cannot create dynamic filenames.
return control_flow_ops.case(flush_op_cases, exclusive=True)
cache = self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG)
if on_tpu:
flush_op = tpu.outside_compilation(_flush_fun,
cache.value(), self._replica_id)
else:
flush_op = _flush_fun(cache.value(), self._replica_id)
with ops.control_dependencies([flush_op]):
reset_value = constant_op.constant(_COMPACT_TRACE_ENTRY_INIT_VALUE,
dtype=cache.dtype,
shape=cache.shape)
assign_op = state_ops.assign(cache, reset_value).op
with ops.control_dependencies([assign_op]):
return constant_op.constant(0).op
def _flush_tensor_values_cache(self, tensor_fetches, op_fetches, on_tpu):
"""Flushes the intermediate tensor values in the graph to the cache.
Args:
tensor_fetches: list of tensor results returned by the model_fn.
op_fetches: list of ops that are returned by the model_fn, e.g., train_op.
on_tpu: if the graph is executed on TPU.
Returns:
An identical copy of tensor_fetches.
"""
# Add a dependency to op and tensor fetches to make sure that all tracing
# ops are executed before flushing trace results.
with ops.control_dependencies(op_fetches +
[tensor.op for tensor in tensor_fetches]):
flush_cache_op = self._generate_flush_cache_op(
self._tt_config.num_replicas, on_tpu)
return control_flow_ops.tuple(tensor_fetches,
control_inputs=[flush_cache_op])
def _process_tensor_fetches(self, tensor_fetches):
"""Check that tensor_fetches is not empty and have valid tensors."""
# If none or empty list.
if tensor_fetches is None:
raise RuntimeError('tensor_fetches provided to tensor_tracer cannot be '
'None.')
if not isinstance(tensor_fetches, (list, tuple)):
tensor_fetches = [tensor_fetches]
elif not tensor_fetches:
raise RuntimeError('tensor_fetches provided to tensor_tracer cannot be '
'empty list.')
fetches = []
for fetch in tensor_fetches:
if isinstance(fetch, ops.Tensor):
fetches.append(fetch)
else:
raise RuntimeError('Given tensor_fetch:%s is not a tensor.' % fetch)
return fetches
def _process_op_fetches(self, op_fetches):
"""Check that op_fetches have valid ops."""
if op_fetches is None:
return []
if not isinstance(op_fetches, (list, tuple)):
op_fetches = [op_fetches]
fetches = []
for fetch in op_fetches:
if isinstance(fetch, ops.Operation):
fetches.append(fetch)
elif isinstance(fetch, ops.Tensor):
fetches.append(fetch.op)
else:
logging.warning('Ignoring the given op_fetch:%s, which is not an op.' %
fetch)
return fetches
def _convert_fetches_to_input_format(self, input_fetches, current_fetches):
"""Changes current_fetches' format, so that it matches input_fetches."""
if isinstance(input_fetches, ops.Tensor):
if len(current_fetches) != 1:
raise RuntimeError('Tensor tracer input/output fetches do not match.')
return current_fetches[0]
else:
if len(current_fetches) != len(current_fetches):
raise RuntimeError('Tensor tracer input/output fetches do not match.')
elif isinstance(input_fetches, tuple):
return tuple(current_fetches)
else:
return current_fetches
def _get_op_control_flow_context(self, op):
"""Returns the control flow of the given op.
Args:
op: tf.Operation for which the control flow context is requested.
Returns:
op_control_flow_context: which the is control flow context of the given
op. If the operation type is LoopExit, returns the outer control flow
context.
"""
# pylint: disable=protected-access
op_control_flow_context = op._control_flow_context
# pylint: enable=protected-access
if control_flow_util.IsLoopExit(op):
op_control_flow_context = op_control_flow_context.outer_context
return op_control_flow_context
def _prepare_host_call_fn(self, processed_t_fetches, op_fetches):
"""Creates a host call function that will write the cache as tb summary.
Args:
processed_t_fetches: List of tensor provided to session.run.
op_fetches: List of operations provided to session.run.
Raises:
ValueError if trace_dir is not set.
"""
if self._parameters.trace_dir is None:
raise ValueError('Provide a trace_dir for tensor tracer in summary mode. '
'--trace_dir=/model/dir')
def _write_cache(step, **kwargs):
"""Writes the given caches as tensor summary.
Args:
step: Step tensor with dimension [num_cores].
**kwargs: The dictionary of tensors that needs to be written as
summaries. Key and value pairs within kwargs correspond to the tag
name, and tensor content that will be written using summary.write.
The trace_modes that use this function are:
- summary: In summary mode, kwargs includes a single (tag, content)
pair which are, _TT_SUMMARY_TAG and a tf.float32 signature_cache
variable. The dimension of the signature_cache is:
num_cores x num_traced_tensors x num_signatures.
- full_tensor_summary: kwargs will include all traced tensors. Tag
and content correspond to the name of the tensor, and its actual
content.
Returns:
A tf.Operation that needs to be executed for the host call dependencies.
"""
# TODO(deveci): Parametrize max_queue, so that flushing op can be called
# less frequently.
# Setting max_queue to 100 appears to be safe even when the number of
# iterations are much lower, as the destructor of the writer will flushes
# it.
summary_write_ops = []
with summary.create_file_writer_v2(
self._parameters.trace_dir,
filename_suffix=_TT_EVENT_FILE_SUFFIX,
max_queue=_TT_SUMMARY_MAX_QUEUE).as_default():
summary_metadata = summary_pb2.SummaryMetadata(
plugin_data=summary_pb2.SummaryMetadata.PluginData(
plugin_name=_TT_TENSORBOARD_PLUGIN_NAME))
for key, value in kwargs.items():
summary_write_ops.append(summary.write(
_TT_SUMMARY_TAG + '/' + key, value, metadata=summary_metadata,
step=step[0]))
return control_flow_ops.group(summary_write_ops)
step = array_ops.reshape(training_util.get_or_create_global_step(), [1])
self._host_call_fn = {}
host_call_deps = op_fetches + [tensor.op for tensor in processed_t_fetches]
caches_to_write = {}
with ops.control_dependencies(host_call_deps):
all_caches = self._get_all_cache_variables()
for cache_name, cache_variable in all_caches.items():
# Increase the cache rank by 1, so that when host call concatenates
# tensors from different replicas, we can identify them with [core_id].
new_cache_shape = [1]
new_cache_shape.extend(cache_variable.shape.as_list())
cache = array_ops.reshape(cache_variable.value(), new_cache_shape)
caches_to_write[cache_name] = cache
# Add step to parameter dictionary.
caches_to_write['step'] = step
# Other options without adding step to parameter dictionary are
# * host_call_fn = (_write_cache(step, caches_to_write)) : fails as it
# considers caches_to_write as a single parameter, rather than a keyword
# parameters.
# * host_call_fn = (_write_cache(step, **caches_to_write)) : fails with
# a syntax error.
self._host_call_fn[_TT_HOSTCALL_KEY] = (_write_cache, caches_to_write)
def host_call_deps_and_fn(self):
return self._host_call_fn
def _trace_execution(self, graph,
tensor_fetches,
op_fetches=None,
on_tpu=True):
"""Commong tracing function for both CPU and TPUs.
The caller function should set device_type, num_replicas,
num_replicas_per_host, num_hosts and replica_id before calling
_trace_execution.
Args:
graph: the graph of Ops executed on the TPU.
tensor_fetches: a (list,tuple,or a single object) of tensor fetches
returned by model_fn given to session.run. Function must be provided
with as least one tensor to fetch.
op_fetches: A list of op fetches returned by model_fn given to
session.run. op_fetches and tensor_fetches are used to determine the
nodes that will be executed. Can be None.
on_tpu: True if executing on TPU.
Returns:
tensor_fetches: an exact copy of tensor_fetches that has additional
dependencies.
Raises:
RuntimeError: If tensor_fetches is None or empty.
"""
def _cast_unsupported_dtypes(tensor):
"""Casts tensor to a supported type."""
if tensor.dtype.__eq__(dtypes.int64):
# outside-compilation doesn't support int64 input yet.
return math_ops.cast(tensor, dtypes.int32)
if tensor.dtype.__eq__(dtypes.bfloat16) or tensor.dtype.__eq__(
dtypes.float16):
# Since host can't handle bf16, convert tensor to f32.
return math_ops.cast(tensor, dtypes.float32)
return tensor
trace_mode = self._parameters.trace_mode
device_type = self._tt_config.device_type
analytics.track_usage('tensor_tracer', [trace_mode, device_type])
TensorTracer.check_device_type(device_type)
TensorTracer.check_trace_mode(device_type, trace_mode)
# Check in_tensor_fetches, and op_fetches and convert them to lists.
processed_t_fetches = self._process_tensor_fetches(tensor_fetches)
op_fetches = self._process_op_fetches(op_fetches)
all_fetches = op_fetches + [tensor.op for tensor in processed_t_fetches]
# Filter out the operations that won't be executed.
# if fetches=None, then ops_in_exec_path = set(operations)
exec_op_set = self._filter_execution_path_operations(graph.get_operations(),
all_fetches)
# Write report file, and determine the traced tensors.
tensor_trace_order = self._determine_trace_and_create_report(
graph, exec_op_set)
tensor_fetch_set = set(processed_t_fetches)
tracing_ops = []
# pylint: disable=protected-access
current_control_flow_context = graph._get_control_flow_context()
# pylint: enable=protected-access
sorted_exec_op_list = list(exec_op_set)
sorted_exec_op_list.sort(key=lambda op: op.name)
# Trace ops only if they are in the execution path.
for op in sorted_exec_op_list:
for i in range(len(op.outputs)):
out_tensor = op.outputs[i]
tensor_name = out_tensor.name
if tensor_name not in tensor_trace_order.tensorname_to_cache_idx:
continue
# Create the list of consumers before calling _preprocess_traced_tensor.
# Otherwise, adding control input below, will introduce a cycle in the
# graph.
consumers = out_tensor.consumers()
# Not all consumers may be in the exec path. Filter out the consumers
# to keep the graph simpler.
consumers = [cop for cop in consumers if cop in exec_op_set]
# If there is no consumer of the tensor, there is no need to trace it;
# unless the tensor itself is one of the fetches.
is_a_fetched_tensor = out_tensor in tensor_fetch_set
if (not consumers) and (not is_a_fetched_tensor):
continue
op_control_flow_context = self._get_op_control_flow_context(op)
# pylint: disable=protected-access
graph._set_control_flow_context(op_control_flow_context)
# pylint: enable=protected-access
processed_tensors = self._preprocess_traced_tensor(out_tensor)
if on_tpu:
for signature in processed_tensors.keys():
processed_tensors[signature] = _cast_unsupported_dtypes(
processed_tensors[signature])
if self._use_tensor_values_cache():
# Use a small cache to store the characteristics of the tensor.
cache_idx = tensor_trace_order.tensorname_to_cache_idx[tensor_name]
trace_op = self._save_tensor_value_to_cache_op(cache_idx,
processed_tensors)
elif self._use_tensor_buffer():
if len(processed_tensors) != 1:
raise RuntimeError('Multiple stats are only allowed in compact '
'mode.')
processed_out_tensor = processed_tensors.values()[0]
# Store the whole tensor in a buffer.
trace_op = self._snapshot_tensor(processed_out_tensor)
else:
def tpu_wrap_trace_fn(tensor, out_tensor_name):
"""Wraps the trace_fn with outside compilation if on TPUs."""
tensor_trace_fn = self._make_tensor_trace_fun(out_tensor_name,
tensor_trace_order)
if on_tpu:
return tpu.outside_compilation(tensor_trace_fn, tensor)
else:
return tensor_trace_fn(tensor)
def conditional_trace_fn(predicate_tensor, out_tensor, trace_fn,
out_tensor_name):
"""Creates a cond op that traces the out_tensor if predicate is satisfied."""
return control_flow_ops.cond(
predicate_tensor, lambda: trace_fn(out_tensor, out_tensor_name),
lambda: constant_op.constant(False)).op
if len(processed_tensors) != 1:
raise RuntimeError('Multiple stats are only allowed in compact '
'mode.')
# Collecting multiple statistics are only supported in the summary
# mode that uses compact format(self._use_tensor_values_cache = true).
# Non-compact mode currently allows single stat per tensor.
processed_out_tensor = six.next(six.itervalues(processed_tensors))
if self._parameters.is_conditional_trace:
trace_op = conditional_trace_fn(processed_out_tensor, out_tensor,
tpu_wrap_trace_fn, tensor_name)
elif self._parameters.included_cores:
should_print = constant_op.constant(False)
for core in self._parameters.included_cores:
should_print = gen_math_ops.logical_or(
should_print, gen_math_ops.equal(self._replica_id, core))
trace_op = conditional_trace_fn(should_print, processed_out_tensor,
tpu_wrap_trace_fn, tensor_name)
else:
trace_op = tpu_wrap_trace_fn(processed_out_tensor, tensor_name)
if is_a_fetched_tensor:
tracing_ops.append(trace_op)
continue
# Add it to all consumers, as some consumers may not be executed if they
# are in a control flow.
for consumer_op in consumers:
# pylint: disable=protected-access
consumer_op._add_control_input(trace_op)
# pylint: enable=protected-access
# pylint: disable=protected-access
graph._set_control_flow_context(current_control_flow_context)
# pylint: enable=protected-access
if tracing_ops:
# If we are tracing a fetched tensor, their dependency is stored in
# tracing_ops.
processed_t_fetches = control_flow_ops.tuple(processed_t_fetches,
control_inputs=tracing_ops)
if self._use_tensor_values_cache() or self._use_tensor_buffer():
if self._create_host_call() and on_tpu:
self._prepare_host_call_fn(processed_t_fetches, op_fetches)
else:
processed_t_fetches = self._flush_tensor_values_cache(
processed_t_fetches, op_fetches, on_tpu=on_tpu)
# processed_t_fetches is a list at this point. Convert it to the same
# format as given in tensor_fetches.
return self._convert_fetches_to_input_format(tensor_fetches,
processed_t_fetches)
def trace_tpu(self, graph,
tensor_fetches,
op_fetches=None,
num_replicas=None,
num_replicas_per_host=None,
num_hosts=None):
"""Traces the tensors generated by TPU Ops in a TF graph.
Args:
graph: the graph of Ops executed on the TPU.
tensor_fetches: a (list,tuple,or a single object) of tensor fetches
returned by model_fn given to session.run. Function must be provided
with as least one tensor to fetch.
op_fetches: A list of op fetches returned by model_fn given to
session.run. op_fetches and tensor_fetches are used to determine the
nodes that will be executed. Can be None.
num_replicas: number of replicas used on the TPU.
num_replicas_per_host: number of replicas per TPU host.
num_hosts: total number of TPU hosts.
Returns:
tensor_fetches: an exact copy of tensor_fetches that has additional
dependencies.
Raises:
RuntimeError: If num_replicas_per_host > 8.
RuntimeError: If tensor_fetches is None or empty.
"""
if graph in TensorTracer._traced_graphs:
logging.warning('Graph is already rewritten with tensor tracer, ignoring '
'multiple calls.')
return tensor_fetches
else:
TensorTracer._traced_graphs.add(graph)
self._tt_config.device_type = _DEVICE_TYPE_TPU
self._tt_config.num_replicas = num_replicas
self._tt_config.num_replicas_per_host = num_replicas_per_host
self._tt_config.num_hosts = num_hosts
if self._tt_config.num_replicas is not None:
if self._tt_config.num_replicas_per_host is None:
self._tt_config.num_replicas_per_host = 8
if self._tt_config.num_hosts is None:
self._tt_config.num_hosts = (
num_replicas // self._tt_config.num_replicas_per_host +
(num_replicas % self._tt_config.num_replicas_per_host > 0))
if self._parameters.graph_dump_path:
graph_io.write_graph(graph, self._parameters.graph_dump_path,
'graph_before_tt.pbtxt')
with graph.as_default():
self._add_replica_id_to_graph()
tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches,
on_tpu=True)
if self._parameters.graph_dump_path:
graph_io.write_graph(graph, self._parameters.graph_dump_path,
'graph_after_tt.pbtxt')
return tensor_fetches
def trace_cpu(self, graph, tensor_fetches, op_fetches=None):
"""Traces the tensors generated by CPU Ops in a TF graph.
Args:
graph: the graph of Ops executed on the CPU.
tensor_fetches: a (list,tuple,or a single object) of tensor fetches
returned by model_fn given to session.run. Function must be provided
with as least one tensor to fetch.
op_fetches: A list of op fetches returned by model_fn given to
session.run. op_fetches and tensor_fetches are used to determine the
nodes that will be executed. Can be None.
Returns:
tensor_fetches: an exact copy of tensor_fetches that has additional
dependencies.
Raises:
RuntimeError: If tensor_fetches is None or empty.
"""
if graph in TensorTracer._traced_graphs:
logging.warning('Graph is already rewritten with tensor tracer, ignoring '
'multiple calls.')
return tensor_fetches
else:
TensorTracer._traced_graphs.add(graph)
self._tt_config.device_type = _DEVICE_TYPE_CPU
self._tt_config.num_replicas = 1
self._tt_config.num_replicas_per_host = 1
self._tt_config.num_hosts = 1
self._replica_id = 0
if self._parameters.graph_dump_path:
graph_io.write_graph(graph, self._parameters.graph_dump_path,
'graph_before_tt.pbtxt')
with graph.as_default():
tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches,
on_tpu=False)
if self._parameters.graph_dump_path:
graph_io.write_graph(graph, self._parameters.graph_dump_path,
'graph_after_tt.pbtxt')
return tensor_fetches
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.