blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
916e8c7b89063ad6ce6aa8d92e0e6f6d877c3e5d
|
1b2f60bfbb38353c829a066b7a5d58b84122e460
|
/python/scale-generator/scale_generator.py
|
dd3627cef2e40277b3338afb90ca55f33b7eda14
|
[] |
no_license
|
krok64/exercism.io
|
9f03553a9efd1eb89f1844265fa2b06210b5803b
|
2c0439f533977a4d935c962e5b3e9a3c7111ac66
|
refs/heads/master
| 2021-01-20T02:20:30.048587
| 2017-08-24T16:34:02
| 2017-08-24T16:34:02
| 101,316,193
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,693
|
py
|
octave_sharp = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
octave_flat = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab']
class Scale(object):
def __init__(self, start, name, intervals=""):
if len(start) > 1:
self.start = start[0].upper() + start[1]
oct_type = start[1]
else:
self.start = start[0].upper()
oct_type = "?"
self.name = start.upper() + " " + name
self.intervals = intervals
self.pitches = []
if intervals == "":
#why? Why??? WHY??????
if self.start[0] == 'F':
octave = octave_flat
else:
octave = octave_sharp
idx = octave.index(self.start)
self.pitches = octave[idx:] + octave[:idx]
else:
if oct_type == "b":
octave = octave_flat
elif oct_type == "#":
octave = octave_sharp
else:
octave = octave_sharp
#why? Why??? WHY??????
if start == 'g' or start == 'd':
octave = octave_flat
idx = octave.index(self.start)
self.pitches.append(octave[idx])
for ch in self.intervals[:-1]:
if ch=='M':
idx_dx = 2
elif ch=='m':
idx_dx = 1
elif ch=='A':
idx_dx = 3
else:
raise ValueError
idx += idx_dx
if idx >= len(octave):
idx = idx - len(octave)
self.pitches.append(octave[idx])
|
[
"you@example.com"
] |
you@example.com
|
ed7dbfe8a4d867bb7f31bb99aa021aed9a7b1869
|
89594edf581b8512d262768fb4c3e0ad001996a9
|
/colibris/shortcuts.py
|
458659843d933d06ecd650c70b38b096a2de2902
|
[
"BSD-3-Clause"
] |
permissive
|
colibris-framework/colibris
|
b8524ac31a100c987dcbb5954b23f8c309370be3
|
9655016637888c480f49f92711caa6088013e442
|
refs/heads/master
| 2023-08-08T11:45:36.191451
| 2023-08-07T07:15:32
| 2023-08-07T07:15:32
| 193,250,040
| 7
| 2
|
BSD-3-Clause
| 2021-09-12T21:52:07
| 2019-06-22T15:35:53
|
Python
|
UTF-8
|
Python
| false
| false
| 1,001
|
py
|
from aiohttp.web import Response
from colibris import api
from colibris import template
def get_object_or_404(model, pk, select_related=None):
select_related = set(select_related or ())
try:
q = model.select(model, *select_related).where(model._meta.primary_key == pk)
for m in select_related:
q = q.join(m)
return q.get()
except model.DoesNotExist:
raise api.ModelNotFoundException(model)
def html_response(body=None, status=200, reason=None, headers=None, content_type='text/html'):
return Response(body=body, status=status, reason=reason,
headers=headers, content_type=content_type)
def html_response_template(template_name=None, status=200, reason=None, headers=None, content_type='text/html',
**context):
return html_response(body=template.render(template_name, **context),
status=status, reason=reason, headers=headers, content_type=content_type)
|
[
"ccrisan@gmail.com"
] |
ccrisan@gmail.com
|
fb125fa8acb5c1f5dfb931330794b6f3a4afe128
|
c8539e19bfc783c41f76ab23cdccdab919c341b4
|
/changes-for-FreeROI/froi/widgets/surfaceview.py
|
9d4c6a9d9e1ac9beee1354f6b56c78fa2d655a61
|
[] |
no_license
|
sunshineDrizzle/backups-for-forked-repo
|
2dbf4a0750aef9d9009f6b921198fecb35ead7c7
|
8f905a6f53b6189e91f7925ac950f1e94f478169
|
refs/heads/master
| 2020-07-26T20:34:51.247940
| 2016-11-24T03:46:28
| 2016-11-24T03:46:28
| 73,715,560
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,230
|
py
|
import os
import sys
import sip
from traits.api import HasTraits, Instance
from traitsui.api import View, Item
from tvtk.api import tvtk
from PyQt4.QtGui import *
from mayavi.core.ui.api import SceneEditor, MayaviScene, MlabSceneModel
from mayavi import mlab
import numpy as np
from treemodel import TreeModel
# Helpers
# ---------------------------------------------------------------------------------------------------------
def _toggle_toolbar(figure, show=None):
"""
Toggle toolbar display
Parameters
----------
figure: the mlab figure
show : bool | None
If None, the state is toggled. If True, the toolbar will
be shown, if False, hidden.
"""
if figure.scene is not None:
if hasattr(figure.scene, 'scene_editor'):
# Within TraitsUI
bar = figure.scene.scene_editor._tool_bar
else:
# Mayavi figure
bar = figure.scene._tool_bar
if show is None:
if hasattr(bar, 'isVisible'):
show = not bar.isVisble()
elif hasattr(bar, 'Shown'):
show = not bar.Shown()
if hasattr(bar, 'setVisible'):
bar.setVisible(show)
elif hasattr(bar, 'Show'):
bar.Show(show)
# show surface
# ---------------------------------------------------------------------------------------------------------
class Visualization(HasTraits):
scene = Instance(MlabSceneModel, ())
view = View(Item("scene", height=400, width=400,
editor=SceneEditor(scene_class=MayaviScene), show_label=False),
resizable=True)
class SurfaceView(QWidget):
def __init__(self, parent=None):
super(SurfaceView, self).__init__(parent)
# initialize GUI
self.setMinimumSize(800, 850)
self.setBackgroundRole(QPalette.Dark)
# get mayavi scene
# The edit_traits call will generate the widget to embed.
self.visualization = Visualization()
surface_view = self.visualization.edit_traits(parent=self, kind="subpanel").control
# self.ui.setParent(self)
# get rid of the toolbar
figure = mlab.gcf()
_toggle_toolbar(figure, False)
# Initialize some fields
self.surface_model = None
self.surf = None
self.coords = None
self.rgba_lut = None
self.gcf_flag = True
hlayout = QHBoxLayout()
hlayout.addWidget(surface_view)
self.setLayout(hlayout)
def _show_surface(self):
"""
render the overlays
"""
hemisphere_list = self.surface_model.get_data()
# clear the old surface
if self.surf is not None:
self.surf.remove()
# reset
first_hemi_flag = True
faces = None
nn = None
self.rgba_lut = None
vertex_number = 0
for hemisphere in hemisphere_list:
if hemisphere.is_visible():
# get geometry's information
geo = hemisphere.surf['white'] # 'white' should be replaced with var: surf_type
hemi_coords = geo.get_coords()
hemi_faces = geo.get_faces()
hemi_nn = geo.get_nn()
# get the rgba_lut
rgb_array = hemisphere.get_composite_rgb()
hemi_vertex_number = rgb_array.shape[0]
alpha_channel = np.ones((hemi_vertex_number, 1), dtype=np.uint8)*255
hemi_lut = np.c_[rgb_array, alpha_channel]
if first_hemi_flag:
first_hemi_flag = False
self.coords = hemi_coords
faces = hemi_faces
nn = hemi_nn
self.rgba_lut = hemi_lut
else:
self.coords = np.r_[self.coords, hemi_coords]
hemi_faces += vertex_number
faces = np.r_[faces, hemi_faces]
nn = np.r_[nn, hemi_nn]
self.rgba_lut = np.r_[self.rgba_lut, hemi_lut]
vertex_number += hemi_vertex_number
# generate the triangular mesh
scalars = np.array(range(vertex_number))
mesh = self.visualization.scene.mlab.pipeline.triangular_mesh_source(self.coords[:, 0],
self.coords[:, 1],
self.coords[:, 2],
faces,
scalars=scalars)
mesh.data.point_data.normals = nn
mesh.data.cell_data.normals = None
# generate the surface
self.surf = self.visualization.scene.mlab.pipeline.surface(mesh)
self.surf.module_manager.scalar_lut_manager.lut.table = self.rgba_lut
# add point picker observer
if self.gcf_flag:
self.gcf_flag = False
fig = mlab.gcf()
fig.on_mouse_pick(self._picker_callback_left)
fig.scene.picker.pointpicker.add_observer("EndPickEvent", self._picker_callback)
def _picker_callback(self, picker_obj, evt):
# test
print 'come in the picker callback'
picker_obj = tvtk.to_tvtk(picker_obj)
tmp_pos = picker_obj.picked_positions.to_array()
# test
print tmp_pos
if len(tmp_pos):
distance = np.sum(np.abs(self.coords - tmp_pos[0]), axis=1)
picked_id = np.argmin(distance)
tmp_lut = self.rgba_lut.copy()
self._toggle_color(tmp_lut[picked_id])
self.surf.module_manager.scalar_lut_manager.lut.table = tmp_lut
@staticmethod
def _toggle_color(color):
"""
make the color look differently
:param color: a alterable variable
rgb or rgba
:return:
"""
green_max = 255
red_max = 255
blue_max = 255
if green_max-color[1] >= green_max / 2.0:
color[:3] = np.array((0, 255, 0))
elif red_max - color[0] >= red_max / 2.0:
color[:3] = np.array((255, 0, 0))
elif blue_max-color[2] >= blue_max / 2.0:
color[:3] = np.array((0, 0, 255))
else:
color[:3] = np.array((0, 0, 255))
def _picker_callback_left(self, picker_obj):
pass
def _create_connections(self):
self.surface_model.repaint_surface.connect(self._show_surface)
# user-oriented methods
# -----------------------------------------------------------------
def set_model(self, surface_model):
if isinstance(surface_model, TreeModel):
self.surface_model = surface_model
self._create_connections()
else:
raise ValueError("The model must be the instance of the TreeModel!")
if __name__ == "__main__":
surface_view = SurfaceView()
surface_view.setWindowTitle("surface view")
surface_view.setWindowIcon(QIcon("/nfs/j3/userhome/chenxiayu/workingdir/icon/QAli.png"))
surface_view.show()
qApp.exec_()
sys.exit()
|
[
"954830460@qq.com"
] |
954830460@qq.com
|
8c326a9f5b917f0c00f6be14192f9f51fcdbbc62
|
142362be3c4f8b19bd118126baccab06d0514c5b
|
/apps/afisha/models.py
|
584eac76f905a53e8ae27099f259719cb122eca0
|
[] |
no_license
|
dkramorov/astwobytes
|
84afa4060ffed77d5fd1a6e8bf5c5c69b8115de6
|
55071537c5c84d0a27757f11ae42904745cc1c59
|
refs/heads/master
| 2023-08-27T07:10:51.883300
| 2023-08-02T16:52:17
| 2023-08-02T16:52:17
| 191,950,319
| 0
| 0
| null | 2022-11-22T09:15:42
| 2019-06-14T13:44:23
|
HTML
|
UTF-8
|
Python
| false
| false
| 4,622
|
py
|
# -*- coding: utf-8 -*-
import os
from django.db import models
from apps.main_functions.string_parser import translit
from apps.main_functions.models import Standard
class Rubrics(Standard):
"""Рубрикатор мест"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - Рубрикатор мест'
verbose_name_plural = 'Афиша - Рубрикатор мест'
class RGenres(Standard):
"""Рубрикатор жанров"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
altname = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
def find_genre_altname(self, z=0):
if self.name:
self.altname = translit(self.name)
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - Жанры'
verbose_name_plural = 'Афиша - Жанры'
class REvents(Standard):
"""События"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
duration = models.CharField(max_length=255, blank=True, null=True, verbose_name="Продолжительность", db_index=True)
label = models.CharField(max_length=255, blank=True, null=True, verbose_name="Ограничение по возрасту", db_index=True)
genre = models.CharField(max_length=255, blank=True, null=True, verbose_name="Жанр", db_index=True)
rgenre = models.ForeignKey(RGenres, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Рубрика")
country = models.CharField(max_length=255, blank=True, null=True, verbose_name="Страна производства")
trailer = models.TextField(blank=True, null=True, verbose_name="Трейлер")
description = models.TextField(blank=True, null=True, verbose_name="Описание")
producer = models.CharField(max_length=255, blank=True, null=True, verbose_name="Режиссер", db_index=True)
actors = models.TextField(blank=True, null=True, verbose_name="Актеры")
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - События'
verbose_name_plural = 'Афиша - События'
class Places(Standard):
"""Места (кинотеатры)"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
address_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
phone_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
worktime_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
site_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
email_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
description = models.TextField(blank=True, null=True)
#branch = models.ForeignKey(Branches, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Привязка к филиалу")
rubric = models.ForeignKey(Rubrics, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Привязка к рубрике")
class Meta:
verbose_name = 'Афиша - Места'
verbose_name_plural = 'Афиша - Места'
class RSeances(Standard):
"""В каких местах, когда происходит событие"""
place = models.ForeignKey(Places, blank=True, null=True, on_delete=models.SET_NULL,)
event = models.ForeignKey(REvents, blank=True, null=True, on_delete=models.SET_NULL,)
date = models.DateField(blank=True, null=True, db_index=True)
hours = models.IntegerField(blank=True, null=True, db_index=True)
minutes = models.IntegerField(blank=True, null=True, db_index=True)
class Meta:
verbose_name = 'Афиша - Сеансы'
verbose_name_plural = 'Афиша - Сеансы'
|
[
"zergo01@yandex.ru"
] |
zergo01@yandex.ru
|
fcbc1a2c3dce5ff711033e550d925ddd94dee24a
|
477630571cef77ad3bf5f9d06890bab39c3abad9
|
/backend/posts/urls.py
|
2721d73eb674691ea165d87bd3ad1e5cf3eb787d
|
[] |
no_license
|
lumenwrites/webacademy
|
52da663a36a2c403ac1ec97ba2687671f28a7c3f
|
4f8bdd4a15b781d7d0a1a7ae312914eaa0d1bd8d
|
refs/heads/master
| 2021-06-11T09:29:00.778011
| 2017-02-24T16:38:51
| 2017-02-24T16:38:51
| 82,233,069
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 736
|
py
|
from django.conf.urls import url
from .views import BrowseView, TagView
from .views import PostDetailView, post_create, post_edit, post_delete
from .views import upvote, unupvote
urlpatterns = [
# url(r'^post/(?P<slug>[^\.]+)/edit$', PostUpdateView.as_view()),
url(r'^post/(?P<slug>[^\.]+)/edit$', post_edit),
url(r'^post/(?P<slug>[^\.]+)/delete$', post_delete),
url(r'^post/(?P<slug>[^\.]+)/$', PostDetailView.as_view(), name='post-detail'),
url(r'^submit$', post_create),
url(r'^upvote/$', upvote),
url(r'^unupvote/$', unupvote),
url(r'^$', BrowseView.as_view()),
url(r'^tag/(?P<slug>[^\.]+)/$', TagView.as_view()),
url(r'^(?P<slug>[^\.]+)-tutorials/$', TagView.as_view()),
]
|
[
"raymestalez@gmail.com"
] |
raymestalez@gmail.com
|
9aff8fe42f3ef76ccebeceaaab4baa446f5804fe
|
463d2ec5da7c7908b27d06d26a51d9645b3d52f1
|
/DeepLearning/mnist.py
|
f98a72a28bb702e2345994bbf5084e1fdb3d3279
|
[] |
no_license
|
zhangdavids/workspace
|
7b899d7385d0921be78658c60ad18578c12ab10a
|
91f3c3e9b27018283132e3928ad2b84db5cc4b77
|
refs/heads/master
| 2021-07-11T13:21:32.445158
| 2018-11-02T01:04:06
| 2018-11-02T01:04:06
| 104,007,756
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 994
|
py
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("Download Done!")
x = tf.placeholder(tf.float32, [None, 784])
# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# init
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# train
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})
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
|
[
"1269969739@qq.com"
] |
1269969739@qq.com
|
c7f69a99827f9898d781abe688c7d8f36bfcbecd
|
b08870f8fe7b3cf1bbab3c52a7bacbb36ee1dcc6
|
/verp/verp_integrations/doctype/shopify_log/shopify_log.py
|
d7025f8e8f220fc107ce8a2e605e779ba5b39c99
|
[] |
no_license
|
vsadminpk18/verpfinalversion
|
7148a64fe6134e2a6371470aceb1b57cc4b5a559
|
93d164b370ad9ca0dd5cda0053082dc3abbd20da
|
refs/heads/master
| 2023-07-13T04:11:59.211046
| 2021-08-27T06:26:48
| 2021-08-27T06:26:48
| 400,410,611
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,244
|
py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe.model.document import Document
from verp.verp_integrations.utils import get_webhook_address
class ShopifyLog(Document):
pass
def make_shopify_log(status="Queued", exception=None, rollback=False):
# if name not provided by log calling method then fetch existing queued state log
make_new = False
if not frappe.flags.request_id:
make_new = True
if rollback:
frappe.db.rollback()
if make_new:
log = frappe.get_doc({"doctype":"Shopify Log"}).insert(ignore_permissions=True)
else:
log = log = frappe.get_doc("Shopify Log", frappe.flags.request_id)
log.message = get_message(exception)
log.traceback = frappe.get_traceback()
log.status = status
log.save(ignore_permissions=True)
frappe.db.commit()
def get_message(exception):
message = None
if hasattr(exception, 'message'):
message = exception.message
elif hasattr(exception, '__str__'):
message = exception.__str__()
else:
message = "Something went wrong while syncing"
return message
def dump_request_data(data, event="create/order"):
event_mapper = {
"orders/create": get_webhook_address(connector_name='shopify_connection', method="sync_sales_order", exclude_uri=True),
"orders/paid" : get_webhook_address(connector_name='shopify_connection', method="prepare_sales_invoice", exclude_uri=True),
"orders/fulfilled": get_webhook_address(connector_name='shopify_connection', method="prepare_delivery_note", exclude_uri=True)
}
log = frappe.get_doc({
"doctype": "Shopify Log",
"request_data": json.dumps(data, indent=1),
"method": event_mapper[event]
}).insert(ignore_permissions=True)
frappe.db.commit()
frappe.enqueue(method=event_mapper[event], queue='short', timeout=300, is_async=True,
**{"order": data, "request_id": log.name})
@frappe.whitelist()
def resync(method, name, request_data):
frappe.db.set_value("Shopify Log", name, "status", "Queued", update_modified=False)
frappe.enqueue(method=method, queue='short', timeout=300, is_async=True,
**{"order": json.loads(request_data), "request_id": name})
|
[
"admin@vespersolutions.tech"
] |
admin@vespersolutions.tech
|
27625b0ca9959a66b5419c730f9e3b38cbd8bdad
|
23392f060c85b5fee645d319f2fd5560653dfd5c
|
/01_jumptopy/chap05/Restaurant_v1.py
|
b8143f488dacff28b307454d80cb4ad6bba75307
|
[] |
no_license
|
heyhello89/openbigdata
|
65192f381de83e4d153c072ff09fa7574f003037
|
b35ff237c32013c3e5380eee782085a64edb9d80
|
refs/heads/master
| 2021-10-22T04:29:00.852546
| 2019-03-08T02:14:34
| 2019-03-08T02:14:34
| 125,938,319
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 613
|
py
|
class Restaurant:
def __init__(self, input_name):
self.restaurant_name = input_name.split()[0]
self.cuisine_type = input_name.split()[1]
def describe_restaurant(self):
print("저희 레스토랑 명칭은 %s이고 %s 전문점입니다."%(self.restaurant_name, self.cuisine_type))
def open_restaurant(self):
print("저희 %s 레스토랑 오픈했습니다. 어서오세요."%(self.restaurant_name))
pey=Restaurant(input_name = input("레스토랑 이름과 요리 종류를 선택하세요.(공백으로 구분): "))
pey.describe_restaurant()
pey.open_restaurant()
|
[
"heyhello89@hanmail.net"
] |
heyhello89@hanmail.net
|
9e94b93f9c625b41373b4d71fa584993116a74ed
|
ad1e55b9a67c798cf4b4ce41c76b26977f8b4e8d
|
/rockit/music/models.py
|
83ff6ae4fca6390c25d1ac6f1e39a2e711c26f0a
|
[
"BSD-3-Clause"
] |
permissive
|
kumar303/rockit
|
7a6ac84bb8c37e5f3b65d7dcecf9b9c549902cf5
|
fc347b5b143835ddd77fd0c1ea4e6f2007a21972
|
refs/heads/master
| 2021-01-10T19:51:30.638073
| 2020-07-26T19:00:37
| 2020-07-26T19:00:37
| 4,219,328
| 0
| 2
|
BSD-3-Clause
| 2020-07-26T19:00:38
| 2012-05-03T22:03:24
|
Python
|
UTF-8
|
Python
| false
| false
| 4,007
|
py
|
import hashlib
import os
from django.conf import settings
from django.db import models
from rockit.base.models import ModelBase
from rockit.base.util import filetype
from rockit.sync import s3
class VerifiedEmail(ModelBase):
email = models.CharField(max_length=255, db_index=True, unique=True)
upload_key = models.CharField(max_length=255, blank=True, null=True)
class Meta:
db_table = 'music_email'
class Track(ModelBase):
email = models.ForeignKey(VerifiedEmail)
session = models.ForeignKey('sync.SyncSession', null=True)
is_active = models.BooleanField(default=True, db_index=True)
temp_path = models.CharField(max_length=255, blank=True, null=True)
artist = models.CharField(max_length=255, db_index=True)
album = models.CharField(max_length=255, db_index=True)
track = models.CharField(max_length=255)
track_num = models.IntegerField(blank=True, null=True)
source_track_file = models.ForeignKey('music.TrackFile', null=True,
related_name='+')
large_art_url = models.CharField(max_length=255, blank=True, null=True)
medium_art_url = models.CharField(max_length=255, blank=True, null=True)
small_art_url = models.CharField(max_length=255, blank=True, null=True)
class Meta:
db_table = 'music_track'
def __unicode__(self):
return u'<%s %s:%s@%s>' % (self.__class__.__name__,
self.artist,
self.track,
self.pk)
def file(self, type):
qs = self.files.filter(type=type)
if qs.count():
return qs.get()
else:
return None
def to_json(self):
def _url(path):
return 'http://%s.s3.amazonaws.com/%s' % (
settings.S3_BUCKET,
path)
s3_urls = {}
for tf in self.files.all():
s3_urls[tf.type] = s3.get_authenticated_url(tf.s3_url)
return dict(id=self.pk,
artist=self.artist,
album=self.album,
track=self.track,
s3_urls=s3_urls,
large_art_url=self.large_art_url,
medium_art_url=self.medium_art_url,
small_art_url=self.small_art_url,
# deprecate this:
album_art_url=self.large_art_url)
def s3_url(self, type):
return '%s/%s.%s' % (self.email.pk, self.pk, type)
class TrackFile(ModelBase):
track = models.ForeignKey(Track, related_name='files')
is_active = models.BooleanField(default=True, db_index=True)
type = models.CharField(max_length=4, db_index=True)
byte_size = models.IntegerField()
sha1 = models.CharField(max_length=40, db_index=True)
s3_url = models.CharField(max_length=255)
session = models.ForeignKey('sync.SyncSession', null=True)
class Meta:
db_table = 'music_track_file'
@classmethod
def from_file(cls, track, filename, session_key, source=False):
"""Creates a track file from a filename.
if source is True it means that this file was the
original one uploaded for the track.
"""
hash = hashlib.sha1()
with open(filename, 'rb') as fp:
while 1:
chunk = fp.read(1024 * 100)
if not chunk:
break
hash.update(chunk)
sha1 = hash.hexdigest()
type = filetype(filename)
tf = cls.objects.create(track=track,
sha1=sha1,
s3_url=track.s3_url(type),
type=type,
session_id=session_key,
byte_size=os.path.getsize(filename))
if source:
Track.objects.filter(pk=track.pk).update(source_track_file=tf)
return tf
|
[
"kumar.mcmillan@gmail.com"
] |
kumar.mcmillan@gmail.com
|
af85c3d57f311d7ceaaf6234d16e697b691c7a68
|
5363e4eaa1af6fe4ba2e8c7f182c125d7b090efd
|
/Sunny/Python/Flask/app.py
|
28d23f9f5e3b921ad6f7bce7314db4dd40acd9e3
|
[] |
no_license
|
Sunnyryu/DaebakStudy
|
a87a24e651491a482b9c92b98e01eae3c3bfc6c9
|
32732f11dd99d3e10625b7695e431e535edeeab1
|
refs/heads/master
| 2022-07-11T21:50:55.018842
| 2020-07-20T07:11:13
| 2020-07-20T07:11:13
| 244,505,943
| 0
| 0
| null | 2022-06-22T02:31:06
| 2020-03-03T00:32:20
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,289
|
py
|
from flask import Flask, render_template, request, redirect, send_file
from scrapper import get_jobs
from exporter import save_to_file
app = Flask("SuperScrapper")
db = {}
@app.route("/")
def home():
return render_template("home.html")
@app.route("/report")
def report():
word = request.args.get("word")
if word:
word =word.lower()
existingJobs = db.get(word)
if existingJobs:
jobs = existingJobs
else:
jobs = get_jobs(word)
db[word] = jobs
else:
return redirect("/")
#print(jobs)
return render_template("report.html", searchingBy= word, resultsNumber=len(jobs), jobs=jobs)
@app.route("/export")
def export():
try:
word = request.args.get("word")
if not word:
raise Exception()
word = word.lower()
jobs = db.get(word)
if not jobs:
raise Exception()
save_to_file(jobs)
return send_file("jobs.csv",
mimetype='text/csv',
attachment_filename='이름을 설정하시오.csv',
as_attachment=True,
cache_timeout=0)
except:
return redirect("/")
app.run(host="0.0.0.0",port="2222")
|
[
"sunny_ryu@outlook.com"
] |
sunny_ryu@outlook.com
|
afa780e0f4321a1068d25a0a735061aefce29115
|
88cf3aa4eb13cda1790cd930ed2cb8c08964c955
|
/chainercv/utils/image/write_image.py
|
b5610c992a0e0703f3c0c5571fc051b16454d9a8
|
[
"MIT"
] |
permissive
|
mingxiaoh/chainercv
|
6ae854f445b7a14f55e41b51b5e4226224702b95
|
cfb7481907efe93e13c729ae2d9df4706d3975a6
|
refs/heads/master
| 2022-11-11T20:44:31.875419
| 2018-05-03T04:09:13
| 2018-05-03T04:33:15
| 131,939,645
| 1
| 2
|
MIT
| 2022-10-26T00:07:37
| 2018-05-03T03:58:59
|
Python
|
UTF-8
|
Python
| false
| false
| 517
|
py
|
import numpy as np
from PIL import Image
def write_image(img, path):
"""Save an image to a file.
This function saves an image to given file. The image is in CHW format and
the range of its value is :math:`[0, 255]`.
Args:
image (~numpy.ndarray): An image to be saved.
path (str): The path of an image file.
"""
if img.shape[0] == 1:
img = img[0]
else:
img = img.transpose((1, 2, 0))
img = Image.fromarray(img.astype(np.uint8))
img.save(path)
|
[
"yuyuniitani@gmail.com"
] |
yuyuniitani@gmail.com
|
bae1ee85529bad01328f91ec316207f6cf065957
|
f7110aaab742fc92179302c5874691078ed05158
|
/book_author_shell/book_author/views.py
|
33d21d80d85a99cfc6465ff8b778e23db2d583fc
|
[] |
no_license
|
Moha327/python_extra
|
0f9252a46a652ffe83d97cd0d6906a1835c2abbf
|
a3e1b31831578484c651d76bfd01173fe9d6eb10
|
refs/heads/master
| 2023-05-23T14:03:21.962212
| 2021-06-16T13:50:06
| 2021-06-16T13:50:06
| 377,511,352
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,341
|
py
|
from django.shortcuts import render,HttpResponse,redirect
from .models import *
# Create your views here.
def index(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all()
# 'books':models.allBook()
}
return render(request, 'index.html' , context)
def register(request):
if request.method=="POST":
Book.objects.create(title=request.POST['title'],desc=request.POST['description'])
return redirect('/')
def index2(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'book.html' , context)
def display(request,id1):
book = Book.objects.get(id =id1)
context={
"books":book,
"authors":Author.objects.all()
}
return render(request, 'book.html' , context)
def add(request,id1):
if request.method=="POST":
author=Author.objects.get(id=request.POST['selects'])
book=Book.objects.get(id=id1)
book.authors.add(author)
return redirect(f"/books/{id1}")
def index3(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'author.html' , context)
def add2(request,id1):
author = Author.objects.get(id =id1)
context={
"authors":author,
"book":Book.objects.all()
}
return render(request, 'author2.html' , context)
def register2(request):
if request.method=="POST":
Author.objects.create(first_name=request.POST['fname'],last_name=request.POST['lname'],notes=request.POST['notes'])
return redirect('/author')
def index4(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'author2.html' , context)
def add3(request,id1):
if request.method=="POST":
author=Author.objects.get(id=request.POST['select'])
book=Book.objects.get(id=id1)
author.clients.add(author)
return redirect(f"/author/{id1}")
# def addBook(request):
# if request.method == 'POST':
# title = req
# desc = req
# def showBook(request,id):
# context = {
# 'this_book':models.getBook(id)
# }
# return render(request,book.html)
|
[
"m7amad9595@outlook.com"
] |
m7amad9595@outlook.com
|
7ed1c30363e1f08e66f3739c047e711d18b9a751
|
0cd64f3f67c6a3b130a788906da84ffc3d15396a
|
/Library/lib/python3.9/site-packages/terminado/__init__.py
|
b719a2732b62668ad85459f6c3593ec181c85a6a
|
[
"MIT",
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-python-cwi",
"Python-2.0"
] |
permissive
|
Ryorama/codeapp
|
32ef44a3e8058da9858924df211bf82f5f5018f1
|
cf7f5753c6c4c3431d8209cbaacf5208c3c664fa
|
refs/heads/main
| 2023-06-26T09:24:13.724462
| 2021-07-27T17:54:25
| 2021-07-27T17:54:25
| 388,520,626
| 0
| 0
|
MIT
| 2021-07-22T16:01:32
| 2021-07-22T16:01:32
| null |
UTF-8
|
Python
| false
| false
| 544
|
py
|
"""Terminals served to xterm.js using Tornado websockets"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
# Distributed under the terms of the Simplified BSD License.
from .websocket import TermSocket
from .management import (TermManagerBase, SingleTermManager,
UniqueTermManager, NamedTermManager)
import logging
# Prevent a warning about no attached handlers in Python 2
logging.getLogger(__name__).addHandler(logging.NullHandler())
__version__ = '0.9.4'
|
[
"ken.chung@thebaselab.com"
] |
ken.chung@thebaselab.com
|
11f2b5cb85357f64b7a41695ae6f16913c41d8d2
|
9431bba2d148f8aef9c0a8f3ca16fcf875890757
|
/matplotlib_exercise/3dplot.py
|
823f335d0f5214c0f6a80c17480335fb03bcdaa1
|
[
"MIT"
] |
permissive
|
terasakisatoshi/pythonCodes
|
fba0b78414b2c85f4a738200354ea583f0516768
|
953210c06e9885a7c885bc01047715a77de08a1a
|
refs/heads/master
| 2023-05-14T12:30:22.201711
| 2023-05-07T13:41:22
| 2023-05-07T13:41:22
| 197,893,702
| 2
| 1
|
MIT
| 2022-11-25T10:59:52
| 2019-07-20T07:09:12
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 407
|
py
|
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(121,projection='3d')
X=Y=np.arange(-3.3,3.3,0.3)
X,Y=np.meshgrid(X,Y)
Z=np.cos(np.sqrt(X*X+Y*Y))
ax1.plot_surface(X,Y,Z,rstride=1,cstride=1)
ax2=fig.add_subplot(122,projection='3d')
ax2.scatter3D(np.random.rand(100),np.random.rand(100),np.random.rand(100))
plt.show()
|
[
"terasakisatoshi.math@gmail.com"
] |
terasakisatoshi.math@gmail.com
|
285fce054cb4b6f25560dec504b9a781325d51d1
|
9009ad47bc1d6adf8ee6d0f2f2b3125dea44c0aa
|
/abc004_2.py
|
bc6cf2f9686dea24440c44413bba61a132f9ed6a
|
[] |
no_license
|
luctivud/Coding-Trash
|
42e880624f39a826bcaab9b6194add2c9b3d71fc
|
35422253f6169cc98e099bf83c650b1fb3acdb75
|
refs/heads/master
| 2022-12-12T00:20:49.630749
| 2020-09-12T17:38:30
| 2020-09-12T17:38:30
| 241,000,584
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 882
|
py
|
# जय श्री राम
import sys; import math; from collections import *
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().split())
def get_list(): return list(get_ints())
def printspx(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")
UGLYMOD = int(1e9+7); SEXYMOD = 998244353; MAXN = int(1e5)
# sys.stdin = open("input.txt","r"); sys.stdout = open("output.txt","w")
matr = []
for i in range(4):
li = list(input().split())
matr.append(li)
for i in range(3, -1, -1):
for j in range(3, -1, -1):
printsp(matr[i][j])
print()
'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
'''
|
[
"luctivud@gmail.com"
] |
luctivud@gmail.com
|
27dd825851e20094d5c582a2aec94b07f03aa620
|
8ca19f1a31070738b376c0370c4bebf6b7efcb43
|
/office365/intune/devices/data.py
|
356d6888c9b603e4568ea707e50f61a7cd4e0156
|
[
"MIT"
] |
permissive
|
vgrem/Office365-REST-Python-Client
|
2ef153d737c6ed5445ba1e446aeaec39c4ef4ed3
|
cbd245d1af8d69e013c469cfc2a9851f51c91417
|
refs/heads/master
| 2023-09-02T14:20:40.109462
| 2023-08-31T19:14:05
| 2023-08-31T19:14:05
| 51,305,798
| 1,006
| 326
|
MIT
| 2023-08-28T05:38:02
| 2016-02-08T15:24:51
|
Python
|
UTF-8
|
Python
| false
| false
| 128
|
py
|
from office365.runtime.client_value import ClientValue
class DeviceAndAppManagementData(ClientValue):
"""Exported Data"""
|
[
"vvgrem@gmail.com"
] |
vvgrem@gmail.com
|
dbd092cd987efe95f6be5c4270e5d9a437ec863f
|
f67986550761cf3ed174d01063f5fdc8a26f59f3
|
/mission/missions/opt.py
|
8a285573d41e8e9e8939678eaaabbd9b6aa4beca
|
[
"BSD-3-Clause"
] |
permissive
|
wpfhtl/software
|
4dd5d116a1c90660264b32006617a6809b0a530e
|
575d424be6b497e0f34f7297a9b322567c2e26c0
|
refs/heads/master
| 2021-01-23T02:40:49.542461
| 2016-04-15T04:16:21
| 2016-04-15T04:16:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,152
|
py
|
'''
Optimal Mission Runner
Introduction:
Usage:
Tasks must expose the following interface:
currentPoints :: double
possibleModes :: () -> [mode]
--> Should take into account state, whether we think we're succeeding.
Tasks are passed the following parameters on run:
mode :: string (the name of the mode)
flex :: bool
Caveats / To Know:
Task instances may be re-run after periods of inactivity (not being run).
This can cause issues with quasi-time-dependent state, e.g. PID loops calculating dts.
Suggested fix: check self.last_run in on_run and reset such state if too much time has passed.
'''
from functools import *
from mission.framework.task import *
from mission.framework.combinators import *
from mission.framework.movement import *
from mission.framework.primitive import *
from mission.opt_aux import *
import shm
def generate(currentPlan, optimizableTasks, topologicalRestrictions):
# The names of the tasks we're already planning to do
currentTaskNames = set(p.taskName for p in currentPlan)
# Cannot do any of the after tasks if we haven't done the before task first.
impermissible = set(r.afterTask for r in topologicalRestrictions if r.beforeTask not in currentTaskNames)
# Possible execution plans
possible = []
for remaining in optimizableTasks:
if remaining.name in impermissible:
continue
others = [t for t in optimizableTasks if t.name is not remaining.name]
for mode in remaining.instance.possibleModes():
taskPlan = TaskPlan(
taskName = remaining.name,
taskInstance = remaining.instance,
startPosition = remaining.startPosition(),
startOrientation = remaining.startOrientation(),
permissibleBoundingBox = remaining.permissibleBoundingBox(),
mode = mode
)
# Construct a possible execution plan in which we execute this task with this mode
remainder = generate(currentPlan + [taskPlan], others, topologicalRestrictions)
possible += remainder
# Construct a possible execution plan in which we just skip the task
skip = generate(currentPlan, others, topologicalRestrictions)
possible += skip
return possible
def stat(executionPlan, capabilities):
points, time, num_poss = 0., 0., len(executionPlan)
for ind in range(num_poss):
currTask = executionPlan[ind]
nextTask = executionPlan[ind + 1] if ind < num_poss - 1 else None
points += currTask.expectedPoints
time += currTask.expectedTime
if nextTask is not None:
# TODO Add time based on vector distance / sub speed.
# distance = auvec.norm(nextTask.startPosition - currTask.startPosition)
distance = 0
time += distance / capabilities.speed
return ExecutionPlanStat(expectedPoints = points, expectedTime = time)
def execute(taskPlan):
# TODO Deal with position, orientation, and bounding box.
taskPlan.taskInstance(
mode = taskPlan.mode,
flex = False
)
class Opt(Task):
def __init__(self, subtasks):
super().__init__() # TODO why
def on_first_run(self):
pass
def on_run(self):
pass
def on_finish(self):
pass
|
[
"software@cuauv.org"
] |
software@cuauv.org
|
ab80221c201f8a39f9ab877abb289b445c676c9f
|
0822d36728e9ed1d4e91d8ee8b5ea39010ac9371
|
/robo/pages/gazetadopovo.py
|
4da3d40428d2a85f59fddd2ee6384492a83ae54e
|
[] |
no_license
|
diegothuran/blog
|
11161e6f425d08bf7689190eac0ca5bd7cb65dd7
|
233135a1db24541de98a7aeffd840cf51e5e462e
|
refs/heads/master
| 2022-12-08T14:03:02.876353
| 2019-06-05T17:57:55
| 2019-06-05T17:57:55
| 176,329,704
| 0
| 0
| null | 2022-12-08T04:53:02
| 2019-03-18T16:46:43
|
Python
|
UTF-8
|
Python
| false
| false
| 1,051
|
py
|
# coding: utf-8
import sys
sys.path.insert(0, '../../../blog')
from bs4 import BeautifulSoup
import requests
from robo.pages.util.constantes import PAGE_LIMIT
GLOBAL_RANK = 2763
RANK_BRAZIL = 123
NAME = 'gazetadopovo.com.br'
def get_urls():
try:
urls = []
root = 'https://www.gazetadopovo.com.br/'
for i in range(PAGE_LIMIT):
if(i == 0):
link = 'https://www.gazetadopovo.com.br/ultimas-noticias/'
else:
link = 'https://www.gazetadopovo.com.br/ultimas-noticias/?offset=' + str(i)
req = requests.get(link)
noticias = BeautifulSoup(req.text, "html.parser").find_all('article', class_='c-chamada lista-ordenada ultimas-chamadas')
for noticia in noticias:
href = noticia.find_all('a', href=True)[0]['href']
full_link = root + href
# print(full_link)
urls.append(full_link)
return urls
except:
raise Exception('Exception in gazetadopovo')
|
[
"diego.thuran@gmail.com"
] |
diego.thuran@gmail.com
|
e87e029eaa2d3d283eadcde19b4a76984da3bf66
|
f40b162d67c1aff030b14f7899c7fc4bbc1c993d
|
/pyvision/logger.py
|
afce2ba8df0aced624489f8594c7f4f3a05e60f5
|
[
"MIT"
] |
permissive
|
afcarl/pyvision
|
c3e7784a9feb585a3feaa936510776d5d1f36db1
|
e464a4ecc60cec49569be90d51708f3ad481f28a
|
refs/heads/master
| 2020-03-20T06:03:06.479246
| 2018-05-01T13:28:40
| 2018-05-01T13:28:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,542
|
py
|
"""
The MIT License (MIT)
Copyright (c) 2017 Marvin Teichmann
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import scipy as scp
import warnings
import deepdish as dd
import logging
from tables.exceptions import NaturalNameWarning
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
class Logger():
def __init__(self, filename=None):
self.data = {}
self.steps = []
self.filename = filename
def init_step(self, step):
self.steps.append(step)
if len(self.steps) > 1:
# Check that step size is constant.
assert(self.steps[-1] - self.steps[-2] ==
self.steps[1] - self.steps[0])
def add_value(self, value, name, step):
assert(self.steps[-1] == step)
if len(self.steps) == 1:
self.data[name] = [value]
else:
self.data[name].append(value)
assert(len(self.data[name]) == len(self.steps))
def add_values(self, value_dict, step, prefix=None):
for name, value in value_dict.items():
if prefix is not None:
name = prefix + "\\" + name
self.add_value(value, name, step)
def save(self, filename):
if filename is None:
assert(self.filename is not None)
filename = self.filename
save_dict = {'data': self.data,
'steps': self.steps}
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=NaturalNameWarning)
dd.io.save(filename, save_dict)
def load(self, filename):
load_dict = dd.io.load(filename)
self.data = load_dict['data']
self.steps = load_dict['steps']
return self
def reduce_step(self, step):
reduced_data = {}
assert(step >= 0)
assert(step <= len(self.steps))
for key, value in self.data.items():
reduced_data[key] = value[step]
return reduced_data
def discard_data(self, step):
reduced_data = {}
assert(step >= 0)
assert(step <= len(self.steps))
for key, value in self.data.items():
reduced_data[key] = value[0:step]
self.data = reduced_data
self.steps = self.steps[0:step]
return
if __name__ == '__main__':
logging.info("Hello World.")
|
[
"marvin.teichmann@googlemail.com"
] |
marvin.teichmann@googlemail.com
|
26ce2c853d6fba5103f7e8c8487635468f81dce4
|
2a67dc681af4c4b9ef7a8e18c2ff75377dc5b44f
|
/aws.athena.Workgroup-python/__main__.py
|
fa1fc79a816edeaa868da2137ad1926dc3a71196
|
[] |
no_license
|
ehubbard/templates-aws
|
e323b693a18234defe6bd56ffcc64095dc58e3a1
|
2ae2e7a5d05490078017fed6d132dcdde1f21c63
|
refs/heads/master
| 2022-11-17T13:53:14.531872
| 2020-07-10T21:56:27
| 2020-07-10T21:56:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 450
|
py
|
import pulumi
import pulumi_aws as aws
example = aws.athena.Workgroup("example", configuration={
"enforceWorkgroupConfiguration": True,
"publishCloudwatchMetricsEnabled": True,
"resultConfiguration": {
"encryption_configuration": {
"encryptionOption": "SSE_KMS",
"kms_key_arn": aws_kms_key["example"]["arn"],
},
"output_location": "s3://{aws_s3_bucket.example.bucket}/output/",
},
})
|
[
"jvp@justinvp.com"
] |
jvp@justinvp.com
|
dc1eebcf72b6afa384ae1dfdeb4a15919adecf59
|
4f2c48896b0ac88b21a109d506296337a3a14807
|
/service.py
|
08955d7620d5742a20b126c253fe191cb9118d5a
|
[] |
no_license
|
mehdi1361/tcp_server
|
0539c6de158a6f6ac26428cc4f14f8bdd566cbdd
|
3a697221c3ba0110fb54e4c94958265b7fbbc0a8
|
refs/heads/master
| 2020-03-26T03:14:49.076505
| 2018-08-28T15:05:29
| 2018-08-28T15:05:29
| 144,384,551
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,705
|
py
|
import os
import sys
sys.path = [os.path.join(os.getcwd(), '.'), ] + sys.path
import json
import settings
# import time
from twisted.internet import reactor, protocol, task
from twisted.application import service, internet
from common.game import Battle
from common.objects import Player, CtmChestGenerate
from common.utils import normal_length
from dal.views import ProfileUpdateViewer, get_user, get_random_user, get_troop_list
clients = []
global_time = 0
def battle_finder(player, bot=False):
if bot:
player1 = Player(client=player, troops=player.troops)
enemy = GameProtocol()
enemy.user = get_random_user(player.user.username)
troops = get_troop_list(enemy.user)
enemy.troops = troops
player2 = Player(client=enemy, troops=enemy.troops)
player2.is_bot = bot
battle = Battle(player1, player2)
player.battle = battle
enemy.battle = battle
battle.start()
else:
for client in clients:
if client.user and client.user != player.user and client.battle is None:
if client.battle:
continue
player1 = Player(client=player, troops=player.troops)
player2 = Player(client=client, troops=client.troops)
battle = Battle(player1, player2)
player.battle = battle
client.battle = battle
battle.start()
class GameProtocol(protocol.Protocol):
def __init__(self):
self.user = set()
self.battle = None
self.troops = None
self.ready = False
self.wait = 0
self.is_bot = False
def connectionMade(self):
self.factory.clientConnectionMade(self)
def connectionLost(self, reason):
self.factory.clientConnectionLost(self)
def dataReceived(self, data):
try:
clean_data = json.loads(data)
print 'clean data:{}'.format(clean_data)
if not self.user:
user = get_user(clean_data['username'])
if user in [client.user for client in clients]:
message = {
"t": "Error",
"v": {'error_code': 501, 'msg': 'user {} already exists with id:{}'.format(user.username, user.id)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
return
if user:
self.user = user
self.troops = clean_data['troops_id']
else:
message = {
"t": "Error",
"v": {'error_code': 500, 'msg': 'user login failed'}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
if not self.battle:
battle_finder(self)
return
if not self.battle.player1.ready or not self.battle.player2.ready:
if clean_data['user_ready']:
if self.battle.player1.player_client == self:
self.battle.player1.ready = True
if self.battle.player2.is_bot:
self.battle.player2.ready = True
if self.battle.player2.player_client == self:
self.battle.player2.ready = True
if self.battle.player1.is_bot:
self.battle.player1.ready = True
self.battle.user_ready()
return
if clean_data['flag'] == "action":
self.battle.action(self, clean_data['spell_index'], clean_data['target_id'])
return
except ValueError as e:
message = {
"t": "Error",
"v": {'error_code': 400, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
print 'value error-{}'.format(e.message)
except KeyError as e:
message = {
"t": "Error",
"v": {'error_code': 401, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", "'")))
print 'KeyError-{}'.format(e.message)
except Exception as e:
message = {
"t": "Error",
"v": {'error_code': 402, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
print 'Exception-{}'.format(e.message)
class ServerFactory(protocol.Factory):
protocol = GameProtocol
def __init__(self):
self.lc = task.LoopingCall(self.announce)
self.global_time = 0
self.lc.start(1)
def announce(self):
for client in clients:
if client.battle:
if client.battle.player1.ready is True and client.battle.player2.ready is True:
client.battle.tick(self.global_time)
else:
if client.wait > 10:
battle_finder(client, bot=True)
client.wait = 0
else:
client.wait += 1
self.global_time += 1
# print self.global_time
def clientConnectionMade(self, client):
clients.append(client)
def clientConnectionLost(self, client):
if client in clients:
clients.remove(client)
if not client.battle.battle_end:
if client.user.username == client.battle.player1.player_client.user.username:
winner = client.battle.player2
loser = client.battle.player1
else:
winner = client.battle.player1
loser = client.battle.player2
winner.victorious = True
loser.victorious = False
if not winner.is_bot:
winner_profile = ProfileUpdateViewer(winner)
winner_data = winner_profile.generate()
chest = CtmChestGenerate(winner.player_client.user)
chest = chest.generate_chest()
winner_message = {
"t": "BattleResult",
"v": {
"victorious": str(winner.victorious),
"reward": {
"coin": winner_data['coin'],
"trophy": winner_data['trophy']
},
"cooldown_data": [],
"connection_lost": "True"
}
}
if chest is not None:
winner_message['v']['reward']['chest_info'] = chest
winner_message = str(winner_message).replace("u'", '"')
client.battle.send("{}{}".format(normal_length(len(str(winner_message))), winner_message), winner)
winner.player_client.transport.loseConnection()
loser_profile = ProfileUpdateViewer(loser)
loser_data = loser_profile.generate()
# game_factory = ServerFactory()
# reactor.listenTCP(settings.PORT, game_factory)
# reactor.run()
application = service.Application('finger', uid=1, gid=1)
game_factory = ServerFactory()
internet.TCPServer(settings.PORT, game_factory).setServiceParent(service.IServiceCollection(application))
|
[
"mhd.mosavi@gmail.com"
] |
mhd.mosavi@gmail.com
|
95644dd622ba8e1d18d9679fb5e4e32b799263ba
|
0694d9f69934cc21a20bd3a47871c04624bf5123
|
/helper/valid_tmp.py
|
33ece6949b3f48b849d026e7991ab68413ec1bc1
|
[] |
no_license
|
ShenDezhou/courtpy
|
fb47edb3b19062d0d60928375c7ab4bf98a3b089
|
338fca9c889994498173631ac2469684483afedd
|
refs/heads/master
| 2020-06-10T18:20:51.660842
| 2017-01-16T13:59:59
| 2017-01-16T13:59:59
| 75,911,371
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 686
|
py
|
# -*- coding:utf-8 -*-
__author__ = 'Mr.Tian'
from log import init_logging
from mongo import ProxyItemsDB, ProxyItemsDropDB, ProxyItemsTmpDB
from valid_proxy import valid_proxy
from get_proxy import GetProxy
def main():
get_proxy = GetProxy(ProxyItemsTmpDB)
while True:
item = get_proxy.get_proxy()
ret = valid_proxy(item)
if ret:
ProxyItemsDB.upsert_proxy_item(ret)
pass
else:
ProxyItemsDropDB.upsert_proxy_item(item)
pass
ProxyItemsTmpDB.remove_proxy_item(item)
pass
if __name__ == "__main__":
init_logging("log/valid_tmp.log", "log/valid_tmp_2.log")
main()
pass
|
[
"bangtech@sina.com"
] |
bangtech@sina.com
|
e6f51b04e362267f3c2c2555c5394eb5c42ea078
|
6362d18d6aadefa9949d10eae31030b25ff46fd0
|
/ndstats/management/commands/saveunknown.py
|
c4c5787ef7c05f1bbaed4013d69d11cbd880a301
|
[] |
no_license
|
yedpodtrzitko/ndstats
|
2ab3c0d389401b4c5e96f976b45f443f09057a70
|
d59b6395729269e311119c6edae7577303ec5d1b
|
refs/heads/master
| 2022-12-09T18:59:03.916427
| 2019-10-23T04:05:36
| 2019-10-23T04:05:36
| 40,006,216
| 0
| 0
| null | 2022-12-08T02:25:49
| 2015-07-31T13:19:30
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 814
|
py
|
from django.core.management.base import BaseCommand
from ndstats.models import UnknownLine, Chatlog
from ndstats.parser import LogParser
class Command(BaseCommand):
def handle(self, *args, **options):
parser = LogParser()
Chatlog.objects.all().delete()
for line in UnknownLine.objects.all():
try:
if '><BOT><' in line.line:
continue
parser.parse_line(
line.ip_address, line.line,
save_unknown=False)
except Exception as e:
raise
else:
continue
delete = raw_input('delete? (y/N)')
# TODO - remove question
if delete.strip().lower() == 'y':
line.delete()
|
[
"yed@vanyli.net"
] |
yed@vanyli.net
|
7f5effb36ac00dad195203e6ac8257fce255d6ce
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_145/ch24_2019_04_03_22_28_52_327688.py
|
6c0c7ab21be1649606ab09c05cbc3f8ed028a92b
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 187
|
py
|
def classifica_triangulo(a,b,c):
if a == b and b == c:
return "equilátero"
if a == b and b != c:
return "isósceles"
if a!= b and b != c:
return "escaleno"
|
[
"you@example.com"
] |
you@example.com
|
92d6f6ca17e33b469cb39f8aa47695ade46268b3
|
2b9914d157d36dfb8a96df10a047ffe630511ba8
|
/string_text/insert_var.py
|
8b38d2e07fe86ffe769e27ed5aff258e86ce9b25
|
[] |
no_license
|
liuxingyuxx/cookbook
|
20dce322a09ea5267c68637d66c18d1cec234610
|
3faad3d8fc2c40b648830f4bdc17b99bcc11c5fd
|
refs/heads/master
| 2020-03-14T06:59:29.831430
| 2018-04-29T12:51:55
| 2018-04-29T12:51:55
| 131,494,393
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 427
|
py
|
#创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。
#format
s = '{name} has {n} messages'
s_fo = s.format(name='LXY', n='8')
print(s_fo)
#format_map() 与 var()
name = 'LXY_'
n = 9
s_fo_var = s.format_map(vars())
print(s_fo_var)
class Info:
def __init__(self, name, n):
self.name = name
self.n = n
a = Info('Furry', 12)
s__ = s.format_map(vars(a))
print(s__)
|
[
"typefj@gmail.com"
] |
typefj@gmail.com
|
8a3b729b6a6bc27ce2e4328b965750b430115181
|
150464efa69db3abf328ef8cd912e8e248c633e6
|
/_4.python/tkinter/_example/tk_ex_Image_Editor.py
|
e890b9404e82f3b701cc5231d8f8fa63a3e4abab
|
[] |
no_license
|
bunshue/vcs
|
2d194906b7e8c077f813b02f2edc70c4b197ab2b
|
d9a994e3afbb9ea84cc01284934c39860fea1061
|
refs/heads/master
| 2023-08-23T22:53:08.303457
| 2023-08-23T13:02:34
| 2023-08-23T13:02:34
| 127,182,360
| 6
| 3
| null | 2023-05-22T21:33:09
| 2018-03-28T18:33:23
|
C#
|
UTF-8
|
Python
| false
| false
| 3,510
|
py
|
import tkinter as tk
from tkinter import filedialog
from tkinter import colorchooser
from PIL import Image, ImageOps, ImageTk, ImageFilter
from tkinter import ttk
root = tk.Tk()
root.geometry("1000x600")
root.title("Image Drawing Tool")
root.config(bg="white")
pen_color = "black"
pen_size = 5
file_path = ""
def add_image():
global file_path
file_path = filedialog.askopenfilename(
initialdir = 'C:/dddddddddd/____download')
image = Image.open(file_path)
width, height = int(image.width / 2), int(image.height / 2)
image = image.resize((width, height), Image.ANTIALIAS)
canvas.config(width=image.width, height=image.height)
image = ImageTk.PhotoImage(image)
canvas.image = image
canvas.create_image(0, 0, image=image, anchor="nw")
def change_color():
global pen_color
pen_color = colorchooser.askcolor(title="Select Pen Color")[1]
def change_size(size):
global pen_size
pen_size = size
def draw(event):
x1, y1 = (event.x - pen_size), (event.y - pen_size)
x2, y2 = (event.x + pen_size), (event.y + pen_size)
canvas.create_oval(x1, y1, x2, y2, fill=pen_color, outline='')
def clear_canvas():
canvas.delete("all")
canvas.create_image(0, 0, image=canvas.image, anchor="nw")
def apply_filter(filter):
image = Image.open(file_path)
width, height = int(image.width / 2), int(image.height / 2)
image = image.resize((width, height), Image.ANTIALIAS)
if filter == "Black and White":
image = ImageOps.grayscale(image)
elif filter == "Blur":
image = image.filter(ImageFilter.BLUR)
elif filter == "Sharpen":
image = image.filter(ImageFilter.SHARPEN)
elif filter == "Smooth":
image = image.filter(ImageFilter.SMOOTH)
elif filter == "Emboss":
image = image.filter(ImageFilter.EMBOSS)
image = ImageTk.PhotoImage(image)
canvas.image = image
canvas.create_image(0, 0, image=image, anchor="nw")
left_frame = tk.Frame(root, width=200, height=600, bg="white")
left_frame.pack(side="left", fill="y")
canvas = tk.Canvas(root, width=750, height=600)
canvas.pack()
image_button = tk.Button(left_frame, text="Add Image",
command=add_image, bg="white")
image_button.pack(pady=15)
color_button = tk.Button(
left_frame, text="Change Pen Color", command=change_color, bg="white")
color_button.pack(pady=5)
pen_size_frame = tk.Frame(left_frame, bg="white")
pen_size_frame.pack(pady=5)
pen_size_1 = tk.Radiobutton(
pen_size_frame, text="Small", value=3, command=lambda: change_size(3), bg="white")
pen_size_1.pack(side="left")
pen_size_2 = tk.Radiobutton(
pen_size_frame, text="Medium", value=5, command=lambda: change_size(5), bg="white")
pen_size_2.pack(side="left")
pen_size_2.select()
pen_size_3 = tk.Radiobutton(
pen_size_frame, text="Large", value=7, command=lambda: change_size(7), bg="white")
pen_size_3.pack(side="left")
clear_button = tk.Button(left_frame, text="Clear",
command=clear_canvas, bg="#FF9797")
clear_button.pack(pady=10)
filter_label = tk.Label(left_frame, text="Select Filter", bg="white")
filter_label.pack()
filter_combobox = ttk.Combobox(left_frame, values=["Black and White", "Blur",
"Emboss", "Sharpen", "Smooth"])
filter_combobox.pack()
filter_combobox.bind("<<ComboboxSelected>>",
lambda event: apply_filter(filter_combobox.get()))
canvas.bind("<B1-Motion>", draw)
root.mainloop()
|
[
"david@insighteyes.com"
] |
david@insighteyes.com
|
07b8a7afb9e5a2d9650d56d56bd5b2392d8e0349
|
1fe0b680ce53bb3bb9078356ea2b25e572d9cfdc
|
/venv/lib/python2.7/site-packages/ansible/galaxy/login.py
|
dda856099160cc82d6dd3235e8a4cfc975f305b1
|
[
"MIT"
] |
permissive
|
otus-devops-2019-02/devopscourses_infra
|
1929c4a9eace3fdb0eb118bf216f3385fc0cdb1c
|
e42e5deafce395af869084ede245fc6cff6d0b2c
|
refs/heads/master
| 2020-04-29T02:41:49.985889
| 2019-05-21T06:35:19
| 2019-05-21T06:35:19
| 175,780,457
| 0
| 1
|
MIT
| 2019-05-21T06:35:20
| 2019-03-15T08:35:54
|
HCL
|
UTF-8
|
Python
| false
| false
| 4,573
|
py
|
########################################################################
#
# (C) 2015, Chris Houseknecht <chouse@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import getpass
import json
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.module_utils.six.moves import input
from ansible.module_utils.six.moves.urllib.parse import quote as urlquote, urlparse
from ansible.module_utils.six.moves.urllib.error import HTTPError
from ansible.module_utils.urls import open_url
from ansible.utils.color import stringc
from ansible.utils.display import Display
display = Display()
class GalaxyLogin(object):
''' Class to handle authenticating user with Galaxy API prior to performing CUD operations '''
GITHUB_AUTH = 'https://api.github.com/authorizations'
def __init__(self, galaxy, github_token=None):
self.galaxy = galaxy
self.github_username = None
self.github_password = None
if github_token is None:
self.get_credentials()
def get_credentials(self):
display.display(u'\n\n' + "We need your " + stringc("GitHub login", 'bright cyan') +
" to identify you.", screen_only=True)
display.display("This information will " + stringc("not be sent to Galaxy", 'bright cyan') +
", only to " + stringc("api.github.com.", "yellow"), screen_only=True)
display.display("The password will not be displayed." + u'\n\n', screen_only=True)
display.display("Use " + stringc("--github-token", 'yellow') +
" if you do not want to enter your password." + u'\n\n', screen_only=True)
try:
self.github_username = input("GitHub Username: ")
except Exception:
pass
try:
self.github_password = getpass.getpass("Password for %s: " % self.github_username)
except Exception:
pass
if not self.github_username or not self.github_password:
raise AnsibleError("Invalid GitHub credentials. Username and password are required.")
def remove_github_token(self):
'''
If for some reason an ansible-galaxy token was left from a prior login, remove it. We cannot
retrieve the token after creation, so we are forced to create a new one.
'''
try:
tokens = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username,
url_password=self.github_password, force_basic_auth=True,))
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
for token in tokens:
if token['note'] == 'ansible-galaxy login':
display.vvvvv('removing token: %s' % token['token_last_eight'])
try:
open_url('https://api.github.com/authorizations/%d' % token['id'], url_username=self.github_username,
url_password=self.github_password, method='DELETE', force_basic_auth=True)
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
def create_github_token(self):
'''
Create a personal authorization token with a note of 'ansible-galaxy login'
'''
self.remove_github_token()
args = json.dumps({"scopes": ["public_repo"], "note": "ansible-galaxy login"})
try:
data = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username,
url_password=self.github_password, force_basic_auth=True, data=args))
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
return data['token']
|
[
"skydevapp@gmail.com"
] |
skydevapp@gmail.com
|
6bfbed10f2be00a9cd038e8db238272c5ddda73d
|
bb53e9883437a4df49da1f9646f67ee51f12c4ca
|
/merge_sort.py
|
9d3356371775d88de2d68e6af35b8005a6db0dd4
|
[] |
no_license
|
petehwu/python_practice
|
513c2260bb7bc34072bd4dafe122e05dfb3baa4c
|
31817ec10bc9bddf6ee82400ca7045b5445c55fe
|
refs/heads/master
| 2020-05-24T03:26:11.915327
| 2019-07-17T14:47:11
| 2019-07-17T14:47:11
| 187,072,284
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,315
|
py
|
#!/Users/pwu/anaconda/bin/python3
""" shebang for linux #!/usr/bin/env python3
merge sort algo
"""
def ms(arr):
""" entry point for merge sort
"""
print("before merge sort {}".format(arr))
rms(arr)
print("after merge sort {}".format(arr))
def rms(arr):
""" recursive function that keep splitting the list till 1 element in left and right
"""
mid = len(arr) // 2
if mid > 0:
left = arr[0:mid]
right = arr[mid:]
rms(left)
rms(right)
mergeLR(arr, left, right)
def mergeLR(arr, left, right):
"""merges the left and right into one orderd list
"""
lIdx = 0
rIdx = 0
aIdx = 0
while lIdx < len(left) and rIdx < len(right):
if left[lIdx] < right[rIdx]:
arr[aIdx] = left[lIdx]
lIdx += 1
else:
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
while lIdx < len(left):
arr[aIdx] = left[lIdx]
lIdx += 1
aIdx += 1
while rIdx < len(right):
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
if __name__ == '__main__':
ms([20,45,78,23,6,7,2,8,13,77])
print("-----")
ms([1, 2, 3])
print("-----")
ms([1])
print("-----")
ms([1,2])
print("-----")
ms([2, 1])
print("-----")
|
[
"pete.h.wu@gmail.com"
] |
pete.h.wu@gmail.com
|
919286dee2cf3f64c831410581789a79c59e10e6
|
5689947a9648966a92e81bdd693b01ea9026b804
|
/archive/Arc.py
|
99c67dc806d9ac398ab86c5dbb5096f80f66b1f2
|
[] |
no_license
|
Renneta/pyge
|
20c44eff9fbdfd01e86f41f23a95196d93d0d6b9
|
747dcbc0dce9890d85834c6d8bd64673a69c767a
|
refs/heads/master
| 2022-04-18T22:53:41.997075
| 2020-03-19T21:37:13
| 2020-03-19T21:37:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 419
|
py
|
import struct
from archive import PygeArchive, GenericEntry
#
# (.arc) Tokoya, I/O
#
# unpack & repack seem to work and give the same filesize, data mod not tested
# since all formats inside the archive are proprietary...
#
class Arc(PygeArchive):
name = "Arc"
desc = "Tokoya / I/O"
sig = "\x01\x00\x00\x00"
ext = "arc"
header_fmt = "<4s4xi4x"
entry_fmt = "<9sii" # 21
entry_order = "nlo"
|
[
"shish@shishnet.org"
] |
shish@shishnet.org
|
153da44cc3daa2381d3adda32901329e35184805
|
fb5b204943101746daf897f6ff6e0a12985543c3
|
/tests/pytests/TestGeneratePoints.py
|
dcbdfc38cb2ced34da4be7681d7545850dfa7f66
|
[
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
baagaard-usgs/geomodelgrids
|
911a31ba23ca374be44873fdeb1e36a70ff25256
|
7d0db3c4ca1a83fea69ceb88f6ceec258928251a
|
refs/heads/main
| 2023-08-03T07:52:25.727039
| 2023-07-27T21:56:19
| 2023-07-27T21:56:19
| 97,262,677
| 5
| 3
|
NOASSERTION
| 2023-03-23T03:34:45
| 2017-07-14T18:34:38
|
C++
|
UTF-8
|
Python
| false
| false
| 3,722
|
py
|
# ======================================================================
#
# Brad T. Aagaard
# U.S. Geological Survey
#
# ======================================================================
#
import unittest
import numpy
import sys
sys.path.append("../../src/scripts")
from generate_points import App
class TestGeneratePoints(unittest.TestCase):
def setUp(self):
"""Setup test data.
"""
self.data_dir = "data"
self.dataE_dir = "dataE"
self.model_config = None
self.blocksE = None
return
def test_write_surfxy(self):
"""Test writing points on ground surface for topography.
"""
app = App(self.model_config, self.data_dir)
app.run("groundsurf")
groundsurf_filename = "%s/%s-topo-xy.txt.gz" % (self.data_dir, app.model.key)
groundsurf = numpy.loadtxt(groundsurf_filename)
groundsurfE_filename = "%s/%s-topo-xy.txt.gz" % (self.dataE_dir, app.model.key)
groundsurfE = numpy.loadtxt(groundsurfE_filename)
self._check(groundsurfE, groundsurf)
return
def test_write_blocks(self):
"""Test writing points in blocks.
"""
app = App(self.model_config, self.data_dir)
app.run("blocks")
for block_name in self.blocksE:
block_filename = "%s/%s-%s-xyz.txt.gz" % (self.data_dir, app.model.key, block_name)
blockE_filename = "%s/%s-%s-xyz.txt.gz" % (self.dataE_dir, app.model.key, block_name)
block = numpy.loadtxt(block_filename)
blockE = numpy.loadtxt(blockE_filename)
self._check(blockE, block)
return
def _check(self, valuesE, values):
"""Verify arrays match.
"""
shapeE = valuesE.shape
shape = values.shape
self.assertEqual(len(shapeE), len(shape))
for vE,v in zip(shapeE,shape):
self.assertEqual(vE, v)
tolerance = 1.0e-6
okay = numpy.zeros(valuesE.shape, dtype=numpy.bool)
maskRatio = valuesE > tolerance
ratio = numpy.abs(1.0 - values[maskRatio] / valuesE[maskRatio])
if len(ratio) > 0:
okay[maskRatio] = ratio < tolerance
maskDiff = ~maskRatio
diff = numpy.abs(valuesE[maskDiff] - values[maskDiff])
if len(diff) > 0:
okay[maskDiff] = diff < tolerance
if numpy.prod(shapeE) != numpy.sum(okay):
print("Expected values (not okay): %s" % valuesE[okay])
print("Computed values (not okay): %s" % values[okay])
self.assertEqual(numpy.prod(shapeE), numpy.sum(okay))
return
class TestGeneratePointsBlock1(TestGeneratePoints):
"""
Test generate_points for model with 1 layer.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_one.cfg"
self.blocksE = ["block0"]
return
class TestGeneratePointsBlock2(TestGeneratePoints):
"""
Test generate_points for model with 2 layers.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_two.cfg"
self.blocksE = ["block0", "block1"]
return
class TestGeneratePointsBlockFlat(TestGeneratePoints):
"""
Test generate_points for model with 1 block and no topography.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_flat.cfg"
self.blocksE = ["block0"]
return
# End of file
|
[
"baagaard@usgs.gov"
] |
baagaard@usgs.gov
|
032a2fb7a4854f6e6761f3e0df0d2ae69186634d
|
b627da650f75bdcf7e0dc0ef5c4419cf53a1d690
|
/src/zqh_core_common/zqh_core_common_wrapper_main.py
|
b481c38b1f21b225f1271790ddc02b7f95e55678
|
[] |
no_license
|
Jusan-zyh/zqh_riscv
|
4aa8a4c51e19fb786ba0c2a120722f1382994a52
|
bccde2f81b42ac258b92c21bb450ec6ff848387a
|
refs/heads/main
| 2023-08-06T12:56:52.420302
| 2021-09-21T01:25:41
| 2021-09-21T01:25:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,130
|
py
|
import sys
import os
from phgl_imp import *
from .zqh_core_common_wrapper_parameters import zqh_core_common_wrapper_parameter
from .zqh_core_common_interrupts_bundles import zqh_core_common_interrupts
from .zqh_core_common_wrapper_bundles import zqh_core_common_wrapper_driven_constants
from zqh_common.zqh_transfer_size import zqh_transfer_size
from .zqh_core_common_ifu_main import zqh_core_common_ifu
from zqh_fpu.zqh_fpu_stub import zqh_fpu_stub
from zqh_rocc.zqh_rocc_stub import zqh_rocc_stub
from .zqh_core_common_ifu_bundles import zqh_core_common_ifu_slave_io
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_master_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_master_io_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_slave_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_slave_io_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_xbar_parameter
from zqh_tilelink.zqh_tilelink_node_module_main import zqh_tilelink_node_module
from zqh_common.zqh_address_space import zqh_address_space
from zqh_common.zqh_address_space import zqh_address_attr
from zqh_common.zqh_address_space import zqh_order_type
from zqh_tilelink.zqh_tilelink_dw_fix_main import zqh_tilelink_burst_split_fix
class zqh_core_common_wrapper(zqh_tilelink_node_module):
def set_par(self):
super(zqh_core_common_wrapper, self).set_par()
self.p = zqh_core_common_wrapper_parameter()
def gen_node_tree(self):
super(zqh_core_common_wrapper, self).gen_node_tree()
self.p.par('lsu_master', zqh_tilelink_node_master_parameter('lsu_master'))
self.p.par('ifu_master', zqh_tilelink_node_master_parameter('ifu_master'))
#itim and dtim's internal access by core
self.p.par(
'core_inner_slave',
zqh_tilelink_node_slave_parameter(
'core_inner_slave',
is_pos = 1,
address = [
zqh_address_space(
base = 0x60000000,
mask = 0x003fffff,
attr = zqh_address_attr.MEM_RWAX_C_S,
order_type = zqh_order_type.RO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 64),
address_mask = 0x003fffff,
process = [[zqh_tilelink_burst_split_fix, None]]))
self.p.par(
'out_extern_master',
zqh_tilelink_node_slave_io_parameter('out_extern_master'))
self.p.par('out_bus', zqh_tilelink_node_xbar_parameter('out_bus',
buffer_in = self.p.buf_params if (self.p.out_bus_has_buffer) else None,
do_imp = 1))
self.p.out_bus.push_up(self.p.lsu_master)
self.p.out_bus.push_up(self.p.ifu_master)
self.p.out_bus.push_down(self.p.out_extern_master)
self.p.out_bus.push_down(self.p.core_inner_slave)
if (len(self.p.extern_masters) > 0):
self.p.out_extern_master.push_down(self.p.extern_masters[0])
self.p.par(
'in_extern_slave',
zqh_tilelink_node_master_io_parameter(
'in_extern_slave',
address_mask = 0x003fffff))
self.p.par(
'ifu_slave',
zqh_tilelink_node_slave_parameter(
'ifu_slave',
is_pos = 1,
address = [
zqh_address_space(
base = 0x00000000,
mask = 0x001fffff,
attr = zqh_address_attr.MEM_RWAX_UC,
order_type = zqh_order_type.SO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 8)))
self.p.par(
'lsu_slave',
zqh_tilelink_node_slave_parameter(
'lsu_slave',
address = [
zqh_address_space(
base = 0x00200000,
mask = 0x001fffff,
attr = zqh_address_attr.MEM_RWAX_UC,
order_type = zqh_order_type.SO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 8)))
if (len(self.p.extern_slaves) > 0):
self.p.in_extern_slave.push_up(self.p.extern_slaves[0])
self.p.par('in_bus', zqh_tilelink_node_xbar_parameter('in_bus', do_imp = 1))
self.p.in_bus.push_up(self.p.in_extern_slave)
self.p.in_bus.push_up(self.p.core_inner_slave)
self.p.in_bus.push_down(self.p.ifu_slave)
self.p.in_bus.push_down(self.p.lsu_slave)
def set_port(self):
super(zqh_core_common_wrapper, self).set_port()
self.io.var(zqh_core_common_interrupts('interrupts').as_input())
self.io.var(zqh_core_common_wrapper_driven_constants('constants'))
def main(self):
super(zqh_core_common_wrapper, self).main()
core = self.instance_core()
ifu = self.instance_ifu()
lsu = self.instance_lsu()
fpu = self.instance_fpu() if (core.p.isa_f) else zqh_fpu_stub('fpu')
rocc = self.instance_rocc() if (core.p.isa_custom) else zqh_rocc_stub('rocc')
ifu.io.cpu /= core.io.ifu
ifu.io.reset_pc /= self.io.constants.reset_pc
core.io.interrupts /= async_dff(self.io.interrupts, self.p.int_sync_delay)
core.io.interrupts.debug /= async_dff(
self.io.interrupts.debug,
self.p.int_sync_delay)
core.io.hartid /= self.io.constants.hartid
core.io.reset_pc /= self.io.constants.reset_pc
lsu.io.cpu /= core.io.lsu
fpu.io.cp_req /= 0
fpu.io.cp_resp.ready /= 0
fpu.io /= core.io.fpu
rocc.io /= core.io.rocc
def instance_core(self):
pass
def instance_ifu(self):
return zqh_core_common_ifu('ifu',
extern_masters = [self.p.ifu_master],
extern_slaves = [self.p.ifu_slave])
def instance_lsu(self):
pass
def instance_fpu(self):
pass
def instance_rocc(self):
pass
|
[
"zhouqinghua888@163.com"
] |
zhouqinghua888@163.com
|
950bc09256b4ca649c9e26ad42137ffece622657
|
44f95e5df3ec15afacd1c35b1aba70764d1a453d
|
/Stock/Select/Ui/Basic/__init__.py
|
aed7e559eb66e05db33511388b818c33653d8c67
|
[
"MIT"
] |
permissive
|
zsl3034669/DevilYuan
|
7e8965e4e4ebcf85df7ded1c0fba06487ad5f416
|
865c1650d3affdccd6926c6527d8c0271774bcc7
|
refs/heads/master
| 2020-04-12T02:02:23.457179
| 2018-12-16T09:26:03
| 2018-12-16T09:26:03
| 162,236,146
| 0
| 1
|
MIT
| 2018-12-18T05:43:32
| 2018-12-18T05:43:32
| null |
UTF-8
|
Python
| false
| false
| 344
|
py
|
import os
from Stock import DynamicLoadStrategyFields
# dynamically load strategies from Stock/Select/Strategy
__pathList = os.path.dirname(__file__).split(os.path.sep)
__stratgyPath = os.path.sep.join(__pathList[:-2] + ['Strategy'])
DyStockSelectStrategyWidgetAutoFields = DynamicLoadStrategyFields(__stratgyPath, 'Stock.Select.Strategy')
|
[
"louis_chu@163.com"
] |
louis_chu@163.com
|
755f30982641e346662accc54a3835916cc17054
|
5c2d3e808a354b4dd59cbad51f6fc4ef877a7d6b
|
/GUI/config-label.py
|
84325928bf3becafdc54461b8409d9491db3708f
|
[] |
no_license
|
itaditya/fun_with_python
|
5e166b0f3d6805b53ddb2f291a18fa304894eeca
|
d9ea23784258184bff8215594cebb93168b47800
|
refs/heads/master
| 2021-07-09T18:54:23.964425
| 2017-09-30T19:26:33
| 2017-09-30T19:26:33
| 106,717,541
| 0
| 0
| null | 2017-10-12T16:23:44
| 2017-10-12T16:23:44
| null |
UTF-8
|
Python
| false
| false
| 277
|
py
|
from tkinter import *
root = Tk()
labelfont = ('times', 20, 'bold')
widget = Label(root, text='Hello Config World')
widget.config(bg='black', fg='yellow')
widget.config(font=labelfont)
widget.config(height=3, width=20)
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
|
[
"prakhar2397@gmail.com"
] |
prakhar2397@gmail.com
|
42a0eba8ac8d1f312f4125297e83edde3007972c
|
6147ed911274012be64eb02d88bff299808cab86
|
/初始化.py
|
bd1f96c59ae1bacfef8b0e4e7e6e865e0b83e9ba
|
[] |
no_license
|
persontianshuang/toasin
|
6dec061afc5964118dac83d5060bb13d957a2a3b
|
62896fac5224301a32c096841d4b17ac53d9abe0
|
refs/heads/master
| 2021-07-02T22:14:47.836627
| 2017-09-25T03:07:59
| 2017-09-25T03:07:59
| 103,622,098
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,600
|
py
|
from goods_url import get_url_page_list
import pymongo
import settings
from bson.objectid import ObjectId
MONGO_URI = '108.61.203.110'
def pymg(highest,collections,port=MONGO_URI):
client = pymongo.MongoClient(port, 29999)
zhihu = client[highest]
collections = zhihu[collections]
return collections
def path_url():
path = "/Users/user/Downloads/url.txt"
with open(path,'r') as f:
fr = f.readlines()
# [print(x.strip()) for x in fr]
return [x.strip() for x in fr if x.strip()!='']
name = settings.NAME
urls = path_url()
amazon_results_url = pymg('amazon_results_url',name)
first_urls = pymg('first_urls',name)
if len(list(first_urls.find({},{'_id':0})))==0:
first_urls_lists = [{'url':x,'status':0} for x in urls]
first_urls.insert_many(first_urls_lists)
def down_one(data):
x = data['url']
to_url_lists = get_url_page_list(x)
url_lists = [{'type':'results_url','urls':x,'status':0} for x in to_url_lists]
amazon_results_url.insert_many(url_lists)
first_urls.update({'_id':ObjectId(data['_id'])},{'$set':{'status':1}})
from concurrent import futures
MAX_WORKER = 20
def download_many(cc_list):
print('download_many')
print(len(cc_list))
workers = min(MAX_WORKER,len(cc_list))
with futures.ThreadPoolExecutor(workers) as executor:
executor.map(down_one,cc_list)
def kk(data):
data['_id'] = str(data['_id'])
return data
d_urls = [kk(x) for x in list(first_urls.find({'status':0}))]
download_many(d_urls)
# 队列
#
# 客户端
# workflow
# 一样的url 读取 设置 返回id
|
[
"mengyouhan@gmail.com"
] |
mengyouhan@gmail.com
|
b93acdccf694fa0412cdcf42545aba82cfd12e2d
|
5a281cb78335e06c631181720546f6876005d4e5
|
/blazar-3.0.0/api-ref/source/conf.py
|
c43a8e3a357451b498583d633bea74875af98c3a
|
[
"Apache-2.0"
] |
permissive
|
scottwedge/OpenStack-Stein
|
d25b2a5bb54a714fc23f0ff0c11fb1fdacad85e8
|
7077d1f602031dace92916f14e36b124f474de15
|
refs/heads/master
| 2021-03-22T16:07:19.561504
| 2020-03-15T01:31:10
| 2020-03-15T01:31:10
| 247,380,811
| 0
| 0
|
Apache-2.0
| 2020-03-15T01:24:15
| 2020-03-15T01:24:15
| null |
UTF-8
|
Python
| false
| false
| 4,358
|
py
|
# 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.
#
# Blazar API reference build configuration file, created by
# sphinx-quickstart on Mon Oct 2 14:47:19 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
extensions = [
'os_api_ref',
'openstackdocstheme'
]
html_theme = 'openstackdocs'
html_theme_options = {
"sidebar_mode": "toc",
}
# openstackdocstheme options
repository_name = 'openstack/blazar'
bug_project = 'blazar'
bug_tag = 'api-ref'
# Must set this variable to include year, month, day, hours, and minutes.
html_last_updated_fmt = '%Y-%m-%d %H:%M'
# -- General configuration ------------------------------------------------
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Reservation API Reference'
copyright = u'2017-present, OpenStack Foundation'
author = u'OpenStack Foundation'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'blazardoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'ReservationAPIReference.tex', u'OpenStack Reservation API Reference Documentation',
u'OpenStack Foundation', 'manual'),
]
|
[
"Wayne Gong@minbgong-winvm.cisco.com"
] |
Wayne Gong@minbgong-winvm.cisco.com
|
1a8d03601b116c5ef6e0c7e118bbdcf64d820b1a
|
31bc3fdc7c2b62880f84e50893c8e3d0dfb66fa6
|
/language/old/python_modules/python_packages/viewing.py
|
5ff6a1d6cd4b0a4e542083160779a45b5320cf27
|
[] |
no_license
|
tpt5cu/python-tutorial
|
6e25cf0b346b8182ebc8a921efb25db65f16c144
|
5998e86165a52889faf14133b5b0d7588d637be1
|
refs/heads/master
| 2022-11-28T16:58:51.648259
| 2020-07-23T02:20:37
| 2020-07-23T02:20:37
| 269,521,394
| 0
| 0
| null | 2020-06-05T03:23:51
| 2020-06-05T03:23:50
| null |
UTF-8
|
Python
| false
| false
| 1,409
|
py
|
# https://stackoverflow.com/questions/19048732/python-setup-py-develop-vs-install
"""
The package directory(s) for a given Python interpreter can be found by running "import site; site.getsitepackages()" in the Python repl.
- The packages for the Homebrew installed Python 2.7 are located in /usr/local/lib/python2.7/site-packages
- The packages for the Homebrew installed Python 3 are located in /usr/local/lib/python3.7/site-packages
The omf package does not exist in either site-packages directory.
When I installed all of the omf stuff, I ran a command $ python2 setup.py develop
This command creates a special link between /Users/austinchang/pycharm/omf and the site-packages directory.
This special link IS the omf.egg-link file located in the site-packages directory for the Homebrew Python 2.7.
This special link treats the chosen folder AS a Python package. The special link makes it so that any changes
I make to my source code are immediately reflected in the omf package so I don't have to recompile the package
over and over again to use it.
It makes sense that pip recognizes omf as a package because of the special link file. But why does pip3 ALSO
recognize the special link? For some reason, when I commented-out the PYTHON path setting in my .bash_profile file
(which pointed to both the omf source files and the python_tutorial source files), pip3 stopped listing omf as a package.
"""
|
[
"uif93194@gmail.com"
] |
uif93194@gmail.com
|
490876621066be76bba945e5210660cfea261a0f
|
acc3bfb8d0cdfbb0c762523b9923382570928ed1
|
/backend/home/migrations/0002_load_initial_data.py
|
246cb0d84c8cd64d6f9c084d7abc08e6b7d1861f
|
[] |
no_license
|
crowdbotics-apps/my-art-23726
|
30266909ff78876c3cf0c1636c76ba23afd930a2
|
50d905b644c425ab4562d0d3bf6b1ccbae5c715f
|
refs/heads/master
| 2023-02-16T05:36:51.832504
| 2021-01-07T23:31:07
| 2021-01-07T23:31:07
| 327,746,125
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,278
|
py
|
from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "My Art"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">My Art</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "my-art-23726.botics.co"
site_params = {
"name": "My Art",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
7246a0afae1a5c34c0079d8003d9a7db1e2cf1fb
|
a9b31181ad6f695a2809018167a52a6d9847c0df
|
/Chap05-funcoes-frutiferas/calcula_distancia.py
|
2cb5d81026a9883ad0c8fe37a508ad4b33a1480d
|
[] |
no_license
|
frclasso/Aprendendo_computacao_com_Python
|
21cdecdebcdbafad35a48d8425d06e4ec2ba1259
|
40276f396c90d25b301e15e855942a607efd895b
|
refs/heads/master
| 2020-03-12T17:38:04.886153
| 2018-10-11T14:17:13
| 2018-10-11T14:17:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 344
|
py
|
#!/usr/bin/env python3
import math
def distancia(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
# print(f'dx vale {dx}') # variveis temporarias
# print(f'dy vale {dy}')
dquadrado = dx**2 + dy**2
#print(f'dquadrado vale {dquadrado}')
resultado = math.sqrt(dquadrado)
return resultado
#print(distancia(1,2,4,6))
|
[
"frclasso@yahoo.com.br"
] |
frclasso@yahoo.com.br
|
d428c476d1c551f1c31af99d093bd82d685cc301
|
b4ca78134c296d8e03c39496bcc57369fd5f619b
|
/kubehub/vbox_api/vbox_functions/vbox_add_network_card.py
|
edd37f768155400ebc3714b5af1738bce351c1f8
|
[] |
no_license
|
dedicatted/kubehub-backend
|
7f4b57033962f1ef8604a2cee0cf55bebd533ec9
|
3b944e462f5366b2dbad55063f325e4aa1b19b0e
|
refs/heads/master
| 2023-02-05T04:44:50.213133
| 2020-06-10T15:02:03
| 2020-06-10T15:02:03
| 236,169,121
| 1
| 1
| null | 2023-01-24T23:19:38
| 2020-01-25T12:45:32
|
Python
|
UTF-8
|
Python
| false
| false
| 311
|
py
|
from os import system
def add_network_card(name, status):
vbox_add_network_card_cmd = f'VBoxManage ' \
f'modifyvm {name} ' \
f'--ioapic {status}'
vbox_add_network_card = system(vbox_add_network_card_cmd)
return vbox_add_network_card
|
[
"noreply@github.com"
] |
dedicatted.noreply@github.com
|
7591c784b3bfe157d30268f0f4c827459b87451e
|
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
|
/pardus/playground/cihan/x11/terminal/tilda/actions.py
|
6365c12bfaa653eb97e910517eb474fc4fc748e3
|
[] |
no_license
|
aligulle1/kuller
|
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
|
7f98de19be27d7a517fe19a37c814748f7e18ba6
|
refs/heads/master
| 2021-01-20T02:22:09.451356
| 2013-07-23T17:57:58
| 2013-07-23T17:57:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 427
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 2
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
def setup():
autotools.configure("--with-x")
def build():
autotools.make()
def install():
autotools.install()
pisitools.dodoc("ChangeLog", "README", "TODO", "NEWS", "AUTHORS")
|
[
"yusuf.aydemir@istanbul.com"
] |
yusuf.aydemir@istanbul.com
|
4be8a9f91ad8fbc6da7e187636382f69d3e9014f
|
3fe272eea1c91cc5719704265eab49534176ff0d
|
/scripts/field/jett_tuto_7_1.py
|
14fea3977f59741c0b2fb4a9b3c317feb3510588
|
[
"MIT"
] |
permissive
|
Bratah123/v203.4
|
e72be4843828def05592298df44b081515b7ca68
|
9cd3f31fb2ef251de2c5968c75aeebae9c66d37a
|
refs/heads/master
| 2023-02-15T06:15:51.770849
| 2021-01-06T05:45:59
| 2021-01-06T05:45:59
| 316,366,462
| 1
| 0
|
MIT
| 2020-12-18T17:01:25
| 2020-11-27T00:50:26
|
Java
|
UTF-8
|
Python
| false
| false
| 805
|
py
|
# Created by MechAviv
# Map ID :: 620100027
# Spaceship : Spaceship Cockpit
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(0)
sm.sendDelay(1000)
sm.showEffect("Effect/DirectionNewPirate.img/newPirate/balloonMsg1/20", 2000, 0, -100, -2, -2, False, 0)
sm.sendDelay(2000)
sm.spawnMob(9420567, -378, -120, False)
sm.setSpeakerID(9270085)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("You there! Get away from those controls, and drop that key!")
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
sm.chatScript("Eliminate the Key Keeper and find the Master Key.")
sm.startQuestNoCheck(5672)
sm.createQuestWithQRValue(5672, "001")
|
[
"pokesmurfuwu@gmail.com"
] |
pokesmurfuwu@gmail.com
|
68f9c64f9fdba88df8225851e68798225af2346d
|
63acfadae1b26e521169191ae441cfdb86817651
|
/tests/argparse/special/modules/defaults/__init__.py
|
3505b0795f024d936847202220a08964b18c6216
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
da-h/miniflask
|
4e1e8889623665309b7194948222635275acea34
|
e8398bcf2b81e1d1cd8d53d9f4b1125c027552b1
|
refs/heads/master
| 2023-05-10T19:28:59.669718
| 2023-05-05T12:54:05
| 2023-05-05T12:54:05
| 240,955,157
| 7
| 1
|
MIT
| 2023-02-28T14:44:33
| 2020-02-16T19:47:49
|
Python
|
UTF-8
|
Python
| false
| false
| 573
|
py
|
def printVal(state, name):
val = state[name]
print("%s:" % state.fuzzy_names[name], val)
def print_all(state):
printVal(state, "var_default")
printVal(state, "var_default_override")
printVal(state, "var_default_override_twice")
printVal(state, "var_default_override_twice_and_cli")
def register(mf):
mf.register_defaults({
"var_default": 1,
"var_default_override": 2,
"var_default_override_twice": 3,
"var_default_override_twice_and_cli": 4
})
mf.register_event('print_all', print_all, unique=False)
|
[
"dhartmann@uni-mainz.de"
] |
dhartmann@uni-mainz.de
|
bda4bdd71bd5d2eeec3b1942611e2b982c0b36bc
|
fe3ecb9b1ddd8de17b8cc93209134f86cd9c4a6f
|
/6_Tensorflow/chap04_Classification/lecture_1x/step05_softmax_classifier.py
|
848aca28e11509d6d891b478e7025c2ba6458666
|
[] |
no_license
|
nsh92/Bigdata-and-Machine-Learning-Education-at-ITWILL
|
d1a7292ee4865a3d0c664dd6ecf3afc0d6325847
|
3cb5661001597499178a2c85f4ccf70dcf0855d6
|
refs/heads/master
| 2022-11-21T23:10:51.421708
| 2020-07-23T12:49:11
| 2020-07-23T12:49:11
| 275,540,204
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,903
|
py
|
# -*- coding: utf-8 -*-
"""
step04_softmax_classifier.py
- 활성함수 : Sotfmax(model)
- 손실함수 : Cross Entropy
"""
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
from sklearn.metrics import accuracy_score
# 1. x, y 공급 data
# [털, 날개]
x_data = np.array(
[[0, 0], [1, 0], [1, 1], [0, 0], [0, 1], [1, 1]]) # [6, 2]
# [기타, 포유류, 조류] : [6, 3] -> one hot encoding : 1과 0으로 표시
y_data = np.array([
[1, 0, 0], # 기타[0]
[0, 1, 0], # 포유류[1]
[0, 0, 1], # 조류[2]
[1, 0, 0],
[1, 0, 0],
[0, 0, 1]
])
# 2. X, Y 변수 정의
X = tf.placeholder(dtype=tf.float32, shape=[None, 2]) # [관측치, 입력수]
Y = tf.placeholder(dtype=tf.float32, shape=[None, 3]) # [관측치, 출력수]
# 3. w, b변수 정의 : 초기값은 난수
w = tf.Variable(tf.random_normal([2,3])) # [입력수, 출력수]
b = tf.Variable(tf.random_normal([3])) # [출력수]
# 4. softmax 분류기
# 1) 회귀방정식 : 예측치
model = tf.matmul(X, w) + b # 회귀모델
# softmax(예측치)
softmax = tf.nn.softmax(model)
# 2) loss function : Cross Entropy 이용 : -sum(Y * log(model))
loss = -tf.reduce_mean(Y * tf.log(softmax) + (1 - Y) * tf.log(1 - softmax))
# 3) optimizer : 오차 최소화(w, b update)
train = tf.train.AdamOptimizer(0.1).minimize(loss) # 오차 최소화
# 4) argmax() : encoding(2진수로된 것) -> decoding(10진수)
y_pred = tf.argmax(softmax, axis = 1)
y_true = tf.argmax(Y, axis = 1)
# 5. 모델 학습
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # w b 초기화
feed_data = {X : x_data, Y : y_data}
# 반복학습 : 500ghl
for step in range(500):
_, loss_val = sess.run([train, loss], feed_dict=feed_data)
if (step+1) % 50 == 0:
print("step = {}, loss = {}".format(step+1, loss_val))
# model result
# 결과값이 몇 번 클래스인지 알아야하기에 y_data를 10진수 표시로 바꿔야 함 혹은 y1, y2, y3 이런 식이거나
y_pred_re = sess.run(y_pred, feed_dict = {X : x_data}) # 예측치
y_true_re = sess.run(y_true, feed_dict = {Y : y_data}) # 정답
print("y pred =", y_pred_re)
print("y true =", y_true_re)
acc = accuracy_score(y_true_re, y_pred_re)
print("분류정확도 =", acc)
'''
step = 50, loss = 0.08309727162122726
step = 100, loss = 0.02883036620914936
step = 150, loss = 0.016369767487049103
step = 200, loss = 0.01092542801052332
step = 250, loss = 0.007947643287479877
step = 300, loss = 0.0061068180948495865
step = 350, loss = 0.004874517675489187
step = 400, loss = 0.004001634661108255
step = 450, loss = 0.003356706351041794
step = 500, loss = 0.0028643012046813965
y pred = [0 1 2 0 0 2]
y true = [0 1 2 0 0 2]
분류정확도 = 1.0
'''
|
[
"totols1092@gmail.com"
] |
totols1092@gmail.com
|
3da9a6b0aae255dd6bffb0296b6c0b05017d03a9
|
7bf51d5550195a7fae26bd626ed82c5f2b5d9737
|
/my_graphs/g_graph_12.py
|
bbfbc1c98ccd7f78677de75c49227f306cf19173
|
[] |
no_license
|
venkatram64/python_ml
|
9fcadc380c2a56856f590b40a7c3b015c19c62a0
|
b0b40fec4547f3675a500af24878cddacc4c270c
|
refs/heads/master
| 2020-04-08T05:07:28.993601
| 2018-12-26T08:30:28
| 2018-12-26T08:30:28
| 159,047,402
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 550
|
py
|
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open('chart_file.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs, ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
|
[
"venkat.veerareddy@hotmail.com"
] |
venkat.veerareddy@hotmail.com
|
4d8c2d81ee6ea261b59ddb4eb91cb66024778ed6
|
ce607df215bd0569a966033092ae3d24f48af714
|
/docs/guide/code/awesome-bot-7/awesome/plugins/usage.py
|
825a57f9849268c8956a25255a3e924fee1d6840
|
[
"MIT"
] |
permissive
|
nonebot/nonebot
|
fbf926e77329fc129dd51a31cfcb62a8f4aab578
|
4b49289759af0ef774d28fd0ffaed7e1a9e35fbf
|
refs/heads/master
| 2023-08-16T00:01:06.288649
| 2023-06-01T08:44:04
| 2023-06-01T08:44:04
| 75,402,138
| 1,521
| 268
|
MIT
| 2022-08-17T06:07:19
| 2016-12-02T14:23:43
|
Python
|
UTF-8
|
Python
| false
| false
| 714
|
py
|
import nonebot
from nonebot import on_command, CommandSession
@on_command('usage', aliases=['使用帮助', '帮助', '使用方法'])
async def _(session: CommandSession):
# 获取设置了名称的插件列表
plugins = list(filter(lambda p: p.name, nonebot.get_loaded_plugins()))
arg = session.current_arg_text.strip().lower()
if not arg:
# 如果用户没有发送参数,则发送功能列表
await session.send(
'我现在支持的功能有:\n\n' + '\n'.join(p.name for p in plugins))
return
# 如果发了参数则发送相应命令的使用帮助
for p in plugins:
if p.name.lower() == arg:
await session.send(p.usage)
|
[
"richardchienthebest@gmail.com"
] |
richardchienthebest@gmail.com
|
8c36bd998975fdb247485f1edf6cec1b02d2fe58
|
f5d4863b6a62ef19ffc98e4f94f6ade1bc8810d3
|
/Linked List/92_Reverse_Linked_List_II.py
|
05f389e0d67f52c991bda6256be9df9eda403617
|
[] |
no_license
|
xiaomojie/LeetCode
|
138808eb83938f9bd3c2e8a755d908509dff0fd3
|
eedf73b5f167025a97f0905d3718b6eab2ee3e09
|
refs/heads/master
| 2021-06-12T09:26:01.257348
| 2019-10-23T10:41:06
| 2019-10-23T10:41:06
| 76,184,467
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 905
|
py
|
"""
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head:
return head
pre = dummy = ListNode(0)
dummy.next = head
for i in range(m-1):
pre = pre.next
start = pre.next
then = start.next
for i in range(m, n):
start.next = then.next
then.next = pre.next
pre.next = then
then = start.next
return dummy.next
|
[
"519399762@qq.com"
] |
519399762@qq.com
|
36e45f93482d35cb5c9a7c17abd4badb5d472b96
|
32257983a6aa9b6f719ce8835e789c94df8b9346
|
/manager/migrations/0001_initial.py
|
57184eafc16e89981afeb99c3c784f17cc78d511
|
[] |
no_license
|
alireza-shirmohammadi/MySite
|
2b165260460ea2a74769b0ceb81e520b26307a64
|
4537069f0ba50ac46f265d0157195f91bac5d853
|
refs/heads/master
| 2023-07-26T13:50:52.249782
| 2021-01-30T10:55:06
| 2021-01-30T10:55:06
| 303,093,825
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 651
|
py
|
# Generated by Django 2.2 on 2020-10-18 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Manager',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('lastname', models.CharField(max_length=50)),
('utext', models.TextField()),
('email', models.TextField(default='')),
],
),
]
|
[
"alireza.sh076@gmail.com"
] |
alireza.sh076@gmail.com
|
9d3aee1939e7056e99df2e8fa0513615f8dad64d
|
98c6ea9c884152e8340605a706efefbea6170be5
|
/examples/data/Assignment_5/mllgad001/question1.py
|
f6592b8f10857fa9939c268f718db83ab9bf37c1
|
[] |
no_license
|
MrHamdulay/csc3-capstone
|
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
|
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
|
refs/heads/master
| 2021-03-12T21:55:57.781339
| 2014-09-22T02:22:22
| 2014-09-22T02:22:22
| 22,372,174
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,801
|
py
|
# program to simulate a simple Bulletin Board System
# Gadija Moollagie
# 14 April 2014
def displayName(): # defines the menu that will be displayed every time
print("Welcome to UCT BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("(L)ist files")
print("(D)isplay file")
print("e(X)it")
def main():
while True: # continues through the loop body as long as expression remains true
displayName() # displays this through every iteration
selection = input("Enter your selection:\n") # displays this through every iteration
selection = selection.upper()
if selection == 'E':
message = input("Enter the message:\n")
elif selection == 'V':
try:
print("The message is:", message)
except(NameError):
print("The message is: no message yet")
# exception raised if there is a NameError and variable cannot be found
elif selection == 'L':
print("List of files: 42.txt, 1015.txt")
elif selection == 'D':
fileName = input("Enter the filename:\n")
if fileName == '42.txt':
print("The meaning of life is blah blah blah ...")
elif fileName == '1015.txt':
print("Computer Science class notes ... simplified")
print("Do all work")
print("Pass course")
print("Be happy")
else: # if fileName is not in list
print("File not found")
elif selection == 'X':
print("Goodbye!")
break # breaks out of loop
main()
|
[
"jarr2000@gmail.com"
] |
jarr2000@gmail.com
|
71987f9861827fdaa4915ab742137953ec85ddef
|
5baf3cb8b08dcea2d53d2ef022e5c6d4b2468494
|
/test/test_io_k8s_api_apps_v1_deployment_strategy.py
|
f56bb807af8c59d37eff53eb5135e7e72f41d20d
|
[] |
no_license
|
atengler/swagger-kqueen-python
|
a4fc0de38378a08c6c2e0c339032ed4ad63f09f5
|
01225c74a743636483211f0274f772193517ffaf
|
refs/heads/master
| 2021-08-07T18:16:28.453730
| 2017-11-08T17:24:53
| 2017-11-08T17:29:03
| 110,007,477
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,040
|
py
|
# coding: utf-8
"""
Kubernetes Queen API
A simple API to interact with Kubernetes clusters
OpenAPI spec version: 0.8
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import swagger_client
from swagger_client.rest import ApiException
from swagger_client.models.io_k8s_api_apps_v1_deployment_strategy import IoK8sApiAppsV1DeploymentStrategy
class TestIoK8sApiAppsV1DeploymentStrategy(unittest.TestCase):
""" IoK8sApiAppsV1DeploymentStrategy unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testIoK8sApiAppsV1DeploymentStrategy(self):
"""
Test IoK8sApiAppsV1DeploymentStrategy
"""
# FIXME: construct object with mandatory attributes with example values
#model = swagger_client.models.io_k8s_api_apps_v1_deployment_strategy.IoK8sApiAppsV1DeploymentStrategy()
pass
if __name__ == '__main__':
unittest.main()
|
[
"atengler@mirantis.com"
] |
atengler@mirantis.com
|
5c6074b51caf0a45af3c5c46d88fbaaddb811393
|
e1d6de1fb5ce02907df8fa4d4e17e61d98e8727d
|
/search2/lagou_query_range.py
|
ccacf67d6ac1eb4513901b1aca0d24fbce30db0d
|
[] |
no_license
|
neuroph12/nlpy
|
3f3d1a8653a832d6230cb565428ee0c77ef7451d
|
095976d144dacf07414bf7ee42b811eaa67326c1
|
refs/heads/master
| 2020-09-16T08:24:37.381353
| 2016-09-10T19:24:05
| 2016-09-10T19:24:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 881
|
py
|
# coding=utf-8
import datetime
from whoosh.index import open_dir
from whoosh.qparser import MultifieldParser
idx_dir = 'lagou_idx'
ix = open_dir(idx_dir)
searcher = ix.searcher()
parser = MultifieldParser(["name", "com_name"], schema=ix.schema)
# Single field parser.
k = u'自然 语言 自然语言 处理 salary_from:[1 TO 5000] salary_to:[ TO 5000] city:上海'
q = parser.parse(k)
today = datetime.datetime.now()
date_to = today
date_from = today + datetime.timedelta(days=-7)
print date_to.strftime('%Y%m%d')
print date_from.strftime('%Y%m%d')
results = searcher.search_page(q, 1, pagelen=30)
print(u'{0} results found for keyword {1}, {2} returned: '.format(len(results), k, results.scored_length()))
for hit in results[:50]:
print(hit['id'])
print(hit['name'])
print(hit['salary_from'], hit['salary_to'])
print(hit['date'])
print('************')
|
[
"anderscui@gmail.com"
] |
anderscui@gmail.com
|
840e123871abe4d70ae652e6987bb7fc4d6070e5
|
f6078890ba792d5734d289d7a0b1d429d945a03a
|
/hw1/submissions/reyesortegacynthia/reyesortegacynthia_35890_1251163_homework 2.py
|
cb61aa6481078c83a83132baf98896513680dbad
|
[] |
no_license
|
huazhige/EART119_Lab
|
1c3d0b986a0f59727ee4ce11ded1bc7a87f5b7c0
|
47931d6f6a2c7bc053cd15cef662eb2f2027712c
|
refs/heads/master
| 2020-05-04T23:40:53.709217
| 2019-06-11T18:30:45
| 2019-06-11T18:30:45
| 179,552,067
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 210
|
py
|
import matplotlib from matplotlib
import numpy as np
V_1 = (1,1)
V_2 = (3,1)
V_3 = (4,2)
V_4 = (3.5,5)
V_5 = (2,4)
A = area_of_polygon
#get number x or y in each v
#set area of ploygon as x_1*y_1
|
[
"hge2@ucsc.edu"
] |
hge2@ucsc.edu
|
8ec98c5c953c24f01a12563fcd3198185f008a6e
|
56014da6ebc817dcb3b7a136df8b11cf9f976d93
|
/Django天天生鲜项目/14.1-注册基本逻辑.py
|
939067bb95629536cb0337f2ca1fc38b2e11d8ce
|
[] |
no_license
|
sunday2146/notes-python
|
52b2441c981c1106e70a94b999e986999334239a
|
e19d2aee1aa9433598ac3c0a2a73b0c1e8fa6dc2
|
refs/heads/master
| 2022-01-12T22:55:45.401326
| 2019-01-18T03:18:26
| 2019-01-18T03:18:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,191
|
py
|
"""
1.将static静态文件添加到static文件夹中----为前端制作完成
2.将register.html文件放入templates文件夹下
3.views.py
def register(request):
""显示注册页面""
return render(request,'register.html')
4.配置url
from user import views
urlpatterns = [
url(r'^register$',views.register,name = 'register'),#注册
5.无法显示全部页面,须在register.html中增加
{% load staticfiles %}
并修改静态文件目录
{% load staticfiles %}
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>天天生鲜-注册</title> #修改处
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %} ">
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">
<script type="text/javascript" src="{% static 'js/jquery-1.12.4.min.js'%}"></script>
<script type="text/javascript" src="{% static 'js/register.js'%}"></script>
</head>
<body>
<div class="register_con">
<div class="l_con fl"> ##修改处
<a class="reg_logo"><img src="{% static 'images/logo02.png'%}"></a>
6.
<form method = "post" action = "user/register_handle">
{%csrf_token%}
"""
|
[
"964640116@qq.com"
] |
964640116@qq.com
|
cb398291bbb438e6bf0220616db35cda393e4eb2
|
254ef44b90485767a3aea8cbe77dc6bf77dddaeb
|
/589N叉树的前序遍历.py
|
767e3339554f17bf5d43e7c275cfe267c364da5a
|
[] |
no_license
|
XinZhaoFu/leetcode_moyu
|
fae00d52a52c090901021717df87b78d78192bdb
|
e80489923c60ed716d54c1bdeaaf52133d4e1209
|
refs/heads/main
| 2023-06-19T02:50:05.256149
| 2021-07-09T00:50:41
| 2021-07-09T00:50:41
| 331,243,022
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 676
|
py
|
"""
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :
返回其前序遍历: [1,3,5,6,2,4]。
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
self.res = []
def dfs(node):
if not node:
return 0
self.res.append(node.val)
for child in node.children:
dfs(child)
dfs(root)
return self.res
|
[
"948244817@qq.com"
] |
948244817@qq.com
|
f597844ce432d96d2774092744d6b634d89b6c85
|
45e376ae66b78b17788b1d3575b334b2cb1d0b1c
|
/tests/terraform/checks/resource/aws/test_CloudfrontDistributionDefaultRoot.py
|
d8d77e5bbb716f2cb97de4f4c46442fb83f1cd30
|
[
"Apache-2.0"
] |
permissive
|
bridgecrewio/checkov
|
aeb8febed2ed90e61d5755f8f9d80b125362644d
|
e64cbd27ffb6f09c2c9f081b45b7a821a3aa1a4d
|
refs/heads/main
| 2023-08-31T06:57:21.990147
| 2023-08-30T23:01:47
| 2023-08-30T23:01:47
| 224,386,599
| 5,929
| 1,056
|
Apache-2.0
| 2023-09-14T20:10:23
| 2019-11-27T08:55:14
|
Python
|
UTF-8
|
Python
| false
| false
| 1,337
|
py
|
import os
import unittest
from checkov.runner_filter import RunnerFilter
from checkov.terraform.checks.resource.aws.CloudfrontDistributionDefaultRoot import check
from checkov.terraform.runner import Runner
class TestCloudfrontDistributionDefaultRoot(unittest.TestCase):
def test(self):
runner = Runner()
current_dir = os.path.dirname(os.path.realpath(__file__))
test_files_dir = current_dir + "/example_CloudfrontDistributionDefaultRoot"
report = runner.run(root_folder=test_files_dir, runner_filter=RunnerFilter(checks=[check.id]))
summary = report.get_summary()
passing_resources = {
"aws_cloudfront_distribution.pass",
}
failing_resources = {
"aws_cloudfront_distribution.fail",
}
passed_check_resources = set([c.resource for c in report.passed_checks])
failed_check_resources = set([c.resource for c in report.failed_checks])
self.assertEqual(summary["passed"], 1)
self.assertEqual(summary["failed"], 1)
self.assertEqual(summary["skipped"], 0)
self.assertEqual(summary["parsing_errors"], 0)
self.assertEqual(passing_resources, passed_check_resources)
self.assertEqual(failing_resources, failed_check_resources)
if __name__ == "__main__":
unittest.main()
|
[
"noreply@github.com"
] |
bridgecrewio.noreply@github.com
|
16c4945708dd2b7588e59f769cc9178b68bbeade
|
f016dd6fd77bb2b135636f904748dbbab117d78b
|
/L07/视频笔记/4.4继承.py
|
c73e1dd32f1d67db92adfd7ce88c54ac9f2b604e
|
[
"Apache-2.0"
] |
permissive
|
w7374520/Coursepy
|
b3eddfbeeb475ce213b6f627d24547a1d36909d8
|
ac13f8c87b4c503135da51ad84c35c745345df20
|
refs/heads/master
| 2020-04-26T23:57:42.882813
| 2018-05-24T07:54:13
| 2018-05-24T07:54:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,539
|
py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:xp
#blog_url: http://blog.csdn.net/wuxingpu5/article/details/71209731
class Parent:
def foo(self):
print('from Parent.foo')
self.bar()
def bar(self):
print('From parent.bar')
class Sub(Parent):
def __init__(self):
pass
#self.bar=123 报错可以看出优先调用了自己的
def bar(self):
print('From Sub.bar')
s=Sub()
s.foo()
'''
执行结果
from Parent.foo
From Sub.bar
'''
#是否是示例 结果都为True
print(isinstance(s,Sub))
print(isinstance(s,Parent))
#继承反映的是一种什么是什么的关系
#--------------------------------------------------------------
#组合可以解决代码冗余问题 但是组合反映的是什么有什么的关系
class Date:
def __init__(self,year,mon,day):
self.year=year
self.mon=mon
self.day=day
def tell(self):
print('%s-%s-%s'%(self.year,self.mon,self.day))
class People:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
class Teacher(People):
def __init__(self,name,age,sex,salary,year,mon,day):
People.__init__(self,name,age,sex)
self.salary=salary
self.birth=Date(year,mon,day) #类的组合 老师有生日
class Student(People):
def __init__(self,name,age,sex,year,mon,day):
People.__init__(self,name,age,sex)
self.birth=Date(year,age,sex)
t=Teacher('eg',18,'male',3000,1954,12,21)
t.birth.tell()
|
[
"windfishing5@gmail.com"
] |
windfishing5@gmail.com
|
e0a0021b739a598d5e7da40233741d987a92d645
|
1040b320168c49e3fd784d93ff30923527582d26
|
/calm/dsl/api/quotas.py
|
172ca96fefdcfea68cac18e809db25579b1930c6
|
[
"Apache-2.0"
] |
permissive
|
nutanix/calm-dsl
|
87eb8a82f202ec0c71b5c8d8fe49db29bdcf2cfc
|
56c52702cec4370f551785508d284e5cbe1a744a
|
refs/heads/master
| 2023-08-31T16:43:51.009235
| 2023-08-28T05:20:41
| 2023-08-28T05:20:41
| 227,190,868
| 41
| 59
|
Apache-2.0
| 2023-08-28T05:20:43
| 2019-12-10T18:38:58
|
Python
|
UTF-8
|
Python
| false
| false
| 1,363
|
py
|
from .resource import ResourceAPI
from .connection import REQUEST
class QuotasAPI(ResourceAPI):
def __init__(self, connection):
super().__init__(connection, resource_type="quotas", calm_api=True)
self.CREATE = self.PREFIX
self.UPDATE_STATE = self.PREFIX + "/update/state"
self.LIST = self.PREFIX + "/list"
self.UPDATE = self.PREFIX + "/{}"
def update_state(self, payload):
return self.connection._call(
self.UPDATE_STATE,
verify=False,
request_json=payload,
method=REQUEST.METHOD.PUT,
timeout=(5, 300),
)
def list(self, payload):
return self.connection._call(
self.LIST,
verify=False,
request_json=payload,
method=REQUEST.METHOD.POST,
timeout=(5, 300),
)
def create(self, payload):
return self.connection._call(
self.CREATE,
verify=False,
request_json=payload,
method=REQUEST.METHOD.POST,
timeout=(5, 300),
)
def update(self, payload, quota_uuid):
return self.connection._call(
self.UPDATE.format(quota_uuid),
verify=False,
request_json=payload,
method=REQUEST.METHOD.PUT,
timeout=(5, 300),
)
|
[
"abhijeet.kaurav@nutanix.com"
] |
abhijeet.kaurav@nutanix.com
|
9362bfbe15c850ef4711769abd97cb5b1a358e37
|
f023692f73992354a0b7823d9c49ae730c95ab52
|
/AtCoderBeginnerContest/1XX/107/D_pypy.py
|
0cdd99bfb61357c3953e409610ae3e254b7b3a46
|
[] |
no_license
|
corutopi/AtCorder_python
|
a959e733f9a3549fab7162023e414ac2c99c4abe
|
a2c78cc647076071549e354c398155a65d5e331a
|
refs/heads/master
| 2023-08-31T09:40:35.929155
| 2023-08-20T06:19:35
| 2023-08-20T06:19:35
| 197,030,129
| 1
| 0
| null | 2022-06-22T04:06:28
| 2019-07-15T15:57:34
|
Python
|
UTF-8
|
Python
| false
| false
| 2,636
|
py
|
# 解説を参考に作成
# https://qiita.com/DaikiSuyama/items/7295f5160a51684554a7
# https://algo-logic.info/binary-indexed-tree/
# import sys
# sys.setrecursionlimit(10 ** 6)
# import bisect
# from collections import deque
class BinaryIndexedTree:
"""
l = [1, 2, 3, 4, 5, 6, 7, 8] のlistを例とした場合、
以下のような範囲での演算結果(sum)を配列に持つ。
1: [1, 2, 3, 4, 5, 6, 7, 8]
2: [1, 2, 3, 4]
3: [1, 2] [5, 6]
4: [1] [3] [5] [7]
1 ~ r までの結果S(r)を、各層で必要な演算済みのデータを使うことで log(N) で計算できる.
l ~ r までの結果は S(r) - S(l - 1) で同じくlog(N)計算できる.
データ構造の作成は N*log(N).
配列データは1始まりとして計算.
"""
def __init__(self, n):
"""
:param n: num of date.
"""
self.num = n
self.tree = [0] * (n + 1)
def add(self, k, x):
"""
:param k: [1, self.num]
:param x: add num.
:return: None
"""
while k <= self.num:
self.tree[k] += x
k += k & -k
def sum(self, k):
"""
1 ~ k までの合計
:param k:
:return:
"""
re = 0
while k > 0:
re += self.tree[k]
k -= k & -k
return re
def sum_lr(self, l, r):
"""
sum of form l to r
:param l: 1 <= l <= r
:param r: l <= r <= self.num
:return:
"""
return self.sum(r) - self.sum(l - 1)
# from decorator import stop_watch
#
#
# @stop_watch
def solve(N, A):
import math
sorted_A = sorted(A)
ok = 0
ng = len(sorted_A)
middle = math.ceil((N * (N + 1)) // 2 / 2)
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
tmp_A = [1 if a >= sorted_A[mid] else -1 for a in A]
sum_A = [0]
for a in tmp_A:
sum_A.append(sum_A[-1] + a)
tmp_m = min(sum_A)
up_A = [a - tmp_m + 1 for a in sum_A]
bit = BinaryIndexedTree(max(up_A))
over = 0
bit.add(up_A[0], 1)
for a in up_A[1:]:
over += bit.sum(a)
bit.add(a, 1)
if over >= middle:
ok = mid
else:
ng = mid
print(sorted_A[ok])
if __name__ == '__main__':
N = int(input())
A = [int(i) for i in input().split()]
solve(N, A)
# # test
# from random import randint
# from func import random_str
# N = 10 ** 5
# A = [randint(1, 10 ** 9) for _ in range(N)]
# solve(N, A)
|
[
"39874652+corutopi@users.noreply.github.com"
] |
39874652+corutopi@users.noreply.github.com
|
28c91f379d6f7e52de4f2d24f3ab989eb31b410d
|
c71b3aa6091d3cc0469198e64cd394fa9dae1817
|
/setup.py
|
f108ef64003f3065d39aab473ffa5fb5a93686e0
|
[
"MIT"
] |
permissive
|
offermann/elizabeth
|
8a30f65f93aee244437de4cd42084cb29607c724
|
3b89512e566895846136809e571abf50b93c5312
|
refs/heads/master
| 2020-01-23T21:40:46.324687
| 2016-11-23T07:21:03
| 2016-11-23T07:21:03
| 74,689,354
| 0
| 1
| null | 2016-11-24T16:27:52
| 2016-11-24T16:27:52
| null |
UTF-8
|
Python
| false
| false
| 1,385
|
py
|
from distutils.core import setup
import elizabeth
setup(
name='elizabeth',
version=elizabeth.__version__,
packages=['elizabeth'],
keywords=['fake', 'data', 'testing',
'generate', 'faker', 'elizabeth',
'bootstrap', 'db', 'generic',
'church', 'dummy'
],
package_data={
'elizabeth': [
'data/*/*',
]
},
url='https://github.com/lk-geimfari/elizabeth',
license='MIT',
author=elizabeth.__author__,
author_email='likid.geimfari@gmail.com',
description='Elizabeth is a library that help you generate fake data.',
long_description="Elizabeth (ex Church) is a library to generate fake data."
"It's very useful when you need to bootstrap "
"your database.",
classifiers=[
"Development Status :: 4 - Beta",
'Intended Audience :: Developers',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development',
'Topic :: Software Development :: Testing',
],
)
|
[
"likid.geimfari@gmail.com"
] |
likid.geimfari@gmail.com
|
2db441df96d69d4eda30cd22d74ee1b62a47205e
|
9680c27718346be69cf7695dba674e7a0ec662ca
|
/Pattern-Python/A shape.py
|
ad545c440e124919825e93bc861239a679658909
|
[] |
no_license
|
Md-Monirul-Islam/Python-code
|
5a2cdbe7cd3dae94aa63298b5b0ef7e0e31cd298
|
df98f37dd9d21784a65c8bb0e46d47a646259110
|
refs/heads/main
| 2023-01-19T05:15:04.963904
| 2020-11-19T06:10:09
| 2020-11-19T06:10:09
| 314,145,135
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 218
|
py
|
for row in range(7):
for col in range(5):
if ((col==0 or col==4) and row!=0) or ((row==0 or row==3) and (col>0 and col<4)):
print('*',end='')
else:
print(end=' ')
print()
|
[
"61861844+Md-Monirul-Islam@users.noreply.github.com"
] |
61861844+Md-Monirul-Islam@users.noreply.github.com
|
687e72bc28d39ba17e95104a1d67e294b817f16e
|
92993cff825da80a8ff601572a0c52b0b7d3cbde
|
/algorithms/Svm/ADMM/L1/ADMM_L1_m162.py
|
47a9f8d3349521c04157398120ef42791fb5ac66
|
[] |
no_license
|
yingzhuoy/MRs-of-linear-models
|
06e8b1f84b08c6aa77553813824cf35c1806c5a7
|
c3df8299e039a12613f2022b370b8c3e9c2dd822
|
refs/heads/master
| 2023-04-07T23:09:37.736952
| 2021-04-04T05:33:37
| 2021-04-04T05:33:37
| 265,124,549
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,222
|
py
|
import numpy as np
from numpy import linalg
#import cvxopt
#from cvxopt import matrix,solvers
#import scipy.sparse.linalg
from algorithms.clf import Clf
"""
Preconditioned Conjugate Gradient Method
"""
def precond(M, r):
q = M * r
return q
def inner_prod(A, B):
A = np.matrix(A)
B = np.matrix(B)
return np.dot(A.reshape(-1,1).T, B.reshape(-1,1))
def cg(A, b, x=None, tol=1.0e-6, max_iter=128):
# precondition
A = np.matrix(A)
b = np.matrix(b)
normb = np.linalg.norm(b, 'fro')
m = b.shape[0]
M = np.eye(m)
x = np.zeros((m, m))
Aq = (A*x)
r = b - Aq # m x m
q = precond(M, r) # m x m
tau_old = np.linalg.norm(q, 'fro')
rho_old = inner_prod(r, q)
theta_old = 0
Ad = np.zeros((m, m))
d = np.zeros((m, m))
res = r.reshape(m, m)
tiny = 1e-30
for i in range(max_iter):
Aq = A * q
sigma = inner_prod(q, Aq)
if abs(sigma.item()) < tiny:
break
else:
alpha = rho_old / sigma;
alpha = alpha.item()
r = r - alpha * Aq
r = r.reshape(m, m)
u = precond(M, r)
theta = np.linalg.norm(u,'fro')/tau_old
c = 1 / np.sqrt(1+theta*theta)
tau = tau_old * theta * c
gam = c*c*theta_old*theta_old
eta = c*c*alpha
d = gam * d + eta * q
x = x + d
# stop
Ad = gam*Ad+eta*Aq
res = res - Ad
if np.linalg.norm(res, 'fro') < tol*normb:
break
else:
rho = inner_prod(r, u)
beta = rho / rho_old
beta = beta.item()
q = u + beta * q
rho_old = rho
tau_old = tau
theta_old = theta
return x
def admm(X, y, max_iter=3000):
# solve by inner point method
m, n = X.shape
X = np.column_stack((X, np.ones((m, 1))))
y = y.astype(np.float64)
data_num = len(y)
C = 1.0
kernel = np.dot(X, np.transpose(X))
p = np.matrix(np.multiply(kernel,np.outer(y, y)))
e = np.matrix(np.ones([data_num, 1], np.float64))
bounds = (0, C)
low, up = bounds
x = np.ones((m,1))
tau = 1.618
sigma = 1
# initial
u = np.ones((m, 1))
t = x
A = p + sigma * np.eye(m)
I = np.eye(m)
invA = cg(A, I)
for it in range(max_iter):
# update x
b = e + u + sigma * t
x = invA * b
# update y
t = x - (1/sigma)*u
t[t < low] = low
t[t > up] = up
# update u
u = u - tau*sigma*(x-t)
dual = -(0.5*x.T*(p*x) - e.T*x)
dual = dual.item()
#----bug----
#y1 = np.reshape(y, (-1, 1))
y1 = np.reshape(y+0.06721138118143437, (-1, 1))
lambda1 = np.multiply(x, y1)
w = np.dot(X.T, lambda1)
w = np.matrix(w).reshape(-1, 1)
tmp = np.maximum(1-np.multiply(y1, X*w),0)
primal = 0.5*np.linalg.norm(w)**2 + 1 * np.sum(tmp)
primal = primal.item()
# stop criteria
if np.abs(dual-primal)/(1+np.abs(dual)+np.abs(primal)) < 1e-12:
break
# print(t, np.linalg.norm(gradient))
# print(np.min(x), np.max(x))
# print(np.sum(x < -1e-4), np.sum(x>1+1e-4))
# print(np.abs(dual-primal)/(1+np.abs(dual)+np.abs(primal)))
#----bug----
#y1 = np.reshape(y, (-1, 1))
y1 = np.reshape(y+0.06721138118143437, (-1, 1))
alpha1 = x
lambda1 = np.multiply(y1,alpha1)
w = np.dot(X.T, lambda1)
w = np.array(w).reshape(-1)
b = w[n]
w = w[0:n]
return w, b
#L1-svm
class ADMM_L1_m162():
def fit(self, X, y):
y[y == 0] = -1
# add logitR to verify the correctness
#from sklearn.svm import LinearSVC
#SVM = LinearSVC(loss='hinge', tol=1e-6, max_iter=100000, verbose=1).fit(X, np.array(y).ravel())
#w1 = SVM.coef_; b1 = SVM.intercept_
#w1 = w1.reshape(-1); b1 = b1[0]
#import time
#t1 = time.time()
w, b = admm(X, y)
#t2 = time.time()
#print('time:', t2-t1)
#print('diff', np.linalg.norm(w1-w), b, b1)
clf = Clf(w, b)
return clf
|
[
"yingzhuoy@qq.com"
] |
yingzhuoy@qq.com
|
5cb4bea24ec8cb56b25d43314f597cbdc352b4cc
|
e749e94163a0e20c551875583baef4e02e72de5e
|
/Github/IPS-10/test_script.py
|
e65add9190f155013f39296105ebadd5a65a640f
|
[] |
no_license
|
tritims/TensorFlow-Program-Bugs
|
3445200179f4b7f5cc4ac1c6f076468ec19e51bb
|
158ba0a23e0cb74e73dbab08571b05fc36848f2a
|
refs/heads/master
| 2022-07-08T16:33:38.511696
| 2020-05-20T14:20:47
| 2020-05-20T14:20:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 811
|
py
|
import tensorflow as tf
import sys
import os
import subprocess
try:
assert len(sys.argv) == 2
version = ["-buggy", "-fix"][int(sys.argv[1])]
except:
print(
"Please run 'python test_script 0' for testing the buggy-version and "
"'python test_script 1' for testing the fix-version.\nAborted...")
exit(1)
interpreter_path = sys.executable
print("Running at: ", interpreter_path)
assert tf.__version__ == "1.8.0"
def get_target_dir():
for x in os.listdir(os.path.dirname(os.path.abspath(__file__))):
if version in x:
return x
raise ValueError("No dir ends with %s!" % version)
subprocess.call(
[interpreter_path, "./%s/src/train_softmax.py" % get_target_dir(), "--data_dir", "./data/test", "--max_nrof_epochs",
"5", "--epoch_size", "50"])
|
[
"zyhzyhzyh@pku.edu.cn"
] |
zyhzyhzyh@pku.edu.cn
|
09900557e13191fe7b23e98ddf0f10fc11d17428
|
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
|
/alipay/aop/api/response/AlipayFundJointaccountAccountModifyResponse.py
|
58d20e1c923c22e32b35d37c8b7fca6babba5937
|
[
"Apache-2.0"
] |
permissive
|
alipay/alipay-sdk-python-all
|
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
|
1fad300587c9e7e099747305ba9077d4cd7afde9
|
refs/heads/master
| 2023-08-27T21:35:01.778771
| 2023-08-23T07:12:26
| 2023-08-23T07:12:26
| 133,338,689
| 247
| 70
|
Apache-2.0
| 2023-04-25T04:54:02
| 2018-05-14T09:40:54
|
Python
|
UTF-8
|
Python
| false
| false
| 470
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundJointaccountAccountModifyResponse(AlipayResponse):
def __init__(self):
super(AlipayFundJointaccountAccountModifyResponse, self).__init__()
def parse_response_content(self, response_content):
response = super(AlipayFundJointaccountAccountModifyResponse, self).parse_response_content(response_content)
|
[
"jishupei.jsp@alibaba-inc.com"
] |
jishupei.jsp@alibaba-inc.com
|
183e2af0650d8c37d8a20a17832530637e0782da
|
d18c9e4bccc85d3c5770515966ce9866f8bc39dc
|
/tests/test_stream_xep_0077.py
|
c47c4de5941515e66302ac4bad41a3d39db6f0b6
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
dhsc19/slixmpp
|
fa1192e05477ebff1ab1fcf92389f75c6a66e30f
|
2ba89727a6627f86e66ec4f3baba464da1b0b19c
|
refs/heads/master
| 2023-03-07T14:27:33.863558
| 2021-02-19T18:06:41
| 2021-02-19T18:06:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,044
|
py
|
"""
This only covers the component registration side of the XEP-0077 plugin
"""
import unittest
from slixmpp import ComponentXMPP, Iq
from slixmpp.xmlstream import register_stanza_plugin
from slixmpp.test import SlixTest
from slixmpp.plugins.xep_0077 import Register
class TestRegistration(SlixTest):
def setUp(self):
self.stream_start(
mode="component", plugins=["xep_0077"], jid="shakespeare.lit", server="lit"
)
def testRegistrationForm(self):
self.stream_start(
mode="component", plugins=["xep_0077"], jid="shakespeare.lit", server="lit"
)
self.recv(
"""
<iq type='get' id='reg1' to='shakespeare.lit' from='bill@server/resource'>
<query xmlns='jabber:iq:register'/>
</iq>
""",
)
self.send(
f"""
<iq type='result' id='reg1' from='shakespeare.lit' to='bill@server/resource'>
<query xmlns='jabber:iq:register'>
<instructions>{self.xmpp["xep_0077"].form_instructions}</instructions>
<username/>
<password/>
</query>
</iq>
""",
use_values=False # Fails inconsistently without this
)
def testRegistrationSuccessAndModif(self):
self.recv(
"""
<iq type='set' id='reg2' to='shakespeare.lit' from="bill@server/resource">
<query xmlns='jabber:iq:register'>
<username>bill</username>
<password>Calliope</password>
</query>
</iq>
"""
)
self.send("<iq type='result' id='reg2' from='shakespeare.lit' to='bill@server/resource'/>")
user_store = self.xmpp["xep_0077"]._user_store
self.assertEqual(user_store["bill@server"]["username"], "bill")
self.assertEqual(user_store["bill@server"]["password"], "Calliope")
self.recv(
"""
<iq type='get' id='reg1' to='shakespeare.lit' from="bill@server/resource">
<query xmlns='jabber:iq:register'/>
</iq>
""",
)
self.send(
f"""
<iq type='result' id='reg1' to="bill@server/resource" from='shakespeare.lit'>
<query xmlns='jabber:iq:register'>
<instructions>{self.xmpp["xep_0077"].form_instructions}</instructions>
<username>bill</username>
<password>Calliope</password>
<registered />
</query>
</iq>
""",
use_values=False # Fails inconsistently without this
)
def testRegistrationAndRemove(self):
self.recv(
"""
<iq type='set' id='reg2' to='shakespeare.lit' from="bill@shakespeare.lit/globe">
<query xmlns='jabber:iq:register'>
<username>bill</username>
<password>Calliope</password>
</query>
</iq>
"""
)
self.send("<iq type='result' id='reg2' from='shakespeare.lit' to='bill@shakespeare.lit/globe'/>")
pseudo_iq = self.xmpp.Iq()
pseudo_iq["from"] = "bill@shakespeare.lit/globe"
user = self.xmpp["xep_0077"].api["user_get"](None, None, None, pseudo_iq)
self.assertEqual(user["username"], "bill")
self.assertEqual(user["password"], "Calliope")
self.recv(
"""
<iq type='set' from='bill@shakespeare.lit/globe' id='unreg1'>
<query xmlns='jabber:iq:register'>
<remove/>
</query>
</iq>
"""
)
self.send("<iq type='result' to='bill@shakespeare.lit/globe' id='unreg1'/>")
user_store = self.xmpp["xep_0077"]._user_store
self.assertIs(user_store.get("bill@shakespeare.lit"), None)
suite = unittest.TestLoader().loadTestsFromTestCase(TestRegistration)
|
[
"mathieui@mathieui.net"
] |
mathieui@mathieui.net
|
c75f84f20e771674176cbd904fd7adf259635e28
|
758ac341257ea099e678fd08830a7b95f5d85e59
|
/tc_gan/networks/tests/test_euler_ssn.py
|
0faf3937702d1e05a5834e3d49e983876d109aa7
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ahmadianlab/tc-gan
|
98d17e087e89d70bc571cb35e7e7b035e87ca0f2
|
06c549e8ae74bc6af62fddeed698565ea1f548c5
|
refs/heads/master
| 2020-04-12T16:52:15.051511
| 2018-12-21T01:06:53
| 2018-12-21T01:06:53
| 162,626,424
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,577
|
py
|
import copy
import numpy
import pytest
from ... import ssnode
from ...utils import report_allclose_tols
from ..fixed_time_sampler import new_JDS
from ..ssn import BandwidthContrastStimulator, EulerSSNModel
from ..wgan import DEFAULT_PARAMS, grid_stimulator_inputs
def make_ssn(model_config):
kwds = dict(model_config)
kwds.pop('bandwidths', None)
kwds.pop('contrasts', None)
kwds.pop('sample_sites', None)
kwds.pop('batchsize', None)
kwds.pop('gen', None)
kwds.pop('disc', None)
stimulator, kwds = BandwidthContrastStimulator.consume_kwargs(**kwds)
model, kwds = EulerSSNModel.consume_kwargs(stimulator, **kwds)
assert not kwds
return model
JDS = copy.deepcopy(new_JDS)
@pytest.mark.parametrize('num_sites, batchsize', [
(10, 1),
(10, 2),
# (10, 100), # worked, but slow (~18 sec)
# (201, 100), # worked, but very slow
])
def test_compare_with_ssnode(num_sites, batchsize,
seqlen=4000, rtol=5e-4, atol=5e-4):
seed = num_sites * batchsize # let's co-vary seed as well
bandwidths = DEFAULT_PARAMS['bandwidths']
contrasts = DEFAULT_PARAMS['contrasts']
stimulator_contrasts, stimulator_bandwidths \
= grid_stimulator_inputs(contrasts, bandwidths, batchsize)
num_tcdom = stimulator_bandwidths.shape[-1]
skip_steps = seqlen - 1
model = make_ssn(dict(
DEFAULT_PARAMS,
num_sites=num_sites,
num_tcdom=num_tcdom,
seqlen=seqlen,
skip_steps=skip_steps,
**JDS
))
# ssnode_fps.shape: (batchsize, num_tcdom, 2N)
zs, ssnode_fps, info = ssnode.sample_fixed_points(
batchsize,
N=num_sites,
bandwidths=bandwidths,
contrast=contrasts,
seed=seed,
io_type=model.io_type,
atol=1e-10,
**JDS
)
# time_avg.shape: (batchsize, num_tcdom, 2N)
time_avg = model.compute_time_avg(
zs=zs,
stimulator_bandwidths=stimulator_bandwidths,
stimulator_contrasts=stimulator_contrasts)
report_allclose_tols(time_avg, ssnode_fps,
rtols=[1e-2, 1e-3, 5e-4, 1e-4],
atols=[1e-2, 1e-3, 5e-4, 1e-4])
numpy.testing.assert_allclose(time_avg, ssnode_fps, rtol=rtol, atol=atol)
@pytest.mark.parametrize('num_sites, batchsize', [
(201, 1),
# (201, 100), # worked, but very slow
(10, 100),
])
def test_compare_with_ssnode_slowtest(num_sites, batchsize):
test_compare_with_ssnode(num_sites, batchsize,
seqlen=10000, rtol=1e-4)
|
[
"aka.tkf@gmail.com"
] |
aka.tkf@gmail.com
|
6fd7ab16aec3e11a12f934268050bab75d09ea8b
|
562d4bf000dbb66cd7109844c972bfc00ea7224c
|
/addons/efact/models/account/account_move.py
|
f03773b2e4e3da25665a8331f5175c34c931716c
|
[] |
no_license
|
Mohamed33/odoo-efact-11-pos
|
e9da1d17b38ddfe5b2d0901b3dbadf7a76bd2059
|
de38355aea74cdc643a347f7d52e1d287c208ff8
|
refs/heads/master
| 2023-03-10T15:24:44.052883
| 2021-03-06T13:25:58
| 2021-03-06T13:25:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,523
|
py
|
from odoo import api,fields,models,_
from odoo.exceptions import UserError, ValidationError
class AccountMove(models.Model):
_inherit = ['account.move']
@api.multi
def post(self):
invoice = self._context.get('invoice', False)
self._post_validate()
for move in self:
move.line_ids.create_analytic_lines()
if move.name == '/':
new_name = False
journal = move.journal_id
if invoice and invoice.move_name and invoice.move_name != '/':
new_name = invoice.move_name
else:
if journal.sequence_id:
# If invoice is actually refund and journal has a refund_sequence then use that one or use the regular one
sequence = journal.sequence_id
if invoice and invoice.type in ['out_refund', 'in_refund'] and journal.refund_sequence:
if not journal.refund_sequence_id:
raise UserError(_('Please define a sequence for the credit notes'))
sequence = journal.refund_sequence_id
new_name = sequence.with_context(ir_sequence_date=move.date).next_by_id()
else:
raise UserError(_('Please define a sequence on the journal.'))
if new_name:
move.name = new_name
return self.write({'state': 'posted'})
|
[
"root@vmi414107.contaboserver.net"
] |
root@vmi414107.contaboserver.net
|
5097e022046f18b13e5260b89c8f292eb264a408
|
967056372d123ad5a86705156aea928d7352fe6a
|
/python实战/pytesttraining/src/ut/test_module.py
|
a20576ceafeee7df7faaa7acddff08cce684ca89
|
[] |
no_license
|
lxy39678/Python
|
ea179ef929eb9ddddb2460656aad07880ae67f84
|
aba0434bc8ca7a2abdaa3ced3c4d84a8de819c61
|
refs/heads/master
| 2020-04-18T22:05:11.683134
| 2019-01-27T07:49:09
| 2019-01-27T07:49:09
| 167,783,919
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 902
|
py
|
#!/usr/bin/env python
# encoding: utf-8
#author: Jim Yin
import unittest
import logging
def setUpModule():
print("setup method\n")
global foo
foo = list(range(10))
class simple_test(unittest.TestCase):
def test_1st(self):
logging.info('info')
logging.error('error')
print('simple_test1_1'+str(foo))
self.assertEqual(foo.pop(), 9)
def test_2nd(self):
print('simple_test1_2' + str(foo))
self.assertEqual(foo.pop(), 8)
class simple_test2(unittest.TestCase):
def test_1st(self):
#foo=[0,....,,,7]
print('simple_test2_1' + str(foo))
self.assertEqual(foo.pop(), 7)
def test_2nd(self):
print('simple_test2_2' + str(foo))
self.assertNotEqual(1.1,1.0)
def tearDownModule():
print("end method")
if __name__ == '__main__':
unittest.main()
|
[
"895902857@qq.com"
] |
895902857@qq.com
|
e2997c7f2c9473f23e58fc3b9d8e197a81943c02
|
16e842bcb73638586d93c17e9838fb89bc2b60bc
|
/Module-13/13.1 Django Framework/django-model-forms/Django-Demos-feature-django-model-forms/model_form_project/model_app/models.py
|
7aed7bad4cb083d98332cb7a9d1e9a1f370c6161
|
[] |
no_license
|
krupa-thakkar/Python
|
dcbda2fe8296ffdd25641cf1e039132f41e0e44e
|
cbf0ec0399084a9a0a4ba5cebe739580bff4ce06
|
refs/heads/master
| 2023-03-24T05:43:58.799704
| 2021-01-25T06:20:44
| 2021-01-25T06:20:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 271
|
py
|
from django.db import models
class UserDetails(models.Model):
Firstname = models.CharField(max_length=100)
Lastname = models.CharField(max_length=255)
Mobile = models.CharField(max_length=11,default='123')
def __str__(self):
return self.title
|
[
"47570231+enji-coder@users.noreply.github.com"
] |
47570231+enji-coder@users.noreply.github.com
|
e692d7540ebbcd152e9cb9b958002b5c933ad7ec
|
eef72818143c9ffef4c759a1331e8227c14be792
|
/sktime/forecasting/online_learning/tests/test_online_learning.py
|
151298059c33206969c1a11bb443b9eb09866944
|
[
"BSD-3-Clause"
] |
permissive
|
jattenberg/sktime
|
66a723d7844146ac1675d2e4e73f35a486babc65
|
fbe4af4d8419a01ada1e82da1aa63c0218d13edb
|
refs/heads/master
| 2023-08-12T07:32:22.462661
| 2022-08-16T10:19:22
| 2022-08-16T10:19:22
| 298,256,169
| 0
| 0
|
BSD-3-Clause
| 2020-09-24T11:20:23
| 2020-09-24T11:20:23
| null |
UTF-8
|
Python
| false
| false
| 3,221
|
py
|
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Test OnlineEnsembleForecaster."""
__author__ = ["magittan"]
import numpy as np
from sklearn.metrics import mean_squared_error
from sktime.datasets import load_airline
from sktime.forecasting.exp_smoothing import ExponentialSmoothing
from sktime.forecasting.model_selection import (
SlidingWindowSplitter,
temporal_train_test_split,
)
from sktime.forecasting.naive import NaiveForecaster
from sktime.forecasting.online_learning._online_ensemble import OnlineEnsembleForecaster
from sktime.forecasting.online_learning._prediction_weighted_ensembler import (
NNLSEnsemble,
NormalHedgeEnsemble,
)
cv = SlidingWindowSplitter(start_with_window=True, window_length=1, fh=1)
def test_weights_for_airline_averaging():
"""Test weights."""
y = load_airline()
y_train, y_test = temporal_train_test_split(y)
forecaster = OnlineEnsembleForecaster(
[
("ses", ExponentialSmoothing(seasonal="multiplicative", sp=12)),
(
"holt",
ExponentialSmoothing(
trend="add", damped_trend=False, seasonal="multiplicative", sp=12
),
),
(
"damped_trend",
ExponentialSmoothing(
trend="add", damped_trend=True, seasonal="multiplicative", sp=12
),
),
]
)
forecaster.fit(y_train)
expected = np.array([1 / 3, 1 / 3, 1 / 3])
np.testing.assert_allclose(forecaster.weights, expected, rtol=1e-8)
def test_weights_for_airline_normal_hedge():
"""Test weights."""
y = load_airline()
y_train, y_test = temporal_train_test_split(y)
hedge_expert = NormalHedgeEnsemble(n_estimators=3, loss_func=mean_squared_error)
forecaster = OnlineEnsembleForecaster(
[
("av5", NaiveForecaster(strategy="mean", window_length=5)),
("av10", NaiveForecaster(strategy="mean", window_length=10)),
("av20", NaiveForecaster(strategy="mean", window_length=20)),
],
ensemble_algorithm=hedge_expert,
)
forecaster.fit(y_train)
forecaster.update_predict(y=y_test, cv=cv, reset_forecaster=False)
expected = np.array([0.17077154, 0.48156709, 0.34766137])
np.testing.assert_allclose(forecaster.weights, expected, atol=1e-8)
def test_weights_for_airline_nnls():
"""Test weights."""
y = load_airline()
y_train, y_test = temporal_train_test_split(y)
hedge_expert = NNLSEnsemble(n_estimators=3, loss_func=mean_squared_error)
forecaster = OnlineEnsembleForecaster(
[
("av5", NaiveForecaster(strategy="mean", window_length=5)),
("av10", NaiveForecaster(strategy="mean", window_length=10)),
("av20", NaiveForecaster(strategy="mean", window_length=20)),
],
ensemble_algorithm=hedge_expert,
)
forecaster.fit(y_train)
forecaster.update_predict(y=y_test, cv=cv, reset_forecaster=False)
expected = np.array([0.04720766, 0, 1.03410876])
np.testing.assert_allclose(forecaster.weights, expected, atol=1e-8)
|
[
"noreply@github.com"
] |
jattenberg.noreply@github.com
|
baf86efde77e669c26a16a2636a47d246e9c6551
|
724d4b6d4d7a834f138b6fe620db30fb9e0fb686
|
/design_principles/modularity_tutorial/parametrized_ml.py
|
ba372e0e5dd4f6b499090803355b13bba47bd53c
|
[] |
no_license
|
spierre91/medium_code
|
0b1d9b8c683b7432d7b1bfb980f436c1afb6e61f
|
0ad618b7a557083216e77717705bc49aa847b17e
|
refs/heads/master
| 2023-09-04T11:03:59.291613
| 2023-08-16T22:18:02
| 2023-08-16T22:18:02
| 214,266,919
| 85
| 80
| null | 2022-08-06T05:56:10
| 2019-10-10T19:20:05
|
Python
|
UTF-8
|
Python
| false
| false
| 2,443
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 9 15:22:18 2023
@author: sadrach.pierre
"""
import numpy as np
import pandas as pd
import catboost as cb
import seaborn as sns
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import confusion_matrix, precision_score, accuracy_score
import matplotlib.pyplot as plt
# Step 1: Read in the data
data = pd.read_csv('synthetic_transaction_data_Dining.csv')
# Step 2: Define the list of merchant states
MERCHANT_STATES = ['New York', 'Florida']
# Step 3: Iterate over merchant states, perform model training and evaluation
cats = ['cardholder_name', 'card_number', 'card_type', 'merchant_name', 'merchant_category',
'merchant_state', 'merchant_city', 'merchant_category_code']
for state in MERCHANT_STATES:
print("Evaluation for '{}' data:".format(state))
# Filter data frames for the current state
filtered_data = data[data['merchant_state'] == state]
# Split the data into training and testing sets
X = filtered_data[['cardholder_name', 'card_number', 'card_type', 'merchant_name', 'merchant_category',
'merchant_state', 'merchant_city', 'transaction_amount', 'merchant_category_code']]
y = filtered_data['fraud_flag']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Perform hyperparameter tuning with grid search and build the model
param_grid = {
'depth': [4, 6, 8],
'learning_rate': [0.01, 0.05, 0.1],
'iterations': [100, 200, 300]
}
model = cb.CatBoostClassifier(cat_features=cats, random_state=42)
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3)
grid_search.fit(X_train, y_train)
best_params = grid_search.best_params_
model = cb.CatBoostClassifier(cat_features=X.columns, random_state=42, **best_params)
model.fit(X_train, y_train)
# Evaluate the model
predictions = model.predict(X_test)
precision = precision_score(y_test, predictions)
accuracy = accuracy_score(y_test, predictions)
print('Precision:', precision)
print('Accuracy:', accuracy)
# Visualize the confusion matrix
cm = confusion_matrix(y_test, predictions)
sns.heatmap(cm, annot=True, cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
print('\n')
|
[
"noreply@github.com"
] |
spierre91.noreply@github.com
|
951505c501fbaadeb5da86e0a7e8d1942d24ca8c
|
0ba7a4571720e8e8af2944ed61fae7542b1fd556
|
/plugins/modules/influxdb_user.py
|
4080c1da7750743aeb3661988c34d375e3138a3e
|
[] |
no_license
|
ansible-collection-migration/database.influxdb
|
1395a40bb2f27482465f1ab190c9275d6cb1bceb
|
81f060e5e02d1e0fa8a0679f45650c6f21ed4cb4
|
refs/heads/master
| 2020-12-18T13:02:11.364756
| 2020-02-03T21:58:43
| 2020-02-03T21:58:43
| 235,393,063
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,106
|
py
|
#!/usr/bin/python
# (c) 2017, Vitaliy Zhhuta <zhhuta () gmail.com>
# insipred by Kamil Szczygiel <kamil.szczygiel () intel.com> influxdb_database module
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: influxdb_user
short_description: Manage InfluxDB users
description:
- Manage InfluxDB users
author: "Vitaliy Zhhuta (@zhhuta)"
requirements:
- "python >= 2.6"
- "influxdb >= 0.9"
options:
user_name:
description:
- Name of the user.
required: True
user_password:
description:
- Password to be set for the user.
required: false
admin:
description:
- Whether the user should be in the admin role or not.
- Since version 2.8, the role will also be updated.
default: no
type: bool
state:
description:
- State of the user.
choices: [ present, absent ]
default: present
grants:
description:
- Privileges to grant to this user. Takes a list of dicts containing the
"database" and "privilege" keys.
- If this argument is not provided, the current grants will be left alone.
If an empty list is provided, all grants for the user will be removed.
extends_documentation_fragment:
- database.influxdb.influxdb
'''
EXAMPLES = '''
- name: Create a user on localhost using default login credentials
influxdb_user:
user_name: john
user_password: s3cr3t
- name: Create a user on localhost using custom login credentials
influxdb_user:
user_name: john
user_password: s3cr3t
login_username: "{{ influxdb_username }}"
login_password: "{{ influxdb_password }}"
- name: Create an admin user on a remote host using custom login credentials
influxdb_user:
user_name: john
user_password: s3cr3t
admin: yes
hostname: "{{ influxdb_hostname }}"
login_username: "{{ influxdb_username }}"
login_password: "{{ influxdb_password }}"
- name: Create a user on localhost with privileges
influxdb_user:
user_name: john
user_password: s3cr3t
login_username: "{{ influxdb_username }}"
login_password: "{{ influxdb_password }}"
grants:
- database: 'collectd'
privilege: 'WRITE'
- database: 'graphite'
privilege: 'READ'
- name: Destroy a user using custom login credentials
influxdb_user:
user_name: john
login_username: "{{ influxdb_username }}"
login_password: "{{ influxdb_password }}"
state: absent
'''
RETURN = '''
#only defaults
'''
from ansible.module_utils.urls import ConnectionError
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
import ansible_collections.database.influxdb.plugins.module_utils.influxdb as influx
def find_user(module, client, user_name):
user_result = None
try:
users = client.get_list_users()
for user in users:
if user['user'] == user_name:
user_result = user
break
except (ConnectionError, influx.exceptions.InfluxDBClientError) as e:
module.fail_json(msg=to_native(e))
return user_result
def check_user_password(module, client, user_name, user_password):
try:
client.switch_user(user_name, user_password)
client.get_list_users()
except influx.exceptions.InfluxDBClientError as e:
if e.code == 401:
return False
except ConnectionError as e:
module.fail_json(msg=to_native(e))
finally:
# restore previous user
client.switch_user(module.params['username'], module.params['password'])
return True
def set_user_password(module, client, user_name, user_password):
if not module.check_mode:
try:
client.set_user_password(user_name, user_password)
except ConnectionError as e:
module.fail_json(msg=to_native(e))
def create_user(module, client, user_name, user_password, admin):
if not module.check_mode:
try:
client.create_user(user_name, user_password, admin)
except ConnectionError as e:
module.fail_json(msg=to_native(e))
def drop_user(module, client, user_name):
if not module.check_mode:
try:
client.drop_user(user_name)
except influx.exceptions.InfluxDBClientError as e:
module.fail_json(msg=e.content)
module.exit_json(changed=True)
def set_user_grants(module, client, user_name, grants):
changed = False
try:
current_grants = client.get_list_privileges(user_name)
# Fix privileges wording
for i, v in enumerate(current_grants):
if v['privilege'] == 'ALL PRIVILEGES':
v['privilege'] = 'ALL'
current_grants[i] = v
elif v['privilege'] == 'NO PRIVILEGES':
del(current_grants[i])
# check if the current grants are included in the desired ones
for current_grant in current_grants:
if current_grant not in grants:
if not module.check_mode:
client.revoke_privilege(current_grant['privilege'],
current_grant['database'],
user_name)
changed = True
# check if the desired grants are included in the current ones
for grant in grants:
if grant not in current_grants:
if not module.check_mode:
client.grant_privilege(grant['privilege'],
grant['database'],
user_name)
changed = True
except influx.exceptions.InfluxDBClientError as e:
module.fail_json(msg=e.content)
return changed
def main():
argument_spec = influx.InfluxDb.influxdb_argument_spec()
argument_spec.update(
state=dict(default='present', type='str', choices=['present', 'absent']),
user_name=dict(required=True, type='str'),
user_password=dict(required=False, type='str', no_log=True),
admin=dict(default='False', type='bool'),
grants=dict(type='list')
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
state = module.params['state']
user_name = module.params['user_name']
user_password = module.params['user_password']
admin = module.params['admin']
grants = module.params['grants']
influxdb = influx.InfluxDb(module)
client = influxdb.connect_to_influxdb()
user = find_user(module, client, user_name)
changed = False
if state == 'present':
if user:
if not check_user_password(module, client, user_name, user_password) and user_password is not None:
set_user_password(module, client, user_name, user_password)
changed = True
try:
if admin and not user['admin']:
client.grant_admin_privileges(user_name)
changed = True
elif not admin and user['admin']:
client.revoke_admin_privileges(user_name)
changed = True
except influx.exceptions.InfluxDBClientError as e:
module.fail_json(msg=to_native(e))
else:
user_password = user_password or ''
create_user(module, client, user_name, user_password, admin)
changed = True
if grants is not None:
if set_user_grants(module, client, user_name, grants):
changed = True
module.exit_json(changed=changed)
if state == 'absent':
if user:
drop_user(module, client, user_name)
else:
module.exit_json(changed=False)
if __name__ == '__main__':
main()
|
[
"ansible_migration@example.com"
] |
ansible_migration@example.com
|
3f0a3b27cc1ee9e8a2ddfae7039cafc76d780269
|
c31c38b567b5a5053e71d0112c069b2728f83582
|
/setup.py
|
034492e1e4ba614cc4cf8489fd443a60fa06ace1
|
[] |
no_license
|
TyberiusPrime/Dicodon_optimization
|
e79d301d4039b3fa4c3f22d8b5490c717bba4c79
|
badeb4daff0984fb6d1481b854afd80d29329fb3
|
refs/heads/master
| 2022-11-06T11:06:44.893498
| 2020-06-25T08:42:00
| 2020-06-25T08:42:00
| 274,868,388
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 577
|
py
|
# -*- coding: utf-8 -*-
"""
Setup file for dicodon_usage.
Use setup.cfg to configure your project.
This file was generated with PyScaffold 3.2.3.
PyScaffold helps you to put up the scaffold of your new Python project.
Learn more under: https://pyscaffold.org/
"""
import sys
from pkg_resources import VersionConflict, require
from setuptools import setup
try:
require('setuptools>=38.3')
except VersionConflict:
print("Error: version of setuptools is too old (<38.3)!")
sys.exit(1)
if __name__ == "__main__":
setup(use_pyscaffold=True)
|
[
"finkernagel@imt.uni-marburg.de"
] |
finkernagel@imt.uni-marburg.de
|
488cc25f3e057e4d4e5c2f5515b8c69b37e885ad
|
3851985ce5793de321c8a6d7eacf889a5c4d89e4
|
/aries_cloudagent/core/tests/test_plugin_registry.py
|
92ec76a398807d161e315d9e6b3ed2472e3f3324
|
[
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] |
permissive
|
Nick-1979/aries-cloudagent-python
|
af812069c648f064e5fac05616b7b4910ab921ed
|
de322abbeaf16a7ca9769d31f9d030c0fb2846a5
|
refs/heads/master
| 2021-04-21T07:48:23.066245
| 2020-03-24T16:45:43
| 2020-03-24T16:45:43
| 249,762,233
| 1
| 0
|
Apache-2.0
| 2020-03-24T16:40:53
| 2020-03-24T16:40:52
| null |
UTF-8
|
Python
| false
| false
| 1,490
|
py
|
from asynctest import TestCase as AsyncTestCase, mock as async_mock
from ...config.injection_context import InjectionContext
from ...utils.classloader import ClassLoader
from ..plugin_registry import PluginRegistry
class TestPluginRegistry(AsyncTestCase):
def setUp(self):
self.registry = PluginRegistry()
async def test_setup(self):
mod_name = "test_mod"
mod = async_mock.MagicMock()
mod.__name__ = mod_name
ctx = async_mock.MagicMock()
self.registry._plugins[mod_name] = mod
assert list(self.registry.plugin_names) == [mod_name]
assert list(self.registry.plugins) == [mod]
mod.setup = async_mock.CoroutineMock()
await self.registry.init_context(ctx)
mod.setup.assert_awaited_once_with(ctx)
async def test_register_routes(self):
mod_name = "test_mod"
mod = async_mock.MagicMock()
mod.__name__ = mod_name
app = async_mock.MagicMock()
self.registry._plugins[mod_name] = mod
mod.routes.register = async_mock.CoroutineMock()
with async_mock.patch.object(
ClassLoader, "load_module", async_mock.MagicMock(return_value=mod.routes),
) as load_module:
await self.registry.register_admin_routes(app)
load_module.assert_called_once_with(mod_name + ".routes")
mod.routes.register.assert_awaited_once_with(app)
def test_repr(self):
assert type(repr(self.registry)) is str
|
[
"cywolf@gmail.com"
] |
cywolf@gmail.com
|
d1d9d993c26ae3c749bd4f9afb49800aefeedb7b
|
c34d3dfeb068b1a8d7b017d352c91ec9401f115b
|
/experiment/tak/text2command/tutorial/venv/bin/ftfy
|
060b4650d6eed19d0baefae8dbede2227b788770
|
[] |
no_license
|
HiroIshikawa/speech2craft
|
ef6c54359f513f5aefe801ae43f2588c8981d891
|
7717aed4942999780164b8c9060e1dc7bd502c1d
|
refs/heads/master
| 2021-01-19T21:59:30.406605
| 2017-06-27T14:59:12
| 2017-06-27T14:59:12
| 88,735,488
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 463
|
#!/Users/hiro99ishikawa/Dropbox/school_projects/6spring2017/175/project/experiment/spacy_tutorial/venv/bin/python3
# EASY-INSTALL-ENTRY-SCRIPT: 'ftfy==4.4.2','console_scripts','ftfy'
__requires__ = 'ftfy==4.4.2'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('ftfy==4.4.2', 'console_scripts', 'ftfy')()
)
|
[
"hiro52ishikawa@gmail.com"
] |
hiro52ishikawa@gmail.com
|
|
5650104f810a270b0667179b4ddcce2860b9be30
|
72cc55e9599276203a99ba3e5dc211559b00ad76
|
/book_liveblog/wsgi.py
|
4c6fee4e22d83f50aa6c89a06c96105b42e32244
|
[] |
no_license
|
hanzhichao/django_liveblog
|
b551cfacc8e0991728aefddc10f54d5a20d0692c
|
0a58ebcfb5fd102b7d83d025c6131aef81923a5c
|
refs/heads/master
| 2021-09-05T22:52:03.262756
| 2018-01-31T13:49:57
| 2018-01-31T13:49:57
| 104,088,838
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 403
|
py
|
"""
WSGI config for book_liveblog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "book_liveblog.settings")
application = get_wsgi_application()
|
[
"han_zhichao@sina.cn"
] |
han_zhichao@sina.cn
|
498e9af00a73cf1f71cbf81f6d19da86078aa56d
|
8613ec7f381a6683ae24b54fb2fb2ac24556ad0b
|
/70~79/ABC071/bnot.py
|
9ea6b41f33667b764a8a5f3a347a202be7a65d15
|
[] |
no_license
|
Forest-Y/AtCoder
|
787aa3c7dc4d999a71661465349428ba60eb2f16
|
f97209da3743026920fb4a89fc0e4d42b3d5e277
|
refs/heads/master
| 2023-08-25T13:31:46.062197
| 2021-10-29T12:54:24
| 2021-10-29T12:54:24
| 301,642,072
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 135
|
py
|
s = input()
for i in range(26):
if s.count(chr(ord("a") + i)) == 0:
print(chr(ord("a") + i))
exit()
print("None")
|
[
"yuuya15009@gmail.com"
] |
yuuya15009@gmail.com
|
a27d5d8af270a654ded5ce5a4130f7bad3dffe0a
|
2e9dbde82d0f9a215d30ee4a807cc5afe4ad848e
|
/clock/profiles/middleware.py
|
1ef4e6c8eed256e32552917668cf7d25d7261ccc
|
[
"MIT"
] |
permissive
|
mimischi/django-clock
|
b053788249ec47b23fc2f741be30b896f54ab149
|
3914da6a48b89cb80ab5205c6ce1c279012472fe
|
refs/heads/develop
| 2020-04-04T06:00:47.981324
| 2018-05-27T12:29:05
| 2018-05-27T12:29:05
| 43,012,938
| 6
| 4
|
MIT
| 2018-05-27T12:29:06
| 2015-09-23T16:25:29
|
Python
|
UTF-8
|
Python
| false
| false
| 1,219
|
py
|
from django.conf.urls.i18n import is_language_prefix_patterns_used
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
from clock.profiles.models import UserProfile
class LocaleMiddlewareExtended(LocaleMiddleware):
"""This middleware extends Djangos normal LocaleMiddleware and looks for the
language preferred by the user.
Normally only the current session is searched for the preferred language,
but the user may want to define it in his profile. This solves the problem
and therefore keeps the set language across logouts/different devices.
"""
def get_language_for_user(self, request):
if request.user.is_authenticated:
try:
account = UserProfile.objects.get(user=request.user)
return account.language
except UserProfile.DoesNotExist:
pass
return translation.get_language_from_request(
request, check_path=is_language_prefix_patterns_used
)
def process_request(self, request):
language = self.get_language_for_user(request)
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
|
[
"gecht.m@gmail.com"
] |
gecht.m@gmail.com
|
107df7a0e5ce28dc0a41353af47e8273ee9ee549
|
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
|
/work_or_world/right_group/work_or_part/young_life/world/new_thing_or_small_woman.py
|
21ff767cbbc1678056687a4bb608c2f90f9a18ff
|
[] |
no_license
|
JingkaiTang/github-play
|
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
|
51b550425a91a97480714fe9bc63cb5112f6f729
|
refs/heads/master
| 2021-01-20T20:18:21.249162
| 2016-08-19T07:20:12
| 2016-08-19T07:20:12
| 60,834,519
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 190
|
py
|
#! /usr/bin/env python
def year_or_work(str_arg):
world(str_arg)
print('number')
def world(str_arg):
print(str_arg)
if __name__ == '__main__':
year_or_work('come_child')
|
[
"jingkaitang@gmail.com"
] |
jingkaitang@gmail.com
|
b2752676dc368bf1edfcca13a05dff4b1d09244d
|
4ce2cff60ddbb9a3b6fc2850187c86f866091b13
|
/tfrecords/src/wai/tfrecords/object_detection/core/batcher_test.py
|
1e22a572cceb6031539e660c79130b2c7b99c527
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
8176135/tensorflow
|
18cb8a0432ab2a0ea5bacd03309e647f39cb9dd0
|
2c3b4b1d66a80537f3e277d75ec1d4b43e894bf1
|
refs/heads/master
| 2020-11-26T05:00:56.213093
| 2019-12-19T08:13:44
| 2019-12-19T08:13:44
| 228,970,478
| 0
| 0
| null | 2019-12-19T03:51:38
| 2019-12-19T03:51:37
| null |
UTF-8
|
Python
| false
| false
| 5,985
|
py
|
# Copyright 2017 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.
# ==============================================================================
"""Tests for object_detection.core.batcher."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import range
import tensorflow as tf
from wai.tfrecords.object_detection.core import batcher
slim = tf.contrib.slim
class BatcherTest(tf.test.TestCase):
def test_batch_and_unpad_2d_tensors_of_different_sizes_in_1st_dimension(self):
with self.test_session() as sess:
batch_size = 3
num_batches = 2
examples = tf.Variable(tf.constant(2, dtype=tf.int32))
counter = examples.count_up_to(num_batches * batch_size + 2)
boxes = tf.tile(
tf.reshape(tf.range(4), [1, 4]), tf.stack([counter, tf.constant(1)]))
batch_queue = batcher.BatchQueue(
tensor_dict={'boxes': boxes},
batch_size=batch_size,
batch_queue_capacity=100,
num_batch_queue_threads=1,
prefetch_queue_capacity=100)
batch = batch_queue.dequeue()
for tensor_dict in batch:
for tensor in tensor_dict.values():
self.assertAllEqual([None, 4], tensor.get_shape().as_list())
tf.initialize_all_variables().run()
with slim.queues.QueueRunners(sess):
i = 2
for _ in range(num_batches):
batch_np = sess.run(batch)
for tensor_dict in batch_np:
for tensor in tensor_dict.values():
self.assertAllEqual(tensor, np.tile(np.arange(4), (i, 1)))
i += 1
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run(batch)
def test_batch_and_unpad_2d_tensors_of_different_sizes_in_all_dimensions(
self):
with self.test_session() as sess:
batch_size = 3
num_batches = 2
examples = tf.Variable(tf.constant(2, dtype=tf.int32))
counter = examples.count_up_to(num_batches * batch_size + 2)
image = tf.reshape(
tf.range(counter * counter), tf.stack([counter, counter]))
batch_queue = batcher.BatchQueue(
tensor_dict={'image': image},
batch_size=batch_size,
batch_queue_capacity=100,
num_batch_queue_threads=1,
prefetch_queue_capacity=100)
batch = batch_queue.dequeue()
for tensor_dict in batch:
for tensor in tensor_dict.values():
self.assertAllEqual([None, None], tensor.get_shape().as_list())
tf.initialize_all_variables().run()
with slim.queues.QueueRunners(sess):
i = 2
for _ in range(num_batches):
batch_np = sess.run(batch)
for tensor_dict in batch_np:
for tensor in tensor_dict.values():
self.assertAllEqual(tensor, np.arange(i * i).reshape((i, i)))
i += 1
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run(batch)
def test_batch_and_unpad_2d_tensors_of_same_size_in_all_dimensions(self):
with self.test_session() as sess:
batch_size = 3
num_batches = 2
examples = tf.Variable(tf.constant(1, dtype=tf.int32))
counter = examples.count_up_to(num_batches * batch_size + 1)
image = tf.reshape(tf.range(1, 13), [4, 3]) * counter
batch_queue = batcher.BatchQueue(
tensor_dict={'image': image},
batch_size=batch_size,
batch_queue_capacity=100,
num_batch_queue_threads=1,
prefetch_queue_capacity=100)
batch = batch_queue.dequeue()
for tensor_dict in batch:
for tensor in tensor_dict.values():
self.assertAllEqual([4, 3], tensor.get_shape().as_list())
tf.initialize_all_variables().run()
with slim.queues.QueueRunners(sess):
i = 1
for _ in range(num_batches):
batch_np = sess.run(batch)
for tensor_dict in batch_np:
for tensor in tensor_dict.values():
self.assertAllEqual(tensor, np.arange(1, 13).reshape((4, 3)) * i)
i += 1
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run(batch)
def test_batcher_when_batch_size_is_one(self):
with self.test_session() as sess:
batch_size = 1
num_batches = 2
examples = tf.Variable(tf.constant(2, dtype=tf.int32))
counter = examples.count_up_to(num_batches * batch_size + 2)
image = tf.reshape(
tf.range(counter * counter), tf.stack([counter, counter]))
batch_queue = batcher.BatchQueue(
tensor_dict={'image': image},
batch_size=batch_size,
batch_queue_capacity=100,
num_batch_queue_threads=1,
prefetch_queue_capacity=100)
batch = batch_queue.dequeue()
for tensor_dict in batch:
for tensor in tensor_dict.values():
self.assertAllEqual([None, None], tensor.get_shape().as_list())
tf.initialize_all_variables().run()
with slim.queues.QueueRunners(sess):
i = 2
for _ in range(num_batches):
batch_np = sess.run(batch)
for tensor_dict in batch_np:
for tensor in tensor_dict.values():
self.assertAllEqual(tensor, np.arange(i * i).reshape((i, i)))
i += 1
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run(batch)
if __name__ == '__main__':
tf.test.main()
|
[
"coreytsterling@gmail.com"
] |
coreytsterling@gmail.com
|
62e64dfe9d700d8ec7b1cead731218ebd10a44ea
|
bb970bbe151d7ac48d090d86fe1f02c6ed546f25
|
/arouse/_dj/db/backends/oracle/compiler.py
|
a098adba42b387847e1a7ea80c74a94da3510a2b
|
[
"Python-2.0",
"BSD-3-Clause"
] |
permissive
|
thektulu/arouse
|
95016b4028c2b8e9b35c5062a175ad04286703b6
|
97cadf9d17c14adf919660ab19771a17adc6bcea
|
refs/heads/master
| 2021-01-13T12:51:15.888494
| 2017-01-09T21:43:32
| 2017-01-09T21:43:32
| 78,466,406
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,048
|
py
|
from arouse._dj.db.models.sql import compiler
class SQLCompiler(compiler.SQLCompiler):
def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False):
"""
Creates the SQL for this query. Returns the SQL string and list
of parameters. This is overridden from the original Query class
to handle the additional SQL Oracle requires to emulate LIMIT
and OFFSET.
If 'with_limits' is False, any limit/offset information is not
included in the query.
"""
# The `do_offset` flag indicates whether we need to construct
# the SQL needed to use limit/offset with Oracle.
do_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)
if not do_offset:
sql, params = super(SQLCompiler, self).as_sql(
with_limits=False,
with_col_aliases=with_col_aliases,
subquery=subquery,
)
else:
sql, params = super(SQLCompiler, self).as_sql(
with_limits=False,
with_col_aliases=True,
subquery=subquery,
)
# Wrap the base query in an outer SELECT * with boundaries on
# the "_RN" column. This is the canonical way to emulate LIMIT
# and OFFSET on Oracle.
high_where = ''
if self.query.high_mark is not None:
high_where = 'WHERE ROWNUM <= %d' % (self.query.high_mark,)
sql = (
'SELECT * FROM (SELECT "_SUB".*, ROWNUM AS "_RN" FROM (%s) '
'"_SUB" %s) WHERE "_RN" > %d' % (sql, high_where, self.query.low_mark)
)
return sql, params
class SQLInsertCompiler(compiler.SQLInsertCompiler, SQLCompiler):
pass
class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
pass
class SQLUpdateCompiler(compiler.SQLUpdateCompiler, SQLCompiler):
pass
class SQLAggregateCompiler(compiler.SQLAggregateCompiler, SQLCompiler):
pass
|
[
"michal.s.zukowski@gmail.com"
] |
michal.s.zukowski@gmail.com
|
7bf98c286a1ea5b67caef02f49147b68a2c65ed7
|
85b8a52f1be2c4838f885f0e5a4d6963f4109dfe
|
/codes_/0242_Valid_Anagram.py
|
2e9af90a62a0b06ef6ba06c0cf8cb3861493ee08
|
[
"MIT"
] |
permissive
|
SaitoTsutomu/leetcode
|
4cc5bac4f983b287ec1540d188589ce3dd6e409a
|
4656d66ab721a5c7bc59890db9a2331c6823b2bf
|
refs/heads/master
| 2023-03-12T11:37:29.051395
| 2021-02-27T06:11:34
| 2021-02-27T06:11:34
| 281,815,531
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 312
|
py
|
# %% [242. *Valid Anagram](https://leetcode.com/problems/valid-anagram/)
# 問題:2つの文字列がアナグラムかどうかを返す
# 解法:collections.Counterを用いる
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return collections.Counter(s) == collections.Counter(t)
|
[
"tsutomu7@hotmail.co.jp"
] |
tsutomu7@hotmail.co.jp
|
a9298b5a6ccd581226c2b508678daf7a0288d332
|
d2c92cfe95a60a12660f1a10c0b952f0df3f0e8e
|
/zz91mobile/mobile/pingpp/certificate_blacklist.py
|
420deff41b859b0b1c656b590b60a8b8b9d0878d
|
[] |
no_license
|
snamper/zzpython
|
71bf70ec3762289bda4bba80525c15a63156a3ae
|
20415249fa930ccf66849abb5edca8ae41c81de6
|
refs/heads/master
| 2021-12-21T16:12:22.190085
| 2017-09-30T06:26:05
| 2017-09-30T06:26:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 968
|
py
|
import hashlib
from pingpp.error import APIError
BLACKLISTED_DIGESTS = [
'05c0b3643694470a888c6e7feb5c9e24e823dc531',
'5b7dc7fbc98d78bf76d4d4fa6f597a0c901fad5c'
]
def verify(certificate):
"""Verifies a PEM encoded certificate against a blacklist of known revoked
fingerprints.
returns True on success, raises RuntimeError on failure.
"""
sha = hashlib.sha1()
sha.update(certificate)
fingerprint = sha.hexdigest()
if fingerprint in BLACKLISTED_DIGESTS:
raise APIError("Invalid server certificate. You tried to "
"connect to a server that has a revoked "
"SSL certificate, which means we cannot "
"securely send data to that server. "
"Please email support@pingxx.com if you "
"need help connecting to the correct API "
"server.")
return True
|
[
"2496256902@qq.com"
] |
2496256902@qq.com
|
9ea296767e1557de0a4f4913f45b4b01c53f2940
|
665add8c434df0445294931aac7098e8a0fa605b
|
/ch5/designer/connect.py
|
2cc9044ec0e4fa25e176af549690aa94c514b07e
|
[] |
no_license
|
swkim01/RaspberryPiWithIOT
|
f43cef567ca48f2ce9deec0cba87fa801dcbcbe2
|
d4b5c9aeb09490429a551f357d3c83ab04deed82
|
refs/heads/master
| 2023-04-14T20:04:33.924243
| 2023-04-12T05:15:32
| 2023-04-12T05:15:32
| 48,477,439
| 4
| 14
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,111
|
py
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'connect.ui',
# licensing of 'connect.ui' applies.
#
# Created: Wed Aug 28 17:40:14 2019
# by: pyside2-uic running on PySide2 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(252, 150)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(80, 110, 161, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 231, 101))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.gridLayoutWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.server = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.server.setObjectName("server")
self.gridLayout.addWidget(self.server, 0, 1, 1, 1)
self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
self.port = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.port.setObjectName("port")
self.gridLayout.addWidget(self.port, 1, 1, 1, 1)
self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
self.name = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.name.setObjectName("name")
self.gridLayout.addWidget(self.name, 2, 1, 1, 1)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Connect", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Dialog", "Server:", None, -1))
self.server.setText(QtWidgets.QApplication.translate("Dialog", "localhost", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("Dialog", "Port:", None, -1))
self.port.setText(QtWidgets.QApplication.translate("Dialog", "8080", None, -1))
self.label_3.setText(QtWidgets.QApplication.translate("Dialog", "Name:", None, -1))
self.name.setText(QtWidgets.QApplication.translate("Dialog", "홍길동", None, -1))
|
[
"swkim01@gmail.com"
] |
swkim01@gmail.com
|
3101f4b4d66bc96addf9fdcaea38f55c99999bca
|
e4638ff152796e13f5d176c3aa303246bc57fced
|
/ontask/migrations/0033_auto_20180829_0940.py
|
9cee4f91ea8ff26b9f7ad6702ef99420218c36f6
|
[
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
LucasFranciscoCorreia/ontask_b
|
8989ec86905d308e929b6149b52b942321be2311
|
5473e9faa24c71a2a1102d47ebc2cbf27608e42a
|
refs/heads/master
| 2020-07-25T16:52:00.173780
| 2019-09-13T23:31:28
| 2019-09-13T23:31:28
| 208,359,655
| 0
| 0
|
MIT
| 2019-09-13T23:00:53
| 2019-09-13T23:00:52
| null |
UTF-8
|
Python
| false
| false
| 414
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-29 00:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ontask', '0032_auto_20180829_0939'),
]
operations = [
migrations.AlterUniqueTogether(
name='scheduledaction',
unique_together=set([]),
),
]
|
[
"abelardo.pardo@gmail.com"
] |
abelardo.pardo@gmail.com
|
fe3662dcd8f362491af0c4761067ffe9eed642c7
|
9f0f5816b9d810c9ce01c56588024e1c804809fe
|
/study/day3/day3_3.py
|
9fc5cd1c0a6e16afeeab8578680ad7c92ea6c11c
|
[] |
no_license
|
parkwisdom/Python-Study-step1
|
bf8cc8c5f89bfb9ccbb395a3827e23d4f0d6ae9a
|
bae2f5653c5a0d1eac1d4b89476ece7e0802d33b
|
refs/heads/master
| 2020-04-03T13:49:58.990930
| 2018-10-30T00:37:29
| 2018-10-30T00:37:29
| 155,300,210
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,885
|
py
|
import re
# re.compile('\\white')#\white
pat = re.compile('Java|Python')
res=pat.match('Python')
print(res)
res=pat.match('Java')
print(res)
res=pat.match('PythonJava')
print(res)
res=pat.match('PythonRuby')
print(res)
res=pat.match('RubyPython')
print(res)
print(re.search('How','How are you'))
print(re.search('are','How are you'))
print(re.match('are','How are you'))
print(re.search('^How','How are you'))
print(re.search('^are','How are you'))
print(re.search('you$','How are you'))
print(re.search('you$','How are you.Hi'))
re.compile('(ABC)+')#ABC가 계속 반복되는 경우
res=pat.search('ABCABCABCABCABCABCDABCD ok?')
print(res)
# print(res.group(1))
pat=re.compile('(\w+)\s+((\d+)[-](\d+)[-](\d+))')
res=pat.search("kim 010-1234-5678")
print(res.group(1))
print(res.group(2))
print(res.group(3))
print(res.group(4))
print(res.group(5))
pat=re.compile('(어제|오늘|내일)')
print(pat.sub('DAY','어제 날씨 그리고 오늘 날씨'))
"""
웹텍스트 스크래핑 ->치환/삭제(sub)->형태소 분석기(형태소 단위로 분해, 8개 품사)->ex)오늘 뉴스 사건 사고
{'오늘':5,'뉴스':1,'사건':10,....}
"""
pat=re.compile('(어제|오늘|내일)')
print(pat.sub('DAY','어제 날씨 그리고 오늘 날씨',count=1))
pat=re.compile("(?P<name>\w+)\s+(?P<phone>(\d+)[-](\d+)[-](\d+))")
print(pat.sub("\g<phone> \g<name>","kim 010-1234-5678"))
print(pat.sub("\g<2> \g<1>","kim 010-1234-5678"))
"""
정규 표현식 예 : 의미
^Test : Test로 시작하는 문자열
test$ : test로 끝나는 문자열
^xyz$ : xyz로 시작하고 xyz로 끝나는 문자열(xyz도 해당
abc : abc가 들어가는 문자열
ab* : a뒤에 b가 0개 이상 있는 문자열(a,ab,abbbbbb)
ab+ : a뒤에 b가 1개 이상 있는 문자열(ab, abbbbb)
ab? : b가 1개 있을 수도 있고 없을 수도 있다(ab,a)
a?b+$ : a는 있을수도 없을수도 있고, 그뒤에 반드시 한개 이상의 b로 끝나는 문자열
ab{2} : a 뒤에 b가 2개있는 문자열(abb)
ab{3,} : a뒤에 b가 3개 이상 있는 문자열(abbb,abbbbbb)
ab{2,4} : a뒤에 2개 이상 4개 이하의 b가 있는 문자열(abb,abbb,abbbb)
a(bc)* : a뒤에 bc가 0번 이상 반복되는 문자열
a(bc){1,3}: a뒤에 bc가 1번 이상 3번 이하 반복되는 문자열
hi|bye : hi 또는 bye가 있는 문자열
(a|bc)de : ade 또는 bcde문자열
(a|b)*c : a와 b가 뒤섞여서 0번 이상 반복되며, 그뒤에 c가 오는 문자열(aababaaac)
. : 한 문자
.. : 두문자
... : 세문자
a.[0-9] : a뒤에 문자가 1개 있으며, 그 뒤에 숫자가 붙는 문자열
^.{3}$ : 반드시 3문자
[ab] : a또는 b(a|b와 같음)
[a-d] : 소문자 a~d(a|b|c|d 또는 [abcd]와 같음
^[a-zA-Z]: 영문자로 시작하는 문자열
[0-9]% :%문자앞에 하난의 숫자가 있는 문자열
[a-zA-Z0-9]$ : 숫자,영문자로 끝나는 문자열
XML 확장가능한
"""
|
[
"43980901+parkwisdom@users.noreply.github.com"
] |
43980901+parkwisdom@users.noreply.github.com
|
7e25a96700cf91cac44a590dab054dbb0d049013
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/verbs/_twinned.py
|
d2947990b7968c1468d068757b1b53885272e675
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 228
|
py
|
from xai.brain.wordbase.verbs._twin import _TWIN
#calss header
class _TWINNED(_TWIN, ):
def __init__(self,):
_TWIN.__init__(self)
self.name = "TWINNED"
self.specie = 'verbs'
self.basic = "twin"
self.jsondata = {}
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
6b87f507408b3fc904e01f2243e6137866d10c72
|
f7258525ad6c311a138a82fc59c4d84e318cc30f
|
/book1/aa.py
|
ea38e13a6b2d90fbb8e0d06ce860a7287256fa16
|
[] |
no_license
|
lianzhang132/book
|
e358ae555de96e36dbf9ac6c1f7f887444d91e81
|
71ed81a6464997c77dd75b4849ef6eecf7a2e075
|
refs/heads/master
| 2020-07-11T03:18:07.352745
| 2019-08-26T08:45:16
| 2019-08-26T08:45:16
| 204,434,003
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,174
|
py
|
class Auther(models.Model):
nid = models.AutoField(primary_key=True)
name= models.CharField(max_length=32)
age=models.IntegerField()
authorinfo=models.OneToOneField(to="Auther_info",on_delete=models.CASCADE)
def __str__(self):
return (self.name)
class Auther_info(models.Model):
nid = models.AutoField(primary_key=True)
birthday = models.DateField()
age = models.IntegerField()
telephone =models.BigIntegerField()
addr=models.CharField(max_length=86)
class Public_info(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
city=models.CharField(max_length=32)
email=models.CharField(max_length=32)
def __str__(self):
return (self.name)
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title= models.CharField(max_length=32)
pub_date=models.DateField()
price = models.DecimalField(max_digits=8,decimal_places=2)
#一对多
public=models.ForeignKey(to="Public_info",to_field="nid",on_delete=models.CASCADE)
#多对多
authers=models.ManyToManyField(to="Auther")
def __str__(self):
return (self.title)
|
[
"2327431669@qq.com"
] |
2327431669@qq.com
|
17d6a1d1e5388c6b85ab8a475b79ab605c31a328
|
8997a0bf1e3b6efe5dd9d5f307e1459f15501f5a
|
/html_parsing/get_population_from_wikidata.py
|
b298fdfe997103ec021047c1272812e4fb2d6d89
|
[
"CC-BY-4.0"
] |
permissive
|
stepik/SimplePyScripts
|
01092eb1b2c1c33756427abb2debbd0c0abf533f
|
3259d88cb58b650549080d6f63b15910ae7e4779
|
refs/heads/master
| 2023-05-15T17:35:55.743164
| 2021-06-11T22:59:07
| 2021-06-11T22:59:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,613
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import requests
from bs4 import BeautifulSoup
def get_populations(url: str) -> dict:
rs = requests.get(url)
root = BeautifulSoup(rs.content, 'html.parser')
# P1082 -- идентификатор для population
population_node = root.select_one('#P1082')
populations = dict()
# Перебор строк в соседнем от population столбце
for row in population_node.select('.wikibase-statementview'):
# Небольшая хитрость -- берем только первые 2 значения, поидеи это будут: количество людей и дата
number_str, data_str = row.select('.wikibase-snakview-value')[:2]
# Вытаскиваем текст из
number_str = number_str.text.strip()
data_str = data_str.text.strip()
# Делаем разделение и берем последнуюю часть, после приводим к числу
# "1 July 2012" -> 2012, "2010" -> 2010
year = int(data_str.split()[-1])
# Добавляем в словарь
populations[year] = number_str
return populations
def get_population_by_year(populations: dict, year: int) -> str:
# Если такой год не будет найден, вернем -1
return populations.get(year, -1)
# Аналогично get_population_by_year, но сначала вытащит данные из
# указанного url, а после достанет значение по year
def get_population_from_url_by_year(url: str, year: int) -> str:
populations = get_populations(url)
return get_population_by_year(populations, year)
if __name__ == '__main__':
url = 'https://www.wikidata.org/wiki/Q148'
populations = get_populations(url)
print(populations) # {2012: '1,375,198,619', 2010: '1,359,755,102', 2015: '1,397,028,553', ...
# Выводим данные с сортировкой по ключу: по возрастанию
for year in sorted(populations):
print("{}: {}".format(year, populations[year]))
# 2010: 1,359,755,102
# 2011: 1,367,480,264
# 2012: 1,375,198,619
# 2013: 1,382,793,212
# 2014: 1,390,110,388
# 2015: 1,397,028,553
# 2016: 1,403,500,365
# 2017: 1,409,517,397
print(get_population_by_year(populations, 2012)) # 1,375,198,619
print(get_population_by_year(populations, 2013)) # 1,382,793,212
print(get_population_by_year(populations, 2014)) # 1,390,110,388
|
[
"ilya.petrash@inbox.ru"
] |
ilya.petrash@inbox.ru
|
457f651d068dae1e551d1eb386df946c6f285aa0
|
200bcbebf6e4009abe2807cd5d844d655fb431c2
|
/ch16/ex_1.py
|
4a5bec19fa2e81e6d802f1d059478721dc42b9d3
|
[] |
no_license
|
SHUHAIB-AREEKKAN/think_python_solutions
|
7b022fd7e19e87495c2c9722e0b1516d4fa83b85
|
bf1996d922574c367ea49e9954940662166c46b2
|
refs/heads/master
| 2021-01-25T08:07:19.865147
| 2017-06-08T07:43:05
| 2017-06-08T07:43:05
| 93,716,778
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 215
|
py
|
class Distance():
""" x start ,and y end poin"""
def distance_between_points(x,y):
print("distance between"+str(y-x))
finder=Distance()
finder.x=10
finder.y=30
distance_between_points(finder.x,finder.y)
|
[
"homeshuhaib@gmail.com"
] |
homeshuhaib@gmail.com
|
c51427dac75e8302202610302e6adea7783b101a
|
1e5cbe7d3085a5406c3bf4c0dd3c64ec08005e19
|
/p017.py
|
b6a8c9aab5a2ed049721f5f7a8d9ce1d7b608766
|
[] |
no_license
|
mingrammer/project-euler
|
0dfdd0ba83592c49003cb54708e2c520de27f6ac
|
4ae57ac9279472c68a27efc50f6d0317f9b73f17
|
refs/heads/master
| 2021-01-21T16:38:28.983077
| 2018-09-26T10:24:21
| 2018-09-26T10:24:21
| 38,953,014
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 484
|
py
|
# Number letter counts
one_digit = [3, 3, 5, 4, 4, 3, 5, 5, 4]
ten_to_twenty = [3, 6, 6, 8, 8, 7, 7, 9, 8, 8]
two_digit = [6, 6, 5, 5, 5, 7, 6, 6]
hundred = 7
thousand = 8
and_letter = 3
sum_len = 0
sum_len += sum(one_digit)
sum_len += sum(ten_to_twenty)
sum_len += 10*sum(two_digit) + 8*sum(one_digit)
sum_len += 100*sum(one_digit) + 900*hundred + 9*99*and_letter + 9*(sum(ten_to_twenty) + 10*sum(two_digit) + 9*sum(one_digit))
sum_len += thousand + one_digit[0]
print(sum_len)
|
[
"k239507@gmail.com"
] |
k239507@gmail.com
|
410bb29639ebcc51003884b5c567fb3451c74f12
|
3dcc44bf8acd3c6484b57578d8c5595d8119648d
|
/MOVED_TO_ROSETTA_TOOLS/pdb_util/read_pdb.py
|
acd9665f3b78b4dcff882cfab945127df48531b7
|
[] |
no_license
|
rhiju/rhiju_python
|
f0cab4dfd4dd75b72570db057a48e3d65e1d92c6
|
eeab0750fb50a3078a698d190615ad6684dc2411
|
refs/heads/master
| 2022-10-29T01:59:51.848906
| 2022-10-04T21:28:41
| 2022-10-04T21:28:41
| 8,864,938
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 948
|
py
|
#!/usr/bin/python
# quick and dirty PDB reader
def read_pdb( filename ):
coords = {}
pdb_lines = {}
sequence = {}
for line in open( filename ):
if (len(line)>54 and (line[0:4] == 'ATOM' or line[0:4] == 'HETA' ) ):
resnum = int( line[22:26] )
chain = line[21]
atom_name = line[12:16]
position = [float(line[30:38]),float(line[38:46]),float(line[46:54])]
if not ( chain in coords.keys() ):
coords[chain] = {}
pdb_lines[chain] = {}
sequence[ chain ] = {}
sequence[chain][resnum] = line[17:20]
if not ( resnum in coords[chain].keys() ):
coords[chain][resnum] = {}
pdb_lines[chain][resnum] = {}
coords[chain][resnum][atom_name] = position
pdb_lines[chain][resnum][atom_name] = line[:-1]
return ( coords, pdb_lines, sequence )
|
[
"rhiju@stanford.edu"
] |
rhiju@stanford.edu
|
bd06eae999b50905759544ab6ba8529547dfa5a9
|
6e466f7432de5f0b66a72583bc33bf0c96120cd4
|
/userprofiles/views.py
|
2985d63d975451dcb8e22f6676228a78da2b4370
|
[] |
no_license
|
Venezolanos/cines-unidos
|
c9ecc471f1d972af0a3dde89b979e3b8426e712c
|
e9f5f3b69d9a87098cb9ebf8e392677f111f7f51
|
refs/heads/master
| 2020-05-29T14:40:30.130621
| 2016-08-25T19:58:53
| 2016-08-25T19:58:53
| 65,574,580
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 356
|
py
|
from django.shortcuts import render
from django.views.generic import CreateView
from .models import UserProfile
class UserCreateView(CreateView):
model = UserProfile
template_name = 'userprofiles/user_create.html'
success_url = '/'
form_class = 'UserForm'
def form_valid(self, form):
form.save()
return super(UserCreate, self).form_valid(form)
|
[
"undefined.hlo.o@gmail.com"
] |
undefined.hlo.o@gmail.com
|
49be057ff2047be2b384ad0122012c526a1548b1
|
afabd1f1778d4911c825409501f215c634319f0b
|
/src/python/wordalign.py
|
3c3e198d3fff84aee4424baca774edd1fa2272e8
|
[] |
no_license
|
texttheater/xlci
|
030b275a8ecf2bea640c9f9b70aa3fb9fbc768df
|
702d3e90b2a97f56b98da62cd072f0988fcfa5a7
|
refs/heads/master
| 2021-12-24T09:40:10.803445
| 2021-12-22T13:54:49
| 2021-12-22T13:54:49
| 173,109,877
| 6
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,162
|
py
|
#!/usr/bin/env python3
"""Converts (M)GIZA++ output to a token-offset-based format.
Input example:
# Sentence pair (1) source length 8 target length 5 alignment score : 0.000275724
tom is obviously scared .
NULL ({ 2 }) jak ({ }) je ({ }) vidět ({ 3 }) , ({ }) tom ({ 1 }) má ({ }) strach ({ 4 }) . ({ 5 })
Assuming the following raw texts:
Jak je vidět, Tom má strach. Tom is obviously scared.
Output example:
0 0 4,6
0 3
4 6
7 12 7,16
12 13
14 17 0,3
18 20
21 27 17,23
27 28 23,24
"""
import re
import sys
import util
# Matches a GIZA++ alignment line and extracts the bits between ({ and }).
ALIGN_PATTERN = re.compile(r'(?<=\(\{) ((?:\d+ )*)(?=}\))')
def trgid_list2english_offsets(trgid_list, english_sentence):
english_offsets = []
for trgid in trgid_list:
eng_from = english_sentence[trgid - 1][0]
eng_to = english_sentence[trgid - 1][1]
english_offsets.append((eng_from, eng_to))
english_offsets = ['{},{}'.format(*p) for p in english_offsets]
english_offsets = ' '.join(english_offsets)
return english_offsets
def read_offset_file(path):
"""Returns a list of lists of offset pairs."""
result = []
with open(path) as f:
for block in util.blocks(f):
result.append([])
for line in block.splitlines():
if line.rstrip():
fr, to, tokid, token = line.split(maxsplit=3)
fr = int(fr)
to = int(to)
result[-1].append((fr, to))
return result
def read_dict_file(path, nbest_out):
"""Returns a list of pairs (eng_token_count, eng_id_lists)."""
result = []
old_sentence_number = 0
with open(path) as f:
for comment_line, eng_line, alignment_line in util.chunk(3, f):
assert comment_line.startswith('# Sentence pair (')
index = comment_line.index(')')
sentence_number = int(comment_line[17:index])
if sentence_number != old_sentence_number:
assert sentence_number == old_sentence_number + 1
if sentence_number > 1:
result.append(sentence_alignments)
sentence_alignments = []
if len(sentence_alignments) < nbest_out:
old_sentence_number = sentence_number
eng_token_count = len(eng_line.split())
eng_id_lists = [[int(i) for i in l.split()] for l
in ALIGN_PATTERN.findall(alignment_line)]
sentence_alignments.append((eng_token_count, eng_id_lists))
result.append(sentence_alignments)
return result
if __name__ == '__main__':
try:
_, dict_path, engoff_path, foroff_path, nbest_out = sys.argv
nbest_out = int(nbest_out)
except ValueError:
print('USAGE (example): python3 wordalign.py nld-eng.dict eng.tok.off nld.tok.off 3',
file=sys.stderr)
sys.exit(1)
dict_data = read_dict_file(dict_path, nbest_out)
eng_sentences = read_offset_file(engoff_path)
for_sentences = read_offset_file(foroff_path)
assert len(dict_data) == len(eng_sentences)
assert len(dict_data) == len(for_sentences)
for alignments, eng_sentence, for_sentence in zip(dict_data, eng_sentences, for_sentences):
for eng_token_count, eng_id_lists in alignments:
if eng_token_count != len(eng_sentence) or \
len(eng_id_lists) != len(for_sentence) + 1:
print('WARNING: token counts don\'t match, skipping', file=sys.stderr)
else:
# Unaligned English words are aligned to a dummy token which we represent by the offsets 0,0:
print(0, 0, trgid_list2english_offsets(eng_id_lists[0], eng_sentence), sep='\t')
# Aligned English tokens are output with each foreign token:
for (for_from, for_to), eng_id_list in zip(for_sentence, eng_id_lists[1:]):
print(for_from, for_to,
trgid_list2english_offsets(eng_id_list, eng_sentence),
sep ='\t')
print()
|
[
"noreply@texttheater.net"
] |
noreply@texttheater.net
|
f9d797c43df21655a86fdee684138f49cb9bed79
|
af33dc088dbbd4274abf44c1356dc3a66c65ca28
|
/normalize.py
|
c4c09e44d178aecccf7ba71c87dc260b8ee0261a
|
[] |
no_license
|
rasoolims/PBreak
|
dce2b14165e864803544a062a4dc68b3a6edffa7
|
f2f5b4bdc626f1695ccd55aed8e35c8c69e827bf
|
refs/heads/master
| 2023-01-18T15:58:07.947365
| 2020-12-09T18:57:34
| 2020-12-09T18:57:34
| 300,011,165
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 478
|
py
|
from break_words import *
if __name__ == "__main__":
parser = get_lm_option_parser()
(options, args) = parser.parse_args()
normalizer = Normalizer()
with open(options.input_path, "r") as r, open(options.output_path, "w") as w:
for i, line in enumerate(r):
sen = line.strip()
sen = normalizer.normalize(sen)
w.write(sen + "\n")
if i % 1000 == 0:
print(i, end="\r")
print("\nFinished")
|
[
"rasooli.ms@gmail.com"
] |
rasooli.ms@gmail.com
|
f457a73cbca000fc2a445c94d38d41594ff73c95
|
64c5341a41e10ea7f19582cbbf3c201d92768b9f
|
/webInterface/aligner_webapp/yalignve/bin/easy_install
|
93fd0dc0b09c482e2de9bddd82e729cf5bbb7991
|
[] |
no_license
|
CLARIN-PL/yalign
|
6b050b5c330b8eaf7e1e2f9ef83ec88a8abe5164
|
6da94fbb74e803bea337e0c171c8abff3b17d7ee
|
refs/heads/master
| 2023-06-10T18:30:42.112215
| 2021-06-24T13:07:17
| 2021-06-24T13:07:17
| 51,368,327
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 281
|
#!/home/nlp/Downloads/Aligner/aligner_webapp/yalignve/bin/python2
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
|
[
"krzysztof@wolk.pl"
] |
krzysztof@wolk.pl
|
|
a773e41ef132000b96c67ea4fe54eb8f7125c6ab
|
93c22f53bc7ce33a4384c53f02988e6c9ccd86c9
|
/re_flags_ascii.py
|
392bb3d7d26fc66b2dea16eb68f1e9ebb5721655
|
[
"Apache-2.0"
] |
permissive
|
Kalpavrikshika/python_modules
|
a5ce678b58f94d32274846811388d991c281d4d3
|
9f338ab006dd5653fd7f65ff253bc50e0fd61fc6
|
refs/heads/master
| 2020-03-08T02:23:08.650248
| 2018-06-28T07:38:01
| 2018-06-28T07:38:01
| 127,858,450
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 389
|
py
|
import re
text = u'Français złoty Österreich'
pattern = r'\w+'
#Give Ascii flag to compile in ascii.
ascii_pattern = re.compile(pattern, re.ASCII)
#Defined in unicode by default.
unicode_pattern = re.compile(pattern)
print ('Text :', text)
print ('Pattern :', pattern)
print ('ASCII : ', list(ascii_pattern.findall(text)))
print('Unicode :', list(unicode_pattern.findall(text)))
|
[
"vrikshikakalpa@gmail.com"
] |
vrikshikakalpa@gmail.com
|
217ccb92296cf39042a30cba2c587c4da9ac194d
|
6e402eabc041dfef73a41a987b53eea6b566fb0c
|
/best/buses/handlers/bus.py
|
b35a6dcae3ad41131a502f9e77f978a3afe77103
|
[] |
no_license
|
batpad/bombayography
|
fb125a168ccdb217aff3672074001edb9866f2e8
|
0c6a64d32f826f8b9e43a695a327d64fcb4f58cf
|
refs/heads/master
| 2021-01-25T05:15:51.161024
| 2011-01-02T10:30:23
| 2011-01-02T10:30:23
| 1,213,841
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 910
|
py
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from rapidsms.contrib.handlers.handlers.keyword import KeywordHandler
from buses.models import *
class BestHandler(KeywordHandler):
keyword = "route"
def help(self):
self.respond("Send route <bus_no>")
def handle(self, text):
bus_no = text.strip()
a = Atlas.objects.filter(route__iexact=bus_no)
if len(a) < 1:
self.respond("Did not find that bus number. Sorry.")
else:
a = a[0]
src = a.src
first_src = a.first_src
last_src = a.last_src
dest = a.dest
first_dest = a.first_dest
last_dest = a.last_dest
schedule = a.schedule
ret = "%s(%s-%s) to %s(%s-%s) from %s" % (src, str(first_src), str(last_src), dest, str(first_dest), str(last_dest), schedule)
self.respond(ret)
|
[
"b@pad.ma"
] |
b@pad.ma
|
1574bf91fa053aef47cf8548c54380b76988e91f
|
80861e99492590d314dde6f3f19103c6d36fd02f
|
/ucsmsdk/methodmeta/EquipmentInstantiateNNamedTemplateMeta.py
|
526b9387bec99f130ce1272c4922def3c95d0f68
|
[
"Apache-2.0"
] |
permissive
|
CiscoUcs/ucsmsdk
|
2abf67cc084b0f23e453ae3192669a56018aa784
|
d0f0fe2bfc7507e3189408e0113e204bd0d69386
|
refs/heads/master
| 2023-08-31T04:07:22.546644
| 2023-08-30T06:44:19
| 2023-08-30T06:44:19
| 46,483,999
| 83
| 94
|
NOASSERTION
| 2023-08-30T06:44:20
| 2015-11-19T10:06:22
|
Python
|
UTF-8
|
Python
| false
| false
| 1,336
|
py
|
"""This module contains the meta information of EquipmentInstantiateNNamedTemplate ExternalMethod."""
from ..ucscoremeta import MethodMeta, MethodPropertyMeta
method_meta = MethodMeta("EquipmentInstantiateNNamedTemplate", "equipmentInstantiateNNamedTemplate", "Version142b")
prop_meta = {
"cookie": MethodPropertyMeta("Cookie", "cookie", "Xs:string", "Version142b", "InputOutput", False),
"dn": MethodPropertyMeta("Dn", "dn", "ReferenceObject", "Version142b", "InputOutput", False),
"in_error_on_existing": MethodPropertyMeta("InErrorOnExisting", "inErrorOnExisting", "Xs:string", "Version142b", "Input", False),
"in_hierarchical": MethodPropertyMeta("InHierarchical", "inHierarchical", "Xs:string", "Version142b", "Input", False),
"in_name_set": MethodPropertyMeta("InNameSet", "inNameSet", "DnSet", "Version142b", "Input", True),
"in_target_org": MethodPropertyMeta("InTargetOrg", "inTargetOrg", "ReferenceObject", "Version142b", "Input", False),
"out_configs": MethodPropertyMeta("OutConfigs", "outConfigs", "ConfigSet", "Version142b", "Output", True),
}
prop_map = {
"cookie": "cookie",
"dn": "dn",
"inErrorOnExisting": "in_error_on_existing",
"inHierarchical": "in_hierarchical",
"inNameSet": "in_name_set",
"inTargetOrg": "in_target_org",
"outConfigs": "out_configs",
}
|
[
"vijayvikrant84@gmail.com"
] |
vijayvikrant84@gmail.com
|
be7c6ed98d927a0bf90132514d10d3e80d087d74
|
6f06e33ee01027b8429fdf8563fae88b65e604e4
|
/Lab04_03_QueuRunners.py
|
c45d63f3a357c54085ef0827a8092782e452a2b9
|
[] |
no_license
|
wjcheon/DeeplearningPractice_MODU
|
0f8bf29f59087dffca92d3cb82eebdab545ee811
|
40e0115c71ab03fc2b038718516780a86feb0bfd
|
refs/heads/master
| 2021-01-01T06:52:01.075539
| 2017-08-24T07:15:55
| 2017-08-24T07:15:55
| 97,533,568
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,366
|
py
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 18 13:58:48 2017
@author: Wonjoong Cheon
"""
#%%
import tensorflow as tf
import numpy as np
filename_queue = tf.train.string_input_producer(['data-01-test-score.csv','data-01-test-score.csv'])
xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype = np.float32)
x_data = xy[:,0:-1]
y_data = xy[:,[-1]]
print(x_data.shape, x_data, len(x_data))
print(y_data.shape, y_data, len(y_data))
#
#
X = tf.placeholder(tf.float32,shape = [None, 3])
Y = tf.placeholder(tf.float32,shape = [None, 1])
W = tf.Variable(tf.random_normal([3, 1]), name = 'Weight')
b = tf.Variable(tf.random_normal([1]), name = 'bias')
#
hypothesis = tf.matmul(X,W) + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))
#
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 1e-5)
train = optimizer.minimize(cost)
#%%
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(2001):
cost_val, hy_val, _ = sess.run([cost, hypothesis, train],
feed_dict = {X:x_data, Y:y_data})
if step % 20 == 0:
print(step, "Cost:", cost_val, "\nPrediction:\n", hy_val)
#%%
print("Your score will be", sess.run(hypothesis, feed_dict={X:[[100, 70, 101]]}))
print("Other socre will be", sess.run(hypothesis, feed_dict={X:[[60, 70, 110], [90, 100, 80]]}))
|
[
"you@example.com"
] |
you@example.com
|
a4e969cf1aba0818fcce2f0589c09f8557df1e0b
|
1867c4c3f402424863f0dce931e4d4553d04bb0a
|
/office/migrations/0007_auto_20210110_2013.py
|
7e6ff6eea0045a4fcfe44fe6ebca6e0a16256754
|
[] |
no_license
|
AnthonyRedGrave/innowise-task-api
|
67f02792cf1b8fe30e0469a85375d9a45cbf858b
|
819593d0873c40bd20925a9cd503548bb1544295
|
refs/heads/master
| 2023-02-20T13:51:35.054540
| 2021-01-27T18:37:57
| 2021-01-27T18:37:57
| 327,998,666
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 870
|
py
|
# Generated by Django 3.1.5 on 2021-01-10 17:13
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('office', '0006_auto_20210110_2006'),
]
operations = [
migrations.AlterField(
model_name='place',
name='client',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='place',
name='data',
field=models.DateField(blank=True, default=datetime.date(2021, 1, 10), null=True, verbose_name='Дата для бронирования'),
),
]
|
[
"obarnev@inbox.ru"
] |
obarnev@inbox.ru
|
a5a46356428a18fbccc661b250af675d7b5334c5
|
8dde6f201657946ad0cfeacab41831f681e6bc6f
|
/62. Unique Paths.py
|
59341fd6c2040b99346b7d2dce4546f675fd0360
|
[] |
no_license
|
peraktong/LEETCODE_Jason
|
c5d4a524ba69b1b089f18ce4a53dc8f50ccbb88c
|
06961cc468211b9692cd7a889ee38d1cd4e1d11e
|
refs/heads/master
| 2022-04-12T11:34:38.738731
| 2020-04-07T21:17:04
| 2020-04-07T21:17:04
| 219,398,022
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 342
|
py
|
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# DP
dp = [[1] * n for i in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
|
[
"caojunzhi@caojunzhisMBP3.fios-router.home"
] |
caojunzhi@caojunzhisMBP3.fios-router.home
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.