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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a7c4d6b4e6bd2511795d7fcb758420f5aa2a213c | db58ec54f85fd8d4ef6904529c5b17393ee041d8 | /elements-of-programming-interviews/6-strings/6.0-is-palindromic/is_palindromic.py | 51af6cba620333b2d1bb581fc6a5ee4538ae64b0 | [
"MIT"
] | permissive | washimimizuku/python-data-structures-and-algorithms | 90ae934fc7d2bac5f50c18e7fbc463ba0c026fa4 | 537f4eabaf31888ae48004d153088fb28bb684ab | refs/heads/main | 2023-08-28T07:45:19.603594 | 2021-11-08T07:53:52 | 2021-11-08T07:53:52 | 334,213,593 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 375 | py | '''
A palindromic string is one which reads
the same when it is reversed.
'''
def is_palindromic(s): # Time: O(n) | Space: O(1)
# Note that s[~i] for i in [0, len(s) - 1] is s[-(i + 1)].
return all(s[i] == s[~i] for i in range(len(s) // 2))
assert(is_palindromic('abba') == True)
assert(is_palindromic('abcba') == True)
assert(is_palindromic('abcdef') == False)
| [
"nuno.barreto@inventsys.ch"
] | nuno.barreto@inventsys.ch |
c410f87411390859475a290062a07792f214d010 | e21599d08d2df9dac2dee21643001c0f7c73b24f | /Others/Modules/pandas/t.py | 5f8e000908eb234c7fd0d1dc48139513a8afcbf0 | [] | no_license | herolibra/PyCodeComplete | c7bf2fb4ce395737f8c67749148de98a36a71035 | 4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b | refs/heads/master | 2022-07-17T05:39:03.554760 | 2020-05-03T07:00:14 | 2020-05-03T07:00:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py | #!/usr/bin/env python
# coding=utf-8
import pandas as pd
import numpy as np
dates = pd.date_range('20170101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
print(df)
print(df.T) | [
"ijumper@163.com"
] | ijumper@163.com |
59ef791b08647f7d518ef7a5725b686527f30927 | fe6d422ab3f5c6f922d22cd3db2a7d539128620e | /apps/course/migrations/0001_initial.py | 013263198febe2f303ce675ec9670b827b4a4523 | [] | no_license | syongyulin/syl_online | 521e81199bf07c2d83371d486a00842716cfa99e | ffb8da789059c115e9ac7597a547d50e6d69603e | refs/heads/master | 2023-01-10T00:35:07.120987 | 2020-11-13T00:14:34 | 2020-11-13T00:14:34 | 312,281,144 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,838 | py | # Generated by Django 2.2.16 on 2020-11-03 11:13
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, verbose_name='课程名')),
('desc', models.CharField(max_length=300, verbose_name='课程描述')),
('detail', models.TextField(verbose_name='课程详情')),
('degree', models.CharField(choices=[('cj', '初级'), ('zj', '中级'), ('gj', '高级')], max_length=2, verbose_name='难度')),
('learn_times', models.IntegerField(default=0, verbose_name='学习时长(分钟数)')),
('students', models.IntegerField(default=0, verbose_name='学习人数')),
('fav_nums', models.IntegerField(default=0, verbose_name='收藏人数')),
('image', models.ImageField(upload_to='courses/%Y/%m', verbose_name='封面图')),
('click_nums', models.IntegerField(default=0, verbose_name='点击数')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '课程',
'verbose_name_plural': '课程',
},
),
migrations.CreateModel(
name='Lesson',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='章节名')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course', verbose_name='课程')),
],
options={
'verbose_name': '章节',
'verbose_name_plural': '章节',
},
),
migrations.CreateModel(
name='Video',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='视频名')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
('lesson', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Lesson', verbose_name='章节')),
],
options={
'verbose_name': '视频',
'verbose_name_plural': '视频',
},
),
migrations.CreateModel(
name='CourseResource',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='名称')),
('download', models.FileField(upload_to='course/resource/%Y/%m', verbose_name='资源文件')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course', verbose_name='课程')),
],
options={
'verbose_name': '课程资源',
'verbose_name_plural': '课程资源',
},
),
]
| [
"1030918477@qq.com"
] | 1030918477@qq.com |
7f5bb23c3917710fc33198ccef0a8d813bb00a59 | cf332f2c6f4d1e1b6c650bdb803fd6bc2966858b | /apps/commission/migrations/0002_initial.py | 9008340c0d3e76449ffa45469b2fe4bc1250c03b | [] | no_license | drc-ima/rabito-crm-sample | 7b873df8e8b6cc4722dfe730c82644943b41f871 | 26ed884b445e8a03b04fd5ea2b4d5402aa66b659 | refs/heads/main | 2023-08-23T01:30:28.147646 | 2021-09-20T22:56:55 | 2021-09-20T22:56:55 | 404,700,138 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,512 | py | # Generated by Django 3.2.6 on 2021-08-23 09:06
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('commission', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='commissionsetup',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='commission_setups', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='commissionsetup',
name='modified_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='modified_commission_setups', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='commission',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='commissions', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='commission',
name='modified_by',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='modified_commissions', to=settings.AUTH_USER_MODEL),
),
]
| [
"emmanuelofosu472@gmail.com"
] | emmanuelofosu472@gmail.com |
40f9d36ee88b4c5c002c4b400c15077afd21d657 | 0df5d17a8c359a4b6f02a29d444a60be946f12e3 | /sem título0.py | 65b5c48272e8bdf02a3f6d6f6f8132fac627aec4 | [] | no_license | andre23arruda/dicom3d-viewer-python | 1ef10d4c7c76b0afb93016bcb7f000fe00f2f8ca | 87423548aafabe5e0067437037c927fbd4da7467 | refs/heads/master | 2020-09-22T07:33:44.066649 | 2019-12-04T02:53:00 | 2019-12-04T02:53:00 | 225,106,019 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 268 | py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 23:29:42 2019
@author: alca0
"""
#%%
import pydicom
dicom_obj = pydicom.dcmread(r"C:\Users\alca0\Downloads\img_example\136_BIOIMAGEM_ARC_45_20190713_CC_L_2.dcm")
dicom_obj.add_new(0x999999,'HUE', 'HARPIA' )
dicom_obj | [
"andre23arruda@gmail.com"
] | andre23arruda@gmail.com |
0bee84389eb15d39e82917e0c96f63e9af076257 | 710816603a6a4988ca8f162da6e70cb6127f3595 | /utilipy/extern/doc_parse_tools/tests/test_napolean_parse_tools.py | 98e6058c5e1029c0a59cc3c71cfc587cde060688 | [
"BSD-3-Clause"
] | permissive | nstarman/utilipy | 8b1e51d5a73f4e0f3226c0905101cb6d02cc9bf0 | 17984942145d31126724df23500bafba18fb7516 | refs/heads/master | 2023-07-25T19:17:03.925690 | 2020-12-21T05:03:10 | 2020-12-21T05:03:10 | 192,425,953 | 2 | 1 | BSD-3-Clause | 2022-09-12T18:57:44 | 2019-06-17T22:20:57 | Python | UTF-8 | Python | false | false | 841 | py | # -*- coding: utf-8 -*-
"""Tests for :mod:`~utilipy.utils.doc_parse_tools.napoleon_parse_tools`."""
__all__ = [
"test_napoleon_parse_tools",
]
##############################################################################
# IMPORTS
# THIRD PARTY
import pytest
##############################################################################
# PARAMETERS
##############################################################################
# CODE
##############################################################################
@pytest.mark.skip(reason="TODO")
def test_napoleon_parse_tools():
"""Test :mod:`~utilipy.utils.doc_parse_tools.napoleon_parse_tools`."""
# /def
# -------------------------------------------------------------------
##############################################################################
# END
| [
"nstarkman@protonmail.com"
] | nstarkman@protonmail.com |
b3c660de08f22bb4f340e969ba674dd9deb04317 | 971e0efcc68b8f7cfb1040c38008426f7bcf9d2e | /tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_MovingMedian_NoCycle_NoAR.py | fa39c3df3ad94b5d3666ad67652be37c9f374d52 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | antoinecarme/pyaf | a105d172c2e7544f8d580d75f28b751351dd83b6 | b12db77cb3fa9292e774b2b33db8ce732647c35e | refs/heads/master | 2023-09-01T09:30:59.967219 | 2023-07-28T20:15:53 | 2023-07-28T20:15:53 | 70,790,978 | 457 | 77 | BSD-3-Clause | 2023-03-08T21:45:40 | 2016-10-13T09:30:30 | Python | UTF-8 | Python | false | false | 151 | py | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['BoxCox'] , ['MovingMedian'] , ['NoCycle'] , ['NoAR'] ); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
4a284415b37d849bfb8c4d03e088073e324cb5d3 | 44fd3b7a2b1f1e382ceffa72afa8a173c509d278 | /test/test_helpers.py | 9a9c81bed74d4eb5d7cba089964c5cb3ddc3284f | [
"Apache-2.0"
] | permissive | flit/cmdis | 1692aec69ea3b53e18efbb2ba85c3f6ea407e3d2 | 91b7c7430114f3cf260206abc926b86c6e81c51b | refs/heads/master | 2020-12-24T19:05:14.820761 | 2019-06-09T00:21:56 | 2019-06-09T00:21:56 | 56,406,698 | 10 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,942 | py | # Copyright (c) 2016-2019 Chris Reed
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cmdis.bitstring import *
from cmdis.helpers import *
class TestAlign:
def test_0(self):
assert Align(0x1001, 4) == 0x1000
def test_1(self):
assert Align(0x1003, 4) == 0x1000
def test_2(self):
assert Align(0x1003, 2) == 0x1002
def test_3(self):
assert Align(0x1007, 16) == 0x1000
def test_4(self):
assert Align(bitstring(0x1001), 4) == bitstring(0x1000)
def test_5(self):
assert Align(bitstring(0x1003), 4) == bitstring(0x1000)
def test_6(self):
assert Align(bitstring(0x1003), 2) == bitstring(0x1002)
def test_7(self):
assert Align(bitstring(0x1007), 16) == bitstring(0x1000)
class TestAddWithCarry:
def test_0(self):
x = bitstring('00000')
y = bitstring('00000')
assert AddWithCarry(x, y, bit0) == (0, 0, 0)
def test_1(self):
x = bitstring('00001')
y = bitstring('00000')
assert AddWithCarry(x, y, bit0) == (1, 0, 0)
def test_1p1(self):
x = bitstring('00001')
y = bitstring('00001')
assert AddWithCarry(x, y, bit0) == (2, 0, 0)
def test_a(self):
x = bitstring('00101')
y = bitstring('00011')
assert AddWithCarry(x, y, bit0) == ('01000', 0, 0)
def test_carry_0(self):
x = bitstring('00000')
y = bitstring('00000')
assert AddWithCarry(x, y, bit1) == ('00001', 0, 0)
def test_b(self):
x = bitstring(5432)
y = bitstring(143223)
assert AddWithCarry(x, y, bit0) == (148655, 0, 0)
def test_c(self):
# x = bitstring()
pass
class TestLSL:
def test_0(self):
assert LSL_C(bitstring('1001'), 1) == ('0010', '1')
def test_1(self):
assert LSL_C(bitstring('0001'), 1) == ('0010', '0')
class TestLSR:
def test_0(self):
assert LSR_C(bitstring('1001'), 1) == ('0100', '1')
def test_1(self):
assert LSR_C(bitstring('0100'), 1) == ('0010', '0')
class TestASR:
def test_0(self):
assert ASR_C(bitstring('1001000'), 1) == ('1100100', '0')
def test_1(self):
assert ASR_C(bitstring('0100000'), 1) == ('0010000', '0')
def test_2(self):
assert ASR_C(bitstring('0100001'), 1) == ('0010000', '1')
def test_3(self):
assert ASR_C(bitstring('1001001'), 1) == ('1100100', '1')
def test_4(self):
assert ASR_C(bitstring('1001001'), 4) == ('1111100', '1')
class TestROR:
def test_0(self):
assert ROR_C(bitstring('1001'), 1) == ('1100', '1')
def test_1(self):
assert ROR_C(bitstring('0100'), 1) == ('0010', '0')
class TestRRX:
def test_0(self):
assert RRX_C(bitstring('1001'), bit0) == ('0100', '1')
def test_1(self):
assert RRX_C(bitstring('0100'), bit1) == ('1010', '0')
def test_2(self):
assert RRX_C(bitstring('0111'), bit1) == ('1011', '1')
def test_3(self):
assert RRX_C(bitstring('0110'), bit0) == ('0011', '0')
class TestDecodeImmShift:
def test_lsl(self):
assert DecodeImmShift(bitstring('00'), bitstring('00000')) == (SRType.SRType_LSL, 0)
assert DecodeImmShift(bitstring('00'), bitstring('00001')) == (SRType.SRType_LSL, 1)
assert DecodeImmShift(bitstring('00'), bitstring('11111')) == (SRType.SRType_LSL, 31)
def test_lsr(self):
assert DecodeImmShift(bitstring('01'), bitstring('00000')) == (SRType.SRType_LSR, 32)
assert DecodeImmShift(bitstring('01'), bitstring('00001')) == (SRType.SRType_LSR, 1)
assert DecodeImmShift(bitstring('01'), bitstring('11111')) == (SRType.SRType_LSR, 31)
def test_asr(self):
assert DecodeImmShift(bitstring('10'), bitstring('00000')) == (SRType.SRType_ASR, 32)
assert DecodeImmShift(bitstring('10'), bitstring('00001')) == (SRType.SRType_ASR, 1)
assert DecodeImmShift(bitstring('10'), bitstring('11111')) == (SRType.SRType_ASR, 31)
def test_rrx(self):
assert DecodeImmShift(bitstring('11'), bitstring('00000')) == (SRType.SRType_RRX, 1)
def test_ror(self):
assert DecodeImmShift(bitstring('11'), bitstring('00001')) == (SRType.SRType_ROR, 1)
assert DecodeImmShift(bitstring('11'), bitstring('11111')) == (SRType.SRType_ROR, 31)
class TestThumbExpandImm:
def test_a(self):
pass
| [
"flit@me.com"
] | flit@me.com |
f31310cb2b2ed1f2ba6a0021484a25f897389644 | fd18ce27b66746f932a65488aad04494202e2e0d | /d16_plot_linalg/codes_plt/mpl14_Axes_Legend_mix.py | c89af939d9ab40b8d34855eb7c6724018b3c3b4e | [] | no_license | daofeng123/ClassCodes | 1acbd843836e550c9cebf67ef21dfca9f6b9fc87 | fbcd1f24d79b8bb56ad0669b07ad118064609612 | refs/heads/master | 2020-06-24T12:34:28.148197 | 2019-08-15T03:56:40 | 2019-08-15T03:56:40 | 198,963,469 | 3 | 0 | null | 2019-07-26T06:53:45 | 2019-07-26T06:53:44 | null | UTF-8 | Python | false | false | 2,760 | py | #!/usr/bin/python
# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
'''
操作并管理Axes中的Legend。
1、绘制主题:
|-Axes.legend(*args, **kwargs)
返回matplotlib.legend.Legend对象
|-handles : sequence of Artist, optional
|-labels : sequence of strings, optional
|-loc : int or string or pair of floats, default: rcParams["legend.loc"] ('best' for axes, 'upper right' for figures)
|-bbox_to_anchor : BboxBase, 2-tuple, or 4-tuple of floats
|-ncol : integer
|-prop : None or matplotlib.font_manager.FontProperties or dict
|-fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
|-numpoints : None or int
|-scatterpoints : None or int
|-scatteryoffsets : iterable of floats
|-markerscale : None or int or float
|-markerfirst : bool
|-frameon : None or bool
|-fancybox : None or bool
|-shadow : None or bool
|-framealpha : None or float
|-facecolor : None or "inherit" or a color spec
|-edgecolor : None or "inherit" or a color spec
|-mode : {"expand", None}
|-bbox_transform : None or matplotlib.transforms.Transform
|-title : str or None
|-title_fontsize: str or None
|-borderpad : float or None
|-labelspacing : float or None
|-handlelength : float or None
|-handletextpad : float or None
|-borderaxespad : float or None
|-columnspacing : float or None
|-handler_map : dict or None
2、返回主题:
|-Axes.get_legend()
|-返回Legend对象
|-Axes.get_legend_handles_labels(legend_handler_map=None)
|-返回Legend句柄与标签
'''
figure = plt.figure('Legend使用', figsize=(5, 4))
# 可以直接在add_axes函数中设置
ax = figure.add_axes([0.1, 0.1, 0.8, 0.8])
ax.set_ylim(-1, 1)
ax.set_xlim(-1, 1)
line1 = plt.Line2D(
xdata=np.linspace(-1, 1, 20),
ydata=np.random.uniform(-1, 1, size=20),
label='Line1',
color=(0, 1, 0, 1)
)
line2 = plt.Line2D(
xdata=np.linspace(-1, 1, 20),
ydata=np.random.uniform(-1, 1, size=20),
label='Line2',
color=(1, 0, 0, 1)
)
line3 = ax.plot(
np.linspace(-1, 1, 20),
np.random.uniform(-1, 1, size=20),
'#0000FF',
label='Line3'
)
# ax.add_artist(line1)
# add_artist不会自动显示label。
ax.add_line(line1)
ax.add_line(line2)
pie = ax.pie([2, 3, 4], labels=['X', 'Y', 'Z'], frame=True)
# 注意上面的添加顺序
# ---------------------------------------------
lg = ax.legend()
# ax.set_axis_on()
# ax.set_frame_on(b=True) # 控制可见
# ---------------------------------------------
figure.show(warn=False)
plt.show()
| [
"38395870@qq.com"
] | 38395870@qq.com |
7ed11620705eef521c64e9e2c2acf8e3d8abf122 | ff81a9d7880f1b85a1dc19d5eba5ac72d7179c86 | /pychron/dvc/fix_identifier.py | abe5d9947d53c7e593ce83ee2e9fa2da1f6f2930 | [
"Apache-2.0"
] | permissive | UManPychron/pychron | 2fb7e479a9f492423c0f458c70102c499e1062c4 | b84c9fd70072f9cbda30abe2c471e64fe3dd75d8 | refs/heads/develop | 2022-12-03T23:32:45.579326 | 2020-01-29T19:02:20 | 2020-01-29T19:02:20 | 36,100,637 | 0 | 0 | null | 2015-05-23T00:10:06 | 2015-05-23T00:10:05 | null | UTF-8 | Python | false | false | 3,816 | py | # ===============================================================================
# Copyright 2018 ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
import os
import shutil
from pychron.dvc import analysis_path, dvc_load, dvc_dump
def fix_identifier(source_id, destination_id, root, repo, aliquots, steps, dest_steps=None, dest_aliquots=None):
if dest_aliquots is None:
dest_aliquots = aliquots
if dest_steps is None:
dest_steps = steps
# for a, da, step, dstep in zip(aliquots, dest_aliquots, steps, dest_steps):
# src_id = '{}-{:02n}{}'.format(source_id, a, step)
# dest_id = '{}-{:02n}{}'.format(destination_id, da, dstep)
def _fix_id(src_id, dest_id, identifier, root, repo, new_aliquot=None):
sp = analysis_path(src_id, repo, root=root)
dp = analysis_path(dest_id, repo, root=root, mode='w')
print(sp, dp)
if not os.path.isfile(sp):
print('not a file', sp)
return
jd = dvc_load(sp)
jd['identifier'] = identifier
if new_aliquot:
jd['aliquot']= new_aliquot
dvc_dump(jd, dp)
print('{}>>{}'.format(sp, dp))
for modifier in ('baselines', 'blanks', 'extraction',
'intercepts', 'icfactors', 'peakcenter', '.data'):
sp = analysis_path(src_id, repo, modifier=modifier, root=root)
dp = analysis_path(dest_id, repo, modifier=modifier, root=root, mode='w')
print('{}>>{}'.format(sp,dp))
if sp and os.path.isfile(sp):
# shutil.copy(sp, dp)
shutil.move(sp,dp)
def swap_identifier(a, a_id, b, b_id, c_id, root, repo):
'''
a -> c
replace a with b
replace b with c
'''
_fix_id(a_id, c_id, a, root, repo)
_fix_id(b_id, a_id, a, root, repo)
_fix_id(c_id, b_id, b, root, repo)
if __name__ == '__main__':
root = '/Users/ross/PychronDev/data/.dvc/repositories/'
repo = 'Henry01104'
_fix_id('66151-01', '66150-21', '66150', root, repo, new_aliquot=21)
_fix_id('66151-12', '66150-22', '66150', root, repo, new_aliquot=22)
_fix_id('66149-20', '66150-23', '66150', root, repo, new_aliquot=23)
_fix_id('66150-06', '66149-29', '66149', root, repo, new_aliquot=29)
# repo = 'FCTest'
#
# a_id = '26389-03'
# a = '26389'
# b_id = '26381-03'
# b = '26381'
# c_id = '26389-03X'
#
# swap_identifier(a,a_id, b, b_id, c_id, root, repo)
# repo = 'Saifuddeen01097'
# fix_identifier('66340', '66431', '/Users/ross/PychronDev/data/.dvc/repositories/',
# 'Saifuddeen01097',
# aliquots=[2],
# steps=['A','B']
# dest_aliquots=[1]
# # aliquots=[1,]#2,3,4,5,6]
# )
# _fix_id('66340-02A', '66341-01A', '66341', root, repo)
# _fix_id('66340-02B', '66341-01B', '66341', root, repo)
# identifier = '66550'
# source_identifier = '66560'
# for step in 'ABCDEFGHIJL':
# _fix_id('{}-01{}'.format(source_identifier, step), '{}-01{}'.format(identifier, step), identifier, root, repo)
# ============= EOF =============================================
| [
"jirhiker@gmail.com"
] | jirhiker@gmail.com |
b616ac2d64848df30978df2bd3675649d66d0a24 | 466607c14d76c8d798e08f05dde2d79a07f6e069 | /src/stk/_internal/topology_graphs/metal_complex/porphyrin.py | f08b0ce0358bd563c93fd9a87d2a2c8a85a7cee8 | [
"MIT"
] | permissive | andrewtarzia/stk | 7c77006bacd4d3d45838ffb3b3b4c590f1bce336 | 9242c29dd4b9eb6927c202611d1326c19d73caea | refs/heads/main | 2023-08-03T12:29:21.096641 | 2023-07-27T09:45:25 | 2023-07-27T09:45:25 | 191,198,174 | 0 | 1 | MIT | 2023-09-04T16:53:05 | 2019-06-10T15:49:25 | Python | UTF-8 | Python | false | false | 3,290 | py | """
Porphyrin
=========
"""
from stk._internal.topology_graphs.edge import Edge
from .metal_complex import MetalComplex
from .vertices import MetalVertex, UnaligningVertex
class Porphyrin(MetalComplex):
"""
Represents a metal complex topology graph.
.. moldoc::
import moldoc.molecule as molecule
import stk
bb1 = stk.BuildingBlock(
smiles='[Fe+2]',
functional_groups=(
stk.SingleAtom(stk.Fe(0, charge=2))
for i in range(6)
),
position_matrix=[[0, 0, 0]],
)
bb2 = stk.BuildingBlock(
smiles=(
'C1=CC2=CC3=CC=C([N]3)C=C4C=CC'
'(=N4)C=C5C=CC(=N5)C=C1[N]2'
),
functional_groups=[
stk.SmartsFunctionalGroupFactory(
smarts='[#6]~[#7]~[#6]',
bonders=(1, ),
deleters=(),
),
],
)
complex = stk.ConstructedMolecule(
topology_graph=stk.metal_complex.Porphyrin(
metals=bb1,
ligands=bb2,
),
)
moldoc_display_molecule = molecule.Molecule(
atoms=(
molecule.Atom(
atomic_number=atom.get_atomic_number(),
position=position,
) for atom, position in zip(
complex.get_atoms(),
complex.get_position_matrix(),
)
),
bonds=(
molecule.Bond(
atom1_id=bond.get_atom1().get_id(),
atom2_id=bond.get_atom2().get_id(),
order=(
1
if bond.get_order() == 9
else bond.get_order()
),
) for bond in complex.get_bonds()
),
)
Metal building blocks with at least four functional groups are
required for this topology.
Ligand building blocks with at least four functional group are
required for this topology graph.
When using a :class:`dict` for initialization, a
:class:`.BuildingBlock` needs to be assigned to each of the
following numbers:
| metals: (0, )
| ligands: (0, )
See :class:`.MetalComplex` for more details and examples.
"""
_metal_vertex_prototypes = (MetalVertex(0, (0, 0, 0)),)
_ligand_vertex_prototypes = (UnaligningVertex(1, (0, 0, 0)),)
_edge_prototypes = (
Edge(
id=0,
vertex1=_metal_vertex_prototypes[0],
vertex2=_ligand_vertex_prototypes[0],
position=(0.1, 0, 0),
),
Edge(
id=1,
vertex1=_metal_vertex_prototypes[0],
vertex2=_ligand_vertex_prototypes[0],
position=(0, 0.1, 0),
),
Edge(
id=2,
vertex1=_metal_vertex_prototypes[0],
vertex2=_ligand_vertex_prototypes[0],
position=(-0.1, 0, 0),
),
Edge(
id=3,
vertex1=_metal_vertex_prototypes[0],
vertex2=_ligand_vertex_prototypes[0],
position=(0, -0.1, 0),
),
)
| [
"noreply@github.com"
] | andrewtarzia.noreply@github.com |
0666fd08858744b6c502b012d302740cac401fd8 | 466e5e56d2f350bcea90683af67e160138af836c | /Onsite/Week-1/Wednesday/Latency.py | 471e936cb47495a806c37af5f5adf64c0b45ab64 | [] | no_license | max180643/Pre-Programming-61 | bafbb7ed3069cda5c2e64cf1de590dfb4a542273 | e68d4a69ffeedd4269fffc64b9b81e845a10da4d | refs/heads/master | 2021-06-17T14:10:44.889814 | 2019-08-01T09:35:42 | 2019-08-01T09:35:42 | 135,553,863 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | """Dorm EP.2 - Latency"""
def main():
"""Main Function"""
latency1 = int(input())
latency2 = int(input())
latency3 = int(input())
latency4 = int(input())
latency5 = int(input())
latency6 = int(input())
print("%i ms"%(min(latency1, latency2, latency3, latency4, latency5, latency6)))
main()
| [
"noreply@github.com"
] | max180643.noreply@github.com |
02f6daeee451eb6708e5ba187eab3cbf161a4536 | d6be053915c065fe6da71afddd28429d144fee68 | /realpython_tutorials/python_type_checking/game_annotated.py | f0c26e340af003ff168f45e93fb238c2911132af | [] | no_license | DrShushen/practice_py | 61bc28f52783f8304cce1d834def4934ba6ee8e1 | cf40ec43ccd73aa835c4e65e6a4b41408b90a3ea | refs/heads/master | 2023-01-08T06:57:10.852157 | 2023-01-03T22:58:11 | 2023-01-03T22:58:11 | 211,668,464 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 920 | py | # game.py
import random
from typing import Dict, List, Tuple
SUITS = "♠ ♡ ♢ ♣".split()
RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split()
Card = Tuple[str, str]
Deck = List[Card]
def create_deck(shuffle: bool = False) -> Deck:
"""Create a new deck of 52 cards"""
deck = [(s, r) for r in RANKS for s in SUITS]
if shuffle:
random.shuffle(deck)
return deck
def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]:
"""Deal the cards in the deck into four hands"""
return (deck[0::4], deck[1::4], deck[2::4], deck[3::4])
def play():
"""Play a 4-player card game"""
deck = create_deck(shuffle=True)
names = "P1 P2 P3 P4".split()
hands = {n: h for n, h in zip(names, deal_hands(deck))}
for name, cards in hands.items():
card_str = " ".join(f"{s}{r}" for (s, r) in cards)
print(f"{name}: {card_str}")
if __name__ == "__main__":
play()
| [
"e.s.saveliev@gmail.com"
] | e.s.saveliev@gmail.com |
4fd702bbbd12443a824253f0216192ae4fc30f7c | 62855ed774f7e0b45e1810dde659a8ce0320fe32 | /demxf/viz.py | cf14601da1843a7ead6e617adaf4b5ed51d4261d | [
"MIT"
] | permissive | dhockaday/demxf | d55323cf974310c47b98e3ae2e871f02dc95ff25 | c45d06ce88dbd173a13ec6da35869d2117e77fee | refs/heads/master | 2023-03-17T05:10:12.574869 | 2017-11-16T12:28:57 | 2017-11-16T12:33:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,000 | py | import graphviz
from demxf.decompiler import (
BasePatchDecompiler,
filter_keys,
get_box_printable_class,
nonprinted_keys,
remove_aesthetics,
)
class PatchGrapher(BasePatchDecompiler):
def initialize(self, content):
super(PatchGrapher, self).initialize(content)
self.graph = graphviz.Digraph()
def process_box(self, box):
id = box['id']
box = box.copy()
if box['maxclass'] == 'comment':
return
d_id = self.divined_id_map[id]
filtered_box = filter_keys(remove_aesthetics(box), nonprinted_keys)
formatted_keys = ['{}={}'.format(key, repr(value)) for (key, value) in sorted(filtered_box.items())]
if box['maxclass'] == 'newobj' and len(filtered_box) == 1:
label = filtered_box['text']
else:
label = '{name}\n{keys}'.format(
name=get_box_printable_class(box),
keys='\n'.join(l[:200] for l in formatted_keys),
)
self.graph.node(d_id, label, shape='box', style=('dotted' if box.get('hidden') else ''))
outlet_types = dict(enumerate(box.get('outlettype', [])))
lines_from_here = self.lines_by_source_id[id]
for line in sorted(lines_from_here):
(source_id, source_pin), (dest_id, dest_pin) = line
type = outlet_types.get(source_pin) or ''
source_outlets = box['numoutlets']
dest_inlets = self.boxes[dest_id]['numinlets']
if source_outlets > 1 or dest_inlets > 1:
label = '%s %d:%d' % (type, source_pin + 1, dest_pin + 1)
else:
label = type
self.graph.edge(
tail_name='{id}'.format(id=self.divined_id_map[source_id], pin=source_pin),
head_name='{id}'.format(id=self.divined_id_map[dest_id], pin=dest_pin),
label=label,
)
def dump(self):
super(PatchGrapher, self).dump()
return self.graph
| [
"akx@iki.fi"
] | akx@iki.fi |
c6f54efd2d6d69af5e8998d81812b49e130f86e0 | 94e06376dc265c7bf1a2e51acb9714d02b21503a | /python打卡/day1_zhihu.py | f6af91e41527a127672468ee695a24ed2082e28a | [] | no_license | zhangquanliang/python | 4b2db32bed4e4746c8c49c309563f456dc41c6be | f45ef96e385b1cd6c5dfb53bf81042d953a9ec46 | refs/heads/master | 2021-04-26T23:30:12.217397 | 2019-03-20T06:18:14 | 2019-03-20T06:18:14 | 124,005,916 | 11 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,869 | py | # -*- coding: utf-8 -*-
import requests
import re
import urllib3
urllib3.disable_warnings()
"""
Title = 知乎关注粉丝
Date = 2018-03-27
"""
class ZhiHu:
"""获取知乎粉丝信息"""
def __init__(self):
self.url = 'https://zhuanlan.zhihu.com/wajuejiprince'
self.headers = {
"user-agent": "Mozilla/1.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)"
" Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"
}
# 知乎粉丝信息
def zh_fans(self):
r = requests.session()
response = r.get(self.url, headers=self.headers, verify=False)
# 查找共有多少人关注
reg = re.findall('target="_blank">(.*?)人关注</a>', response.text)
fans_number = int(reg[0].strip())
num = int(fans_number/20) # 共有44页
f = open('test.txt', 'a', encoding='utf-8')
for i in range(num+1):
if i == 0:
fans_url = 'https://zhuanlan.zhihu.com/api/columns/wajuejiprince/followers?limit=20'
else:
offset = i*20
fans_url = 'https://zhuanlan.zhihu.com/api/columns/wajuejiprince/followers?limit=20&offset={}'\
.format(offset)
response = r.get(fans_url, headers=self.headers, verify=False)
for fans_list in response.json():
job_name = fans_list['bio']
name = fans_list['name']
uid = str(fans_list['uid'])
if job_name is None:
job_name = ""
f.write(name)
f.write(' ')
f.write(job_name)
f.write(' ')
f.write(uid)
f.write('\n')
f.flush()
f.close()
if __name__ == '__main__':
zhihu = ZhiHu()
zhihu.zh_fans() | [
"1007228376@qq.com"
] | 1007228376@qq.com |
badacbed26551cc4a429b5598c7e25ef3836be2d | a47ac7c64cb6bb1f181eadff8e4b24735c19080a | /PythonStudy/9-Tkinter/11-Menu菜单.py | 02c687ce0e7cf07976ffc9e57f3d9cd58f84776b | [
"MIT"
] | permissive | CoderTitan/PythonDemo | 6dcc88496b181df959a9d43b963fe43a6e4cb032 | feb5ef8be91451b4622764027ac684972c64f2e0 | refs/heads/master | 2020-03-09T09:15:28.299827 | 2018-08-21T03:43:25 | 2018-08-21T03:43:25 | 128,708,650 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,163 | py | # 主窗口
from tkinter import *
# 创建主窗口
window = Tk()
# 设置标题
window.title('Titanjun')
# 设置窗口大小
window.geometry('400x400')
'''
def menuAction1():
print('menubar')
# 菜单条
menubar = Menu(window)
window.configure(menu=menubar)
# 创建一个菜单选项
menu1 = Menu(menubar, tearoff=False)
# 菜单选项添加内容
for item in ['Python', 'PHP', 'CPP', 'C', 'Java', 'JavaScript', 'VBScript', 'Exit']:
if item == 'Exit':
# 添加分割线
menu1.add_separator()
menu1.add_command(label=item, command=window.quit)
else:
menu1.add_command(label=item, command=menuAction1)
# 想菜单条上添加菜单选项
menubar.add_cascade(label='语言', menu=menu1)
# 菜单2的事件处理
def menuAction2():
print(menuStr.get())
menuStr = StringVar()
menu2 = Menu(menubar, tearoff=True)
for item in ['red', 'orange', 'blue', 'gray']:
menu2.add_radiobutton(label=item, variable=menuStr, command=menuAction2)
# 添加到菜单列表
menubar.add_cascade(label='颜色', menu=menu2)
'''
# 鼠标右键菜单
menubar2 = Menu(window)
menu3 = Menu(menubar2, tearoff=False)
for item in ['Python', 'PHP', 'CPP', 'C', 'Java', 'JavaScript', 'VBScript', 'Exit']:
menu3.add_command(label=item)
menubar2.add_cascade(label='开发语言', menu=menu3)
# 添加/删除菜单
def menuClick():
print("menu3")
# 添加command项
menu3.insert_command(1, label='command', command=menuClick)
# 添加radiobutton项
menu3.insert_radiobutton(3, label='radiobutton', command=menuClick)
# 添加checkbutton项
menu3.insert_checkbutton(5, label='checkbutton', command=menuClick)
# 添加分割线
menu3.insert_separator(4)
# menu3.insert_separator(0)
# 删除
# 两个参数: 参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只获取第一个索引处的内容
menu3.delete(2, 4)
menu3.delete(0)
# 用于显示菜单
def showMenu(event):
print('window')
# 鼠标点击处的坐标
menubar2.post(event.x_root, event.y_root)
# window绑定鼠标事件
window.bind("<Button-2>", showMenu)
# 进入消息循环
window.mainloop()
| [
"quanjunt@163.com"
] | quanjunt@163.com |
e6d3436e3d161e1e676e909ca9d50025702b66c8 | fc9bd84a2e560309dd7ddb2509b4bfcfbfe37e6b | /timesketch/ui/views/user_test.py | 20addf67538f17ff539c078accb72cde0a9d5567 | [
"Apache-2.0"
] | permissive | oi-buhtig/timesketch | 37ad823c08f24fc9021764a8843ede7d1693ab4b | bb2dccc041dff907ae428155ae45dbf5f26f19a3 | refs/heads/master | 2020-05-29T09:52:24.480339 | 2015-10-14T13:20:01 | 2015-10-14T13:20:01 | 44,555,537 | 1 | 0 | null | 2015-10-19T18:36:37 | 2015-10-19T18:36:37 | null | UTF-8 | Python | false | false | 2,071 | py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the user views."""
from flask_login import current_app
from flask_login import current_user
from timesketch.lib.definitions import HTTP_STATUS_CODE_REDIRECT
from timesketch.lib.testlib import BaseTest
class UserViewTest(BaseTest):
"""Test the user view."""
def test_login_view_unauthenticated(self):
"""Test the login view handler with an unauthenticated session."""
response = self.client.get(u'/login/')
self.assert200(response)
self.assert_template_used(u'user/login.html')
def test_login_view_form_authenticated(self):
"""Test the login view handler with an authenticated session."""
self.login()
response = self.client.get(u'/login/')
self.assertEquals(response.status_code, HTTP_STATUS_CODE_REDIRECT)
def test_login_view_sso_authenticated(self):
"""Test the login view handler with an SSO authenticated session."""
current_app.config[u'SSO_ENABLED'] = True
with self.client:
response = self.client.get(
u'/login/', environ_base={u'REMOTE_USER': u'test1'})
self.assertEqual(current_user.username, u'test1')
self.assertEquals(response.status_code, HTTP_STATUS_CODE_REDIRECT)
def test_logout_view(self):
"""Test the logout view handler."""
self.login()
response = self.client.get(u'/logout/')
self.assertEquals(response.status_code, HTTP_STATUS_CODE_REDIRECT)
| [
"jberggren@gmail.com"
] | jberggren@gmail.com |
4be91b40e73d1f9dfd744a278f9275e198d7b882 | 8f2c55a2530c3e59dab5907c0044c618b88dd09b | /tests_python/resources/_debugger_case_generator2.py | 59c6ee88d1d2b503bcdb97c56156fb71084af719 | [
"Apache-2.0",
"EPL-1.0"
] | permissive | fabioz/PyDev.Debugger | 5a9c6d4c09be85a0e2d9fb93567fd65faf04c81d | 26864816cbfcf002a99913bcc31ebef48042a4ac | refs/heads/main | 2023-08-18T01:08:34.323363 | 2023-04-15T11:15:47 | 2023-04-15T11:15:47 | 21,870,144 | 363 | 126 | Apache-2.0 | 2023-07-30T23:03:31 | 2014-07-15T18:01:12 | Python | UTF-8 | Python | false | false | 287 | py | def get_return():
return 10
def generator():
print('start') # break here
yield 10 # step 1
return \
get_return() # step 2
if __name__ == '__main__':
for i in generator(): # generator return
print(i)
print('TEST SUCEEDED!') # step 3
| [
"fabiofz@gmail.com"
] | fabiofz@gmail.com |
5327fc8f8debafd9cb4c83a7e844fc228e595b5c | 457776337d8dcaa75df1c48869e9be1ab58be253 | /py3/pachong/2017_07_18a.py | d922f93beebcd18c966ae80f17e495c7829dfb0b | [] | no_license | tiankangbo/dashboard | c63d0df6e2eb60a6e17e4d7fde19e8e12a7958a9 | 8f6c6f806f3f8a8fe4ab8937d5c5a00986522c40 | refs/heads/master | 2021-07-14T20:18:18.843903 | 2017-10-22T06:16:15 | 2017-10-22T06:16:15 | 103,809,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 844 | py | # coding:utf8
__author__ = 'tiankangbo'
from multiprocessing import Pipe, Process
import random
import time, os
def proc_send(pipe, urls):
"""
pipe的发送端
:param pipe:
:param urls:
:return:
"""
for url in urls:
print("process %s --send %s " %(os.getpid(), url) )
pipe.send(url)
time.sleep(random.random())
def proc_recv(pipe):
"""
数据接收端
:param pipe:
:return:
"""
while True:
print('process %s >>>rev%s ' % (os.getpid(), pipe.recv()))
time.sleep(random.random())
if __name__ == '__main__':
pipe = Pipe()
p1 = Process(target=proc_send, args=(pipe[0], ['url_'+str(i) for i in range(10)],))
p2 = Process(target=proc_recv, args=(pipe[1],))
#启动进程
p1.start()
p2.start()
p1.join()
p2.terminate() | [
"tiankangbo@gmail.com"
] | tiankangbo@gmail.com |
bd1ac0ef7ac86f79c795a06aa2ed66928a0b9339 | 9afeff62ff369bcf0a370b257e2d5c82ea1e27fb | /map/test_layers.py | 96281ae3e9ec72935297b79c011c5d563faea87f | [] | no_license | raphaelshirley/decals-web | d5404765c29f0e538193c70a13737cb400eb92b0 | 4897e21fa6844a3179667910c4b0a99c7b4883ad | refs/heads/master | 2020-06-04T16:32:15.841911 | 2019-06-11T14:41:31 | 2019-06-11T14:41:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,511 | py | test_layers = []
test_cats = []
test_ccds = []
# test_layers.append(("dr8-test1", "DR8 test1 images"))
# test_layers.append(("dr8-test1-model", "DR8 test1 models"))
# test_layers.append(("dr8-test1-resid", "DR8 test1 residuals"))
# test_layers.append(("dr8-test2", "DR8 test2 (outliers) images"))
# test_layers.append(("dr8-test2-model", "DR8 test2 (outliers) models"))
# test_layers.append(("dr8-test2-resid", "DR8 test2 (outliers) residuals"))
# test_layers.append(("dr8-test3", "DR8 test3 (outliers) images"))
# test_layers.append(("dr8-test3-model", "DR8 test3 (outliers) models"))
# test_layers.append(("dr8-test3-resid", "DR8 test3 (outliers) residuals"))
# test_layers.append(("dr8-test4", "DR8 test4 (large-galaxies) images"))
# test_layers.append(("dr8-test4-model", "DR8 test4 (large-galaxies) models"))
# test_layers.append(("dr8-test4-resid", "DR8 test4 (large-galaxies) residuals"))
# test_layers.append(("dr8-test5", "DR8 test5 (trident) images"))
# test_layers.append(("dr8-test5-model", "DR8 test5 (trident) models"))
# test_layers.append(("dr8-test5-resid", "DR8 test5 (trident) residuals"))
#
# test_layers.append(("dr8-test6", "DR8 test6 (sky) images"))
#
# test_layers.append(("dr8-test7", "DR8 test7 (outliers) images"))
#
# test_layers.append(("dr8-test10", "DR8 test10 (rc) images"))
# test_layers.append(("dr8-test10-model", "DR8 test10 (rc) models"))
# test_layers.append(("dr8-test10-resid", "DR8 test10 (rc) residuals"))
#
# test_layers.append(("dr8-test14", "DR8 test14 (rc) images"))
# test_layers.append(("dr8-test14-model", "DR8 test14 (rc) models"))
# test_layers.append(("dr8-test14-resid", "DR8 test14 (rc) residuals"))
test_layers.append(("dr8a", "DR8a (rc) images"))
test_layers.append(("dr8a-model", "DR8a (rc) models"))
test_layers.append(("dr8a-resid", "DR8a (rc) residuals"))
test_layers.append(("dr8b-decam", "DR8b DECam images"))
test_layers.append(("dr8b-decam-model", "DR8b DECam models"))
test_layers.append(("dr8b-decam-resid", "DR8b DECam residuals"))
test_layers.append(("dr8b-90p-mos", "DR8b BASS+MzLS images"))
test_layers.append(("dr8b-90p-mos-model", "DR8b BASS+MzLS models"))
test_layers.append(("dr8b-90p-mos-resid", "DR8b BASS+MzLS residuals"))
test_cats.append(("dr8b-decam", "Catalog: DR8b DECam"))
test_cats.append(("dr8b-90p-mos", "Catalog: DR8b BASS+MzLS"))
test_layers.append(("dr8c-90p-mos", "DR8c BASS+MzLS images"))
test_layers.append(("dr8c-90p-mos-model", "DR8c BASS+MzLS models"))
test_layers.append(("dr8c-90p-mos-resid", "DR8c BASS+MzLS residuals"))
test_cats.append(("dr8c-90p-mos", "Catalog: DR8c BASS+MzLS"))
test_layers.append(("dr8c-decam", "DR8c DECam images"))
test_layers.append(("dr8c-decam-model", "DR8c DECam models"))
test_layers.append(("dr8c-decam-resid", "DR8c DECam residuals"))
test_cats.append(("dr8c-decam", "Catalog: DR8c DECam"))
test_ccds.append(("dr8c-decam", "CCDs: DR8c DECam"))
test_layers.append(("dr8i-decam", "DR8i DECam images"))
test_layers.append(("dr8i-decam-model", "DR8i DECam models"))
test_layers.append(("dr8i-decam-resid", "DR8i DECam residuals"))
test_layers.append(("dr8i-90p-mos", "DR8i MzLS+BASS images"))
test_layers.append(("dr8i-90p-mos-model", "DR8i MzLS+BASS models"))
test_layers.append(("dr8i-90p-mos-resid", "DR8i MzLS+BASS residuals"))
test_cats.append(("dr8i-decam", "Catalog: DR8i DECam"))
test_cats.append(("dr8i-90p-mos", "Catalog: DR8i MzLS+BASS"))
test_ccds.append(("dr8i-decam", "CCDs: DR8i DECam"))
test_ccds.append(("dr8i-90p-mos", "CCDs: DR8i MzLS+BASS"))
| [
"dstndstn@gmail.com"
] | dstndstn@gmail.com |
5177b8f64631bc86748170335a481b8931d1265a | 84d891b6cb6e1e0d8c5f3e285933bf390e808946 | /Demo/python_MOOC/Python基础/Unit_5_函数和代码复用/KochDrawV1.py | df7942f10207b2f26d0486d9b5de3038bf80277b | [] | no_license | zzlzy1989/web_auto_test | 4df71a274eb781e609de1067664264402c49737e | 3e20a55836144e806496e99870f5e8e13a85bb93 | refs/heads/master | 2020-05-24T10:37:29.709375 | 2019-10-28T06:14:31 | 2019-10-28T06:14:31 | 187,230,775 | 2 | 0 | null | 2019-06-20T11:06:32 | 2019-05-17T14:29:11 | null | UTF-8 | Python | false | false | 554 | py | # -*- coding:utf-8 -*-
# @Author : GaoXu
# @Time : 2019/8/24 16:30
# @File : KochDrawV1.py
# @Software : web_auto_test
# 科赫曲线绘制源代码
import turtle
def koch(size, n):
if n == 0:
turtle.fd(size)
else:
for angle in [0, 60, -120, 60]:
turtle.left(angle)
koch(size/3, n-1)
def main():
turtle.setup(800,400)
turtle.penup()
turtle.goto(-300, -50)
turtle.pendown()
turtle.pensize(2)
koch(600,3) # 0阶科赫曲线长度,阶数
turtle.hideturtle()
main() | [
"394845369@qq.com"
] | 394845369@qq.com |
d9507018888a7618e9bea33aa3984633483a1f65 | 15514b8cdb9ef2bb25a33e44a2abe79e5eb86439 | /analyze_in_vivo/analyze_domnisoru/plots_for_thesis/fraction_burst.py | 29db8337758722bb7be32ad824a545b4741947a8 | [] | no_license | cafischer/analyze_in_vivo | 389ce0d51c6cbeb3e39648aaff13263f0c99060a | e38e1057420b5329504f7095f1ee89e2a293df23 | refs/heads/master | 2021-06-10T00:18:47.741793 | 2019-09-14T08:47:53 | 2019-09-14T08:47:53 | 100,512,098 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,853 | py | import matplotlib.pyplot as pl
import numpy as np
import os
from analyze_in_vivo.load.load_domnisoru import get_cell_ids_DAP_cells, get_celltype_dict, load_cell_ids
pl.style.use('paper')
if __name__ == '__main__':
save_dir_img = '/home/cf/Dropbox/thesis/figures_results'
save_dir = '/home/cf/Phd/programming/projects/analyze_in_vivo/analyze_in_vivo/data/domnisoru'
save_dir_ISI_hist = '/home/cf/Phd/programming/projects/analyze_in_vivo/analyze_in_vivo/results/domnisoru/whole_trace/ISI_hist'
cell_type_dict = get_celltype_dict(save_dir)
grid_cells = np.array(load_cell_ids(save_dir, 'grid_cells'))
stellate_cells = load_cell_ids(save_dir, 'stellate_cells')
pyramidal_cells = load_cell_ids(save_dir, 'pyramidal_cells')
stellate_idxs = np.array([np.where(cell_id == grid_cells)[0][0] for cell_id in stellate_cells])
pyramidal_idxs = np.array([np.where(cell_id == grid_cells)[0][0] for cell_id in pyramidal_cells])
# load
fraction_burst = np.load(os.path.join(save_dir_ISI_hist, 'cut_ISIs_at_200', 'grid_cells', 'fraction_burst.npy'))
# plot
fig, ax = pl.subplots(figsize=(4, 6))
ax.plot(np.zeros(len(stellate_cells)), fraction_burst[stellate_idxs], 'ok')
ax.errorbar(0.2, np.mean(fraction_burst[stellate_idxs]), yerr=np.std(fraction_burst[stellate_idxs]),
marker='o', color='k', capsize=3)
ax.plot(np.ones(len(pyramidal_cells))*0.6, fraction_burst[pyramidal_idxs], 'ok')
ax.errorbar(0.8, np.mean(fraction_burst[pyramidal_idxs]), yerr=np.std(fraction_burst[pyramidal_idxs]),
marker='o', color='k', capsize=3)
ax.set_xlim(-0.2, 1.0)
ax.set_xticks([0, 0.6])
ax.set_xticklabels(['Stellate', 'Pyramidal'])
ax.set_ylabel('Fraction burst')
pl.tight_layout()
pl.savefig(os.path.join(save_dir_img, 'fraction_burst.png'))
pl.show()
| [
"coralinefischer@gmail.com"
] | coralinefischer@gmail.com |
8ffe7071c683152556da838ec3a17236daa37678 | c92a60d7968130cf21b20a943976c0e1929b6eb8 | /apps/dashboard/forms/courses_form.py | 42fc57a32e986e0c4b09b13a1a6744fad9bb1d16 | [] | no_license | BeAnhTran/yoga-center-website | efb40103f343b9be627ce926156e66fe9f985435 | 8b7532f103a73a467cd903923f7cd2ccfc09d949 | refs/heads/master | 2022-11-25T09:51:27.000385 | 2020-08-03T01:44:22 | 2020-08-03T01:44:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,480 | py | from django import forms
from django.db import transaction
from apps.courses.models import Course
from apps.lectures.models import Lecture
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, Fieldset
from apps.cards.models import CardType
from django.utils.translation import ugettext_lazy as _
from ..forms.lectures_form import LectureInlineForm
from django.forms.models import inlineformset_factory
from apps.dashboard.custom_layout_object import Formset
LectureFormSet = inlineformset_factory(
Course, Lecture, form=LectureInlineForm,
fields=['name'], extra=1, can_delete=True
)
class CourseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update(
{'autofocus': 'autofocus', 'placeholder': 'Yoga cơ bản'})
self.fields['description'].widget.attrs.update(
{'placeholder': 'Yoga cho người mới bắt đầu với động tác cơ bản'})
self.fields['price_per_lesson'].widget.attrs.update({
'placeholder': '50.000'
})
self.fields['price_per_month'].widget.attrs.update({
'placeholder': '600.000'
})
self.fields['price_for_training_class'].widget.attrs.update({
'placeholder': '10.000.000'
})
self.fields['card_types'] = forms.ModelMultipleChoiceField(label=_(
'Card types'), widget=forms.CheckboxSelectMultiple(), queryset=CardType.objects.all())
self.fields['level'].required = False
self.helper = FormHelper()
self.helper.layout = Layout(
'name',
'description',
Row(
Column('course_type', css_class='form-group col-md-4 mb-0'),
Column('level', css_class='form-group col-md-4 mb-0'),
css_class='form-row'
),
'card_types',
'content',
'image',
'wages_per_lesson',
Row(
Column('price_per_lesson', css_class='form-group col-md-4 mb-0'),
Column('price_per_month', css_class='form-group col-md-4 mb-0'),
Column('price_for_training_class',
css_class='form-group col-md-4 mb-0'),
css_class='form-row'
),
Fieldset(_('Lectures'), Formset('lectures')),
Submit('submit', 'Save', css_class='btn btn-success')
)
class Meta:
model = Course
exclude = ['slug', 'created_at', 'updated_at']
def clean_name(self):
from django.utils.text import slugify
from django.core.exceptions import ValidationError
name = self.cleaned_data['name']
slug = slugify(name)
if Course.objects.filter(slug=slug).exists():
raise ValidationError('A course with this name already exists.')
return name
class CourseEditForm(CourseForm):
def clean_name(self):
name = self.cleaned_data['name']
if 'name' in self.changed_data:
from django.utils.text import slugify
from django.core.exceptions import ValidationError
slug = slugify(name)
if Course.objects.filter(slug=slug).exists():
raise ValidationError(
_('A course with this name already exists.'))
return name
else:
return name
| [
"giatruongtran27@gmail.com"
] | giatruongtran27@gmail.com |
cafdb03b3c85c33fab56156890ff9c9e6e356031 | 7fba01da6426480612d7cef9ceb2e15f3df6d01c | /PYTHON/pythonDesafios/desafio026.py | 09a9abe13c925116c934a1eaefb7fb7274226769 | [
"MIT"
] | permissive | Santos1000/Curso-Python | f320fec1e7ced4c133ade69acaa798d431e14113 | 549223a1633f6f619c87554dd8078cf7841bb1df | refs/heads/main | 2023-05-26T12:01:23.868814 | 2021-05-26T13:22:58 | 2021-05-26T13:22:58 | 371,039,290 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | frase = str(input('Digite a frase:')).upper().strip()
print('A primeira letra A aparece: na {} posicao.'.format(frase.find('A')+1))
print('A letra A aparece: {} vezes.'.format(frase.count('A')))
print('A ultima letra A aparece: na {} posicao.'.format(frase.rfind('A')+1))
| [
"83990871+Santos1000@users.noreply.github.com"
] | 83990871+Santos1000@users.noreply.github.com |
e1d69df5b96a8284caf0e616b10529f32b2b0641 | 3775102a3f59bc8aac9b8121ba2aef87409724ee | /Medium/pass_triangle.py | 7fecb020cf0b692b29563050feb428790dc7045e | [] | no_license | csikosdiana/CodeEval | a446ec6673e9f97439662bfccbd7454e5740d509 | 15cdd9ca454939e93c77d5ed5076595ecc7e4301 | refs/heads/master | 2016-08-11T14:49:27.565799 | 2016-03-22T17:48:20 | 2016-03-22T17:48:20 | 46,176,059 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 511 | py | data = ["5", "9 6", "4 6 8", "0 7 1 5"]
#import sys
#test_cases = open(sys.argv[1], 'r')
#data = test_cases.readlines()
S = []
for test in data:
test = test.rstrip()
nums = test.split(" ")
nums = map(int, nums)
if S == []:
S = nums
continue
else:
T = nums
E = []
for i in range(0, len(T)):
if i == 0:
E.append((T[i] + S[i]))
elif i == len(T) - 1:
E.append((T[i] + S[len(S)-1]))
else:
m = max(S[i-1], S[i])
E.append((T[i] + m))
S = E
print max(S)
#test_cases.close()
| [
"csikosdiana@gmail.com"
] | csikosdiana@gmail.com |
f840e829bc9dfe916b409569d8d751b1d3de80fc | 8c6867a4019ca8e622df216dc0e2566c51b3d396 | /ashesiundergraduate/migrations/0001_initial.py | bd2a3c50c5fc4bdce49570d8e213249771eaf334 | [] | no_license | deone/apply | 3cd36233bc191393b05ef32073fdaa4a3b56fb2e | 724e024c1455cd193901e2f7f5a8377806ffe974 | refs/heads/master | 2021-01-21T04:41:33.605076 | 2019-05-22T12:29:13 | 2019-05-22T12:29:13 | 54,662,123 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,268 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-03 09:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('setup', '0011_auto_20160402_2153'),
]
operations = [
migrations.CreateModel(
name='PersonalInformation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('middle_name', models.CharField(max_length=30, verbose_name='middle name')),
('date_of_birth', models.DateField(null=True, verbose_name='date of birth')),
('applied_before', models.NullBooleanField(choices=[(True, 'Yes'), (False, 'No')], verbose_name='applied before')),
('year_applied', models.CharField(max_length=4, null=True, verbose_name='year applied')),
('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], max_length=1, null=True, verbose_name='gender')),
('application', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='setup.Application')),
],
),
]
| [
"alwaysdeone@gmail.com"
] | alwaysdeone@gmail.com |
6bb6754a843f836266657cf3d64f58fec17a3cc7 | b0a1008bd20b8325328f62473acab216216fd72f | /static/playdrone/Reference_ref/com.google.android.apps.books-30149/constraints1_0.py | bb63b21546dc9ee9d3c67a7ce311cf4cb20ebbd6 | [] | no_license | zhuowei/IntelliDroidUiEvaluationCode | 14bffcbf707455a83bdcb7fc7e75f7dfcf461c11 | eab8bed4490739e2f5b2633e2817b46500e6d201 | refs/heads/master | 2020-03-09T07:33:00.053786 | 2018-04-09T18:26:45 | 2018-04-09T18:26:45 | 128,666,963 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 339 | py | # Entrypoint: com.google.android.apps.books.app.AccountPickerFragment.onDismiss(Landroid/content/DialogInterface;)V
# Target: invokevirtual < Application, Landroid/app/Activity, startActivity(Landroid/content/Intent;)V >@38
IAAv0 = Int('IAAv0') # Pointer<972229980>.equal(Pointer<-570473851>.getCurrentAccount())
s.add((IAAv0 == 0))
| [
"zhuoweizhang@yahoo.com"
] | zhuoweizhang@yahoo.com |
a7f5240b5cde3a626f32d2dca6f20e950e24b9b6 | 43598dd1e251b1733ed16981a148834bd9faca9b | /main.py | a0dfa3259f49652c346ab01ac8a5adc5a0e0ea8b | [] | no_license | SamL98/PhysicsEngine | 86e6f38a34d7261c13cc76e78f2702e72c4c0c3b | 440e9042cc999277bbc1961cbb4b8f2300f28fde | refs/heads/master | 2020-03-23T18:51:45.246905 | 2018-07-22T22:50:14 | 2018-07-22T22:50:14 | 141,936,554 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,030 | py | import cv2 as cv
import numpy as np
from time import sleep
from draw_util import clear
from draw import draw_shape
from line import create_line
from circle import create_ball
from collider import collide_inelastic
g = 9.8
w, h = 250, 500
kexit = 27
canvas = np.ones((h, w))
ball = create_ball(pos=[0, w//2-10])
ball.a = [g, 0]
ball.mass = 10.0
#line = create_line((h-2, 0), (h//2, w-1))
line = create_line((h//2, 0), (h-2, w-1))
line.restitution = 10.0
shapes = [ball, line]
def shdUpdate():
for i in range(len(shapes)):
if shapes[i].needsUpdate:
return True
return False
cv.namedWindow('canvas')
init_timestep = True
while(1):
if init_timestep or shdUpdate():
init_timestep = False
clear(canvas)
draw_shape(canvas, ball)
draw_shape(canvas, line)
collide_inelastic(ball, line)
for shape in shapes:
shape.nextPos()
cv.imshow('canvas', canvas)
k = cv.waitKey(20)
if k == kexit:
break
cv.destroyAllWindows() | [
"lerner98@gmail.com"
] | lerner98@gmail.com |
e1d31a086d8d654f5f697c298c2e6e14355fe901 | 02ce6d29fec0d68ca2a2a778d37d2f2cff1a590e | /Old/PythonOne/20.3.1.py | bb4f66a90f65ad532544ff1f65ce40b1439c06cf | [] | no_license | CalvinCheungCoder/Python-100-Days | 605045122e40c119abc32466c32479559a4d4b9b | 0f9bec8893954d4afbe2037dad92885c7d4d31f8 | refs/heads/master | 2020-04-17T11:49:42.148478 | 2019-09-19T10:22:37 | 2019-09-19T10:22:37 | 166,556,771 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 443 | py | import threading
import time
def thread_body():
t = threading.current_thread()
for n in range(5):
print('第 {0} 次执行线程 {1}'.format(n, t.name))
time.sleep(1)
print('线程 {0} 执行完成!'.format(t.name))
def main():
t1 = threading.Thread(target=thread_body())
t1.start()
t2 = threading.Thread(target=thread_body(),name='MyThread')
t2.start()
if __name__ == '__main__':
main() | [
"984382258@qq.com"
] | 984382258@qq.com |
727d16455790234bc5ad2fa656380bfc5a8ff77a | 1852be4726dc1d83780740678819192277159e0f | /LC/97.py | 4b43cefdb31dc175807adac8a7da8d074298f5c2 | [
"MIT"
] | permissive | szhu3210/LeetCode_Solutions | f0a32e30df54b655fdb9c7d48622382f29781409 | 64747eb172c2ecb3c889830246f3282669516e10 | refs/heads/master | 2020-06-30T05:45:40.550146 | 2017-08-11T04:10:25 | 2017-08-11T04:10:25 | 74,389,515 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,631 | py | class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
## iterative (DP) (35ms)
l1=len(s1)
l2=len(s2)
l3=len(s3)
co=[(-1,-1)]
x=0
while x<l3 and co:
nco=[]
for c in co:
if c[0]<l1-1 and s3[x]==s1[c[0]+1] and (c[0]+1,c[1]) not in nco:
nco.append((c[0]+1,c[1]))
if c[1]<l2-1 and s3[x]==s2[c[1]+1] and (c[0],c[1]+1) not in nco:
nco.append((c[0],c[1]+1))
co=nco
x+=1
return (l1-1,l2-1) in co
## recursive (keep historical record) (68ms)
# d={}
# return self.helper(s1,s2,s3,d)
# def helper(self, s1,s2,s3,d):
# if len(s1)+len(s2)!=len(s3):
# return False
# if (s1,s2,s3) in d:
# return False
# if s1=='':
# t = s2==s3
# if t:
# return True
# else:
# d[(s1,s2,s3)]=t
# return False
# if s2=='':
# t = s1==s3
# if t:
# return True
# else:
# d[(s1,s2,s3)]=t
# return False
# t1 = self.helper(s1[1:],s2,s3[1:],d) if s3[0]==s1[0] else False
# if t1:
# return True
# t2 = self.helper(s1,s2[1:],s3[1:],d) if s3[0]==s2[0] else False
# if t2:
# return True
# d[(s1,s2,s3)]=False
# return False | [
"szhu@email.arizona.edu"
] | szhu@email.arizona.edu |
ec1b3f7c328d034d94959ab8c0c4ca7566c4ba57 | 03f1560cedc273f99d64a93224fe7a2211aa5680 | /src/vsc/report/coverage_report.py | 510e26b55a5197191af6e48a1e4d499269a02eb5 | [
"Apache-2.0"
] | permissive | cmarqu/pyvsc | 9be19fbcd3df37a406ecaa1cdf46b5209e9e9866 | c7ff708256b7cdce0eccab8b7d6e2037edbdc5fa | refs/heads/master | 2021-06-14T07:19:25.381354 | 2020-04-08T01:50:49 | 2020-04-08T01:50:49 | 254,485,300 | 0 | 0 | Apache-2.0 | 2020-04-09T21:47:58 | 2020-04-09T21:47:57 | null | UTF-8 | Python | false | false | 1,100 | py | '''
Created on Mar 25, 2020
@author: ballance
'''
from typing import List
class CoverageReport(object):
"""Coverage report in object-model form. Converted to text for display"""
def __init__(self):
self.covergroups : List['CoverageReport.Covergroup'] = []
class Coveritem(object):
def __init__(self, name):
self.name = name
self.coverage = 0.0
class Covergroup(Coveritem):
def __init__(self, name : str, is_type : bool):
CoverageReport.Coveritem.__init__(self, name)
self.is_type = is_type
self.covergroups = []
self.coverpoints = []
self.crosses = []
class Coverpoint(Coveritem):
def __init__(self, name : str):
CoverageReport.Coveritem.__init__(self, name)
self.bins = []
class Coverbin(Coveritem):
def __init__(self, name : str, n_hits):
CoverageReport.Coveritem.__init__(self, name)
self.n_hits = n_hits
| [
"matt.ballance@gmail.com"
] | matt.ballance@gmail.com |
21c40f16baa986546f9ac952a9717fba5b578383 | 8e576efb1b76a038cf7e7ec631eb33db9f1c0155 | /continue_debug.py | 9ca606d666a9cec932b2851b03fb61c42c2edf8a | [] | no_license | sugar-activities/4378-activity | 779ec91bb60f05c617edb5b5393fe95b454a9b71 | eedab96fc1bf541983eb66f0aaf417d767cc0df7 | refs/heads/master | 2021-01-19T23:14:24.238128 | 2017-04-21T05:52:23 | 2017-04-21T05:52:23 | 88,937,226 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,823 | py | #!/usr/bin/env python
#
# Copyright (C) 2007, Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import with_statement
import os
import sys
#debug tool to analyze the activity environment
# Initialize logging.
import logging
from pydebug_logging import _logger, log_environment
_logger.setLevel(logging.DEBUG)
from sugar.activity import activityfactory
from sugar.bundle.activitybundle import ActivityBundle
#define the interface with the GUI
from Rpyc import *
try:
c = SocketConnection('localhost')
db = c.modules.pydebug.pydebug_instance
except AttributeError:
print('cannot connect to localhost')
except e:
print(e[1])
assert False
#define interface with the command line ipython instance
from IPython.core import ipapi
ip = ipapi.get()
global __IPYTHON__
try:
__IPYTHON__
print('IPTHON is defined')
except:
__IPYTHON__ = ip
o = ip.options
o.xmode = db.traceback
def edit_glue(self,filename,linenumber):
_logger.debug('position to editor file:%s. Line:%d'%(filename,linenumber))
ip.set_hook('editor',edit_glue)
def sync_called(self,filename,line,col):
print('synchronize called. file:%s. line:%s. Col:%s'%(filename,line,col))
ip.set_hook('synchronize_with_editor',sync_called)
#get the information about the Activity we are about to debug
child_path = db.child_path
_logger.debug('child path: %s'%child_path)
print('child path starting activity: %s'%child_path)
go_cmd = 'run -d -b %s %s'%(os.path.join(db.pydebug_path,'bin','start_debug.py'),child_path)
_logger.debug('defining go: %s'%go_cmd)
ip.user_ns['go'] = go_cmd
_logger.debug('pydebug home: %s'%db.debugger_home)
path = child_path
pydebug_home = db.debugger_home
os.environ['PYDEBUG_HOME'] = pydebug_home
os.chdir(path)
os.environ['SUGAR_BUNDLE_PATH'] = path
_logger.debug('sugar_bundle_path set to %s'%path)
#set up module search path
sys.path.insert(0,path)
activity = ActivityBundle(path)
cmd_args = activityfactory.get_command(activity)
_logger.debug('command args:%r'%cmd_args)
bundle_name = activity.get_name()
bundle_id = activity.get_bundle_id()
#need to get activity root, but activity bases off of HOME which some applications need to change
#following will not work if storage system changes with new OS
#required because debugger needs to be able to change home so that foreign apps will work
activity_root = os.path.join('/home/olpc/.sugar/default/',bundle_id)
os.environ['SUGAR_ACTIVITY_ROOT'] = activity_root
_logger.debug('sugar_activity_root set to %s'%activity_root)
#following is useful for its side-effects
info = activityfactory.get_environment(activity)
_logger.debug("Command to execute:%s."%cmd_args[0])
if not cmd_args[0].startswith('sugar-activity'):
target = os.path.join(pydebug_home,os.path.basename(cmd_args[0]))
with open(target,'w') as write_script_fd:
with open(cmd_args[0],'r') as read_script_fd:
for line in read_script_fd.readlines():
if line.startswith('exec') or line.startswith('sugar-activity'):
pass
else:
write_script_fd.write(line)
line = 'export -p > %s_env\n'%target
write_script_fd.write(line) #write the environment variables to another file
write_script_fd.close()
os.chmod(target,0755)
os.system(target)
_logger.debug('writing env script:%s'%target)
#read the environment back into the current process
with open('%s_env'%target,'r') as env_file:
env_dict = {}
for line in env_file.readlines():
if not line.startswith('export'):
pass
payload = line.split()[1]
pair = payload.split('=')
if len(pair)> 1:
key = pair[0]
value = pair[1]
env_dict[key] = value
_logger.debug('reading environment. %s => %s'%(key,value,))
os.environ = env_dict
more_args = ['-a',bundle_name,'-b',bundle_id]
sys.argv = cmd_args[:2] + more_args
_logger.debug('about to call main.main() with args %r'%sys.argv)
log_environment()
from sugar.activity import main
main.main()
| [
"ignacio@sugarlabs.org"
] | ignacio@sugarlabs.org |
42464cf07abf0758db1a5c82e682019c368ab0cf | 2e50af6e12bf1c815c8efb3695a5bb41507d66bd | /ppomppu/crawling_data/migrations/0001_initial.py | 23053b1d9b999d1506fdd26719ba032e71a32c7e | [] | no_license | KimDoKy/Ppomppu_check | e5fe57ba2bed84e4236742bfc4352460b7313f89 | b7d09ac1ab46d051636f54b5890f190b3ad97419 | refs/heads/master | 2022-12-15T10:42:10.717898 | 2021-06-22T12:46:20 | 2021-06-22T12:46:20 | 167,160,601 | 2 | 1 | null | 2022-12-08T01:48:49 | 2019-01-23T10:01:49 | JavaScript | UTF-8 | Python | false | false | 871 | py | # Generated by Django 2.1.5 on 2019-01-30 14:50
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CrawlingData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField()),
('category', models.CharField(max_length=10)),
('write_date', models.CharField(max_length=10)),
('detail_link', models.URLField()),
('prod_image', models.URLField(blank=True, null=True)),
('crawling_data', models.DateTimeField(auto_now_add=True)),
('status', models.BooleanField(default=False)),
],
),
]
| [
"makingfunk0@gmail.com"
] | makingfunk0@gmail.com |
d64e9569c2249f8d5cf47948bb273030c95f0a6c | a14b3e43705d74da97451de8663e9a98c088aec3 | /dohq_teamcity/models/vcs_roots.py | 1fe9c882557685c3fed4ad0ab2c3b8e4d637f5b0 | [
"MIT"
] | permissive | devopshq/teamcity | b5a36d6573cdde2f7c72e77a8e605198a7c7124d | 7a73e05c0a159337ed317f8b8d8072e478a65ca6 | refs/heads/develop | 2023-01-16T07:06:07.514297 | 2022-12-30T10:24:07 | 2022-12-30T10:24:07 | 153,228,762 | 29 | 13 | MIT | 2023-09-08T08:49:56 | 2018-10-16T05:42:15 | Python | UTF-8 | Python | false | false | 3,982 | py | # coding: utf-8
from dohq_teamcity.custom.base_model import TeamCityObject
# from dohq_teamcity.models.vcs_root import VcsRoot # noqa: F401,E501
class VcsRoots(TeamCityObject):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'count': 'int',
'href': 'str',
'next_href': 'str',
'prev_href': 'str',
'vcs_root': 'list[VcsRoot]'
}
attribute_map = {
'count': 'count',
'href': 'href',
'next_href': 'nextHref',
'prev_href': 'prevHref',
'vcs_root': 'vcs-root'
}
def __init__(self, count=None, href=None, next_href=None, prev_href=None, vcs_root=None, teamcity=None): # noqa: E501
"""VcsRoots - a model defined in Swagger""" # noqa: E501
self._count = None
self._href = None
self._next_href = None
self._prev_href = None
self._vcs_root = None
self.discriminator = None
if count is not None:
self.count = count
if href is not None:
self.href = href
if next_href is not None:
self.next_href = next_href
if prev_href is not None:
self.prev_href = prev_href
if vcs_root is not None:
self.vcs_root = vcs_root
super(VcsRoots, self).__init__(teamcity=teamcity)
@property
def count(self):
"""Gets the count of this VcsRoots. # noqa: E501
:return: The count of this VcsRoots. # noqa: E501
:rtype: int
"""
return self._count
@count.setter
def count(self, count):
"""Sets the count of this VcsRoots.
:param count: The count of this VcsRoots. # noqa: E501
:type: int
"""
self._count = count
@property
def href(self):
"""Gets the href of this VcsRoots. # noqa: E501
:return: The href of this VcsRoots. # noqa: E501
:rtype: str
"""
return self._href
@href.setter
def href(self, href):
"""Sets the href of this VcsRoots.
:param href: The href of this VcsRoots. # noqa: E501
:type: str
"""
self._href = href
@property
def next_href(self):
"""Gets the next_href of this VcsRoots. # noqa: E501
:return: The next_href of this VcsRoots. # noqa: E501
:rtype: str
"""
return self._next_href
@next_href.setter
def next_href(self, next_href):
"""Sets the next_href of this VcsRoots.
:param next_href: The next_href of this VcsRoots. # noqa: E501
:type: str
"""
self._next_href = next_href
@property
def prev_href(self):
"""Gets the prev_href of this VcsRoots. # noqa: E501
:return: The prev_href of this VcsRoots. # noqa: E501
:rtype: str
"""
return self._prev_href
@prev_href.setter
def prev_href(self, prev_href):
"""Sets the prev_href of this VcsRoots.
:param prev_href: The prev_href of this VcsRoots. # noqa: E501
:type: str
"""
self._prev_href = prev_href
@property
def vcs_root(self):
"""Gets the vcs_root of this VcsRoots. # noqa: E501
:return: The vcs_root of this VcsRoots. # noqa: E501
:rtype: list[VcsRoot]
"""
return self._vcs_root
@vcs_root.setter
def vcs_root(self, vcs_root):
"""Sets the vcs_root of this VcsRoots.
:param vcs_root: The vcs_root of this VcsRoots. # noqa: E501
:type: list[VcsRoot]
"""
self._vcs_root = vcs_root
| [
"allburov@gmail.com"
] | allburov@gmail.com |
4614138089e9786f27b020db0dca4e5c32f2cf16 | f160d992d0ea5fa4e36af0025b5637c8962f2a29 | /dz101_spider/questions/mini_spider/dz101_question_mini_spider.py | f38e3cf331ad1a52bb4a38d8cdce2becab852b51 | [] | no_license | Zachypentakill/Afanti_tiku | 369dde43a32cecb136eb1207bf4223f6decd9843 | aebee5b3d8dce76f95620cb52fda5a0f19965945 | refs/heads/master | 2021-07-11T15:59:03.099600 | 2017-10-11T10:27:43 | 2017-10-11T10:27:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,615 | py | # -*- coding: utf-8 -*-
import asyncio
import logging
import json
from achihuo_mini.async_loop import AsyncLoop
from achihuo_mini.item import Item
from afanti_tiku_lib.utils import md5_string
from afanti_tiku_lib.dbs.mysql_pool import CommonMysql
from afanti_tiku_lib.dbs import html_archive
from afanti_tiku_lib.dbs.execute import execute
from afanti_tiku_lib.html.extract import get_html_element
from adsl_server.proxy import Proxy
from login import login
LOGGING_FORMAT = '%(asctime)-15s:%(levelname)s: %(message)s'
logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO,
filename='working/achihuo_mini.log', filemode='a')
mysql = CommonMysql('html_archive2')
mysql_conn = mysql.connection()
_proxy = Proxy()
INFOS = (
{'key': '初中语文', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 189, 'subj': '初中语文', 'aft_subj_id': 1,},
{'key': '初中数学', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 193, 'subj': '初中数学', 'aft_subj_id': 2,},
{'key': '初中英语', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 194, 'subj': '初中英语', 'aft_subj_id': 3,},
{'key': '初中物理', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 195, 'subj': '初中物理', 'aft_subj_id': 5,},
{'key': '初中化学', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 196, 'subj': '初中化学', 'aft_subj_id': 6,},
{'key': '初中生物', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 197, 'subj': '初中生物', 'aft_subj_id': 9,},
{'key': '初中政治', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 198, 'subj': '初中政治', 'aft_subj_id': 10,},
{'key': '初中历史', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 199, 'subj': '初中历史', 'aft_subj_id': 8,},
{'key': '初中地理', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 200, 'subj': '初中地理', 'aft_subj_id': 7,},
{'key': '高中语文', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 109, 'subj': '高中语文', 'aft_subj_id': 21,},
{'key': '高中数学', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 161, 'subj': '高中数学', 'aft_subj_id': 22,},
{'key': '高中英语', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 165, 'subj': '高中英语', 'aft_subj_id': 23,},
{'key': '高中物理', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 166, 'subj': '高中物理', 'aft_subj_id': 25,},
{'key': '高中化学', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 167, 'subj': '高中化学', 'aft_subj_id': 26,},
{'key': '高中生物', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 168, 'subj': '高中生物', 'aft_subj_id': 29,},
{'key': '高中政治', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 169, 'subj': '高中政治', 'aft_subj_id': 30,},
{'key': '高中历史', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 170, 'subj': '高中历史', 'aft_subj_id': 28,},
{'key': '高中地理', 'grade': '全部', 'limit': 100, 'skip':0, 'subj_id': 171, 'subj': '高中地理', 'aft_subj_id': 27,},
)
PARAM = ('Key={key}&Subject={subj}&QuestionTypes=&Difficulty=&Year='
'&Grade={grade}&Type=&Area=&subject_id={subj_id}'
'&Limit={limit}&Skip={skip}')
INTERNAL = 2 * 24 * 60 * 60
class Dz101QuestionMiniSpider(AsyncLoop):
NAME = 'dz101_question_mini_spider'
def __init__(self):
super(Dz101QuestionMiniSpider, self).__init__(concurrency=2, cache_backend='ssdb')
self.cookies = login('15542652940', 'www888xxx')
async def run(self):
for info in INFOS:
asyncio.ensure_future(self.get_pages(info))
async def get_pages(self, info):
no_new_question = 0
page_num = 0
N = 0
while True:
if no_new_question > 30:
no_new_question = 0
page_num = 0
await asyncio.sleep(INTERNAL)
continue
ninfo = dict(info)
ninfo['skip'] = page_num * 100
item = make_page_item(ninfo)
logging.info('[get_pages]: {}, {}'.format(info['key'], page_num))
item.proxy = 'http://' + '119.7.227.133:9990' # _proxy.get(server_id=105)
item.cookies = self.cookies
with await self.lock:
await asyncio.sleep(10)
resp = await self.async_web_request(item, check_html=check_pg)
if not (resp and resp.content):
continue
html_string = resp.text
if not N:
s = html_string.rfind('</div>|*|') + len('</div>|*|')
e = html_string.find('|', s)
qs_num = html_string[s:e]
if not qs_num:
logging.warn('not qs_num: {}'.format(
json.dumps(item.json(), ensure_ascii=False)))
continue
N = int(qs_num) + 100
if page_num * 100 > N:
await asyncio.sleep(INTERNAL)
continue
questions = get_html_element(
'<div [^<>]*class="Problems_item"',
html_string,
regex=True
)
has_qs = False
for qs in questions:
s = qs.find('<tt>') + 4
e = qs.find('</tt>')
qid = qs[s:e]
hkey = 'dz101_question_{}'.format(qid)
if is_archived(hkey):
continue
has_qs = True
logging.info('[question]: {}, {}'.format(info['key'], hkey))
save_html(hkey, qs, ninfo['aft_subj_id'], ninfo)
if not has_qs:
no_new_question += 1
else:
no_new_question = 0
page_num += 1
logging.info('[page done]')
def make_page_item(info):
url = 'http://www.dz101.com/zujuan/zhishidian/Problems'
item = Item(dict(
method = 'GET',
url = url + '?' + PARAM.format(**info),
max_retry = 2,
timeout = 120,
))
return item
def check_pg(html_string):
return 'class="Problems_item"' in html_string
def get_mysql_connection():
global mysql
global mysql_conn
try:
if mysql_conn.ping() is False:
mysql_conn = mysql.connection()
return mysql_conn
except Exception:
mysql_conn = mysql.connection()
return mysql_conn
def save_html(url, html_string, subj_id, info, flag=0):
mysql_conn = get_mysql_connection()
info = json.dumps(info, ensure_ascii=False)
sql, vals = html_archive.insert_sql(
'dz101_spider_html_archive_table',
dict(
key = url,
html = html_string,
md5 = md5_string(html_string),
subject = subj_id,
source = 56,
flag=flag,
info = info,
), ignore=True
)
execute(mysql_conn, sql, values=vals)
def is_archived(url):
mysql_conn = get_mysql_connection()
cmd = 'select html_id from dz101_spider_html_archive_table where `key` = %s and flag = 0'
result = execute(mysql_conn, cmd, values=(url,))
if result:
return True
else:
return False
# cmd = 'select question_id from question_pre.question where spider_url = %s and flag = 0'
# result = execute(mysql_conn, cmd, values=(url,))
# if result:
# result = True
# else:
# result = False
if __name__ == '__main__':
loop = Dz101QuestionMiniSpider()
loop.start()
| [
"yanfeng.li@lejent.com"
] | yanfeng.li@lejent.com |
50635945d92a8a30c541386a94cb0d6921c5d146 | 933cf8cc4cff1083f9e2d24528c97a94758bc8e0 | /astropy/wcs/wcsapi/utils.py | 53379b993dc646aa57a45e54f4c0a676d7dfff9e | [
"BSD-3-Clause"
] | permissive | eteq/astropy | e728384624d0c5d497bc5561f303f2a1bc4582ff | 6a4f41e22bd8bc6a0031415c771aa8f9d744e34e | refs/heads/staging | 2023-09-01T08:51:08.804445 | 2021-12-07T00:51:15 | 2021-12-07T00:51:15 | 2,103,466 | 1 | 1 | BSD-3-Clause | 2018-12-20T19:56:55 | 2011-07-25T21:02:57 | Python | UTF-8 | Python | false | false | 677 | py | import importlib
def deserialize_class(tpl, construct=True):
"""
Deserialize classes recursively.
"""
if not isinstance(tpl, tuple) or len(tpl) != 3:
raise ValueError("Expected a tuple of three values")
module, klass = tpl[0].rsplit('.', 1)
module = importlib.import_module(module)
klass = getattr(module, klass)
args = tuple([deserialize_class(arg) if isinstance(arg, tuple) else arg for arg in tpl[1]])
kwargs = dict((key, deserialize_class(val)) if isinstance(val, tuple) else (key, val) for (key, val) in tpl[2].items())
if construct:
return klass(*args, **kwargs)
else:
return klass, args, kwargs
| [
"thomas.robitaille@gmail.com"
] | thomas.robitaille@gmail.com |
3c6e5cf00966edb4796301a929fbbc97791f5cd9 | 4d387b596167e6636341bae268b2e582b22d5ff8 | /scripts/Meta/Copy_Files.py | 86fb8385b7b207de12f8ea0d64c6141be3e8cd91 | [] | no_license | tanmayshankar/Visualize_Primitives | f3357b1da95759567bf3abf4bf592cfddef5211e | 58f346208cc89265219295ecd5b617e1b8c9dd97 | refs/heads/master | 2021-01-19T13:52:57.156669 | 2017-03-26T23:01:58 | 2017-03-26T23:01:58 | 82,424,203 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 646 | py | #!/usr/bin/env python
import os
import subprocess
import sys
import shutil
import time
import signal
import numpy as npy
# FRCNN_DIR = "/home/tanmay/Code/py-faster-rcnn/tools"
# CPM_DIR = "/home/tanmay/Code/Realtime_Multi-Person_Pose_Estimation/testing/python"
# INTERP_DIR = "/home/tanmay/Code/Meta_Scripts"
IMG_DIR = "/home/tanmay/Code/Grid_Demo/Grid_Demo/"
LOC_DIR = "/home/tanmay/catkin_ws/src/Visualize_Primitives/Data/K2_Demos/Grid_Demo"
command = "scp tanmay@128.2.194.56:~/Code/Grid_Demo/Grid_Demo/D{0}/Interpolated_Depth_*.png D{0}/"
for i in range(1,11):
p = subprocess.Popen(command.format(i),shell=True)
p.wait()
time.sleep(2)
| [
"tanmay.shankar@gmail.com"
] | tanmay.shankar@gmail.com |
38d791179d75775bfc94f3b94fcadf5825a1ce61 | 642b7138da231474154a83c2dc3b4a2a42eb441b | /dp/subset_sum_divisible_by_num.py | e26d12eb1e480aa628c9042d7900f4e49be48bc5 | [] | no_license | somanshu/python-pr | 15465ed7182413591c709f9978420f6a16c9db91 | 7bfee6fc2a8340ba3e343f991a1da5bdb4ae9cb2 | refs/heads/master | 2020-07-02T17:21:37.132495 | 2019-08-22T08:04:11 | 2019-08-22T08:04:11 | 201,602,731 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 494 | py | # Given a set of non-negative distinct integers, and a value m, determine if
# there is a subset of the given set with sum divisible by m.
def get_subset(s, index, m, currentSum):
if currentSum > 0 and currentSum % m == 0:
return True
if index < 0:
return False
return get_subset(s, index - 1, m, currentSum) or get_subset(s, index - 1, m, currentSum + s[index])
s = [3, 1, 7, 5]
# s = [1, 6]
m = 6
# m = 5
index = len(s) - 1
print(get_subset(s, index, m, 0))
| [
"somanshu@logos.social"
] | somanshu@logos.social |
d3217f0ee0a2b85006978be11d3a0ae29fb0ac17 | 84a1f9d626828b6ecaee4ef037081f4d8750a990 | /编程/程序/十进制转二进制.py | 06d8e39924ca9cd5220c784d369d7cdda9e95e6b | [] | no_license | dujiaojingyu/Personal-programming-exercises | 5a8f001efa038a0cb3b6d0aa10e06ad2f933fe04 | 72a432c22b52cae3749e2c18cc4244bd5e831f64 | refs/heads/master | 2020-03-25T17:36:40.734446 | 2018-10-01T01:47:36 | 2018-10-01T01:47:36 | 143,986,099 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | def Dec2Bin(dec):
temp = []
result = ''#字符串
while dec:
quo = dec % 2
dec = dec // 2
temp.append(quo)
while temp:
result += str(temp.pop())
return result
print(Dec2Bin(62))
| [
"34296128+dujiaojingyu@users.noreply.github.com"
] | 34296128+dujiaojingyu@users.noreply.github.com |
dc4917189b065071bb39984413668e2ac2c859f5 | 793913495349a2a53565c9238915ff928995b555 | /django-easyvisa/english_page/views.py | a3028e1c80e00cc3317da7ef9721274453469c6d | [] | no_license | Naumov1889/django_easyvisa | 48ff9f56569e5950dbb700159c2a4b7515d87413 | 8c81f9e37ef4c6f44ad1f5aef3d00c136ef7bc40 | refs/heads/master | 2023-04-09T07:26:38.432411 | 2021-04-03T09:16:43 | 2021-04-03T09:16:43 | 277,068,342 | 0 | 0 | null | 2021-04-03T09:16:44 | 2020-07-04T08:15:02 | JavaScript | UTF-8 | Python | false | false | 235 | py | from django.shortcuts import render
from english_page.models import EnglishPrice
def english_page(request):
prices = EnglishPrice.objects.all().first()
return render(request, 'english_page/english.html', {'prices': prices})
| [
"144112passgitword"
] | 144112passgitword |
35e0daa8466311b20ce6fa92c764d84d2f973a23 | 8acffb8c4ddca5bfef910e58d3faa0e4de83fce8 | /ml-flask/Lib/site-packages/networkx/generators/tests/test_duplication.py | 6f0c7bba2b4170d7128591683cf7b26ad6244ece | [
"MIT"
] | permissive | YaminiHP/SimilitudeApp | 8cbde52caec3c19d5fa73508fc005f38f79b8418 | 005c59894d8788c97be16ec420c0a43aaec99b80 | refs/heads/master | 2023-06-27T00:03:00.404080 | 2021-07-25T17:51:27 | 2021-07-25T17:51:27 | 389,390,951 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:99d43639bea0ce795ffc6fcf063a2bc982ee6f2e94b736c4b58c242837a71094
size 1945
| [
"yamprakash130@gmail.com"
] | yamprakash130@gmail.com |
9406c2bdaf5dddc7a4148100cbd8ef8babd66090 | 3ee1bb0d0acfa5c412b37365a4564f0df1c093fb | /keras/keras36_hist5_diabets.py | 4fabc80b4372746cb9370aec93a29547b2966c07 | [] | no_license | moileehyeji/Study | 3a20bf0d74e1faec7a2a5981c1c7e7861c08c073 | 188843c6415a4c546fdf6648400d072359d1a22b | refs/heads/main | 2023-04-18T02:30:15.810749 | 2021-05-04T08:43:53 | 2021-05-04T08:43:53 | 324,901,835 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,406 | py | # hist를 이용하여 그래프를 그리시오
# loss, val_loss
import numpy as np
#1. 데이터
from sklearn.datasets import load_diabetes
dataset =load_diabetes()
x = dataset.data
y = dataset.target
print(x.shape)
print(y.shape)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.8, shuffle = True, random_state = 66)
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, train_size = 0.5, shuffle = False, random_state = 30)
#데이터 전처리3
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
x_val = scaler.transform(x_val)
#2.모델구성
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input
input1 = Input(shape=(10,))
dense = Dense(50, activation='linear')(input1)
dense = Dense(90, activation='linear')(dense)
# dense = Dense(100, activation='linear')(dense)
# dense = Dense(100, activation='linear')(dense)
# dense = Dense(100, activation='linear')(dense)
dense = Dense(80, activation='linear')(dense)
dense = Dense(80, activation='linear')(dense)
dense = Dense(80, activation='linear')(dense)
dense = Dense(20, activation='linear')(dense)
output = Dense(1)(dense)
model = Model(inputs=input1, outputs=output)
#3. 컴파일, 훈련
from tensorflow.keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='loss', patience=20, mode='auto')
model.compile(loss='mse', optimizer='adam', metrics=['mae'])
hist = model.fit(x_train, y_train, epochs=2000, batch_size=50, validation_data = (x_val, y_val), callbacks=[early_stopping])
# 그래프
import matplotlib.pyplot as plt
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('loss')
plt.ylabel('epochs')
plt.xlabel('loss')
plt.legend(['loss', 'val loss'])
plt.show()
# #4. 평가, 예측
# loss, mae = model.evaluate(x_test, y_test, batch_size=10)
# print('loss, mae : ', loss, mae)
# y_predict = model.predict(x_test)
# from sklearn.metrics import mean_squared_error, r2_score
# def RMSE (y_test, y_predict):
# return(np.sqrt(mean_squared_error(y_test, y_predict)))
# print('RMSE : ', RMSE(y_test, y_predict))
# print('R2 : ', r2_score(y_test, y_predict)) | [
"noreply@github.com"
] | moileehyeji.noreply@github.com |
9757613bcff8082143262d20e2291b9e7dc4f47c | 3b3585bb12becfe72af03814cec645b0c8e6c779 | /satchmo/fulfilment/modules/six/config.py | 5843693df8d189a95a02372e005d2daf69ad4a29 | [
"BSD-2-Clause"
] | permissive | juderino/jelly-roll | aac548073487511c5b935d9fb20c5a995c665b9b | ccac91bf3aab06fec4f83a7f9eabfa22d41b922a | refs/heads/master | 2021-01-18T21:04:15.232998 | 2015-07-21T20:35:26 | 2015-07-21T20:35:26 | 36,597,803 | 0 | 0 | null | 2015-05-31T10:16:21 | 2015-05-31T10:16:21 | null | UTF-8 | Python | false | false | 1,680 | py | from django.utils.translation import ugettext_lazy as _
from satchmo.configuration import (
ConfigurationGroup,
config_register_list,
StringValue,
BooleanValue,
)
from satchmo.fulfilment.config import ACTIVE_FULILMENT_HOUSE
import logging
log = logging.getLogger(__name__)
ACTIVE_FULILMENT_HOUSE.add_choice(('satchmo.fulfilment.modules.six', _('Six')))
FULILMENT_HOUSE = ConfigurationGroup(
'satchmo.fulfilment.modules.six',
_('Six Fulfilment Settings'),
requires=ACTIVE_FULILMENT_HOUSE,
ordering=101
)
config_register_list(
StringValue(
FULILMENT_HOUSE,
'API_KEY',
description=_("API Key"),
help_text=_("Client's API key, provided by fulfiller."),
default=u""
),
BooleanValue(
FULILMENT_HOUSE,
'TEST_MODE',
description=_("Test mode"),
help_text=_("Test identifier, must equal false for order to be processed."),
default=True
),
StringValue(
FULILMENT_HOUSE,
'URL',
description=_("API URL"),
help_text=_("URL of fulfillers API."),
default=u"https://[client].sixworks.co.uk/api/1/"
),
BooleanValue(
FULILMENT_HOUSE,
'UPDATE_STOCK',
description=_("Update Stock"),
help_text=_("Update stock based on the fulfilment houses stock levels."),
default=True
),
BooleanValue(
FULILMENT_HOUSE,
'ALLOW_PREORDER',
description=_("Allow Preorder"),
help_text=_("If true, permits acceptance of orders which contain lines currently out of stock. Disables Out-Of-Stock feedback in API response."),
default=False
),
)
| [
"tony@ynottony.net"
] | tony@ynottony.net |
11bcf91fc23f175de6c1f7766a58c9558e8198ab | 29f6b4804f06b8aabccd56fd122b54e4d556c59a | /CodeAnalysis/SourceMeter_Interface/SourceMeter-8.2.0-x64-linux/Python/Demo/ceilometer/ceilometer/tests/storage/test_impl_log.py | a12a4c4a5e8878baa8e02622ebde5d5722f131db | [
"Apache-2.0"
] | permissive | obahy/Susereum | 6ef6ae331c7c8f91d64177db97e0c344f62783fa | 56e20c1777e0c938ac42bd8056f84af9e0b76e46 | refs/heads/master | 2020-03-27T11:52:28.424277 | 2018-12-12T02:53:47 | 2018-12-12T02:53:47 | 146,511,286 | 3 | 2 | Apache-2.0 | 2018-12-05T01:34:17 | 2018-08-28T21:57:59 | HTML | UTF-8 | Python | false | false | 1,134 | py | #
# Copyright 2012 New Dream Network, LLC (DreamHost)
#
# Author: Doug Hellmann <doug.hellmann@dreamhost.com>
#
# 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 ceilometer/storage/impl_log.py
"""
from oslotest import base
from ceilometer.storage import impl_log
class ConnectionTest(base.BaseTestCase):
def test_get_connection(self):
conn = impl_log.Connection(None)
conn.record_metering_data({'counter_name': 'test',
'resource_id': __name__,
'counter_volume': 1,
})
| [
"abelgomezr45@gmail.com"
] | abelgomezr45@gmail.com |
0088554cddbce79223fbc75f4ed10baaafd29148 | 50de76eb887892c2085e1aa898987962a5d75380 | /_8_TensorFlowBasics/Kaggle/MNIST_example/MyVersion.py | 303758586192ffed1c2223ce19a995b6a0619cd1 | [] | no_license | cyrsis/TensorflowPY36CPU | cac423252e0da98038388cf95a3f0b4e62d1a888 | 6ada50adf63078ba28464c59808234bca3fcc9b7 | refs/heads/master | 2023-06-26T06:57:00.836225 | 2021-01-30T04:37:35 | 2021-01-30T04:37:35 | 114,089,170 | 5 | 2 | null | 2023-05-25T17:08:43 | 2017-12-13T07:33:57 | Jupyter Notebook | UTF-8 | Python | false | false | 3,555 | py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
np.random.seed(2)
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from keras.utils.np_utils import to_categorical # convert to one-hot-encoding
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import Adam , RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
train_data = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
X_train = train_data.drop("label", axis=1)
Y_train = train_data["label"]
X_train.isnull().any().describe()
test.isnull().any().describe()
# normalize the data
X_train = X_train / 255.0
test = test / 255.0
X_train = X_train.values.reshape(-1, 28, 28, 1)
test = test.values.reshape(-1, 28, 28, 1)
# one_hot on y
Y_train = to_categorical(Y_train, num_classes=10)
# Splite the data into 2
random_seed = 2
X_train, X_value, Y_train, Y_value = train_test_split(X_train, Y_train, test_size=0.2, random_state=random_seed)
g = plt.imshow(X_train[0][:, :, 0])
# Layer 1 = 2Conv 1 Max 1 Dropout
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='same', activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='same', activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# layer 2 = 2Conv 1 Max 1 Dropout
model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation="softmax"))
model.summary()
optimizer = Adam(lr=0.001)
model.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"])
epochs = 8000
batch_size = 100
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range=0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=False, # randomly flip images
vertical_flip=False) # randomly flip images
datagen.fit(X_train)
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001)
history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size),
epochs=epochs, validation_data=(X_value, Y_value),
verbose=2, steps_per_epoch=X_train.shape[0] // batch_size
, callbacks=[learning_rate_reduction])
model.save('kaggleMnist.h5') | [
"em3888@gmail.com"
] | em3888@gmail.com |
631df51128d1ead7ea74a4165ad84d1ae6ba2c21 | 113b962bd5e2eb770067bd374a15dfe8a1c2d09f | /py_scripts/ALC_Classify_mem.py | ac329f05c8175852db002aa7f765e64b208a2500 | [] | no_license | aungthurhahein/biotech_script | ecce51950bcef69405843da12ece2f84ea5541d6 | 2fda699343e6c46543fa1df2412c8ca2f2622cda | refs/heads/master | 2020-12-24T06:20:13.028141 | 2016-07-06T15:23:34 | 2016-07-06T15:23:34 | 25,574,741 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | #! /usr/bin/env/ python
"""
#
# usage:
# output:
# Dev: __author__ = 'aung'
# Date:
"""
import sys
A_id = sys.argv[1] # A
L_id = sys.argv[2] # L
C_id = sys.argv[3] # C
Cu_id = sys.argv[4] # C Unmap
cluster_file = sys.argv[5] # cluster parsed file
open_Aid = open(A_id, 'r')
open_Lid = open(L_id, 'r')
open_Cid = open(C_id, 'r')
open_Cuid = open(Cu_id, 'r')
open_cluster = open(cluster_file, 'r')
A_id_list = []
L_id_list = []
C_id_list = []
Cu_id_list = []
clst_list = []
for id1 in open_Aid:
A_id_list.append(id1.strip())
for id2 in open_Lid:
L_id_list.append(id2.strip())
for id3 in open_Cid:
C_id_list.append(id3.strip())
for id4 in open_Cuid:
Cu_id_list.append(id4.strip())
for cluster in open_cluster:
clst_list.append(cluster.strip())
for x in clst_list:
x_split = x.split('\t')
A_count = 0
L_count = 0
C_count = 0
Cu_count = 0
for mem in x_split[1:]:
if mem.strip() in A_id_list:
A_count += 1
elif mem.strip() in L_id_list:
L_count += 1
elif mem.strip() in C_id_list:
C_count += 1
elif mem.strip() in Cu_id_list:
Cu_count += 1
print x_split[0] + '\t' + str(A_count) +'\t' + str(L_count) +'\t' + str(C_count) +'\t' + str(Cu_count)
| [
"aungthurhahein@gmail.com"
] | aungthurhahein@gmail.com |
068c7cd5bd637d350ce9bd048c76e37c66724ddc | 84617010027b08e65412b0e187bc0612a59cfbc7 | /nomenklatura/views/sessions.py | 52b22af40c4de8eb7066b51ea550ebcf98409300 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | gabelula/nomenklatura | 16d52def8bb1c0dbc5a6aa386336366de31ffd79 | eae335a44ef6bb08728083d4d10386f3a9e16def | refs/heads/master | 2020-12-02T15:07:10.350344 | 2013-12-02T11:35:02 | 2013-12-02T11:35:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,968 | py | import requests
from flask import url_for, session, Blueprint, redirect
from flask import request
from flask.ext.utils.serialization import jsonify
from nomenklatura import authz
from nomenklatura.core import db, github
from nomenklatura.model import Account, Dataset
section = Blueprint('sessions', __name__)
@section.route('/sessions')
def status():
return jsonify({
'logged_in': authz.logged_in(),
'api_key': request.account.api_key if authz.logged_in() else None,
'account': request.account
})
@section.route('/sessions/authz')
def get_authz():
permissions = {}
dataset_name = request.args.get('dataset')
if dataset_name is not None:
dataset = Dataset.find(dataset_name)
permissions[dataset_name] = {
'view': True,
'edit': authz.dataset_edit(dataset),
'manage': authz.dataset_manage(dataset)
}
return jsonify(permissions)
@section.route('/sessions/login')
def login():
callback=url_for('sessions.authorized', _external=True)
return github.authorize(callback=callback)
@section.route('/sessions/logout')
def logout():
authz.require(authz.logged_in())
session.clear()
#flash("You've been logged out.", "success")
return redirect(url_for('index'))
@section.route('/sessions/callback')
@github.authorized_handler
def authorized(resp):
if not 'access_token' in resp:
return redirect(url_for('index'))
access_token = resp['access_token']
session['access_token'] = access_token, ''
res = requests.get('https://api.github.com/user?access_token=%s' % access_token,
verify=False)
data = res.json()
for k, v in data.items():
session[k] = v
account = Account.by_github_id(data.get('id'))
if account is None:
account = Account.create(data)
db.session.commit()
#flash("Welcome back, %s." % account.login, "success")
return redirect(url_for('index'))
| [
"friedrich@pudo.org"
] | friedrich@pudo.org |
c71e76456021d181e3109d58483b2b6cb52826cc | 811e4542f6728e2f3de98fc227f9f4a111d4eb1e | /templates/topics/math/factorization.py | 4c5332d9ce120a59f4ac95ff1464c5f004608320 | [] | no_license | Alfred-Walker/ppst | ab2902f04a73048f73b50d3c79d9e80cd257a985 | 8685d0ca7e89be34372a7d2673e21abb77bb3778 | refs/heads/master | 2021-01-04T05:07:08.813035 | 2020-02-19T02:35:07 | 2020-02-19T02:35:07 | 240,400,000 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 816 | py | """factorization examples"""
class PrimeFactorization:
@staticmethod
def factorization(number):
ret = []
for i in range(2, int(number ** 0.5) + 1):
while number % i == 0:
ret.append(i)
number //= i
if number > 1:
ret.append(number)
return ret
prime_factors = PrimeFactorization.factorization(32)
print(prime_factors)
# >>> [2, 2, 2, 2, 2]
prime_factors = PrimeFactorization.factorization(15)
print(prime_factors)
# >>> [3, 5]
class Practice:
@staticmethod
def factorization(num):
ret = []
for i in range(2, int(num ** 0.5) + 1):
while num % i == 0:
ret.append(i)
num //= i
if num >= 2:
ret.append(num)
return ret
| [
"studio.alfred.walker@gmail.com"
] | studio.alfred.walker@gmail.com |
17cc97ea656c6d3d58dba14ba7110219c4c455a7 | 9e27f91194541eb36da07420efa53c5c417e8999 | /twilio/rest/chat/v1/__init__.py | 7698c973fa1814942bb972c9ac2a08709c89c066 | [] | no_license | iosmichael/flask-admin-dashboard | 0eeab96add99430828306b691e012ac9beb957ea | 396d687fd9144d3b0ac04d8047ecf726f7c18fbd | refs/heads/master | 2020-03-24T05:55:42.200377 | 2018-09-17T20:33:42 | 2018-09-17T20:33:42 | 142,508,888 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,299 | py | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from admin.twilio.base.version import Version
from admin.twilio.rest.chat.v1.credential import CredentialList
from admin.twilio.rest.chat.v1.service import ServiceList
class V1(Version):
def __init__(self, domain):
"""
Initialize the V1 version of Chat
:returns: V1 version of Chat
:rtype: twilio.rest.chat.v1.V1.V1
"""
super(V1, self).__init__(domain)
self.version = 'v1'
self._credentials = None
self._services = None
@property
def credentials(self):
"""
:rtype: twilio.rest.chat.v1.credential.CredentialList
"""
if self._credentials is None:
self._credentials = CredentialList(self)
return self._credentials
@property
def services(self):
"""
:rtype: twilio.rest.chat.v1.service.ServiceList
"""
if self._services is None:
self._services = ServiceList(self)
return self._services
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Chat.V1>'
| [
"michaelliu@iresearch.com.cn"
] | michaelliu@iresearch.com.cn |
68a6a2550cc81753aa234a09cb81ae0d79c49c3b | 2b15168bc67ee935446f51c46045f73346369c5a | /extract_ckpt_to_h5_weight.py | faeda2d12d610e45a0d94bce680cbd2a9bfed7bc | [] | no_license | jason9075/tf2_arcface | 6c37500c9c14170ea6731f6a0d79a19f088c32d3 | 6fabcdf9c3c9a12603456476fc8052de2830684d | refs/heads/master | 2023-04-30T11:42:52.845549 | 2021-04-01T06:59:39 | 2021-04-01T06:59:39 | 311,858,885 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 501 | py | import tensorflow as tf
from convert_tensorflow import create_training_model
num_of_class = 20000
IMAGE_SIZE = (112, 112)
CKPT = 'checkpoints/2021-03-29-10-26-19_e_1400'
MODEL_TYPE = 'mobilenetv3'
def main():
model = create_training_model(IMAGE_SIZE, num_of_class, mode='train', model_type=MODEL_TYPE)
model.load_weights(CKPT)
filename = CKPT.split('/')[-1]
model.save(f'saved_model/{filename}.h5', include_optimizer=True, save_format='h5')
if __name__ == '__main__':
main()
| [
"jason9075@gmail.com"
] | jason9075@gmail.com |
66620a99f9c591d0399fb64135bc18f5511daf3e | 9fa8c280571c099c5264960ab2e93255d20b3186 | /system/scientist/experiment/remove/view.py | e49dc213fd8a1d49e71b132d6416187033778689 | [
"MIT"
] | permissive | thuchula6792/AutoOED | 8dc97191a758200dbd39cd850309b0250ac77cdb | 272d88be7ab617a58d3f241d10f4f9fd17b91cbc | refs/heads/master | 2023-07-23T16:06:13.820272 | 2021-09-08T14:22:18 | 2021-09-08T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 636 | py | from system.gui.widgets.factory import create_widget
class RemoveExperimentView:
def __init__(self, root_view):
self.window = create_widget('toplevel', master=root_view.root, title='Remove Experiment')
self.widget = {}
self.widget['experiment_name'] = create_widget('labeled_combobox', master=self.window, row=0, column=0, columnspan=2,
text='Experiment name', required=True)
self.widget['remove'] = create_widget('button', master=self.window, row=1, column=0, text='Remove')
self.widget['cancel'] = create_widget('button', master=self.window, row=1, column=1, text='Cancel') | [
"yunsheng@mit.edu"
] | yunsheng@mit.edu |
9a38399c9e91b0b590e07ffec154c506173b08a7 | e526543920e4974504cb62802c393d5bc46559db | /female-labor-force/female_labor_force.py | 8661eaf2f43beec409de2f01b78fb6af53fc144d | [] | no_license | mare-astrorum/python-crash-course-practice | b843f2067208b749558c4423556498e643c5fa42 | 47423808902b75af9d7888d4f9fa9f083bce88f4 | refs/heads/master | 2020-09-06T19:02:09.837740 | 2019-11-08T17:30:52 | 2019-11-08T17:30:52 | 220,516,919 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,775 | py | import csv
from pygal_maps_world.maps import World
from country_codes import get_country_code
# Load the data.
filename = 'data/female_labor_force.csv'
with open(filename) as f:
reader = csv.reader(f)
# Find the header row.
for i, row in enumerate(reader):
if i == 4:
header_row = row
# Create the dictionary containing country code and percentage of women
# in labor force.
cc_pop = {}
for row in reader:
# Eliminate the empty rows.
if row:
# Find population in 2016.
population = row[61]
# Eliminate empty values.
if population != '':
population = int(float(population))
country_name = row[0]
country_code = get_country_code(country_name)
if country_code:
cc_pop[country_code] = population
# Group the countries into 3 percentage levels.
cc_pop_1, cc_pop_2, cc_pop_3 = {}, {}, {}
for cc, pop in cc_pop.items():
if pop < 30:
cc_pop_1[cc] = pop
elif pop < 45:
cc_pop_2[cc] = pop
else:
cc_pop_3[cc] = pop
# See how many countries are in each group.
print(len(cc_pop_1), len(cc_pop_2), len(cc_pop_3))
# Create the map.
wm = World()
wm.title = 'Female Labor Force in 2016, %'
wm.add('<30%', cc_pop_1)
wm.add('30-45%', cc_pop_2)
wm.add('>45%', cc_pop_3)
wm.render_to_file('female_labor_force.svg')
| [
"a@a.com"
] | a@a.com |
967ce7d0a562a19af62f740ed144332b93de848f | 89055b2f91fb608806d4cb92754ee51f9fd7b436 | /sign_up_students_first_version/signup_stats.py | 0c99c7abfe71c556a5e98605529d69cc7cf6a7f1 | [] | no_license | rosedu/web-workshops | 52c778242e62dd7dbf8e629ab5fc8424e86a63f4 | 28ff91dca7f84a4a58f2ece6b94f28403e667776 | refs/heads/webdev-landing | 2023-05-11T06:38:48.370896 | 2023-05-03T16:47:58 | 2023-05-03T16:47:58 | 2,889,807 | 2 | 0 | null | 2023-05-03T16:47:59 | 2011-12-01T08:53:18 | HTML | UTF-8 | Python | false | false | 1,222 | py | import sys
from collections import defaultdict
import yaml
mail_blacklist = ['google@gigibecali.ro']
def main():
count = defaultdict(int)
for document in list(yaml.load_all(sys.stdin))[5:-1]:
if document['email'] in mail_blacklist:
continue
count['_total'] += 1
value_sunt = document['sunt']
count['sunt', value_sunt] += 1
if value_sunt == 'student':
facultate = document['student-facultate']
if ('automatica' in facultate.lower() or
'calculatoare' in facultate.lower()):
facultate = 'ACS'
an = document.get('student-an')
if an == 'I':
an = '1'
if an == 'II':
an = '2'
if an == 'III':
an = '3'
if an and an[0] == '3':
an = '3'
count['sunt-student',
facultate,
an] += 1
for name in document['topic-stiu']:
count['stiu', name] += 1
for name in document['topic-vreau']:
count['vreau', name] += 1
from pprint import pprint
pprint(dict(count))
if __name__ == '__main__':
main()
| [
"alex@grep.ro"
] | alex@grep.ro |
e037b4c7567e546162b66093e9500d87196bea8f | 70fa6468c768d4ec9b4b14fc94fa785da557f1b5 | /lib/surface/compute/target_http_proxies/list.py | e0e69989cde89c8fa89a984c02884926d50f4f55 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | kylewuolle/google-cloud-sdk | d43286ef646aec053ecd7eb58566ab2075e04e76 | 75f09ebe779e99fdc3fd13b48621fe12bfaa11aa | refs/heads/master | 2020-04-20T22:10:41.774132 | 2019-01-26T09:29:26 | 2019-01-26T09:29:26 | 169,131,028 | 0 | 0 | NOASSERTION | 2019-02-04T19:04:40 | 2019-02-04T18:58:36 | Python | UTF-8 | Python | false | false | 2,877 | py | # -*- coding: utf-8 -*- #
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for listing target HTTP proxies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import lister
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.target_http_proxies import flags
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA)
class List(base.ListCommand):
"""List target HTTP proxies."""
@staticmethod
def Args(parser):
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
lister.AddBaseListerArgs(parser)
parser.display_info.AddCacheUpdater(flags.TargetHttpProxiesCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
request_data = lister.ParseNamesAndRegexpFlags(args, holder.resources)
list_implementation = lister.GlobalLister(
client, client.apitools_client.targetHttpProxies)
return lister.Invoke(request_data, list_implementation)
List.detailed_help = base_classes.GetGlobalListerHelp('target HTTP proxies')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(base.ListCommand):
"""List Target HTTP Proxies.."""
@classmethod
def Args(cls, parser):
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
lister.AddMultiScopeListerFlags(parser, regional=True, global_=True)
parser.display_info.AddCacheUpdater(flags.TargetHttpProxiesCompleterAlpha)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
request_data = lister.ParseMultiScopeFlags(args, holder.resources)
list_implementation = lister.MultiScopeLister(
client,
regional_service=client.apitools_client.regionTargetHttpProxies,
global_service=client.apitools_client.targetHttpProxies,
aggregation_service=client.apitools_client.targetHttpProxies)
return lister.Invoke(request_data, list_implementation)
ListAlpha.detailed_help = base_classes.GetMultiScopeListerHelp(
'target HTTP proxies',
scopes=[
base_classes.ScopeType.global_scope,
base_classes.ScopeType.regional_scope
])
| [
"cloudsdk.mirror@gmail.com"
] | cloudsdk.mirror@gmail.com |
8ee1e63fa12d87ff629257f88095d3dd0647cd17 | 92874c7364a5c7f026fbff1f06d3100280438724 | /pelicanconf.py | 54517ea5a124a86cd208cd1e99324be8e4b4bbcc | [] | no_license | quintusdias/quintusdias.github.io-src | 0c3e9d4d17def5a8761f0a1636d52c1147c9288f | 1dd2b3143abcc38d88d0f056e5023251c615ba36 | refs/heads/master | 2021-01-21T11:16:15.017329 | 2017-03-04T12:50:16 | 2017-03-04T12:50:16 | 83,545,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 909 | py | # -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'John Evans'
SITENAME = 'https://quintusdias.github.io'
SITEURL = 'https://quintusdias.github.io'
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
DEFAULT_DATE = 'fs'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| [
"john.g.evans.ne@gmail.com"
] | john.g.evans.ne@gmail.com |
0a360c6b7f3a6caf3da4bcdc61eee7acace23b5c | 75d04e22b2688bc0b2c0a8dd14a4336eeb4be3bd | /distribute_data.py | 69002acf95b7fa55d644aaa6f411974aa0a92fb3 | [] | no_license | vbvg2008/CAPSNET | 2cae7580b5e5ded96bceb67f80083f2f06654e08 | 5d069f7fbd8c42e2f24807f7740a97682172c254 | refs/heads/master | 2020-03-06T20:04:47.583855 | 2018-04-27T20:15:30 | 2018-04-27T20:15:30 | 127,044,254 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,710 | py | import os
from shutil import copyfile
original_root = '/home/jenno/Desktop/core50_128x128/'
train_root = '/home/jenno/Desktop/core50_static/train'
test_root = '/home/jenno/Desktop/core50_static/test'
train_session = ['s1','s2','s4','s5']
test_session = ['s3','s6']
#now begin copy training data
for s_current in train_session:
print(s_current)
session_folder = os.path.join(original_root,s_current)
object_list = os.listdir(session_folder)
for o_current in object_list:
object_folder = os.path.join(session_folder,o_current)
image_list = os.listdir(object_folder)
#check if the object folder exists in training
destination_root = os.path.join(train_root,o_current)
if os.path.isdir(destination_root) is False:
os.mkdir(destination_root)
for image in image_list:
src = os.path.join(object_folder,image)
dst = os.path.join(destination_root,image)
copyfile(src,dst)
#now begin copy testing data
for s_current in test_session:
print(s_current)
session_folder = os.path.join(original_root,s_current)
object_list = os.listdir(session_folder)
for o_current in object_list:
object_folder = os.path.join(session_folder,o_current)
image_list = os.listdir(object_folder)
#check if the object folder exists in training
destination_root = os.path.join(test_root,o_current)
if os.path.isdir(destination_root) is False:
os.mkdir(destination_root)
for image in image_list:
src = os.path.join(object_folder,image)
dst = os.path.join(destination_root,image)
copyfile(src,dst) | [
"shawnmengdong@gmail.com"
] | shawnmengdong@gmail.com |
0f04671661041f0b708c2620229f78f0c46f83c2 | 4d66af0a7c2cbcfae37fa12f650ccc2accf2708b | /NPAF_pb2_grpc.py | 1266fb26145d2dccfccf06644f48145b69d4b02d | [] | no_license | Tiffanyyor23/gRPC | 804a38bcce2c509feffee101b998385d529fad80 | 18c06a9cb14eae7e8a673fce5aad7811c7821c3a | refs/heads/master | 2023-08-01T09:42:44.731850 | 2021-09-16T04:10:43 | 2021-09-16T04:10:43 | 407,016,166 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,372 | py | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import NPAF_pb2 as NPAF__pb2
class RouteDataStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.CollectRoutes = channel.unary_unary(
'/RouteData/CollectRoutes',
request_serializer=NPAF__pb2.RouteRequest.SerializeToString,
response_deserializer=NPAF__pb2.DeviceRoutes.FromString,
)
class RouteDataServicer(object):
"""Missing associated documentation comment in .proto file."""
def CollectRoutes(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteDataServicer_to_server(servicer, server):
rpc_method_handlers = {
'CollectRoutes': grpc.unary_unary_rpc_method_handler(
servicer.CollectRoutes,
request_deserializer=NPAF__pb2.RouteRequest.FromString,
response_serializer=NPAF__pb2.DeviceRoutes.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'RouteData', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class RouteData(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def CollectRoutes(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/RouteData/CollectRoutes',
NPAF__pb2.RouteRequest.SerializeToString,
NPAF__pb2.DeviceRoutes.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
40876e5aad4716d60a85e698a8107b820be76212 | 2f19adddc875673df742475c1c97b5aca720cac7 | /venv/Lib/site-packages/pygame/examples/audiocapture.py | a5688898e35d724f0f1d1a57201e42275c36d548 | [] | no_license | rosepcaldas/Cursoemvideo | 4e71b1ce0fe6e5c2ac83a15ff9e18768778d1dab | c722b1f7f902e43168279cd4e0414215b8395dc6 | refs/heads/master | 2020-07-28T20:19:46.004918 | 2019-09-19T10:24:31 | 2019-09-19T10:24:31 | 209,524,974 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,276 | py | import time
import pygame as pg
if pg.get_sdl_version()[0] < 2:
raise SystemExit('This example requires pygame 2 and SDL2.')
from pygame._sdl2 import (
get_audio_device_name,
get_num_audio_devices,
AudioDevice,
AUDIO_F32,
AUDIO_ALLOW_FORMAT_CHANGE
)
pg.mixer.pre_init(44100, 32, 2, 512)
pg.init()
# init_subsystem(INIT_AUDIO)
names = [get_audio_device_name(x, 1) for x in range(get_num_audio_devices(1))]
print(names)
iscapture = 1
sounds = []
sound_chunks = []
def callback(audiodevice, audiomemoryview):
""" This is called in the sound thread.
Note, that the frequency and such you request may not be what you get.
"""
# print(type(audiomemoryview), len(audiomemoryview))
# print(audiodevice)
sound_chunks.append(bytes(audiomemoryview))
audio = AudioDevice(
devicename=names[0],
iscapture=1,
frequency=44100,
audioformat=AUDIO_F32,
numchannels=2,
chunksize=512,
allowed_changes=AUDIO_ALLOW_FORMAT_CHANGE,
callback=callback,
)
# start recording.
audio.pause(0)
print('recording with :%s:' % names[0])
time.sleep(5)
print('Turning data into a pygame.mixer.Sound')
sound = pg.mixer.Sound(buffer=b''.join(sound_chunks))
print('playing back recorded sound')
sound.play()
time.sleep(5)
| [
"rosepcaldas@gmail.com"
] | rosepcaldas@gmail.com |
fe123e0751e952b397db20f1c47b285ee1f6d27b | f569978afb27e72bf6a88438aa622b8c50cbc61b | /douyin_open/ShareIdShareId/__init__.py | b05b76dadef0b38f532e88c1a0b30e636ba79cb3 | [] | no_license | strangebank/swagger-petstore-perl | 4834409d6225b8a09b8195128d74a9b10ef1484a | 49dfc229e2e897cdb15cbf969121713162154f28 | refs/heads/master | 2023-01-05T10:21:33.518937 | 2020-11-05T04:33:16 | 2020-11-05T04:33:16 | 310,189,316 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 966 | py | # coding: utf-8
# flake8: noqa
"""
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import apis into sdk package
from douyin_open.ShareIdShareId.api.share_id_api import ShareIdApi
# import ApiClient
from douyin_open.ShareIdShareId.api_client import ApiClient
from douyin_open.ShareIdShareId.configuration import Configuration
# import models into sdk package
from douyin_open.ShareIdShareId.models.description import Description
from douyin_open.ShareIdShareId.models.error_code import ErrorCode
from douyin_open.ShareIdShareId.models.extra_body import ExtraBody
from douyin_open.ShareIdShareId.models.inline_response200 import InlineResponse200
from douyin_open.ShareIdShareId.models.inline_response200_data import InlineResponse200Data
| [
"strangebank@gmail.com"
] | strangebank@gmail.com |
4a0beee1ac136b3e523feffcfa1e9a36ce6d967f | 9c58a1f594e18cee20128f2c8dad8257429b10d1 | /custom_business_reports/wizard/sales_per_product.py | 495d5e1113521f969a5ae62178d4d361b1ebd2c6 | [] | no_license | gastonfeng/Odoo-eBay-Amazon | e8919768b2a1500209f209ee3aecc7f2fb10cda7 | a9c4a8a7548b19027bc0fd904f8ae9249248a293 | refs/heads/master | 2022-04-05T00:23:50.483430 | 2020-02-19T04:58:56 | 2020-02-19T04:58:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,007 | py | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from pytz import timezone
import pytz
from odoo import models, fields, api
class SalesPerProduct(models.TransientModel):
_name = 'sales.per.product.wizard'
period_start = fields.Date('Period start', help="Date when the current period starts, sales will be counted one day/week/month to the past and to the future of this date",
default = datetime.now() + timedelta(weeks=-1), required = True)
grouping_criteria = fields.Selection([('day', 'Day'), ('week', 'Week'), ('month', 'Month')], 'Grouping criteria', required=True, default='week')
drop_percentage = fields.Integer(required=True, help="This report shows LADs where the sales drop percentage is higher than this percentage", default=0)
@api.multi
def button_download_report(self):
return {
'type': 'ir.actions.act_url',
'url': '/reports/sales_per_product?id=%s' % (self.id),
'target': 'new',
}
| [
"yjm@mail.ru"
] | yjm@mail.ru |
ab83b4c18b59a01c63603528d3559e0f3d384862 | cd5746f8cc7aee1f20606a65b4fae0d5e8ee78dc | /Python Books/Mastering-Machine-Learning-scikit-learn/NumPy-Beginner/CODE/Chapter2/shapemanipulation.py | b1649ea9beac68249de1ddd6e164eba87ed89124 | [] | no_license | theGreenJedi/Path | df24fca355590efef0c6cb5c52e7216c6b5d2464 | b5ed2805dbb046480929e49e550bfd8af5bb4d6f | refs/heads/master | 2023-07-27T14:23:37.694546 | 2021-07-16T01:38:55 | 2021-07-16T01:38:55 | 87,686,563 | 8 | 2 | null | 2023-07-11T22:49:03 | 2017-04-09T05:57:30 | Jupyter Notebook | UTF-8 | Python | false | false | 1,451 | py | from __future__ import print_function
import numpy as np
# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates multi dimensional arrays slicing.
#
# Run from the commandline with
#
# python shapemanipulation.py
print("In: b = arange(24).reshape(2,3,4)")
b = np.arange(24).reshape(2,3,4)
print("In: b")
print(b)
#Out:
#array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
#
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
print("In: b.ravel()")
print(b.ravel())
#Out:
#array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
# 17, 18, 19, 20, 21, 22, 23])
print("In: b.flatten()")
print(b.flatten())
#Out:
#array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
# 17, 18, 19, 20, 21, 22, 23])
print("In: b.shape = (6,4)")
b.shape = (6,4)
print("In: b")
print(b)
#Out:
#array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]])
print("In: b.transpose()")
print(b.transpose())
#Out:
#array([[ 0, 4, 8, 12, 16, 20],
# [ 1, 5, 9, 13, 17, 21],
# [ 2, 6, 10, 14, 18, 22],
# [ 3, 7, 11, 15, 19, 23]])
print("In: b.resize((2,12))")
b.resize((2,12))
print("In: b")
print(b)
#Out:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
# [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
| [
"GreenJedi@protonmail.com"
] | GreenJedi@protonmail.com |
8db48489893a0ddd39db9dc8bd3cba251c0a46ba | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_determinations.py | 19cd727e8dba49b7d873037177329135ce8d5944 | [
"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 | 287 | py |
from xai.brain.wordbase.nouns._determination import _DETERMINATION
#calss header
class _DETERMINATIONS(_DETERMINATION, ):
def __init__(self,):
_DETERMINATION.__init__(self)
self.name = "DETERMINATIONS"
self.specie = 'nouns'
self.basic = "determination"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
83c9ee9ea54b7d98e295f2b62de4a2bc7770d39d | a6cea8d1455f4927126b848c8598310a9242ab86 | /Handlers/Account.py | 53bd377011f4f62cef75ae4977af6e7d137b55db | [] | no_license | martin-woolstenhulme/sendwithfriends | 35b4410bda49fbfdfaf8920311e217db6758d2cf | 2daa32553dbace291c950ccd6de1bc5107ef50f7 | refs/heads/master | 2020-06-08T19:41:36.802905 | 2014-09-07T09:13:13 | 2014-09-07T09:13:13 | 23,756,328 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,823 | py | from flask import make_response
from flask import render_template, request, url_for, redirect, session, flash
from db_schema.db_functions import *
import json
from flask import jsonify
import logging
def signup_account():
data = request.json
print data
# retrieve information
password = data.get('password')
email = data.get('email')
userid = addUserAccount('', '', email, '')
mm={'error':None, 'status':'ok'}
mm['next_url'] = '/profile'
if mm['error'] is not None:
mm['status'] = 'error'
mm['userid'] = userid
resp = make_response(jsonify(mm))
resp.headers['Content-Type'] = "application/json"
return resp
def update_account():
data = request.json
print data
token = data.get('token')
provider = 'braintree'
userid = read_cookie()
# retrieve information
name = data.get('name').split()
firstname = name[0]
lastname = name[1]
phone = data.get('tel')
user = getUser(userid)
email = user[2]
userid = updateUserAccount(userid, firstname, lastname, email, phone)
addPayment(userid, token, provider)
mm={'error':None, 'status':'ok'}
mm['next_url'] = '/add_contact'
if mm['error'] is not None:
mm['status'] = 'error'
resp = make_response(jsonify(mm))
resp.headers['Content-Type'] = "application/json"
return resp
def update_contacts():
data = request.json
print data
emails = data.get('emails')
userid = read_cookie()
for e in emails:
addFriendByEmail(userid, e)
mm={'error':None, 'status':'ok'}
mm['next_url'] = '/send_money'
resp = make_response(jsonify(mm))
resp.headers['Content-Type'] = "application/json"
return resp
def read_cookie():
return request.cookies.get('userid') | [
"elaine.ou@gmail.com"
] | elaine.ou@gmail.com |
4c93cf5084fb9a5d19b1bb301af8711a8767007c | 75169b83f2b975bff8baf61f0cf1264cf4b71a28 | /worker/Reversion/model/alert.py | 5d39269c05c0207078a50efc165d26a768c682bb | [] | no_license | Pangpang2/Python | a27024587ae51923954deefaaff304a26e5a944f | 0b3bcfbdcaa71253c798090713c052fd397bff3f | refs/heads/master | 2022-12-01T10:03:23.214443 | 2020-08-26T00:21:15 | 2020-08-26T00:21:15 | 290,171,195 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 268 | py |
class Alert(object):
def __init__(self):
self.id = ''
self.description = ''
def to_dictionary(self):
alert_dict = {}
alert_dict['id'] = self.id
alert_dict['description'] = self.description
return alert_dict
| [
"may.li@internetbrands.com"
] | may.li@internetbrands.com |
9d831a96d6db798d73e1650111af5d03adeab6f4 | 89260668655a46278e8f22a5807b1f640fd1490c | /mySite/records/migrations/0014_auto_20170529_0026.py | 0f52f66b638d5bcb22cd6f408f1e76344fa3d40d | [] | no_license | happychallenge/mySite | 926136859c5b49b7fd8baff09b26f375b425ab30 | ddbda42d5d3b9c380a594d81a27875b4ad10358b | refs/heads/master | 2020-12-30T13:28:31.018611 | 2017-11-08T02:52:18 | 2017-11-08T02:52:18 | 91,218,922 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,759 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-29 00:26
from __future__ import unicode_literals
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),
('records', '0013_auto_20170525_2329'),
]
operations = [
migrations.CreateModel(
name='Evidence',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('created_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('news', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='records.News')),
('personevent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='records.PersonEvent')),
],
),
migrations.AlterUniqueTogether(
name='eventnews',
unique_together=set([]),
),
migrations.RemoveField(
model_name='eventnews',
name='created_user',
),
migrations.RemoveField(
model_name='eventnews',
name='event',
),
migrations.RemoveField(
model_name='eventnews',
name='news',
),
migrations.DeleteModel(
name='EventNews',
),
migrations.AlterUniqueTogether(
name='evidence',
unique_together=set([('personevent', 'news')]),
),
]
| [
"happychallenge@outlook.com"
] | happychallenge@outlook.com |
0805fbf1572f603152c9f49194310966efe9515c | 846906de1e1ce1579ed8c0bc6ba3454f87791856 | /NetworkBehaviour/Logic/TensorflowModules/TensorflowBehaviour.py | 262439e6a4403a4cd3f4d29f39b56674682f1f88 | [] | no_license | abahmer/PymoNNto | 48d1a53d660c6da7f45048e61f6bd8954f24ecaf | 17e117c971c1faa44205a69fc095a392aa7a7b9a | refs/heads/master | 2023-03-21T07:40:42.336567 | 2021-03-08T12:28:46 | 2021-03-08T12:28:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py | from PymoNNto.NetworkCore.Behaviour import *
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
class TensorflowBehaviour(Behaviour):
def set_variables(self, neurons):
if not hasattr(neurons, 'tf'):
neurons.tf = tf
super().set_variables(neurons)
| [
"mv15go@gmail.com"
] | mv15go@gmail.com |
e2eb4050d6367ccba352643e8999a26590f0a3d0 | 453ca12d912f6498720152342085636ba00c28a1 | /leetcode/backtracking/python/wildcard_matching_leetcode.py | 67c7f721cab4c6eab9cd03006a6c461377f9bfb3 | [] | no_license | yanbinkang/problem-bank | f9aa65d83a32b830754a353b6de0bb7861a37ec0 | bf9cdf9ec680c9cdca1357a978c3097d19e634ae | refs/heads/master | 2020-06-28T03:36:49.401092 | 2019-05-20T15:13:48 | 2019-05-20T15:13:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,976 | py | """
https://leetcode.com/problems/wildcard-matching/
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") => false
isMatch("aa","aa") => true
isMatch("aaa","aa") => false
isMatch("aa", "*") => true
isMatch("aa", "a*") => true
isMatch("ab", "?*") => true
isMatch("aab", "c*a*b") => false
"""
"""
ref: https://longwayjade.wordpress.com/2015/04/26/leetcode-recursion-dp-greedy-wildcard-matching/
O(p * s) where p and s are the lengths of the pattern and input strings.
"""
def is_match_2(s, p):
i, j = 0, 0
asterick, match = -1, -1
"""
asterick: once we found a star, we want to record the place of the star
match: once we found a star, we want to start to match the rest of the pattern with the string, starting from the match position. This is for remembering the place where we need to start
"""
# we check and match every char in s
while i < len(s):
# we are not currently at '*'. s and p match or p == '?'
if j < len(p) and (s[i] == p[j] or p[j] == '?'):
i += 1
j += 1
# we are currently at a '*'
elif j < len(p) and p[j] == '*':
match = i
asterick = j
j += 1
# they do not match, we are not currently at '*' but the last match is '*'
elif asterick >= 0:
match += 1
i = match
j = asterick + 1
# they do not match, we are not at '*' and last matched is not a '*', then the answer is false
else:
return False
# when we finish matching all chars in s, is pattern also finished? we cound only allow '*' at the rest of pattern
while j < len(p) and p[j] == '*':
j += 1
return j == len(p)
def is_match_1(s, p):
return is_match_rec(s, p, 0, 0)
def is_match_rec(text, pattern, i, j):
if i == len(text) and j == len(pattern):
return True
if j < len(pattern) and pattern[j] == '*':
while j < len(pattern) - 1 and pattern[j + 1] == '*':
j += 1
for k in range(i, len(text) + 1):
if is_match_rec(text, pattern, k, j + 1):
return True
# if k >= len(text):
# return False
# if pattern[j] != '*' and k != j:
# return False
return False
elif i < len(text) and j < len(pattern) and\
(pattern[j] == '?' or pattern[j] == text[i]):
return is_match_rec(text, pattern, i + 1, j + 1)
return False
def is_match(s, p):
string = list(s)
pattern = list(p)
write_index = 0
is_first = True
# replace multiple * with one *
# e.g a**b***c --> a*b*c
for i in range(len(pattern)):
if pattern[i] == '*':
if is_first:
pattern[write_index] = pattern[i]
write_index += 1
is_first = False
else:
pattern[write_index] = pattern[i]
write_index += 1
is_first = True
table = [[False for i in range(write_index + 1)] for j in range(len(s) + 1)]
if write_index > 0 and pattern[0] == '*':
table[0][1] = True
table[0][0] = True
for i in range(1, len(table)): # string
for j in range(1, len(table[0])): # pattern
if pattern[j -1] == '?' or string[i - 1] == pattern[j - 1]:
table[i][j] = table[i - 1][j - 1]
elif pattern[j - 1] == '*':
table[i][j] = table[i - 1][j] or table[i][j - 1]
# print table
return table[-1][-1]
# print is_match('xaylmz', 'x?y*z')
# print is_match('aab', 'c*a*b')
# print is_match('aaa','aa')
# print is_match('aa', '*')
# print is_match('aa','a')
# print is_match('aa','aa')
# print is_match('ab', '?*')
# print is_match('aa', 'a*')
# print is_match('', '')
# print is_match('zacabz', '*a?b*')
# print('\n')
# print is_match_1('xaylmz', 'x?y*z')
# print is_match_1('aab', 'c*a*b')
# print is_match_1('aaa','aa')
# print is_match_1('aa', '*')
# print is_match_1('aa','a')
# print is_match_1('aa','aa')
# print is_match_1('ab', '?*')
# print is_match_1('aa', 'a*')
# print is_match_1('', '')
# print is_match_1('zacabz', '*a?b*')
# print is_match_1('babaaababaabababbbbbbaabaabbabababbaababbaaabbbaaab', '***bba**a*bbba**aab**b')
# print('\n')
print is_match_2('xaylmz', 'x?y*z')
print is_match_2('aab', 'c*a*b')
print is_match_2('aaa','aa')
print is_match_2('aa', '*')
print is_match_2('aa','a')
print is_match_2('aa','aa')
print is_match_2('ab', '?*')
print is_match_2('aa', 'a*')
print is_match_2('', '')
print is_match_2('zacabz', '*a?b*')
print is_match_2('babaaababaabababbbbbbaabaabbabababbaababbaaabbbaaab', '***bba**a*bbba**aab**b')
| [
"albert.agram@gmail.com"
] | albert.agram@gmail.com |
ef815d59dad6b7592dd1e4fd7515e8cce1897def | 6189f34eff2831e3e727cd7c5e43bc5b591adffc | /WebMirror/management/rss_parser_funcs/feed_parse_extractMasterpasterWordpressCom.py | 4f0f90aed8ef9c7ad57e152828a2279189a98583 | [
"BSD-3-Clause"
] | permissive | fake-name/ReadableWebProxy | 24603660b204a9e7965cfdd4a942ff62d7711e27 | ca2e086818433abc08c014dd06bfd22d4985ea2a | refs/heads/master | 2023-09-04T03:54:50.043051 | 2023-08-26T16:08:46 | 2023-08-26T16:08:46 | 39,611,770 | 207 | 20 | BSD-3-Clause | 2023-09-11T15:48:15 | 2015-07-24T04:30:43 | Python | UTF-8 | Python | false | false | 647 | py | def extractMasterpasterWordpressCom(item):
'''
Parser for 'masterpaster.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('shinmai', 'Shinmai Maou no Keiyakusha', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"something@fake-url.com"
] | something@fake-url.com |
9f6345850132d48dabb1e26044ea02ea449056c4 | 4c9a5f1b44ad6fa84a984b8164414c99aba7f391 | /pepper/modules/python/Stitch.py | 0734eb61c124c59b09ff199496d23bcc7754cb4f | [
"MIT"
] | permissive | kishwarshafin/pepper | 20760a2a820d77ca5fc798957f0de658e936dcca | 30c8907501b254bb72d8f64dfb8cf54a1b7a60eb | refs/heads/r0.8 | 2023-08-04T07:03:53.564606 | 2022-07-08T18:22:01 | 2022-07-08T18:22:01 | 185,895,043 | 219 | 41 | MIT | 2023-07-22T05:17:46 | 2019-05-10T01:13:11 | Python | UTF-8 | Python | false | false | 5,521 | py | import h5py
import sys
from os.path import isfile, join
from os import listdir
import concurrent.futures
import numpy as np
from collections import defaultdict
import operator
from pepper.modules.python.Options import ImageSizeOptions
from datetime import datetime
label_decoder = {1: 'A', 2: 'C', 3: 'G', 4: 'T', 0: ''}
MIN_SEQUENCE_REQUIRED_FOR_MULTITHREADING = 2
def get_file_paths_from_directory(directory_path):
"""
Returns all paths of files given a directory path
:param directory_path: Path to the directory
:return: A list of paths of files
"""
file_paths = [join(directory_path, file) for file in listdir(directory_path)
if isfile(join(directory_path, file)) and file[-2:] == 'h5']
return file_paths
def chunks(file_names, threads):
"""Yield successive n-sized chunks from l."""
chunks = []
for i in range(0, len(file_names), threads):
chunks.append(file_names[i:i + threads])
return chunks
def small_chunk_stitch(contig, small_chunk_keys):
# for chunk_key in small_chunk_keys:
base_prediction_dictionary = defaultdict()
# phred_score_dictionary = defaultdict()
all_positions = set()
# ignore first 2 * MIN_IMAGE_OVERLAP bases as they are just overlaps
buffer_positions = ImageSizeOptions.MIN_IMAGE_OVERLAP * 2
for file_name, contig_name, _st, _end in small_chunk_keys:
chunk_name = contig_name + '-' + str(_st) + '-' + str(_end)
with h5py.File(file_name, 'r') as hdf5_file:
smaller_chunks = set(hdf5_file['predictions'][contig][chunk_name].keys()) - {'contig_start', 'contig_end'}
smaller_chunks = sorted(smaller_chunks)
for i, chunk in enumerate(smaller_chunks):
with h5py.File(file_name, 'r') as hdf5_file:
bases = hdf5_file['predictions'][contig][chunk_name][chunk]['bases'][()]
# phred_score = hdf5_file['predictions'][contig][chunk_name][chunk]['phred_score'][()]
positions = hdf5_file['predictions'][contig][chunk_name][chunk]['position'][()]
indices = hdf5_file['predictions'][contig][chunk_name][chunk]['index'][()]
positions = np.array(positions, dtype=np.int64)
base_predictions = np.array(bases, dtype=np.int)
# if _st == 107900:
# print(positions)
for pos, indx, base_pred in zip(positions, indices, base_predictions):
# not take the first buffer bases for every chunk that has an overlap to the last chunk
if _st > 0 and pos <= _st + buffer_positions:
continue
if indx < 0 or pos < 0:
continue
base_prediction_dictionary[(pos, indx)] = base_pred
# phred_score_dictionary[(pos, indx)] = base_score + 33
all_positions.add((pos, indx))
if len(all_positions) == 0:
return -1, -1, ''
pos_list = sorted(list(all_positions), key=lambda element: (element[0], element[1]))
dict_fetch = operator.itemgetter(*pos_list)
# weird but python has no casting between np.int64 to list
if len(pos_list) > 1:
predicted_base_labels = list(dict_fetch(base_prediction_dictionary))
# predicted_phred_scores = list(dict_fetch(phred_score_dictionary))
else:
predicted_base_labels = [dict_fetch(base_prediction_dictionary)]
# predicted_phred_scores = [dict_fetch(phred_score_dictionary)]
sequence = ''.join([label_decoder[base] for base in predicted_base_labels])
# phred_score = ''.join([chr(phred_score) for base, phred_score in zip(predicted_base_labels, predicted_phred_scores) if base != 0])
first_pos = pos_list[0][0]
last_pos = pos_list[-1][0]
return first_pos, last_pos, sequence
def create_consensus_sequence(contig, sequence_chunk_keys, threads):
sequence_chunk_keys = sorted(sequence_chunk_keys, key=lambda element: (element[1]))
sequence_chunk_key_list = list()
for file_name, sequence_chunk_key, contig_start, contig_end in sequence_chunk_keys:
sequence_chunk_key_list.append((file_name, contig, int(contig_start), int(contig_end)))
sequence_chunk_key_list = sorted(sequence_chunk_key_list, key=lambda element: (element[2], element[3]))
sequence_chunks = list()
# generate the dictionary in parallel
with concurrent.futures.ProcessPoolExecutor(max_workers=threads) as executor:
file_chunks = chunks(sequence_chunk_key_list, max(MIN_SEQUENCE_REQUIRED_FOR_MULTITHREADING,
int(len(sequence_chunk_key_list) / threads) + 1))
futures = [executor.submit(small_chunk_stitch, contig, chunk) for chunk in file_chunks]
for fut in concurrent.futures.as_completed(futures):
if fut.exception() is None:
first_pos, last_pos, sequence = fut.result()
if first_pos != -1 and last_pos != -1:
sequence_chunks.append((first_pos, last_pos, sequence))
else:
sys.stderr.write("[" + str(datetime.now().strftime('%m-%d-%Y %H:%M:%S')) + "] ERROR: " + str(fut.exception()) + "\n")
fut._result = None # python issue 27144
sequence_chunks = sorted(sequence_chunks, key=lambda element: (element[0], element[1]))
stitched_sequence = ''
for first_pos, last_pos, sequence in sequence_chunks:
stitched_sequence = stitched_sequence + sequence
return stitched_sequence
| [
"kishwar.shafin@gmail.com"
] | kishwar.shafin@gmail.com |
6557d0f91c736194fd7b901916bf5c217d93a5c8 | e2f20ded13f4877248b2db7d5251c701bc586745 | /hggStyle.py | b743da4cb04a28f2693918482b6b945763ab6a92 | [] | no_license | flashgg-validation/plotZeeValidation | 965f1c8c8dd5aa5e7250abad04add18a48955ee8 | 0c845060d7498ce92780839ec2da46515145abf3 | refs/heads/master | 2021-01-17T07:52:56.292151 | 2017-02-13T15:18:21 | 2017-02-13T15:18:21 | 60,186,146 | 0 | 2 | null | 2016-06-03T15:03:54 | 2016-06-01T14:53:36 | Python | UTF-8 | Python | false | false | 1,451 | py | import ROOT
def hggStyle():
hggStyle = ROOT.TStyle("hggPaperStyle","Hgg Paper Style")
hggStyle.SetFrameFillColor(0)
hggStyle.SetStatColor(0)
hggStyle.SetOptStat(0)
hggStyle.SetTitleFillColor(0)
hggStyle.SetCanvasBorderMode(0)
hggStyle.SetPadBorderMode(0)
hggStyle.SetFrameBorderMode(0)
hggStyle.SetPadColor(ROOT.kWhite)
hggStyle.SetCanvasColor(ROOT.kWhite)
hggStyle.SetCanvasDefH(600) #Height of canvas
hggStyle.SetCanvasDefW(600) #Width of canvas
hggStyle.SetCanvasDefX(0) #POsition on screen
hggStyle.SetCanvasDefY(0)
hggStyle.SetPadLeftMargin(0.13)#0.16)
hggStyle.SetPadRightMargin(0.1)#0.02)
hggStyle.SetPadTopMargin(0.085)#0.02)
hggStyle.SetPadBottomMargin(0.12)#0.02)
# For hgg axis titles:
hggStyle.SetTitleColor(1, "XYZ")
hggStyle.SetTitleFont(42, "XYZ")
hggStyle.SetTitleSize(0.05, "XYZ")
hggStyle.SetTitleXOffset(0.95)#0.9)
hggStyle.SetTitleYOffset(1.15) # => 1.15 if exponents
# For hgg axis labels:
hggStyle.SetLabelColor(1, "XYZ")
hggStyle.SetLabelFont(42, "XYZ")
hggStyle.SetLabelOffset(0.007, "XYZ")
hggStyle.SetLabelSize(0.04, "XYZ")
# Legends
hggStyle.SetLegendBorderSize(0)
hggStyle.SetLegendFillColor(ROOT.kWhite)
hggStyle.SetLegendFont(42)
hggStyle.SetFillColor(10)
# Nothing for now
hggStyle.SetTextFont(42)
hggStyle.SetTextSize(0.03)
hggStyle.cd()
| [
"matteosan1@gmail.com"
] | matteosan1@gmail.com |
868f76281959f6253538cf380f9a2a1802982d27 | 80bbc5a4a5ebbf1be75afc8cd0102dcd60a6a081 | /huaula/github.py | 3aa2e1ee9344de60626d53cb4631a59a37e5ffcd | [
"MIT"
] | permissive | renzon/hu | 642dc6bac9501eaee99623108d4c5c0aa04a1c52 | 4147f38e138e73db54cd9a81812795e793bdb921 | refs/heads/master | 2021-01-01T05:01:03.889460 | 2016-05-13T20:55:08 | 2016-05-13T20:55:08 | 58,227,578 | 2 | 1 | MIT | 2019-10-22T18:03:47 | 2016-05-06T18:38:25 | Python | UTF-8 | Python | false | false | 501 | py | import json
from os import path
import requests
diretorio_dese_arquivo = path.dirname(__file__)
diretorio_huaula = path.join(diretorio_dese_arquivo, '..')
diretorio_do_projeto = path.abspath(diretorio_huaula)
import sys
sys.path.append(diretorio_do_projeto)
from huaula import dunder_main
def buscar_avatar(nome):
r = requests.get('https://api.github.com/users/{}'.format(nome),)
dados = json.loads(r.text)
dunder_main.b
return dados['avatar_url']
print(buscar_avatar('renzon')) | [
"renzon@gmail.com"
] | renzon@gmail.com |
9e677bece07b63a388f96d5c6dd85353008dfab7 | 531c5c6fab45a69c36b716196c713fa1b67cc88f | /0x00_ret2win/32-bit/exploit.py | 11229c37cbfd158ba3eb985b9b7c4fcab0a002ed | [] | no_license | youngkao/ROP_Emporium | b79a06bb97db9fc3d156c064a84f35e585493fa5 | d4ca8b99bf2960e2c867f3360c901e649a614f8c | refs/heads/master | 2022-02-19T04:05:33.706883 | 2019-09-25T12:23:39 | 2019-09-25T12:23:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 362 | py | import sys; sys.path.append("../..")
import shared_pwn
from pwn import *
BINARY_NAME = "ret2win32"
BUFFER_LEN = 44
io = process(f"./{BINARY_NAME}")
junk = b"\x90" * BUFFER_LEN
# Pointers
win_addr = p32(0x08048659)
# Payload creation
payload = b""
payload += junk
payload += win_addr
io.recvuntil("> ")
io.send(payload)
io.send("\n")
shared_pwn._recvall(io) | [
"afray@protonmail.com"
] | afray@protonmail.com |
c036217771fed754eb3e8ccbcefae4fe4921134a | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_variegated.py | 066dd80491cf63f80a64cabdac0ff24abbe116a3 | [
"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 | 414 | py |
#calss header
class _VARIEGATED():
def __init__(self,):
self.name = "VARIEGATED"
self.definitions = [u'having a pattern of different colours or marks: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'adjectives'
def run(self, obj1, obj2):
self.jsondata[obj2] = {}
self.jsondata[obj2]['properties'] = self.name.lower()
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
1b0da8a0baa221478bc19fb0a1088a711ad3a254 | 6ea679ac5cdaf5e6f8d9584194ad74440762eea3 | /lib/exabgp/bgp/message/open/capability/capability.py | 7a6fccdf09ef4c9778a8b12e6ea3e2e5c7eff9fa | [] | no_license | h-naoto/exabgp | 0d7b307d9e23e50a295bc70283141c58f9ef83f1 | 05a96e99c35256160df8923e7a17f57e3ca36e3d | refs/heads/master | 2021-01-15T18:04:42.333066 | 2015-02-05T08:11:37 | 2015-02-05T08:11:37 | 30,223,499 | 0 | 0 | null | 2015-02-03T03:48:25 | 2015-02-03T03:48:25 | null | UTF-8 | Python | false | false | 4,190 | py | # encoding: utf-8
"""
capability.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from exabgp.bgp.message.notification import Notify
# =================================================================== Capability
#
class Capability (object):
class CODE (int):
__slots__ = []
RESERVED = 0x00 # [RFC5492]
MULTIPROTOCOL = 0x01 # [RFC2858]
ROUTE_REFRESH = 0x02 # [RFC2918]
OUTBOUND_ROUTE_FILTERING = 0x03 # [RFC5291]
MULTIPLE_ROUTES = 0x04 # [RFC3107]
EXTENDED_NEXT_HOP = 0x05 # [RFC5549]
# 6-63 Unassigned
GRACEFUL_RESTART = 0x40 # [RFC4724]
FOUR_BYTES_ASN = 0x41 # [RFC4893]
# 66 Deprecated
DYNAMIC_CAPABILITY = 0x43 # [Chen]
MULTISESSION = 0x44 # [draft-ietf-idr-bgp-multisession]
ADD_PATH = 0x45 # [draft-ietf-idr-add-paths]
ENHANCED_ROUTE_REFRESH = 0x46 # [draft-ietf-idr-bgp-enhanced-route-refresh]
OPERATIONAL = 0x47 # ExaBGP only ...
# 70-127 Unassigned
ROUTE_REFRESH_CISCO = 0x80 # I Can only find reference to this in the router logs
# 128-255 Reserved for Private Use [RFC5492]
MULTISESSION_CISCO = 0x83 # What Cisco really use for Multisession (yes this is a reserved range in prod !)
EXTENDED_MESSAGE = -1 # No yet defined by draft http://tools.ietf.org/html/draft-ietf-idr-extended-messages-02.txt
unassigned = range(70,128)
reserved = range(128,256)
# Internal
AIGP = 0xFF00
names = {
RESERVED: 'reserved',
MULTIPROTOCOL: 'multiprotocol',
ROUTE_REFRESH: 'route-refresh',
OUTBOUND_ROUTE_FILTERING: 'outbound-route-filtering',
MULTIPLE_ROUTES: 'multiple-routes',
EXTENDED_NEXT_HOP: 'extended-next-hop',
GRACEFUL_RESTART: 'graceful-restart',
FOUR_BYTES_ASN: 'asn4',
DYNAMIC_CAPABILITY: 'dynamic-capability',
MULTISESSION: 'multi-session',
ADD_PATH: 'add-path',
ENHANCED_ROUTE_REFRESH: 'enhanced-route-refresh',
OPERATIONAL: 'operational',
ROUTE_REFRESH_CISCO: 'cisco-route-refresh',
MULTISESSION_CISCO: 'cisco-multi-sesion',
AIGP: 'aigp',
}
def __str__ (self):
name = self.names.get(self,None)
if name is None:
if self in Capability.CODE.unassigned:
return 'unassigned-%s' % hex(self)
if self in Capability.CODE.reserved:
return 'reserved-%s' % hex(self)
return 'capability-%s' % hex(self)
return name
def __repr__ (self):
return str(self)
@classmethod
def name (cls,self):
name = cls.names.get(self,None)
if name is None:
if self in Capability.CODE.unassigned:
return 'unassigned-%s' % hex(self)
if self in Capability.CODE.reserved:
return 'reserved-%s' % hex(self)
return name
registered_capability = dict()
_fallback_capability = None
@staticmethod
def hex (data):
return '0x' + ''.join('%02x' % ord(_) for _ in data)
@classmethod
def fallback_capability (cls, imp):
if cls._fallback_capability is not None:
raise RuntimeError('only one fallback function can be registered')
cls._fallback_capability = imp
@staticmethod
def register_capability (klass,capability=None):
# ID is defined by all the subclasses - otherwise they do not work :)
what = klass.ID if capability is None else capability # pylint: disable=E1101
if what in klass.registered_capability:
raise RuntimeError('only one class can be registered per capability')
klass.registered_capability[what] = klass
@classmethod
def klass (cls,what):
if what in cls.registered_capability:
kls = cls.registered_capability[what]
kls.ID = what
return kls
if cls._fallback_capability:
return cls._fallback_capability
raise Notify (2,4,'can not handle capability %s' % what)
@classmethod
def unpack (cls,capability,capabilities,data):
instance = capabilities.get(capability,Capability.klass(capability)())
return cls.klass(capability).unpack_capability(instance,data,capability)
| [
"thomas.mangin@exa-networks.co.uk"
] | thomas.mangin@exa-networks.co.uk |
2afaad96ff00e3e3de0b221b11e2f3db5bd578bf | d1f971b9fa0edfa633b62887cf9d173d6a86a440 | /data_structures_and_algorithms/exercises/Recursions/sum_digits_iterative.py | d6529b86b2ccb00c3aef778d5028fdab5cc12eec | [] | no_license | papan36125/python_exercises | d45cf434c15aa46e10967c13fbe9658915826478 | 748eed2b19bccf4b5c700075675de87c7c70c46e | refs/heads/master | 2020-04-28T10:01:10.361108 | 2019-05-10T13:45:35 | 2019-05-10T13:45:35 | 175,187,760 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 288 | py | # Linear - O(N)
def sum_digits(n):
if n < 0:
ValueError("Inputs 0 or greater only!")
result = 0
while n is not 0:
result += n % 10
n = n // 10
return result + n
sum_digits(12)
# 1 + 2
# 3
sum_digits(552)
# 5 + 5 + 2
# 12
sum_digits(123456789)
# 1 + 2 + 3 + 4...
# 45
| [
"noreply@github.com"
] | papan36125.noreply@github.com |
51278c6c7c276bdac6699685e2380d14239b4a52 | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/binaryTree2_20200617161602.py | 904a5a72342f25c5640e14213b27638d3386851d | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,105 | py | # Create a node and assign a value to the node
# A tree node contains data then pointer to left child and pointer to right child
class Node:
def __init__(self,data):
# designate one node as root
self.data = data
# then the two others as child nodes
self.left = None
self.right = None
def inorder(root,newArr):
if root:
# Traverse left
inorder(root.left,newArr)
newArr.append(root.data)
inorder(root.right,newArr)
print(newArr)
return newArr
def morris_traversal(root):
# function for iterative inorder tree traversal
current = root
while current is not None:
# do the following
if current.left is None:
yield current.data
else:
# find the current in order predecessor of current
pre = current.left
while pre.right is not None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(4)
root.left.left = Node(7)
print(inorder(root,[]))
| [
"mary.jereh@gmail.com"
] | mary.jereh@gmail.com |
c5c6fbb99ac0691b8a7dfdef534b8d24fd07f978 | 7b9527f6a66bf544071c07498163883ae33ff9ec | /python/1890.py | abe9b60579196c7c25b4d2637e34034451d9754d | [] | no_license | rhyun9584/BOJ | ec4133718934e59689cdcc0d3284bad9a412dc7a | f4c651da7c4840595175abf201d07151d4ac9402 | refs/heads/master | 2023-08-31T21:29:07.550395 | 2023-08-25T16:53:53 | 2023-08-25T16:53:53 | 225,122,352 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 861 | py | # 갈 수 없는 경로에 대해 체크할 수 있으면 시간이 더 줄어들것같은데...
import sys
sys.setrecursionlimit(10**5)
N = int(input())
maps = [list(map(int, input().split())) for _ in range(N)]
dp_table = [[0]*N for _ in range(N)]
dp_table[N-1][N-1] = 1
road = []
def dfs(x, y):
global count
d = maps[x][y]
if dp_table[x][y] > 0:
# (x,y)에 도착했을때 이미 갈 수 있는 경로의 경우의 수가 기록된 위치인 경우
# 그 경우의 수 만큼 더해주어 기록
for rx, ry in road:
dp_table[rx][ry] += dp_table[x][y]
return
# 중간에 0을 만나면 더이상 갈 수 없음
if d == 0:
return
road.append((x,y))
if x + d < N:
dfs(x+d, y)
if y + d < N:
dfs(x, y+d)
road.pop()
dfs(0, 0)
print(dp_table[0][0]) | [
"rhyun9584@naver.com"
] | rhyun9584@naver.com |
f0273087f58f8b16f942e2277ca294b63150082b | 7e40c8bb28c2cee8e023751557b90ef7ef518326 | /npuctf_2020_bad_guy/npuctf_2020_bad_guy.py | 932efdc96ee2919b873e1565c181f2bb8861c812 | [] | no_license | 1337536723/buuctf_pwn | b6e5d65372ed0638a722faef1775026a89321fa3 | cca3c4151a50c7d7c3237dab2c5a283dbcf6fccf | refs/heads/master | 2023-08-29T19:35:04.352530 | 2021-11-16T14:06:20 | 2021-11-16T14:06:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,190 | py | from pwn import *
#context.log_level = 'debug'
context.arch = 'amd64'
#p = remote('node4.buuoj.cn', )
libc = ELF('libc-2.23.buu.so')
ru = lambda s : p.recvuntil(s)
sn = lambda s : p.send(s)
sla = lambda r, s : p.sendlineafter(r, s)
sa = lambda r, s : p.sendafter(r, s)
sl = lambda s : p.sendline(s)
rv = lambda s : p.recv(s)
def debug(s):
gdb.attach(p, '''
source ~/libc/loadsym.py
loadsym ~/libc/2.23/64/libc-2.23.debug.so
''' + s)
def alloc(index, size, content):
sla(b'>> ', b'1')
sla(b'Index :', str(index).encode())
sla(b'size: ', str(size).encode())
sa(b'Content:', content)
def edit(index, size, content):
sla(b'>> ', b'2')
sla(b'Index :', str(index).encode())
sla(b'size: ', str(size).encode())
sa(b'content:', content)
def delete(index):
sla(b'>> ', b'3')
sla(b'Index :', str(index).encode())
def exp():
alloc(0, 0x10, b'a')
alloc(1, 0x10, b'a')
alloc(2, 0x60, b'a')
alloc(3, 0x10, b'a')
delete(2)
edit(0, 0x20, b'\x00' * 0x10 + p64(0) + p64(0x91))
delete(1)
alloc(1, 0x10, b'a')
edit(1, 0x22, b'a' * 0x10 + p64(0) + p64(0x71) + b'\xdd\x85')
alloc(2, 0x60, b'a')
# padding flag read_buf write_buf
layout = [
'\x00' * 0x33, 0xfbad1800, 0, 0, 0, b'\x58'
]
alloc(3, 0x60, flat(layout))
one_gadgets = [0x45206, 0x4525a, 0xef9f4, 0xf0897]
one_gadgets_buu = [0x45216, 0x4526a, 0xf02a4, 0xf1147]
libc_base = u64(rv(8)) - libc.sym['_IO_2_1_stdout_'] - 131
malloc_hook = libc_base + libc.sym['__malloc_hook']
one = libc_base + one_gadgets_buu[3]
success('libc_base -> {}'.format(hex(libc_base)))
#uaf
alloc(0, 0x60, b'a')
alloc(0, 0x60, b'a')
alloc(1, 0x60, b'a')
alloc(2, 0x60, b'a')
alloc(3, 0x30, b'a') #avoid merge
edit(0, 0x70, b'\x00' * 0x60 + p64(0) + p64(0xe1))
delete(1)
alloc(1, 0x60, b'a')
alloc(3, 0x60, b'a')
delete(3)
edit(2, 0x8, p64(malloc_hook - 0x23))
alloc(0, 0x60, b'a')
alloc(0, 0x60, b'\x00' * 0x13 + p64(one))
sla(b'>> ', b'1')
sla(b'Index :', b'0')
sla(b'size: ', b'20')
p.interactive()
if __name__ == "__main__":
while True:
try:
#p = process('./npuctf_2020_bad_guy')
p = remote('node4.buuoj.cn', 29604)
exp()
break
except:
p.close()
| [
"admin@srmxy.cn"
] | admin@srmxy.cn |
7280ce1423804ba07d711d41cda2d662613bc199 | 809e1b7ca0d9e265c4f3e49e18e4e3c64e561526 | /login/loginreg/views - Copy.py | f0f7cf87a84a6fd07bf8955930eddf73b1b74626 | [] | no_license | gitanjali1077/Login | e4a9c6ede5916a2d42440b29fdf424ad6a80a688 | 5823579b14df68874c8df07a95ec9a796b705207 | refs/heads/master | 2021-01-22T21:41:33.529308 | 2017-08-14T15:45:43 | 2017-08-14T15:45:43 | 85,465,261 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,251 | py | from login.settings import SENDER,PASS
import smtplib
from django.shortcuts import render,render_to_response
from django import forms
from django.views.generic import View
from django.views.generic.edit import FormView
from django.views import generic
#require a form to create a new object
from django.views.generic.edit import CreateView,UpdateView ,DeleteView
# for uploading form
from django.core.urlresolvers import reverse_lazy
# for login
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate,login,logout
from django.views.generic import View
from .forms import UserForm ,UserFormlog
from django.template import RequestContext
from django.contrib.auth import views as auth_views
from django.contrib import auth
from django.contrib.auth.decorators import login_required
# Create your views here.
def create_profile(request):
if request.method == 'GET':
user_form = UserForm
return render(request, 'profile.html', {
'user_form': user_form
})
if request.method == 'POST':
user_form = UserForm(request.POST)
if user_form.is_valid() :
user1= user_form.save(commit=False)
#prof= profile_form.save()
username = user_form.cleaned_data['username']
fname = user_form.cleaned_data['first_name']
password = user_form.cleaned_data['password']
email = user_form.cleaned_data['email']
user1.set_password(password)
user1.save()
msg="Hello , \n Welcome here"
smtp= smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(SENDER,PASS)
smtp.sendmail(SENDER,email,msg)
smtp.quit()
#profile=profile_form.save(commit=False)
#profile.user_id=user1.id+1
#profile.college=profile_form.cleaned_data['college']
#profile.save()
user = authenticate(username=username ,password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('index.html')
#return render(request,'index.html'
#profile_form.save()
#return redirect('settings:profile')
return render(request, 'register/profile.html', {
'user_form': user_form
})
def indexpage(request):
if request.method == 'GET':
user_form = UserForm
return render(request, 'index.html', )
global user_form1
#@login_required for stopping user from some pages
def userlogin(request):
ab="pagal hai"
if request.method == 'GET':
user_form = UserFormlog
return render(request, 'login.html', {
'form': user_form #user_form
})
if request.method == 'POST':
user_form1 = UserFormlog(request.POST)
if user_form1.is_valid() :
ab="post chala"
#prof= profile_form.save()
username = user_form1.cleaned_data['username']
password = user_form1.cleaned_data['password']
#profile=profile_form.save(commit=False)
#profile.user_id=user1.id+1
#profile.college=profile_form.cleaned_data['college']
#profile.save()
user1 = authenticate(username=username ,password=password)
if user1 :
auth.login(request, user1)
#return redirect('index.html')
return render(request,'index.html',{ 'user1': user_form1 })
else:
return redirect('nope.html')
#profile_form.save()
#return redirect('settings:profile')
else:
print user_form1.errors
return render(request, 'login.html', {
'user_form': user_form1 ,'ab':ab
})
def logout(request):
auth.logout(request)
#user_form1= users.objects.filter(user__username=request.user)
user_form1=request.user
user_form1.username=''
return render_to_response('login.html', {'box_width': '402',
'logged_out': '1',})
# context_instance=RequestContext(request))
| [
"gitanjali1077@gmail.com"
] | gitanjali1077@gmail.com |
65804be70908e44da99b1c7b18eab58a05435784 | 5fff534c0f5b5c1de498a9be7d7cd7f1f86ba5a1 | /myvenv/bin/viewer.py | 8aaa5b0ed68e599bb3af7c711324c71e7f4f1f55 | [] | no_license | baidoosik/portfolio | 1287d2e4803608f83e1ba4190d82af76fd29db08 | 6f4b2c861231fae326d47cbbe9711139ab041d59 | refs/heads/master | 2021-01-18T03:14:01.288730 | 2017-06-14T14:59:51 | 2017-06-14T14:59:51 | 85,835,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 998 | py | #!/Users/doosikbai/worldnomade/myvenv/bin/python3
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
try:
from tkinter import Tk, Label
except ImportError:
from Tkinter import Tk, Label
from PIL import Image, ImageTk
#
# an image viewer
class UI(Label):
def __init__(self, master, im):
if im.mode == "1":
# bitmap image
self.image = ImageTk.BitmapImage(im, foreground="white")
Label.__init__(self, master, image=self.image, bg="black", bd=0)
else:
# photo image
self.image = ImageTk.PhotoImage(im)
Label.__init__(self, master, image=self.image, bd=0)
#
# script interface
if __name__ == "__main__":
import sys
if not sys.argv[1:]:
print("Syntax: python viewer.py imagefile")
sys.exit(1)
filename = sys.argv[1]
root = Tk()
root.title(filename)
im = Image.open(filename)
UI(root, im).pack()
root.mainloop()
| [
"qoentlr37@naver.com"
] | qoentlr37@naver.com |
7b710a4e7e7137dd09a8b44701b6dd14e45c605a | 4fbd844113ec9d8c526d5f186274b40ad5502aa3 | /algorithms/python3/arithmetic_slices.py | c77282972d02cdeaf46c52a16d55caf6ef39dc8d | [] | no_license | capric8416/leetcode | 51f9bdc3fa26b010e8a1e8203a7e1bcd70ace9e1 | 503b2e303b10a455be9596c31975ee7973819a3c | refs/heads/master | 2022-07-16T21:41:07.492706 | 2020-04-22T06:18:16 | 2020-04-22T06:18:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,095 | py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given.
A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic.
In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
"""
""" ==================== body ==================== """
class Solution:
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
""" ==================== body ==================== """
| [
"capric8416@gmail.com"
] | capric8416@gmail.com |
1a28e3779dba8c219f0d15eae95d6f27d2cc046a | 99ec9dbc139fda4d2b29509dcf606cf836eacc5f | /Dust-wave/zones-v-n-plane-RSG.py | 6625fd7fe00248f28491c893b585b5e894f714c3 | [] | no_license | will-henney/bowshock-shape | 1f1caa9a6fea2681ce356d5679cafacef2aab9e1 | dfdb1f997bf05fa0f8a5b5101aeaa8d4292e012f | refs/heads/master | 2022-11-17T09:22:46.334456 | 2020-07-14T04:29:22 | 2020-07-14T04:29:22 | 5,662,223 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,705 | py | import sys
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
from vec_root import chandrupatla
figname = sys.argv[0].replace('.py', '.pdf')
sns.set_style('ticks')
sns.set_color_codes('dark')
fig, axes = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(3.3, 4))
stardata = [
[20.0, 15.6, 0.0476, 0.0, axes],
]
# Velocities in units of km/s (10 km/s -> 100 km/s)
vgrid = np.linspace(10.0, 100.0, 800)
# Densities in units of 1 pcc (0.01 -> 1e5)
logngrid = np.linspace(-3.3, 6.3, 800)
# 2d versions of velocity and density grids
vv, nn = np.meshgrid(vgrid, 10**logngrid)
def rstar(v10, n, L4):
"""Characteristic radius in pc"""
return 2.21*np.sqrt(L4/n)/v10
def taustar(v10, n, L4, kappa600=1.0):
"""Characteristic optical depth"""
return 0.0089*kappa600*np.sqrt(L4*n)/v10
def xfunc(x, ts, eta):
"""Function to be zeroed to find x"""
return x**2 - (1.0 - np.exp(-2*ts*x)) - eta
R0s = (0.0003, 0.001, 0.003, 0.01, 0.03,
0.1, 0.3, 1.0, 3.0, 10.0, 30.0)
lws = np.linspace(0.3, 2.5, len(R0s))
cformats = { 0.0001: "0.0001 pc", 0.001: "0.001 pc", 0.01: "0.01 pc", 0.1:
"0.1 pc", 1.0: "1 pc", 10.0: "10 pc", }
clevs_to_label = list(cformats.keys())
box_params = dict(fc='w', ec='0.8', lw=0.4, pad=2)
RBW_label = r"Radiation bow wave, $\eta < \tau < 1$"
RBS_label = r"Radiation bow shock, $\tau > 1$"
WBS_label = r"Wind bow shock, $\tau < \eta$"
# Miscellaneous panel-dependent plot params
d = {
"RBW y": {33.0: 1500.0, 20.0: 1e5, 40.0: 2500.0},
"trapped y": {33.0: 250, 20.0: 2.5e5, 40.0: 1.5e5},
"trapped bg": {33.0: 'w', 20.0: 'w', 40.0: 'w'},
"IF tau": {33.0: 0.2, 20.0: 3.7, 40.0: 6.4},
"IF tau gas": {33.0: 5.0, 20.0: 5.0, 40.0: 5.0},
}
T0 = 1000
kappa = 60.0
for M, L4, eta, S49, ax in stardata:
Mlabel = "\n".join([
"M supergiant", "",
rf"$M = {M:.0f}\, M_\odot$",
rf"$L = {1e4*L4:.1e}\, L_\odot$".replace("e+0", r"\times 10^"),
rf"$\eta = {eta}$"])
Rs = rstar(vv/10, nn, L4)
ts = taustar(vv/10, nn, L4, kappa600=kappa/600.0)
a, b = 0.0, 2*np.sqrt(1.0 + eta)
x = chandrupatla(xfunc, a, b, args=(ts, eta))
R0 = x*Rs
tau = 2*x*ts
ax.contourf(vv, nn, tau, (eta, 1.0), colors='k', alpha=0.15)
# ax.contour(vv, nn, tau, (eta/3, eta, 3*eta), colors='r')
# ax.contour(vv, nn, tau, (1.0, 3.0), colors='m')
cs = ax.contour(vv, nn, R0, R0s, linewidths=lws, colors='k')
clevs = [level for level in clevs_to_label if level in cs.levels]
ax.clabel(cs, clevs,
fontsize='x-small', fmt=cformats,
inline=True, inline_spacing=2, use_clabeltext=True)
ax.text(62.0, 1e-2, Mlabel, zorder=100, fontsize='x-small', bbox=box_params)
ax.text(18.0, d["RBW y"][M], RBW_label, rotation=15, fontsize='xx-small', bbox={**box_params, **dict(fc='0.85', ec='0.6')})
ax.text(16.0, 2e6, RBS_label, rotation=15, fontsize='xx-small', bbox=box_params)
ax.text(20.0, 300.0, WBS_label, rotation=15, fontsize='xx-small', bbox=box_params)
#
# Now do the cooling length
#
# Sound speed:
cs = 11.4*np.sqrt(T0/1e4)
# pre-shock Mach number
M0 = vv/cs
# post-shock Mach number
M1 = np.sqrt((M0**2 + 3)/(5*M0**2 - 1))
# post-shock temperature in units of T0
T1 = (5*M0**2 - 1)*(1 + 3/M0**2) / 16
# post-shock density
n1 = nn*4*M0**2 / (M0**2 + 3)
# post-shock velocity
v1 = vv*nn/n1
# Cooling rate
Lam1 = 3.3e-24 * (T1*T0/1e4)**2.3
Lam2 = 1e-20 / (T1*T0/1e4)
k = 3
Lambda = (Lam1**(-k) + Lam2**(-k))**(-1/k)
# Heating rate
Gamma = 1e-26
# Cooling length in parsec
dcool = 3*(1e5*v1)*(1.3806503e-16 * T1*T0) / (n1*(Lambda - Gamma)) / 3.085677582e18
dcool[vv < cs] = np.nan
# Ratio with respect to adiabatic shell thickness
h1 = 0.177*R0
cool_ratio1 = dcool / R0
# Ratio with respect to isothermal shell thickness
h2 = 3*R0/(4*M0**2) * (2 / (1 + np.sqrt(1 + (18/M0**2)) ))
cool_ratio2 = dcool / h2
cs = ax.contour(vv, nn, cool_ratio1, (1.0,),
linewidths=2, colors='b', alpha=0.5)
ax.clabel(cs,
fontsize='xx-small', fmt=r"$d_\mathrm{cool} = R_0$",
inline=True, inline_spacing=2, use_clabeltext=True)
cs = ax.contour(vv, nn, cool_ratio2, (1.0,),
linewidths=1, colors='b', alpha=0.5)
ax.clabel(cs,
fontsize='xx-small', fmt=r"$d_\mathrm{cool} = h_0$",
inline=True, inline_spacing=2, use_clabeltext=True)
ax.set(yscale='log')
axes.set(xlabel=r"$v$, km s$^{-1}$", ylabel=r"$n$, cm$^{-3}$")
sns.despine()
fig.tight_layout()
fig.savefig(figname)
print(figname, end='')
| [
"will@henney.org"
] | will@henney.org |
5e388aaa8b1c889e2a5ad3e841a1666c7eaea2b3 | 74b12c96a73d464e3ca3241ae83a0b6fe984b913 | /python/tvm/relay/backend/contrib/ethosu/tir/pooling.py | 7fdebf05f068c8a5c0a9529650aaaf625625f4c4 | [
"Apache-2.0",
"BSD-3-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-2-Clause"
] | permissive | masahi/tvm | cf765bb892655f02135e1ce3afde88698f026483 | c400f7e871214451b75f20f4879992becfe5e3a4 | refs/heads/master | 2023-08-22T20:46:25.795382 | 2022-04-13T08:47:10 | 2022-04-13T08:47:10 | 138,661,036 | 4 | 2 | Apache-2.0 | 2021-09-03T20:35:19 | 2018-06-25T23:39:51 | Python | UTF-8 | Python | false | false | 3,729 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=invalid-name, unused-argument
"""Extract information from the pooling operators in TIR."""
from typing import Dict, Tuple
import tvm
from .utils import get_outer_loops, get_op_attrs, get_loads, get_stores
from .dma import get_ifm_params, get_ofm_params
from .spec import SerialKernel, SerialActivation, SerialPooling
def get_pooling_params(
stmt: tvm.tir.AttrStmt,
producers: Dict[tvm.tir.Var, tvm.tir.AttrStmt],
consumers: Dict[tvm.tir.Var, tvm.tir.AttrStmt],
) -> Tuple[SerialPooling, tvm.tir.Var, tvm.tir.Var]:
"""Get the parameters necessary to construct a call_extern for a pooling.
Parameters
----------
stmt : tvm.tir.AttrStmt
The outermost attribute statement of a convolution loop nest.
producers : Dict[tvm.tir.Var, tvm.tir.AttrStmt]
A dictionary to associate pointers with the loop nest
that produces their values.
consumers : Dict[tvm.tir.Var, tvm.tir.AttrStmt]
A dictionary to associate pointers with the loop nest
that consumes their values.
Returns
-------
SerialPooling
The parameters needed to construct a 2D convolution.
output_pointer : tvm.tir.Var
The output pointer of the convolution operation.
replace_pointer : tvm.tir.Var
The output pointer of the DMA write operation, which is to replace
the convolution output pointer.
is_allocator : bool
Whether this operator allocates its output.
"""
attrs, body = get_op_attrs(stmt)
_, _, _, _, _, inner = get_outer_loops(body, "NHWC")
rh = inner
rw = rh.body
# loads = [output, input, LUT, LUT]
loads = get_loads(rw.body)
# stores = [output]
stores = get_stores(rw.body)
input_pointer = loads[1].buffer.data
output_pointer = stores[0].buffer.data
# Get feature map info
serial_ifm, serial_padding = get_ifm_params(input_pointer, producers)
serial_ofm, serial_block_config, replace_pointer, is_allocator = get_ofm_params(
output_pointer, consumers, producers
)
# Get kernel info
serial_kernel = SerialKernel(
width=int(rw.extent),
height=int(rh.extent),
stride_w=int(attrs["stride_w"]),
stride_h=int(attrs["stride_h"]),
dilation_w=1,
dilation_h=1,
)
# Get activation info
serial_activation = SerialActivation(
op=attrs["activation"], clip_min=attrs["clip_min"], clip_max=attrs["clip_max"]
)
return (
SerialPooling(
ifm=serial_ifm,
ofm=serial_ofm,
pooling_type=attrs["pooling_type"],
pool_shape=serial_kernel,
padding=serial_padding,
activation=serial_activation,
rounding_mode=attrs["rounding_mode"],
upscale=attrs["upscale"],
block_config=serial_block_config,
),
output_pointer,
replace_pointer,
is_allocator,
)
| [
"noreply@github.com"
] | masahi.noreply@github.com |
9042bc2e7dfed5812249fb189fa1277d8d1c2be2 | 8f26514c451e2398d5e3688c184ea74d1dad21b2 | /month_02/teacher/day16/epoll_server.py | d519fab12014a4ac0890707f142243e5f1733a11 | [] | no_license | CircularWorld/Python_exercise | 25e7aebe45b4d2ee4e3e3afded082c56483117de | 96d4d9c5c626f418803f44584c5350b7ce514368 | refs/heads/master | 2022-11-21T07:29:39.054971 | 2020-07-20T10:12:24 | 2020-07-20T10:12:24 | 281,081,559 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,421 | py | """
基于epoll方法实现IO并发
重点代码 !
"""
from socket import *
from select import *
# 全局变量
HOST = "0.0.0.0"
PORT = 8889
ADDR = (HOST,PORT)
# 创建tcp套接字
tcp_socket = socket()
tcp_socket.bind(ADDR)
tcp_socket.listen(5)
# 设置为非阻塞
tcp_socket.setblocking(False)
p = epoll() # 建立epoll对象
p.register(tcp_socket,EPOLLIN) # 初始监听对象
# 准备工作,建立文件描述符 和 IO对象对应的字典 时刻与register的IO一致
map = {tcp_socket.fileno():tcp_socket}
# 循环监听
while True:
# 对关注的IO进行监控
events = p.poll()
# events--> [(fileno,event),()....]
for fd,event in events:
# 分情况讨论
if fd == tcp_socket.fileno():
# 处理客户端连接
connfd, addr = map[fd].accept()
print("Connect from", addr)
connfd.setblocking(False) # 设置非阻塞
p.register(connfd,EPOLLIN|EPOLLERR) # 添加到监控
map[connfd.fileno()] = connfd # 同时维护字典
elif event == EPOLLIN:
# 收消息
data = map[fd].recv(1024)
if not data:
# 客户端退出
p.unregister(fd) # 移除关注
map[fd].close()
del map[fd] # 从字典也移除
continue
print(data.decode())
map[fd].send(b'OK')
| [
"jiayuhaowork@163.com"
] | jiayuhaowork@163.com |
6ab5b5216d0eb2a8650fcd1a62bcbabf049f5313 | bf99b1b14e9ca1ad40645a7423f23ef32f4a62e6 | /AtCoder/abc/089c_2.py | 94da387294f84700a87543a31909ed7bb1b5e285 | [] | no_license | y-oksaku/Competitive-Programming | 3f9c1953956d1d1dfbf46d5a87b56550ff3ab3db | a3ff52f538329bed034d3008e051f30442aaadae | refs/heads/master | 2021-06-11T16:14:12.635947 | 2021-05-04T08:18:35 | 2021-05-04T08:18:35 | 188,639,647 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 344 | py | from itertools import combinations
from collections import defaultdict
import sys
input = sys.stdin.readline
N = int(input())
cnt = defaultdict(int)
for _ in range(N):
s = input()
cnt[s[0]] += 1
ans = 0
for h in combinations(['M', 'A', 'R', 'C', 'H'], r=3):
prd = 1
for s in h:
prd *= cnt[s]
ans += prd
print(ans)
| [
"y.oksaku@stu.kanazawa-u.ac.jp"
] | y.oksaku@stu.kanazawa-u.ac.jp |
9515c0bdd85d803050097e6ea7dac81417d8aa7d | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /benchmark/startQiskit_QC2883.py | 3831cd0f21334b15907eb8542ea5d15be806d7d0 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,471 | py | # qubit number=4
# total number=40
import cirq
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=20
prog.cz(input_qubit[0],input_qubit[3]) # number=21
prog.h(input_qubit[3]) # number=22
prog.x(input_qubit[3]) # number=13
prog.h(input_qubit[3]) # number=23
prog.cz(input_qubit[0],input_qubit[3]) # number=24
prog.h(input_qubit[3]) # number=25
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
prog.h(input_qubit[0]) # number=5
prog.y(input_qubit[2]) # number=18
prog.cx(input_qubit[3],input_qubit[0]) # number=37
prog.z(input_qubit[3]) # number=38
prog.cx(input_qubit[3],input_qubit[0]) # number=39
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1]) # number=6
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[3]) # number=8
prog.h(input_qubit[0]) # number=9
prog.h(input_qubit[0]) # number=33
prog.cz(input_qubit[2],input_qubit[0]) # number=34
prog.h(input_qubit[0]) # number=35
prog.h(input_qubit[1]) # number=19
prog.h(input_qubit[0]) # number=15
prog.cz(input_qubit[2],input_qubit[0]) # number=16
prog.h(input_qubit[0]) # number=17
prog.rx(1.6838936623241292,input_qubit[2]) # number=36
prog.y(input_qubit[1]) # number=26
prog.y(input_qubit[1]) # number=27
prog.swap(input_qubit[1],input_qubit[0]) # number=29
prog.swap(input_qubit[1],input_qubit[0]) # number=30
prog.x(input_qubit[0]) # number=31
prog.x(input_qubit[0]) # number=32
# circuit end
for i in range(n):
prog.measure(input_qubit[i], classical[i])
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational == True))
sample_shot =8000
info = execute(prog, backend=backend, shots=sample_shot).result().get_counts()
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_QC2883.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
fc65a08e5902987c77d2744f2246f2ddbcaabf20 | 2ce27b05f45cef6ce3ae5c02b8e83e548def2fc6 | /ADVANCE/Functions/Built in Function/reversed( ).py | dee1fad79a5a200d090d2edf08814e238497790f | [] | no_license | Ajay2521/Python | 775b7d99736e83e4d0c37302b91d1413dd2c0d3b | a426dd7717de8a5e60e584d208ae7120bb84c1b3 | refs/heads/master | 2022-12-01T17:49:12.672061 | 2020-08-15T14:55:12 | 2020-08-15T14:55:12 | 273,632,074 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 957 | py | # In this lets see about the "Built-in functions" in python.
# Built-in function is defined as the functions whose functionality is pre-defined in the python compiler.
# Lets see about "reversed( ) bilt-in function" in python.
# reversed( ) - Used to returns the reversed iterator of the given sequence.
# Here is the program for reversed( ).
String = "MaayoN"
List = [ 1, 2, 3, 4, 5 ]
Tuple = ( 1, 2, 3, 4, 5 )
print( ) # prints empty line for readability.
print( reversed( String ) )
print ( list( reversed( String ) ) ) # Converting reversed value into List for readability.
print( ) # prints empty line for readability.
print( reversed( List ) )
print ( list( reversed( List ) ) ) # Converting reversed value into List for readability.
print( ) # prints empty line for readability.
print( reversed( Tuple ) )
print ( list( reversed( Tuple ) ) ) # Converting reversed value into List for readability.
| [
"noreply@github.com"
] | Ajay2521.noreply@github.com |
2f7fe328ac611be8426399a64197dce120f4b2ec | 978e8e7397237a269ce55dff551aee65948d3803 | /trading/settings.py | 5f9f8f43ae749e67986d13bd7fa39f95cfc9ae2c | [] | no_license | AlexsandroMO/Bitcoin | cca28beeb712b63f31c7ef1c54aced47d8de3153 | e19498660d5e3a9fdaee7fdb17e9a5464ebdac8d | refs/heads/master | 2020-09-26T02:47:41.616660 | 2019-12-05T16:48:48 | 2019-12-05T16:48:48 | 226,146,249 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,176 | py |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '#v!6idcn2=1^#6s_2x=v*r7ru(^ktkf@rz8#w)jk(_l!po4!yv'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'coin',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'trading.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'trading.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media_files' | [
"sandrobass@hotmail.com"
] | sandrobass@hotmail.com |
e89f4fa1910b5e1ead9f3d1bcd08b5811ee1944a | 5a8214b3a452c574e6c883bf5d90ba58ba87c461 | /leetcode/1140.stone-game-ii.py | abbfd17a569afa2a85d2de22865c2faaa350ab43 | [] | no_license | phlalx/algorithms | 69a3c8519687816e3c6333ec12b40659d3e3167f | f4da5a5dbda640b9bcbe14cb60a72c422b5d6240 | refs/heads/master | 2023-02-03T10:30:30.181735 | 2020-12-26T09:47:38 | 2020-12-26T09:47:38 | 129,254,618 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,129 | py | #
# @lc app=leetcode id=1140 lang=python3
#
# [1140] Stone Game II
#
# https://leetcode.com/problems/stone-game-ii/description/
#
# algorithms
# Medium (62.00%)
# Likes: 335
# Dislikes: 75
# Total Accepted: 11.4K
# Total Submissions: 18.4K
# Testcase Example: '[2,7,9,4,4]'
#
# Alex and Lee continue their games with piles of stones. There are a number
# of piles arranged in a row, and each pile has a positive integer number of
# stones piles[i]. The objective of the game is to end with the most stones.
#
# Alex and Lee take turns, with Alex starting first. Initially, M = 1.
#
# On each player's turn, that player can take all the stones in the first X
# remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
#
# The game continues until all the stones have been taken.
#
# Assuming Alex and Lee play optimally, return the maximum number of stones
# Alex can get.
#
#
# Example 1:
#
#
# Input: piles = [2,7,9,4,4]
# Output: 10
# Explanation: If Alex takes one pile at the beginning, Lee takes two piles,
# then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If
# Alex takes two piles at the beginning, then Lee can take all three piles
# left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since
# it's larger.
#
#
#
# Constraints:
#
#
# 1 <= piles.length <= 100
# 1 <= piles[i] <= 10 ^ 4
#
#
# TAGS dp
# very classic dp
# @lc code=start
import functools
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
total = sum(piles)
n = len(piles)
@functools.lru_cache(maxsize=None)
def f(i, M) -> int:
# return best score achievable by player
if i == n:
return 0
else:
best = float('-inf')
cur_sum = 0
# last pile taken by player
for x in range(i, min(i + 2 * M, n)):
cur_sum += piles[x]
best = max(best, cur_sum - f(x+1, max(M, x-i+1)))
return best
score = f(0, 1)
return (total + score) // 2
# @lc code=end
| [
"phlalx@users.noreply.github.com"
] | phlalx@users.noreply.github.com |
c1b22849629d6c3615ebfb29f802a866b205482b | 3b79a802f8dd9f26bee0bfde4630ac0cab932803 | /srcHashTag/statisticHashtag.py | 11eb49bb3a43550f017598f6d4cfd9ad00cbd48b | [] | no_license | qolina/Twevent | 87fc4706564088361e9db6ddc44efc10647e67fe | 4b90b0604493b20dee90448c17e0a8e0d557165e | refs/heads/master | 2021-06-24T19:06:02.022882 | 2017-08-15T05:20:09 | 2017-08-15T05:20:09 | 100,341,172 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,044 | py | #! /usr/bin/env python
#coding=utf-8
import time
import re
import os
import math
import cPickle
############################
## load tweets' social feature
def loadsocialfeature(filepath):
inFile = file(filepath,"r")
tweSFHash = cPickle.load(inFile)
inFile.close()
print "### " + str(time.asctime()) + " " + str(len(tweSFHash)) + " tweets' social features are loaded from " + inFile.name
return tweSFHash
'''
feahash["RT"] = RT
feahash["Men"] = Men
feahash["Reply"] = Reply
feahash["Url"] = Url
feahash["RTC"] = RTC
feahash["Fav"] = Fav
feahash["Tag"] = Tag
feahash["Past"] = Past
'''
############################
##
def statisticHashtag(dataFilePath, toolDirPath):
fileList = os.listdir(dataFilePath)
# output hashtag statistics
hashtagfreqFile = file(toolDirPath + "hashTagFreqFile", "w")
hashtagFile = file(toolDirPath + "hashTagFile", "w")
hashtagByTFFile = file(toolDirPath + "hashTagTFFile", "w")
hashtagByDFFile = file(toolDirPath + "hashTagDFFile", "w")
hashTagHashAppHash = {}
tweetTagHash = {}
for item in sorted(fileList):
if item.find("segged") != 0:
continue
tStr = item[len(item)-2:len(item)]
print "Time window: " + tStr
tweetSocialFeatureFilePath = toolDirPath + "tweetSocialFeature" + tStr
tweSFHash = loadsocialfeature(tweetSocialFeatureFilePath)
tagHash = dict([(tid, tweSFHash[tid]["Tag"]) for tid in tweSFHash if len(tweSFHash[tid]["Tag"]) > 1])
tweetTagHash.update(tagHash)
print "### " + str(time.asctime()) + " " + str(len(tagHash)) + " tweets contain hashtags"
tweSFHash.clear()
for tid in tagHash:
tagStr = tagHash[tid]
tagArr = tagStr.split(" ")
for tag in tagArr:
illegelLetter = False
for letter in tag:
encodeNum = ord(letter)
if (encodeNum < 32) | (encodeNum > 126):
illegelLetter = True
break
# if re.match("[a-zA-Z0-9]", letter):
# puncOnly = False
if illegelLetter: #contain illegel letter
continue
apphash = {}
if tag in hashTagHashAppHash:
apphash = hashTagHashAppHash[tag]
if tid in apphash:
apphash[tid] += 1
else:
apphash[tid] = 1
hashTagHashAppHash[tag] = apphash
# print tag + " " + str(apphash)
print "### " + str(len(hashTagHashAppHash)) + " hashtags are loaded already."
print "### " + str(time.asctime()) + " " + str(len(hashTagHashAppHash)) + " hashtag are loaded."
print "### " + str(time.asctime()) + " " + str(len(tweetTagHash)) + " tweets contain hashtags."
cPickle.dump(hashTagHashAppHash, hashtagfreqFile)
hashtagList = hashTagHashAppHash.keys()
sortedByTF = {}
sortedByDF = {}
tagLenHash = {}
for tag in sorted(hashtagList):
apphash = hashTagHashAppHash[tag]
df = len(apphash)
tf = sum(apphash.values())
sortedByTF[tag] = tf
sortedByDF[tag] = df
hashtagFile.write(tag + "\t" + str(tf) + "\t" + str(df) + "\n")
tagLen = len(tag)
if tagLen in tagLenHash:
tagLenHash[tagLen] += 1
else:
tagLenHash[tagLen] = 1
print "### " + str(sum(tagLenHash.values())) + " hash tags, length distribution: "
print sorted(tagLenHash.items(), key = lambda a:a[1], reverse = True)
for tagItem in sorted(sortedByTF.items(), key = lambda a:a[1], reverse = True):
tag = tagItem[0]
tf = tagItem[1]
df = sortedByDF[tag]
hashtagByTFFile.write(tag + "\t" + str(tf) + "\t" + str(df) + "\n")
for tagItem in sorted(sortedByDF.items(), key = lambda a:a[1], reverse = True):
tag = tagItem[0]
df = tagItem[1]
tf = sortedByTF[tag]
hashtagByDFFile.write(tag + "\t" + str(tf) + "\t" + str(df) + "\n")
hashtagFile.close()
hashtagByTFFile.close()
hashtagByDFFile.close()
hashtagfreqFile.close()
print "### " + str(time.asctime()) + " hashtag statistics (alpha order) are stored into " + hashtagFile.name
print "### " + str(time.asctime()) + " hashtag statistics (tf) are stored into " + hashtagByTFFile.name
print "### " + str(time.asctime()) + " hashtag statistics (df) are stored into " + hashtagByDFFile.name
print "### " + str(time.asctime()) + " hashtag statistics (dump) are stored into " + hashtagfreqFile.name
############################
## main Function
print "###program starts at " + str(time.asctime())
dataFilePath = r"../Data_hfmon/segged_ltwe/"
toolDirPath = r"../Tools/"
statisticHashtag(dataFilePath, toolDirPath)
print "###program ends at " + str(time.asctime())
| [
"qolina@gmail.com"
] | qolina@gmail.com |
8e3884896f59a39e13d0286dd45828194ff0cc9f | c5746efe18a5406764c041d149d89c0e0564c5a5 | /1. Python语言核心编程/1. Python核心/Day07/exercise/exercise02.py | 32cc7fbbb5ffb79abbadf328b32b5dc4fe0f60f2 | [] | no_license | ShaoxiongYuan/PycharmProjects | fc7d9eeaf833d3711211cd2fafb81dd277d4e4a3 | 5111d4c0a7644c246f96e2d038c1a10b0648e4bf | refs/heads/master | 2021-12-15T05:45:42.117000 | 2021-11-23T06:45:16 | 2021-11-23T06:45:16 | 241,294,858 | 3 | 1 | null | 2021-02-20T15:29:07 | 2020-02-18T07:06:08 | Jupyter Notebook | UTF-8 | Python | false | false | 528 | py | def if_same_element(target_list):
"""
判断列表中是否有相同元素
:param target_list: 一个列表
:return: 是否有相同元素
"""
# result = False
for i in range(len(target_list) - 1):
for a in range(i + 1, len(target_list)):
if target_list[i] == target_list[a]:
return True
# result = True
# break
# if result:
# break
return False
list1 = [34, 8, 56, 9, 8, 9]
print(if_same_element(list1))
| [
"ysxstevenpp123@gmail.com"
] | ysxstevenpp123@gmail.com |
853c926761dfcdcbcd017ed1b743532f010314aa | 9e55f933b1228d50597b3ee723881674b8c25adf | /store_backend/config/settings/common.py | fd2c0b762d042217d8b942c8c0c2fb4bba89c152 | [
"MIT"
] | permissive | rudolphpienaar/ChRIS_store | e77abdcc892bb5066d697add5673f1c9e198fa4f | db924ded8e3323bc77b5eb974516df1d70cdd4d4 | refs/heads/master | 2020-03-06T21:41:59.060552 | 2019-11-14T02:43:31 | 2019-11-14T02:43:31 | 127,084,343 | 0 | 0 | null | 2018-03-28T04:37:25 | 2018-03-28T04:37:24 | null | UTF-8 | Python | false | false | 4,016 | py | # -*- coding: utf-8 -*-
"""
Django settings for chris_backend project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_filters',
'mod_wsgi.server',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'collectionjson',
'plugins',
'pipelines',
'users'
]
# Pagination
REST_FRAMEWORK = {
'PAGE_SIZE': 10,
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'DEFAULT_RENDERER_CLASSES': (
'collectionjson.renderers.CollectionJsonRenderer',
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'collectionjson.parsers.CollectionJsonParser',
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
)
}
MIDDLEWARE = [
'core.middleware.ResponseMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
| [
"jbernal0019@yahoo.es"
] | jbernal0019@yahoo.es |
fefdc0b44aed4811b72cf261766d16d88f7f1353 | 1bd3076902117867ec048210905195ba2aaaaa6b | /exercise/leetcode/python_src/by2017_Sep/Leet395.py | b0a38ca7d29434c505c9378e24dcca7f581c9b1f | [] | no_license | SS4G/AlgorithmTraining | d75987929f1f86cd5735bc146e86b76c7747a1ab | 7a1c3aba65f338f6e11afd2864dabd2b26142b6c | refs/heads/master | 2021-01-17T20:54:31.120884 | 2020-06-03T15:04:10 | 2020-06-03T15:04:10 | 84,150,587 | 2 | 0 | null | 2017-10-19T11:50:38 | 2017-03-07T03:33:04 | Python | UTF-8 | Python | false | false | 1,068 | py | class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if len(s) == 0:
return 0
return self.divideRecursive(s, k)
def divideRecursive(self, s, k):
cntDict = {}
for i in s:
cntDict.setdefault(i, 0)
cntDict[i] += 1
badIdx = [-1, ]
flag = True
for idx in range(len(s)): # save the bad idx
if cntDict[s[idx]] < k:
badIdx.append(idx)
flag = False
if flag:
return len(s)
badIdx.append(len(s))
newStrs = []
for i in range(1, len(badIdx)):
s0 = s[badIdx[i-1] + 1: badIdx[i]]
if len(s0) != 0:
newStrs.append(s0)
maxLen = 0
for s1 in newStrs:
maxLen = max(maxLen, self.divideRecursive(s1, k))
return maxLen
if __name__ == "__main__":
s = Solution()
s0 = "ababbc"
k = 2
print(s.longestSubstring(s0, k)) | [
"ziheng_song@126.com"
] | ziheng_song@126.com |
8d9d148953206e97e3b9e765ea30a82e1f309b3c | b52781b9065f6c571beb1b87cc1bbe2bd121d272 | /homework02-2.py | ec526d0046c8919a827e61fc4c767ff2980b0b1d | [
"Apache-2.0"
] | permissive | liuhuihui123/liuhuihui | 97e4182bb2003b95d1236f8f8e108215beaa9dfa | 5dfa7b6ba7bc752edc48e981dd71f81017d3b673 | refs/heads/master | 2020-03-29T18:06:07.971173 | 2018-10-12T01:28:21 | 2018-10-12T01:28:21 | 150,194,561 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,844 | py | '''#1
import math
a, b, c = eval(raw_input("Enter a, b, c:"))
n = b*b-4*a*c
if (n>0):
r1 =( -b + math.sqrt(b*b-4*a*c))/2*a
r2 =( -b - math.sqrt(b*b-4*a*c))/2*a
print(r1 , r2)
elif (n==0):
r1 =( -b + math.sqrt(b*b-4*a*c))/2*a
r2 =( -b - math.sqrt(b*b-4*a*c))/2*a
r1 = r2
print(r1)
if (n<0) :
print("The equation has no real roots")
'''
'''#2
import random
n1=random.randint(1,100)
n2=random.randint(1,100)
n=n1+n2
num = raw_input(("qing shu ru shang mian de lia ge shu zhi he:"))
if num == n:
print("True")
else:
print("False")
print(n)
'''
'''#3
today = eval (raw_input("jin tian shi :"))
day = eval(raw_input("guo le ji tian :"))
week = (today+day)%7
if week == 0:
print("jin tian shi {} and the future day is Sunday".format(today))
elif week == 1:
print("jin tian shi {} and the future day is Monday".format(today))
elif week == 2:
print("jin tian shi {} and the future day is Tuesday".format(today))
elif week == 3:
print("jin tian shi {} and the future day is Wendnesday".format(today))
elif week == 4:
print("jin tian shi {} and the future day is Thurday".format(today))
elif week == 5:
print("jin tian shi {} and the future day is Firday".format(today))
'''
'''#4
print("qing shu ru san ge zheng shu :")
x = eval(raw_input(">>"))
y = eval(raw_input(">>"))
z = eval(raw_input(">>"))
if x>y:
x,y = y,x
if x>z:
x,z = z,x
if y>z:
y,z = z,y
print(x,y,z)
'''
'''#5
w1,p1 = eval(raw_input('Enter weight and price for package 1"'))
w2,p2 = eval(raw_input('Enter weight and price for package 2"'))
baozhuang1 = p1 / w1
baozhuang2 = p2 / w2
if baozhuang1 < baozhuang2:
print('package 1 has the better price')
elif baozhuang1 >baozhuang2:
print('package 2 has the better price')
else:
print('package 1 the same as package 2')
'''
'''#6
month ,year = eval(raw_input("shu ru month and years:"))
a = 0
if(a){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12 :print("31\n");break
case 2:if (year%4==0 and year%100!=0 | year%400==0):
a=29
else:
a=28
case 4:
case 6:
case 9:
case 11:print("30\n");
}
print(a)
'''
'''#7
import random
yingbi = eval(raw_input("cha shi zhengmian(1) huanshi fanmian(0):"))
n = random.randint(0,1)
if (n == 1):
print('True')
if n==0:
print('False')
'''
'''#11
num = eval(raw_input("shu ru yi ge san wei shu:"))
bai = num /100
shi = num/10%10
ge = num % 10
if bai == ge:
print("{} is a pailndrome".format(num))
else:
print("{} is not a pailndrome".format(num))
'''
'''#12
a,b,c = eval(raw_input("shu ru san jiao xing de san ge bian:"))
zc = a+b+c
if (a+b>c):
print("The perimeter is {}".format(zc))
else:
print("shu ru fei fa")
'''
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
9687778c402ee8e82a0755b2f05fcccedc652e9c | 747afe9a5915c28831b86b0a5e2c044212664da5 | /20170908/lyrichu_20170908_02.py | c61772bc56e104218c145a6deb05cb7f8116d16d | [] | no_license | nitinreddy3/Python-Machine-Learning-Homework | 61c7b882b49e868ca37443feaa89494d5b6eba4a | b088bdcdb24892260e1db416d50f0750872e80bc | refs/heads/master | 2021-07-17T04:42:12.233768 | 2017-10-23T15:29:24 | 2017-10-23T15:29:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,303 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/9/8 17:55
# @Author : Lyrichu
# @Email : 919987476@qq.com
# @File : lyrichu_20170908_02.py
'''
@Description:
2、100个人围成一圈,编号从1开始到100.从1开始报数,报到M的人自动退出,下一个人接着从1开始报数,直到剩余人数小于M。求最后剩余人的编号。
样例输入:
3
样例输出:
58 91
样例输入2:
4
样例输出2:
34 45 97
'''
m = int(raw_input())
restNum = 100 # 剩余人数
indexNumberList = [[i,(i-1)%m + 1] for i in range(1,restNum+1)] # [学生序号,列表] 组成的列表
lastNumber = m if restNum % m == 0 else restNum % m # 最后一个学生的报数
while(restNum >= m):
indexNumberList = [v for v in indexNumberList if v[1] != m] # 删除报数为 m的学生
indexNumberList[0][1] = 1 if lastNumber+1>m else lastNumber+1 # 学生报数m之后,下一个为1
restNum = len(indexNumberList) # 更新剩余人数
# 逐个报数
for i in range(restNum-1):
indexNumberList[i+1][1] = indexNumberList[i][1] + 1
if(indexNumberList[i+1][1] > m):
indexNumberList[i+1][1] = 1
lastNumber = indexNumberList[-1][1] # 记录最后一个人的报数
print(" ".join(map(lambda x:str(x),[v[0] for v in indexNumberList])))
| [
"919987476@qq.com"
] | 919987476@qq.com |
07a0488b1aea8b5844b465d7c255d1e90e95f08c | 45034fd848c701ecdcb5f3bd1d3ea43d24abce2d | /agency/xml/feed_avito.py | cb819342318182284342678e39ff819c7382551e | [] | no_license | JazinBazin/height | b5740d17fb5e6e184f8af40d16ccad12d57cea58 | 06fd76fc62567efd3688688197cc66a205a0c309 | refs/heads/master | 2020-05-20T17:05:20.892218 | 2019-06-29T13:40:40 | 2019-06-29T13:40:40 | 185,679,726 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,041 | py | import xml.etree.ElementTree as ET
avito_feed_file_name = 'feed_avito.xml'
def avito_add_lot_offer(instance):
try:
if instance.transaction_type != 'p':
return
tree = ET.parse(avito_feed_file_name)
feed = tree.getroot()
avito_create_lot_offer(feed, instance)
tree.write(avito_feed_file_name, encoding='UTF-8',
xml_declaration=False)
except Exception as ex:
with open('log.txt', 'a') as log_file:
log_file.write('error in function avito_add_lot_offer. pk = ' +
str(instance.pk) + '\nwhat: ' + str(ex) + '\n')
def avito_remove_lot_offer(pk):
try:
pk = str(pk)
tree = ET.parse(avito_feed_file_name)
feed = tree.getroot()
for ad in feed:
ad_id = ad.find('Id')
if ad_id.text == pk:
feed.remove(ad)
break
tree.write(avito_feed_file_name, encoding='UTF-8',
xml_declaration=False)
except Exception as ex:
with open('log.txt', 'a') as log_file:
log_file.write('error in function avito_remove_lot_offer. pk = ' +
str(pk) + '\nwhat: ' + str(ex) + '\n')
def avito_update_lot_offer(instance):
avito_remove_lot_offer(instance.pk)
avito_add_lot_offer(instance)
def avito_create_lot_offer(feed, instance):
Ad = ET.Element('Ad')
feed.append(Ad)
ad_id = ET.SubElement(Ad, 'Id')
ad_id.text = str(instance.pk)
AllowEmail = ET.SubElement(Ad, 'AllowEmail')
AllowEmail.text = 'Да'
ManagerName = ET.SubElement(Ad, 'ManagerName')
ManagerName.text = 'Юденич Светлана Станиславовна'
ContactPhone = ET.SubElement(Ad, 'ContactPhone')
ContactPhone.text = '+7 (978) 834-31-76'
Address = ET.SubElement(Ad, 'Address')
Address.text = 'Россия, Крым'
if instance.district:
Address.text += ', ' + str(instance.district)
if 'район' not in str(instance.district).lower():
Address.text += ' район'
if instance.populated_area:
Address.text += ', ' + str(instance.populated_area)
DistanceToCity = ET.SubElement(Ad, 'DistanceToCity')
DistanceToCity.text = '0'
Description = ET.SubElement(Ad, 'Description')
Description.text = str(instance.description)
Category = ET.SubElement(Ad, 'Category')
Category.text = 'Земельные участки'
OperationType = ET.SubElement(Ad, 'OperationType')
OperationType.text = 'Продам'
Price = ET.SubElement(Ad, 'Price')
if instance.currency == 'r':
Price.text = str(int(instance.price))
elif instance.currency == 'd':
Price.text = str(int(instance.price * 60))
else:
Price.text = str(int(instance.price * 70))
LandArea = ET.SubElement(Ad, 'LandArea')
if instance.area_units == 'm':
LandArea.text = str(int(instance.area / 100))
elif instance.area_units == 'h':
LandArea.text = str(int(instance.area * 100))
else:
LandArea.text = str(int(instance.area))
PropertyRights = ET.SubElement(Ad, 'PropertyRights')
if instance.cadastral_number:
PropertyRights.text = 'Собственник'
CadastralNumber = ET.SubElement(Ad, 'CadastralNumber')
CadastralNumber.text = str(instance.cadastral_number)
else:
PropertyRights.text = 'Посредник'
ObjectType = ET.SubElement(Ad, 'ObjectType')
if instance.lot_type == 'i':
ObjectType.text = 'Поселений (ИЖС)'
else:
ObjectType.text = 'Сельхозназначения (СНТ, ДНП)'
Images = ET.SubElement(Ad, 'Images')
Image = ET.SubElement(Images, 'Image')
Image.set('url', 'https://высота-крым.рф' + str(instance.image.url))
for photo in instance.images.all():
Image = ET.SubElement(Images, 'Image')
Image.set('url', 'https://высота-крым.рф' + str(photo.image.url))
| [
"yudenichaa@yandex.ru"
] | yudenichaa@yandex.ru |
c9b0c8e2dfee1bbb42c1b6a641db68ca4e2c25d9 | 037877a31670a85fa78b61df9ceabe981cfdfbf6 | /sympy/concrete/__init__.py | ad08eb41b7aa48ef70be397eb1ba68e3f15b61f0 | [] | no_license | certik/sympy_gamma | 6343b02e5d6d1c7d511a3329bbbd27cd11cd7ec8 | b0e555ca03f8476533cb1c19575f4461533837de | refs/heads/master | 2020-12-25T03:52:40.132034 | 2010-02-15T08:02:31 | 2010-02-15T08:02:31 | 344,391 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 136 | py |
from products import product, Product
from summations import sum, Sum
from sums_products import Sum2
from gosper import normal, gosper
| [
"ondrej@certik.cz"
] | ondrej@certik.cz |
03dfab3cd71fc24f153386023aa51f38c46348bd | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/build/android/gyp/pack_relocations.py | 89c01f05a61391682feebe40ddd3c8c1930db4b5 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,671 | py | #!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Pack relocations in a library (or copy unchanged).
If --enable-packing and --configuration-name=='Release', invoke the
relocation_packer tool to pack the .rel.dyn or .rela.dyn section in the given
library files. This step is inserted after the libraries are stripped.
If --enable-packing is zero, the script copies files verbatim, with no
attempt to pack relocations.
"""
import ast
import optparse
import os
import shutil
import sys
import tempfile
from util import build_utils
def PackLibraryRelocations(android_pack_relocations, library_path, output_path):
shutil.copy(library_path, output_path)
pack_command = [android_pack_relocations, output_path]
build_utils.CheckOutput(pack_command)
def CopyLibraryUnchanged(library_path, output_path):
shutil.copy(library_path, output_path)
def main(args):
args = build_utils.ExpandFileArgs(args)
parser = optparse.OptionParser()
build_utils.AddDepfileOption(parser)
parser.add_option('--clear-dir', action='store_true',
help='If set, the destination directory will be deleted '
'before copying files to it. This is highly recommended to '
'ensure that no stale files are left in the directory.')
parser.add_option('--configuration-name',
default='Release',
help='Gyp configuration name (i.e. Debug, Release)')
parser.add_option('--enable-packing',
choices=['0', '1'],
help=('Pack relocations if 1 and configuration name is \'Release\','
' otherwise plain file copy'))
parser.add_option('--android-pack-relocations',
help='Path to the relocations packer binary')
parser.add_option('--stripped-libraries-dir',
help='Directory for stripped libraries')
parser.add_option('--packed-libraries-dir',
help='Directory for packed libraries')
parser.add_option('--libraries', action='append',
help='List of libraries in Python dictionary format')
parser.add_option('--stamp', help='Path to touch on success')
parser.add_option('--filelistjson',
help='Output path of filelist.json to write')
options, _ = parser.parse_args(args)
enable_packing = (options.enable_packing == '1' and
options.configuration_name == 'Release')
libraries = []
for libs_arg in options.libraries:
libraries += ast.literal_eval(libs_arg)
if options.clear_dir:
build_utils.DeleteDirectory(options.packed_libraries_dir)
build_utils.MakeDirectory(options.packed_libraries_dir)
output_paths = []
for library in libraries:
library_path = os.path.join(options.stripped_libraries_dir, library)
output_path = os.path.join(
options.packed_libraries_dir, os.path.basename(library))
output_paths.append(output_path)
if enable_packing:
PackLibraryRelocations(options.android_pack_relocations,
library_path,
output_path)
else:
CopyLibraryUnchanged(library_path, output_path)
if options.filelistjson:
build_utils.WriteJson({ 'files': output_paths }, options.filelistjson)
output_paths.append(options.filelistjson)
if options.depfile:
build_utils.WriteDepfile(options.depfile, output_paths[-1], libraries)
if options.stamp:
build_utils.Touch(options.stamp)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
b5261996143a809047a41f5fd39fe46b57b79f0c | 15b12d69ac3123d1562986970ce01d7a47d171de | /typings/nltk/misc/wordfinder.pyi | 8fbb7b9a5fbec1e043e6e51712347842946e93d0 | [
"Apache-2.0"
] | permissive | simplymanas/python-learning | 9b67b5a7acfb3a7c2455a7d1fc66203a2b419c37 | 75bc99c0dce211fd1bce5f6ce1155e0f4c71d7d0 | refs/heads/master | 2021-07-11T06:40:24.803589 | 2021-06-20T12:06:02 | 2021-06-20T12:06:02 | 241,769,614 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,103 | pyi | """
This type stub file was generated by pyright.
"""
def revword(word):
...
def step(word, x, xf, y, yf, grid):
...
def check(word, dir, x, y, grid, rows, cols):
...
def wordfinder(words, rows=..., cols=..., attempts=..., alph=...):
"""
Attempt to arrange words into a letter-grid with the specified
number of rows and columns. Try each word in several positions
and directions, until it can be fitted into the grid, or the
maximum number of allowable attempts is exceeded. Returns a tuple
consisting of the grid and the words that were successfully
placed.
:param words: the list of words to be put into the grid
:type words: list
:param rows: the number of rows in the grid
:type rows: int
:param cols: the number of columns in the grid
:type cols: int
:param attempts: the number of times to attempt placing a word
:type attempts: int
:param alph: the alphabet, to be used for filling blank cells
:type alph: list
:rtype: tuple
"""
...
def word_finder():
...
if __name__ == '__main__':
...
| [
"manas.dash@tesco.com"
] | manas.dash@tesco.com |
6f9545c1c44ca8d988e519fb3ea7915411b32e56 | bf76afd4a984e5cee607a76f2bb9490797010b33 | /accounts/api/urls.py | 33d0ccc97a22e3b2c5a927ae38ee366e7f23f25f | [] | no_license | itsloys/tweet | a0c75718dd78971aae03129895b0e710dad0b7cc | dfd3a745ac83842999ca9af9085ab26adb150295 | refs/heads/master | 2021-09-07T02:51:33.646734 | 2018-02-16T05:55:49 | 2018-02-16T05:55:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 189 | py | from django.conf.urls import url
from tweets.api.views import (
TweetListAPIView
)
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/tweet/$', TweetListAPIView.as_view(), name='list'),
] | [
"louisaleksieb.dagusen@gmail.com"
] | louisaleksieb.dagusen@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.