blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
69
| license_type
stringclasses 2
values | repo_name
stringlengths 5
118
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
63
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 2.91k
686M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 213
values | src_encoding
stringclasses 30
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 2
10.3M
| extension
stringclasses 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7e04e05013d0ba91eda5ecf46be0d67853f47faf
|
9573947f0ded2ccc57358119ec4a644db8ae0239
|
/variance_reduction/weight_importances_tests/shielding_problem_1/forward/forward_cadis_importance_weight.py
|
eb118a44420a7e511f5bb9d2b7426339140602d5
|
[] |
no_license
|
psbritt/FRENSIE-tests
|
bc945e48550b3248a381b291f57ac1548f4ad10d
|
321663e1b564607b4525e83fde4a5bf2dddc49e8
|
refs/heads/master
| 2021-11-20T08:21:09.233258
| 2021-09-04T13:17:18
| 2021-09-04T13:17:18
| 243,323,405
| 0
| 0
| null | 2020-02-26T17:28:01
| 2020-02-26T17:28:00
| null |
UTF-8
|
Python
| false
| false
| 8,477
|
py
|
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from argparse import *
import PyFrensie.Geometry.DagMC as DagMC
import PyFrensie.Utility.Distribution as Distribution
import PyFrensie.MonteCarlo as MonteCarlo
import PyFrensie.MonteCarlo.Collision as Collision
import PyFrensie.MonteCarlo.ActiveRegion as ActiveRegion
import PyFrensie.MonteCarlo.Event as Event
import PyFrensie.MonteCarlo.Manager as Manager
import PyFrensie.Data as Data
import PyFrensie.Utility.Mesh as Mesh
import PyFrensie.Utility as Utility
import PyFrensie.Utility.MPI as MPI
from cadis_importance_weight_converter import cadis_importance_weight_converter
if __name__ == "__main__":
#--------------------------------------------------------------------------------#
# SIMULATION PARAMETERS
#--------------------------------------------------------------------------------#
#GEOMETRY AND MATERIAL DENSITIES ARE IN THE .trelis FILE
parser = ArgumentParser()
parser.add_argument("--threads", dest="threads", type=int, default=1)
parser.add_argument("--num_particles", dest="num_particles", type=float, default=1e2)
args=parser.parse_args()
## Initialize the MPI session
session = MPI.GlobalMPISession( len(sys.argv), sys.argv )
# Suppress logging on all procs except for the master (proc=0)
Utility.removeAllLogs()
session.initializeLogs( 0, True )
db_path = os.environ.get("DATABASE_PATH")
sim_name = "forward_cadis_importance_weight"
num_particles = args.num_particles
threads = args.threads
print(threads)
if db_path is None:
print('The database path must be specified!')
sys.exit(1)
## Set the simulation properties for forward
simulation_properties = MonteCarlo.SimulationProperties()
#USE PHOTONS
simulation_properties.setParticleMode( MonteCarlo.PHOTON_MODE )
simulation_properties.setNumberOfHistories( num_particles )
simulation_properties.setMaxRendezvousBatchSize( int(num_particles) )
simulation_properties.setIncoherentModelType(MonteCarlo.FULL_PROFILE_DB_IMPULSE_INCOHERENT_MODEL)
model_properties = DagMC.DagMCModelProperties("../model.h5m")
model_properties.setMaterialPropertyName( "material" )
model_properties.setDensityPropertyName( "density" )
model_properties.setTerminationCellPropertyName( "termination.cell" )
model_properties.useFastIdLookup()
model = DagMC.DagMCModel( model_properties )
data_file_type = Data.PhotoatomicDataProperties.Native_EPR_FILE
## Set up the materials
database = Data.ScatteringCenterPropertiesDatabase( db_path )
#MATERIAL INFO. MATERIAL IS ASSIGNED IN TRELIS FILE ALONG WITH DENSITY. ZAID IS BELOW.
# Extract the properties for Mn from the database
Mn_properties = database.getAtomProperties( Data.ZAID(25000) )
# Extract the properties for Ge from the database
Ge_properties = database.getAtomProperties( Data.ZAID(32000) )
# Extract the properties for H from the database
H_properties = database.getAtomProperties( Data.ZAID(1000) )
# Extract the properties for Pb from the database
Pb_properties = database.getAtomProperties( Data.ZAID(82000) )
# Set the definition for H, Pb, Mn, Ge for this simulation
scattering_center_definitions = Collision.ScatteringCenterDefinitionDatabase()
Mn_definition = scattering_center_definitions.createDefinition( "Mn", Data.ZAID(25000) )
Ge_definition = scattering_center_definitions.createDefinition( "Ge", Data.ZAID(32000) )
H_definition = scattering_center_definitions.createDefinition( "H", Data.ZAID(1000) )
Pb_definition = scattering_center_definitions.createDefinition( "Pb", Data.ZAID(82000) )
file_version = 0
Mn_definition.setPhotoatomicDataProperties( Mn_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version) )
Ge_definition.setPhotoatomicDataProperties( Ge_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version) )
H_definition.setPhotoatomicDataProperties( H_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version) )
Pb_definition.setPhotoatomicDataProperties( Pb_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version) )
# Set the definition for materials
material_definitions = Collision.MaterialDefinitionDatabase()
material_definitions.addDefinition( "Mn", 1, ["Mn"], [1.0] )
material_definitions.addDefinition( "Ge", 2, ["Ge"], [1.0] )
material_definitions.addDefinition( "H", 3, ["H"], [1.0] )
material_definitions.addDefinition( "Pb", 4, ["Pb"], [1.0] )
filled_model = Collision.FilledGeometryModel( db_path, scattering_center_definitions, material_definitions, simulation_properties, model, True )
#MESH INFORMATION. MESH IS 50x50x50 WITH EACH ELEMENT SIZE 2x2x2.
xyz0=-25
geometry_dimension_size = 50
mesh_element_size = 2
x_planes = []
y_planes = []
z_planes = []
for i in range((geometry_dimension_size/mesh_element_size)+1):
x_planes.append(xyz0 + i*mesh_element_size)
y_planes.append(xyz0 + i*mesh_element_size)
z_planes.append(xyz0 + i*mesh_element_size)
mesh = Mesh.StructuredHexMesh(x_planes, y_planes, z_planes)
#SOURCE DESCRIPTION. SOURCE IS CONTAINED IN VOLUME 4
source_x_raw_distribution = Distribution.UniformDistribution(-17, -15, 1)
source_y_raw_distribution = Distribution.UniformDistribution(-1, 1, 1)
source_z_raw_distribution = Distribution.UniformDistribution(-1, 1, 1)
source_x_distribution = ActiveRegion.IndependentPrimarySpatialDimensionDistribution(source_x_raw_distribution)
source_y_distribution = ActiveRegion.IndependentSecondarySpatialDimensionDistribution(source_y_raw_distribution)
source_z_distribution = ActiveRegion.IndependentTertiarySpatialDimensionDistribution(source_z_raw_distribution)
particle_distribution = ActiveRegion.StandardParticleDistribution("Forward source")
particle_distribution.setDimensionDistribution(source_x_distribution)
particle_distribution.setDimensionDistribution(source_y_distribution)
particle_distribution.setDimensionDistribution(source_z_distribution)
#MONOENERGETIC SOURCE AT 0.835 MeV
particle_distribution.setEnergy(0.835)
particle_distribution.constructDimensionDistributionDependencyTree()
source_component = ActiveRegion.StandardPhotonSourceComponent(1, 1.0, model, particle_distribution)
source = ActiveRegion.StandardParticleSource([source_component])
event_handler = Event.EventHandler( model, simulation_properties )
#I DON'T THINK MCNP HAS THIS KIND OF ESTIMATOR, SO IGNORE IF IT DOESN'T EXIST
cell_integral_estimator = Event.WeightMultipliedCellCollisionFluxEstimator(1, 1.0, [5], model)
cell_integral_estimator.setParticleTypes([MonteCarlo.PHOTON])
cell_integral_estimator.setEnergyDiscretization([1e-3, 0.835])
event_handler.addEstimator(cell_integral_estimator)
#ESTIMATOR OF INTEREST - TRACK LENGTH ESTIMATOR IN VOLUME 5
cell_integral_tl_estimator = Event.WeightMultipliedCellTrackLengthFluxEstimator(2, 1.0, [5], model)
cell_integral_tl_estimator.setParticleTypes([MonteCarlo.PHOTON])
cell_integral_tl_estimator.setEnergyDiscretization([1e-3, 0.835])
event_handler.addEstimator(cell_integral_tl_estimator)
cadis_converter = cadis_importance_weight_converter(mesh)
importance_weight_energy_bounds = cadis_converter.getImportanceWeightEnergyBounds()
importance_weight_map = cadis_converter.getImportanceWeightMap()
importance_weight_handler = Event.WeightImportanceMesh()
importance_weight_handler.setEnergyDiscretization(importance_weight_energy_bounds)
importance_weight_handler.setMesh(mesh)
importance_weight_handler.setWeightImportanceMap(importance_weight_map)
importance_weight_handler.setMaxSplit(100)
importance_weight_handler.setControlledParticleType(MonteCarlo.PHOTON)
importance_weight_handler.setNonImportanceWeightTransform(False)
factory = Manager.ParticleSimulationManagerFactory( filled_model,
source,
event_handler,
simulation_properties,
sim_name,
"xml",
threads )
factory.setPopulationControl(importance_weight_handler)
manager = factory.getManager()
manager.useSingleRendezvousFile()
session.restoreOutputStreams()
## Run the simulation
manager.runSimulation()
|
[
"philip.s.britt@gmail.com"
] |
philip.s.britt@gmail.com
|
42b25b8500cee6bdeb42389321db42391aba6249
|
ebb51eda50d34570d896321cc2e6b184ab2aa4e9
|
/app/serializers/user.py
|
d786b5c48eecdf69d284bb50272bb20aad89b1fd
|
[] |
no_license
|
NEWME0/food-calories-telegram
|
38703f8ab394ee8770a72289f9a6b06e0191c54e
|
ba0af1e8356940b9c270378048a943ceca387803
|
refs/heads/master
| 2022-12-07T07:41:58.305064
| 2020-09-01T10:43:14
| 2020-09-01T10:43:14
| 286,481,244
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 402
|
py
|
from datetime import datetime, date
from pydantic import BaseModel
class UserApiKeyCreate(BaseModel):
username: str
class UserApiKeyDetail(BaseModel):
message: str
api_key: str
class UserProfileDetail:
id: int
date_created: datetime
date_modified: datetime
gender: str
height: int
weight: int
date_of_birth: date
user: int
class UserTarget:
pass
|
[
"ordersone@gmail.com"
] |
ordersone@gmail.com
|
88548bb1fc407a53d26b136f6cf6a59077717ca2
|
621ae05f9703768f7a1ea6ef497eed8fadc2c78d
|
/tests/test_factories.py
|
d80f01b2d8b87e50e7c110d7dad7973bffb55bc5
|
[
"MIT"
] |
permissive
|
TheBiggerGuy/piecash
|
19f90284a6d361ffcdb7f99317aa1965551f3963
|
6a32ae323e4a9629c1c58bd097368518194b06c5
|
refs/heads/master
| 2021-04-03T20:11:36.665519
| 2018-03-11T20:25:43
| 2018-03-11T20:25:43
| 124,446,841
| 0
| 0
| null | 2018-03-08T20:52:45
| 2018-03-08T20:52:45
| null |
UTF-8
|
Python
| false
| false
| 6,651
|
py
|
# coding=utf-8
from __future__ import unicode_literals
from datetime import datetime
from decimal import Decimal
import pytest
import tzlocal
from piecash import GnucashException, Commodity
from piecash.core import factories
from test_helper import db_sqlite_uri, db_sqlite, new_book, new_book_USD, book_uri, book_basic, needweb
# dummy line to avoid removing unused symbols
a = db_sqlite_uri, db_sqlite, new_book, new_book_USD, book_uri, book_basic
class TestFactoriesCommodities(object):
def test_create_stock_accounts_simple(self, book_basic):
with pytest.raises(GnucashException):
factories.create_stock_accounts(book_basic.default_currency,
broker_account=book_basic.accounts(name="broker"))
broker = book_basic.accounts(name="broker")
appl = Commodity(namespace="NMS", mnemonic="AAPL", fullname="Apple")
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker)
assert inc_accounts == []
assert broker.children == [acc]
def test_create_stock_accounts_incomeaccounts(self, book_basic):
broker = book_basic.accounts(name="broker")
income = book_basic.accounts(name="inc")
appl = Commodity(namespace="NMS", mnemonic="AAPL", fullname="Apple")
appl["quoted_currency"] = "USD"
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker,
income_account=income,
income_account_types="D")
assert len(inc_accounts) == 1
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker,
income_account=income,
income_account_types="CL")
assert len(inc_accounts) == 1
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker,
income_account=income,
income_account_types="CS")
assert len(inc_accounts) == 1
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker,
income_account=income,
income_account_types="I")
assert len(inc_accounts) == 1
acc, inc_accounts = factories.create_stock_accounts(appl,
broker_account=broker,
income_account=income,
income_account_types="D/CL/CS/I")
assert len(income.children) == 4
assert sorted(income.children, key=lambda x: x.guid) == sorted([_acc.parent for _acc in inc_accounts],
key=lambda x: x.guid)
assert broker.children == [acc]
@needweb
def test_create_stock_from_symbol(self, book_basic):
assert len(book_basic.commodities) == 2
factories.create_stock_from_symbol("AAPL", book_basic)
assert len(book_basic.commodities) == 3
cdty = book_basic.commodities(mnemonic="AAPL")
assert cdty.namespace == "NMS"
assert cdty.quote_tz == "EST"
assert cdty.quote_source == "yahoo"
assert cdty.mnemonic == "AAPL"
assert cdty.fullname == "Apple Inc."
def test_create_currency_from_ISO(self, book_basic):
assert factories.create_currency_from_ISO("CAD").fullname == "Canadian Dollar"
with pytest.raises(ValueError):
factories.create_currency_from_ISO("EFR").fullname
class TestFactoriesTransactions(object):
def test_single_transaction(self, book_basic):
today = datetime.today()
print("today=", today)
factories.single_transaction(today.date(),
today,
"my test",
Decimal(100),
from_account=book_basic.accounts(name="inc"),
to_account=book_basic.accounts(name="asset"))
book_basic.save()
tr = book_basic.transactions(description="my test")
assert len(tr.splits) == 2
sp1, sp2 = tr.splits
if sp1.value > 0:
sp2, sp1 = sp1, sp2
# sp1 has negative value
assert sp1.account == book_basic.accounts(name="inc")
assert sp2.account == book_basic.accounts(name="asset")
assert sp1.value == -sp2.value
assert sp1.quantity == sp1.value
assert tr.enter_date == tzlocal.get_localzone().localize(today.replace(microsecond=0))
assert tr.post_date == tzlocal.get_localzone().localize(today).date()
def test_single_transaction_tz(self, book_basic):
today = tzlocal.get_localzone().localize(datetime.today())
factories.single_transaction(today.date(),
today,
"my test",
Decimal(100),
from_account=book_basic.accounts(name="inc"),
to_account=book_basic.accounts(name="asset"))
book_basic.save()
tr = book_basic.transactions(description="my test")
assert tr.post_date == today.date()
assert tr.enter_date == today.replace(microsecond=0)
def test_single_transaction_rollback(self, book_basic):
today = tzlocal.get_localzone().localize(datetime.today())
factories.single_transaction(today.date(),
today,
"my test",
Decimal(100),
from_account=book_basic.accounts(name="inc"),
to_account=book_basic.accounts(name="asset"))
book_basic.validate()
assert len(book_basic.transactions) == 1
book_basic.cancel()
assert len(book_basic.transactions) == 0
|
[
"sdementen@gmail.com"
] |
sdementen@gmail.com
|
826855eff63732ea45b8828f4215461a69663118
|
e80e4878ed4343efe330c45a3e85c9028544284d
|
/youtool/HTTPQuery.py
|
e3c1459bb0fd0a8c1ac99d73002b9e6fa09d1bf4
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Unlicense"
] |
permissive
|
ctcq/yaylist
|
c94239cdde51725a504da9cff5fbaf01a29e953c
|
bd8abfef86a6c285111e1fee87535bd329c7f3c6
|
refs/heads/master
| 2022-11-25T16:46:25.364204
| 2020-08-08T14:30:29
| 2020-08-08T14:30:29
| 286,055,726
| 0
| 0
| null | 2020-08-08T14:30:30
| 2020-08-08T14:12:08
|
Python
|
UTF-8
|
Python
| false
| false
| 1,625
|
py
|
import urllib.parse
import requests
class HTTPQuery:
def __init__(self, query):
query = query.replace(" ", "+")
self.query = urllib.parse.quote(query)
self.max_attempts = 20
def send_query(self):
base_url = "https://www.youtube.com/results?search_query="
url = f"{base_url}{self.query}"
self.url = url
headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"}
response = requests.get(url, headers = headers)
return response.text
def filter_response(self, response):
attempts = 0
current_index = 0
id_prefix = 'data-video-ids="'
title_prefix = 'title="'
while(attempts < self.max_attempts):
r = response[current_index:]
#Find the id
id, i = self.find_assignment_in_string(r, 'data-video-ids="')
title, i = self.find_assignment_in_string(r[i:], 'title="')
if True: #self.query_matches_title(title):
return id
else:
attempts += 1
current_index += i
return None
def find_assignment_in_string(self, string, key):
i = string.find(key)
start = i + len(key)
end = start + string[start:].find('"')
value = string[start:end]
return value, end
def query_matches_title(self, title):
query_split = self.query.split("+")
title_split = title.split(" ")
for word in query_split:
if not word in title_split:
return False
return True
|
[
"c_wied05@uni-muenster.de"
] |
c_wied05@uni-muenster.de
|
636a207ff0e49734b5801a6a8c8106cbab384c7c
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/MiCMj8HvevYzGSb8J_17.py
|
1019062c3bbb1b60d25995c70003f2d401b4ba35
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 205
|
py
|
def fibo_word(n):
s="b, a, "
a="a"
b="b"
c=""
if n<2:
return "invalid"
for i in range(2,n):
c=a+b
b=a
a=c
if i==n-1:
s=s+c
return s
else:
s=s+c+", "
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
01fe8df90c60347168481f79e7c0e7b49c51b723
|
6ca8fc2feac0ba4fdb4ab9710cbf853a9d0f0f3b
|
/package/branching.py
|
5b6aabe13cb3cec1bd520fe451bf717b0b9e5b10
|
[
"MIT"
] |
permissive
|
byavkin/python-template
|
bcfafff8ca5fba24258a7dec4f24d97771abecd2
|
a3df9db2bba6911895d231ae5d893e172c38e677
|
refs/heads/master
| 2022-04-24T20:25:05.989560
| 2020-04-29T13:39:10
| 2020-04-29T13:39:10
| 259,921,107
| 0
| 0
|
MIT
| 2020-04-29T12:37:36
| 2020-04-29T12:37:36
| null |
UTF-8
|
Python
| false
| false
| 70
|
py
|
import numpy as np
#import blah
from . import module
a = module.Bass
|
[
"boris.yavkin@gmail.com"
] |
boris.yavkin@gmail.com
|
2f9c3a276216eedf29c7990ee4b3e77e19710b6f
|
77669891d957d728613143d341ec5ee8aec81bea
|
/tests/__init__.py
|
11634db77cbafb78f92f4f70bc83d3bb54a92f68
|
[
"BSD-3-Clause"
] |
permissive
|
ska-telescope/sdp-lmc
|
56a572435dbf5ff64dbf1f7eb9bd6c647c64c134
|
870d41cfef29ca0777c34e0d27cd5b754bb4e9a3
|
refs/heads/master
| 2023-07-09T11:36:16.727053
| 2021-08-11T13:09:54
| 2021-08-11T13:09:54
| 295,661,049
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 31
|
py
|
"""Tests for Tango devices."""
|
[
"maja1@mrao.cam.ac.uk"
] |
maja1@mrao.cam.ac.uk
|
cba3b48fe847b5a01528621677091588b2dfa50d
|
edd3da6431675ce3b048b3557f1b410192491558
|
/mpl_starting.py
|
585609254bed79c62b69597db851c09da557ed6f
|
[] |
no_license
|
abdlkdrgndz/data-mining
|
f845a5821f0800a5fd75807766593c97e5221b9f
|
9882f60f75acfc55e5dc9cb2248c92e093b461e6
|
refs/heads/master
| 2023-02-14T21:24:39.921072
| 2021-01-10T01:19:59
| 2021-01-10T01:19:59
| 328,273,023
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,151
|
py
|
# Görselleştirme Kütüphanesidir
# bir csv dosyasını okuyarak başlayalım ve onu data frames e dönüştürelim
# iris.csv dosyası çiçek türlerine ait bir dosya. 150 adet örnek datayı barındırıyor. Data içeriğini inceleyerek sütun ve data bilgilerini görebiliriz.
import pandas
import matplotlib.pyplot as plt
df = pandas.read_csv('iris.csv')
# tüm türleri gösterelim.
print(df.Species)
# kaç farklı tür olduğunu listeleyelim.
print("-- Kaç Tür Var? ---")
print(df.Species.unique())
# elimizdeki cvs dosyası ile ilgili genel bilgileri öğrenelim.
print("--- Genel Bilgiler ---")
print(df.info())
# mesela numeric değerleri listeleyelim
print("--- Numeric Değerler ve Özellikler ---")
print(df.describe())
# bir türe ait dataları listeleyelim ve karşılaştıralım
print("-- Iris-setosa ve Iris-virginica Karşılaştırması --")
setosa = df[df.Species == "Iris-setosa"]
virginica = df[df.Species == "Iris-virginica"]
print(setosa.describe()) # bir property e ait sonuç istersek setosa.SepalLengthCm.describe().mean() şeklinde çağırabiliriz.
print(virginica.describe())
# MATPLOTLIB E BAŞLAYALIM
|
[
"abdulkadir.gunduz@modanisa.com"
] |
abdulkadir.gunduz@modanisa.com
|
7604053a02411d08fa1e4abd49436ef2b7a5b072
|
b04e31d2beaeba952ff34d374e349079dac90ccf
|
/Agent.py
|
a941713fb95d834a880804841b9c2e88a631e695
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
helloric/pydial3
|
9ba9d06cfc94d1107a329cd2089afa5b4b304402
|
34988f4592c4e28388b2818de8768d841696efbb
|
refs/heads/main
| 2023-03-13T23:11:19.294128
| 2021-03-22T15:01:15
| 2021-03-22T15:01:34
| 350,398,432
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 45,960
|
py
|
###############################################################################
# PyDial: Multi-domain Statistical Spoken Dialogue System Software
###############################################################################
#
# Copyright 2015 - 2019
# Cambridge University Engineering Department Dialogue Systems Group
#
#
# 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.
#
###############################################################################
'''
Agent.py - wrapper for all components required in a dialogue system
==========================================================================
Copyright CUED Dialogue Systems Group 2015 - 2017
Contains 3 classes::
DialogueAgent, AgentFactoy, CallValidator
.. seealso:: CUED Imports/Dependencies:
import :mod:`utils.Settings` |.|
import :mod:`utils.ContextLogger` |.|
import :class:`utils.DiaAct.DiaAct` |.|
import :class:`utils.DiaAct.DiaActWithProb` |.|
import :mod:`semo.SemOManager` |.|
import :mod:`semanticbelieftracking.SemanticBeliefTrackingManager` |.|
import :mod:`policy.PolicyManager` |.|
import :mod:`evaluation.EvaluationManager` |.|
import :mod:`topictracking.TopicTracking` |.|
import :mod:`ontology.Ontology` |.|
************************
'''
from utils import Settings, ContextLogger
from topictracking import TopicTracking
from ontology import Ontology
from utils.DiaAct import DiaAct, DiaActWithProb
import time, re
logger = ContextLogger.getLogger('')
__author__ = "cued_dialogue_systems_group"
__version__ = Settings.__version__
#----------------------------------------------------------------
# DIALOGUE AGENT
#----------------------------------------------------------------
class DialogueAgent(object):
'''
Contains all components required for multi domain dialogue: {topic tracking, semi belief tracking, policy, semo}
- each of these components is a manager for that ability for all domains.
- DialogueAgent() controls the flow of calls/information passing between all of these components in order to execute a dialog
'''
# pylint: disable=too-many-instance-attributes
def __init__(self, agent_id='Smith', hub_id='dialogueserver'):
# Define all variables in __init__:
self.prompt_str = None
self.reward = None
self.currentTurn = None
self.maxTurns = None
self.ENDING_DIALOG = None
self.SUBJECTIVE_RETRIEVAL_ATTEMPS = None
self.TASK_RETRIEVAL_ATTEMPTS = None
self.constraints = None
self.task = None
self.taskId = None
self.subjective = None
self.session_id = None
self.callValidator = CallValidator()
# DEFAULTS:
# meta params - note these define the 'state' of the dialogue, along with those defined in restart_agent()
assert(hub_id in ['texthub', 'simulate', 'dialogueserver'])
self.hub_id = hub_id # defines certain behaviour of the agent. One of [texthub, simulate, dialogueserver]
self.agent_id = agent_id
self.NUM_DIALOGS = 0
self.SYSTEM_CAN_HANGUP = False
self.SAVE_FREQUENCY = 10 # save the policy after multiples of this many dialogues
self.MAX_TURNS_PROMPT = "The dialogue has finshed due to too many turns"
self.NO_ASR_MSG = "I am afraid I did not understand. Could you please repeat that."
self.maxTurns_per_domain = 30
self.traceDialog = 2
self.sim_level = 'dial_act'
# CONFIGS:
if Settings.config.has_option('agent', 'savefrequency'):
self.SAVE_FREQUENCY = Settings.config.getint('agent', 'savefrequency')
if Settings.config.has_option("agent","systemcanhangup"):
self.SYSTEM_CAN_HANGUP = Settings.config.getboolean("agent", "systemcanhangup")
if Settings.config.has_option("agent", "maxturns"):
self.maxTurns_per_domain = Settings.config.getint("agent", "maxturns")
if Settings.config.has_option("GENERAL", "tracedialog"):
self.traceDialog = Settings.config.getint("GENERAL", "tracedialog")
if Settings.config.has_option("usermodel", "simlevel"):
self.sim_level = Settings.config.get("usermodel", "simlevel")
# TOPIC TRACKING:
#-----------------------------------------
self.topic_tracker = TopicTracking.TopicTrackingManager()
# SemI + Belief tracker
self.semi_belief_manager = self._load_manger('semanticbelieftrackingmanager','semanticbelieftracking.SemanticBeliefTrackingManager.SemanticBeliefTrackingManager')
# Policy.
#-----------------------------------------
self.policy_manager = self._load_manger('policymanager','policy.PolicyManager.PolicyManager')
# SemO.
#-----------------------------------------
if self.hub_id == 'simulate': # may or may not have NLG in simulate (default is not to)
generate_prompts = False
if Settings.config.has_option('simulate', 'generateprompts'):
generate_prompts = Settings.config.getboolean('simulate', 'generateprompts')
else:
generate_prompts = True # default for Texthub and DialogueServer
if generate_prompts:
self.semo_manager = self._load_manger('semomanager','semo.SemOManager.SemOManager')
else:
self.semo_manager = None
# Evaluation Manager.
#-----------------------------------------
self.evaluation_manager = self._load_manger('evaluationmanager','evaluation.EvaluationManager.EvaluationManager')
# Restart components - NB: inefficient - will be called again before 1st dialogue - but enables _logical_requirements()
self.restart_agent(session_id=None)
# Finally, enforce some cross module requirements:
self._logical_requirements()
def start_call(self, session_id, domainSimulatedUsers=None, maxNumTurnsScaling=1.0, start_domain=None):
'''
Start a new call with the agent.
Works through policy > semo -- for turn 0
Start domain is used if external topic tracking is used.
Input consists of a n-best list of either ASR hypotheses (with confidence) or (mostly only in case of simulation) pre-interpreted DiaActWithProb objects.
:param session_id: session id
:type session_id: string
:param domainSimulatedUsers: simulated users in different domains
:type domainSimulatedUsers: dict
:param maxNumTurnsScaling: controls the variable turn numbers allowed in a dialog, based on how many domains are involved (used only for simulate)
:type maxNumTurnsScaling: float
:param start_domain: used by DialPort/external topictracking with DialogueServer to hand control to certain domain
:type start_domain: str
:return: string -- the system's reponse
'''
self._check_agent_not_on_call()
self.NUM_DIALOGS += 1
logger.dial(">> NEW DIALOGUE SESSION. Number: "+str(self.NUM_DIALOGS))
# restart agent:
self.restart_agent(session_id, maxNumTurnsScaling, start_domain=start_domain)
self.callValidator.init()
# SYSTEM STARTS DIALOGUE first turn:
#---------------------------------------------------------
self._print_turn()
currentDomain = self.topic_tracker.operatingDomain
last_sys_act = self.retrieve_last_sys_act(currentDomain)
# SYSTEM ACT:
# 1. Belief state tracking -- (currently just in single domain as directed by topic tracker)
logger.debug('active domain is: '+currentDomain)
state = self.semi_belief_manager.update_belief_state(ASR_obs=None, sys_act=last_sys_act,
dstring=currentDomain, turn=self.currentTurn,hub_id = self.hub_id)
# 2. Policy -- Determine system act/response
sys_act = self.policy_manager.act_on(dstring=self.topic_tracker.operatingDomain,
state=state)
self._print_sys_act(sys_act)
# EVALUATION: - record the system action taken in the current domain if using tasks for evaluation (ie DialogueServer)
self._evaluate_agents_turn(domainSimulatedUsers, sys_act)
# SEMO:
self.prompt_str = self._agents_semo(sys_act)
self.callValidator.validate(sys_act)
sys_act.prompt = self.prompt_str
state.setLastSystemAct(sys_act)
#---Return the generated prompt---------------------------------------------------
return sys_act
def continue_call(self, asr_info, domainString=None, domainSimulatedUsers=None):
'''
Works through topictracking > semi belief > policy > semo > evaluation -- for turns > 0
Input consists of a n-best list of either ASR hypotheses (with confidence) or (mostly only in case of simulation) pre-interpreted DiaActWithProb objects.
:param asr_info: information fetched from the asr
:type asr_info: list of string or DiaActWithProb objects
:param domainString: domain name
:type domainString: string
:param domainSimulatedUsers: simulated users in different domains
:type domainSimulatedUsers: dict
:return: DiaAct -- the system's reponse dialogue act with verbalization
'''
logger.dial("user input: {}".format([(x.to_string() if isinstance(x,DiaAct) else x[0], round(x.P_Au_O, 3) if isinstance(x,DiaAct) else x[1]) for x in asr_info]))
# Check if user says bye and whether this is already valid
self.callValidator.validate() # update time once more
if self.callValidator.check_if_user_bye(asr_info) and not self.callValidator.isValid:
logger.info("User tries to end dialogue before min dialogue length.")
return self.callValidator.getNonValidPrompt() + " " + self.prompt_str
# 0. Increment turn and possibly set ENDING_DIALOG if max turns reached:
#--------------------------------------------------------------------------------------------------------------
if self._increment_turn_and_check_maxTurns():
sys_act = DiaAct('bye()')
sys_act.prompt = self.MAX_TURNS_PROMPT
return sys_act
# 1. USER turn:
#--------------------------------------------------------------------------------------------------------------
# Make sure there is some asr information:
if not len(asr_info):
sys_act = DiaAct('null()')
sys_act.prompt = self.NO_ASR_MSG
return sys_act
# TOPIC TRACKING: Note: can pass domainString directly here if cheating/developing or using simulate
currentDomain = self._track_topic_and_hand_control(domainString=domainString, userAct_hyps=asr_info)
prev_sys_act = self.retrieve_last_sys_act(currentDomain)
# 2. SYSTEM response:
#--------------------------------------------------------------------------------------------------------------
# SYSTEM ACT:
# 1. Belief state tracking -- (currently just in single domain as directed by topic tracker)
logger.debug('active domain is: '+currentDomain)
state = self.semi_belief_manager.update_belief_state(ASR_obs=asr_info, sys_act=prev_sys_act,
dstring=currentDomain, turn=self.currentTurn,hub_id = self.hub_id, sim_lvl=self.sim_level)
self._print_usr_act(state, currentDomain)
# 2. Policy -- Determine system act/response
sys_act = self.policy_manager.act_on(dstring=currentDomain,
state=state)
# Check ending the call:
sys_act = self._check_ENDING_CALL(state, sys_act) # NB: this may change the self.prompt_str
self._print_sys_act(sys_act)
# SEMO:
self.prompt_str = self._agents_semo(sys_act)
sys_act.prompt = self.prompt_str
# 3. TURN ENDING
#-----------------------------------------------------------------------------------------------------------------
# EVALUATION: - record the system action taken in the current domain if using tasks for evaluation (ie DialogueServer)
self._evaluate_agents_turn(domainSimulatedUsers, sys_act, state)
self.callValidator.validate(sys_act)
sys_act.prompt = self.prompt_str
state.setLastSystemAct(sys_act)
#---Return the generated prompt---------------------------------------------------
return sys_act
def end_call(self, domainSimulatedUsers=None, noTraining=False):
'''
Performs end of dialog clean up: policy learning, policy saving and housecleaning. The NoTraining parameter is used in
case of an abort of the dialogue where you still want to gracefully end it, e.g., if the dialogue server receives
a clean request.
:param domainSimulatedUsers: simulated users in different domains
:type domainSimulatedUsers: dict
:param noTraining: train the policy when ending dialogue
:type noTraining: bool
:return: None
'''
# Finalise any LEARNING:
finalInfo = {}
if self.hub_id=='simulate' and domainSimulatedUsers is not None:
usermodels = {}
for operatingDomain in domainSimulatedUsers:
user_model_holder = domainSimulatedUsers[operatingDomain]
if user_model_holder is not None:
usermodels[operatingDomain] = user_model_holder.um
finalInfo['usermodel'] = usermodels
finalInfo['task'] = self.task
finalInfo['subjectiveSuccess'] = self.subjective
final_rewards = self.evaluation_manager.finalRewards(finalInfo)
self.policy_manager.finalizeRecord(domainRewards = final_rewards)
if not noTraining:
if self.callValidator.isTrainable:
self.policy_manager.train(self.evaluation_manager.doTraining())
# Print dialog summary.
self.evaluation_manager.print_dialog_summary()
# Save the policy:
self._save_policy()
self.session_id = None # indicates the agent is not on a call.
self.ENDING_DIALOG = False
def restart_agent(self, session_id, maxNumTurnsScaling=1.0, start_domain=None):
'''
Restart the agnet
:param session_id: unique session identifier for the dialogue
:type session_id: str
:param maxNumTurnsScaling: controls the variable number of turns allowed for the dialog, based on how many domains are involved (used only for simulate)
:type maxNumTurnsScaling: float
:param start_domain: used by DialPort/external topictracking with DialogueServer to hand control to certain domain
:type start_domain: str
:return: None
'''
self.currentTurn = 0
Settings.global_currentturn = self.currentTurn #TODO: this is used in the action mask. would this work for multiple domain dialogues?
self.maxTurns = self.maxTurns_per_domain * maxNumTurnsScaling
self.ENDING_DIALOG = False
self.SUBJECTIVE_RETRIEVAL_ATTEMPS = 0
self.TASK_RETRIEVAL_ATTEMPTS = 0
self.ood_count = 0
# Init the specific dialogue parameters:
self.constraints = None # used to conditionally set the belief state of a new domain
self.task = None # The task this dialogue involved
self.taskId = None # The task this dialogue involved
self.subjective = None # The 0/1 DTMF feedback from MTurk user - received or not?
self.session_id = session_id
# Restart all STATEFULL objects: {topic tracker, belief, policy, evaluation}
self.topic_tracker.restart()
self.policy_manager.restart()
self.semi_belief_manager.restart()
self.evaluation_manager.restart()
# Give initial control to starting domain/topictracker:
if start_domain is not None:
self.topic_tracker.operatingDomain = start_domain
self._hand_control(domainString=self.topic_tracker.operatingDomain, previousDomainString=None)
def retrieve_last_sys_act(self, domainString=None):
'''
Retreives the sys act from domain domainString if a domain switch has occurred
:param domainString: domain name
:type domainString: string
:return: string -- the system's dialogue act reponse
'''
if domainString is None:
domainString = self.topic_tracker.operatingDomain
sys_act = self.policy_manager.getLastSystemAction(domainString)
return sys_act
def _logical_requirements(self):
'''
Ensure system always says hello at first turn
:return: None
'''
if self.topic_tracker.USE_SINGLE_DOMAIN:
if self.policy_manager.domainPolicies[self.topic_tracker.operatingDomain].startwithhello is False:
logger.warning('Enforcing hello() at first turn in singledomain system')
self.policy_manager.domainPolicies[self.topic_tracker.operatingDomain].startwithhello = True
return
def _track_topic_and_hand_control(self, userAct_hyps=None, domainString=None):
"""
userAct_hyps can possibly be various things: for example just semantic hyps with probs, or ASR n-best
:param userAct_hyps: hypotheses of user's dialogue act
:type userAct_hyps: list
:param domainString: domain name
:type domainString: string
:return: either None or a list of conditional constraints
"""
# 1. Track the topic
newDomainString = self.topic_tracker.track_topic(userAct_hyps, domainString)
# 2. Hand control to [__ASSUMPTION__] single domain (NB:tracker may end up returning a list --- committee)
self._hand_control(domainString=newDomainString, previousDomainString=self.topic_tracker.previousDomain)
return newDomainString
def _hand_control(self, domainString, previousDomainString=None):
"""
Hands control of dialog to 'domainString' domain. Boots up the ontology/belief/policy as required.
:param domainString: domain name
:type domainString: string
:param previousDomainString: previous domain name
:type previousDomainString: string
:return: None
"""
# Ensure that the ontology for domainString is loaded:
# logger.info('agent: _hand_control')
Ontology.global_ontology.ensure_domain_ontology_loaded(domainString)
if domainString is None:
logger.warning("Topic tracker was unable to resolve domain. Remaining with previous turns operating domain: "\
+ self.topic_tracker.operatingDomain)
elif not self._check_currently_booted(domainString):
# The Bootup part - when first launching a new dialogue manager:
logger.info('Launching Dialogue Manager for domain: '+domainString)
# 1. Note that this domain is now involved in current dialog:
self.topic_tracker.in_present_dialog.append(domainString)
self._bootup(domainString, previousDomainString)
return
elif previousDomainString is not None:
# then we are switching domains:
if domainString not in self.topic_tracker.in_present_dialog:
# note that this domain is now involved in current dialog:
self.topic_tracker.in_present_dialog.append(domainString)
self.semi_belief_manager.hand_control(domainString, previousDomainString)
logger.info('Handing control from {} to running - {} - dialogue manager'.format(previousDomainString,domainString))
return
else:
# moving back to a domain that occured in an earlier turn of dialog.
logger.info('Handing control <BACK> to running - '+domainString+' - dialogue manager')
else:
logger.info('Domain '+domainString+' is both already running and has control')
return
def _bootup(self, domainString, previousDomainString=None):
"""
Note: only time bootup is called, self.topic_tracker.operatingDomain is set to the domain already
:param domainString: domain name
:type domainString: string
:param previousDomainString: previous domain name
:type previousDomainString: string
:return: None
"""
self.semi_belief_manager.bootup(domainString, previousDomainString)
self.policy_manager.bootup(domainString)
return
def _check_currently_booted(self, dstring):
"""
Pertains to whole simulate run over multiple dialogs. Has the dialog manager and belief tracker for this domain been
booted up?
:param dstring: domain name string
:param dstring: string
:return: bool -- whether the system is booted or not
"""
policy_booted = dstring in [domain for domain, value in self.policy_manager.domainPolicies.items() if value is not None]
belief_booted = dstring in [domain for domain, value in self.semi_belief_manager.domainSemiBelieftrackers.items() if value is not None]
return policy_booted and belief_booted
def _evaluate_agents_turn(self, domainSimulatedUsers=None, sys_act=None, state=None):
'''
This function needs to record per exchange rewards and pass them to dialogue management.
NB: asssume that the initiative is with the user only, and that we evaluate each exchange - which consists of a user turn,
followed by a system response.
Currently, the process is as follows: if singledomain is False -- then Generic policy starts and we ignore the first turn
If singledomain==True - then we enforce the system to say hello() at turn 0, and ignore the rest of this method
--> in both cases we form User+System response pairs and evaluate these
.. warning:: assumes that ONLY the user has initiative to change domains
:param domainSimulatedUsers: simulated users in different domains
:type domainSimulatedUsers: dict
:param sys_act: system's dialogue act
:type sys_act: string
:return: None
'''
if self.currentTurn==0:
logger.debug('Note that we are ignoring any evaluation of the systems first action')
return
operatingDomain = self.topic_tracker.operatingDomain # Simply for easy access:
# # 0. If using RNN evaluator, extract turn level feature:
# #---------------------------------------------------------------------------------------------------------
#
# if self.evaluation_manager.domainEvaluators[operatingDomain] is not None:
# if self.evaluation_manager.domainEvaluators[operatingDomain].success_measure == "rnn":
# # This is the order that makes sense I think - userAct THEN sys RESPONSE = domain pair
# turnNo = self.evaluation_manager.domainEvaluators[operatingDomain].final_turns +1
# # turn count for this domain only - note turn count will be incremented by per_turn_reward
# belief = self.semi_belief_manager.getDomainBelief(operatingDomain)
# prev_sys_act = self.retrieve_last_sys_act(operatingDomain)
# # TODO -double check that this is the correct act above
# self.evaluation_manager.domainEvaluators[operatingDomain].rnn.set_turn_feature(belief,prev_sys_act,turnNo)
# 1. Get reward
#---------------------------------------------------------------------------------------------------------
self.reward = None
turnInfo = {}
turnInfo['sys_act']=sys_act.to_string()
turnInfo['state']=state
turnInfo['prev_sys_act']=state.getLastSystemAct(operatingDomain)
if self.hub_id=='simulate':
user_model_holder = domainSimulatedUsers[operatingDomain]
if user_model_holder is None:
logger.warning('Simulated user not present for domain %s - passing reward None thru to policy' % operatingDomain)
else:
turnInfo['usermodel'] = user_model_holder.um
self.reward = self.evaluation_manager.turnReward(domainString=operatingDomain, turnInfo=turnInfo)
# 2. Pass reward to dialogue management:
#---------------------------------------------------------------------------------------------------------
self.policy_manager.record(domainString=operatingDomain, reward=self.reward)
return
def _print_turn(self):
'''
Prints the turn in different ways for different hubs (dialogueserver, simulate or texthub)
:return: None
'''
if self.hub_id=='dialogueserver':
logger.dial('Turn %d' % self.currentTurn)
else:
if self.traceDialog>1: print(' Turn %d' % self.currentTurn)
logger.dial('** Turn %d **' % self.currentTurn)
return
def _print_sys_act(self, sys_act):
'''Prints the system act in different ways for different hubs (dialogueserver, simulate or texthub)
:param sys_act: system's dialogue act
:type sys_act: string
:return: None
'''
if self.hub_id=='dialogueserver':
logger.dial('Sys > {}'.format(sys_act))
else:
if self.traceDialog>1: print(' Sys > {}'.format(sys_act))
logger.dial('| Sys > {}'.format(sys_act))
def _print_usr_act(self, state, currentDomain):
'''Prints the system act in different ways for different hubs (dialogueserver, simulate or texthub)
:param sys_act: system's dialogue act
:type sys_act: string
:return: None
'''
if self.traceDialog>2: state.printUserActs(currentDomain)
def _check_ENDING_CALL(self, state = None, sys_act = None):
'''
Sets self.ENDING_DIALOG as appropriate -- checks if USER ended FIRST, then considers SYSTEM.
:param state: system's state (belief)
:type state: :class:`~utils.DialgoueState.DialgoueState`
:param sys_act: system's dialogue act
:type sys_act: string
:return: bool -- whether to end the dialogue or not
'''
sys_act = self._check_USER_ending(state, sys_act=sys_act)
if not self.ENDING_DIALOG:
# check if the system can end the call
self._check_SYSTEM_ending(sys_act)
return sys_act
def _check_SYSTEM_ending(self, sys_act):
'''
Checks if the *system* has ended the dialogue
:param sys_act: system's dialogue act
:type sys_act: string
:return: None
'''
if self.SYSTEM_CAN_HANGUP: # controls policys learning to take decision to end call.
if sys_act.to_string() in ['bye()']:
self.ENDING_DIALOG = True # SYSTEM ENDS
else:
# still possibly return true if *special* domains [topictracker, wikipedia] have reached their own limits
if sys_act.to_string() in ['bye(toptictrackertimedout)', 'bye(wikipediatimedout)', 'bye(topictrackeruserended)']:
self.ENDING_DIALOG = True # SYSTEM ENDS
def _check_USER_ending(self, state = None, sys_act = None):
'''Sets boolean self.ENDING_DIALOG if user has ended call.
.. note:: can change the semo str if user ended.
:param state: system's state (belief)
:type state: :class:`~utils.DialgoueState.DialgoueState`
:param sys_act: system's dialogue act
:type sys_act: string
:return: bool -- whether to end the dialogue or not
'''
# assert(not self.ENDING_DIALOG)
self.ENDING_DIALOG = state.check_user_ending()
if self.ENDING_DIALOG:
if self.semo_manager is not None:
if 'bye' not in self.prompt_str:
logger.warning('Ignoring system act: %s and saying goodbye as user has said bye' % sys_act)
self.prompt_str = 'Goodbye. ' # TODO - check how system can say bye --otherwise user has said bye,
# and we get some odd reply like 'in the south. please enter the 5 digit id ...'
sys_act = DiaAct('bye()')
return sys_act
def _agents_semo(self, sys_act):
'''
Wrapper for semo -- agent used in simulate for example may not be using semo.
:param sys_act: system's dialogue act
:type sys_act: string
:return string -- system's sentence reponse
'''
if self.semo_manager is not None:
logger.dial("Domain with CONTROL: "+self.topic_tracker.operatingDomain)
prompt_str = self.semo_manager.generate(sys_act, domainTag=self.topic_tracker.operatingDomain)
else:
prompt_str = None
return prompt_str
def _save_policy(self, FORCE_SAVE=False):
"""
A wrapper for policy_manager.savePolicy() - controls frequency with which policy is actually saved
:param FORCE_SAVE: whether to force save the policy or not
:type FORCE_SAVE: bool
:return: None
"""
if FORCE_SAVE:
self.policy_manager.savePolicy(FORCE_SAVE)
elif self.NUM_DIALOGS % self.SAVE_FREQUENCY == 0:
self.policy_manager.savePolicy()
else:
pass # neither shutting down agent, nor processed enough dialogues to bother saving.
return
# Agent Utility functions:
#--------------------------------------
def _increment_turn_and_check_maxTurns(self):
'''
Returns boolean from :method:_check_maxTurns - describing whether dialog has timed (ie turned!) out.
:return: bool -- call _check_maxTurns() to check whether the conversation reaches max turns
'''
self._increment_turn()
self._print_turn()
return self._check_maxTurns()
def _increment_turn(self):
'''
Count turns.
:return: None
'''
self.currentTurn += 1
Settings.global_currentturn = self.currentTurn
def _check_maxTurns(self):
'''
Checks that we haven't exceeded set max number. Note: sets self.prompt_str if max turns reached.
Returns a boolean on this check of num turns.
:return: bool -- check whether the conversation reaches max turns
'''
if self.currentTurn > self.maxTurns:
logger.dial("Ending dialog due to MAX TURNS being reached: "+str(self.currentTurn))
self.ENDING_DIALOG = True
return True
return False
def _check_agent_not_on_call(self):
'''
need a check here that the agent is indeed not talking to anyone ...
:return: None
'''
if self.session_id is not None:
logger.error("Agent is assumed to be only on one call at a time")
def _load_manger(self, config, defaultManager):
'''
Loads and instantiates the respective manager (e.g. policymanager, semomanager, etc) as configured in config file. The new object is returned.
:param config: the config option which contains the manager configuration
:type config: str
:param defaultManager: the config string pointing to default manager
:type defaultManager: str
:returns: the new manager object
'''
manager = defaultManager
if Settings.config.has_section('agent') and Settings.config.has_option('agent', config):
manager = Settings.config.get('agent', config)
try:
# try to view the config string as a complete module path to the class to be instantiated
components = manager.split('.')
packageString = '.'.join(components[:-1])
classString = components[-1]
mod = __import__(packageString, fromlist=[classString])
klass = getattr(mod, classString)
return klass()
except ImportError as e:
logger.error('Manager "{}" could not be loaded: {}'.format(manager, e))
#******************************************************************************************************************
# AGENT FACTORY
#******************************************************************************************************************
class AgentFactory(object):
'''
Based on the config (Settings.config) - a primary agent (called Smith) is created.
This agent can be duplicated as required by concurrent traffic into the dialogue server.
Duplicated agents are killed at end of their calls if more agents are running
than a specified minimum (MAX_AGENTS_RUNNING)
'''
def __init__(self, hub_id='dialogueserver'):
self.MAX_AGENTS_RUNNING = 2 # always start with 1, but we dont kill agents below this number
self.init_agents(hub_id)
self.session2agent = {}
self.historical_sessions = []
def init_agents(self, hub_id):
'''
Creates the first agent. All other agents created within the factory will be deep copies of this agent.
:param hub_id: hub id
:type hub_id: string
:return: None
'''
self.agents = {}
self.agents['Smith'] = DialogueAgent(agent_id='Smith', hub_id=hub_id) # primary agent, can be copied
def start_call(self, session_id, start_domain=None):
'''
Locates an agent to take this call and uses that agents start_call method.
:param session_id: session_id
:type session_id: string
:param start_domain: used by DialPort/external topictracking with DialogueServer to hand control to certain domain
:type start_domain: str
:return: start_call() function of agent object, string -- the selected agent, agent id
'''
agent_id = None
# 1. make sure session_id is not in use by any agent
if session_id in list(self.session2agent.keys()):
agent_id = self.session2agent[session_id]
logger.info('Attempted to start a call with a session_id %s already in use by agent_id %s .' % (session_id, agent_id))
# 2. check if there is an inactive agent
if agent_id is None:
for a_id in list(self.agents.keys()):
if self.agents[a_id].session_id is None:
agent_id = a_id
break
# 3. otherwise create a new agent for this call
if agent_id is None:
agent_id = self.new_agent()
else:
logger.info('Agent {} has been reactivated.'.format(agent_id))
# 4. record that this session is with this agent, and that it existed:
self.session2agent[session_id] = agent_id
self.historical_sessions.append(session_id)
# 5. start the call with this agent:
return self.agents[agent_id].start_call(session_id, start_domain=start_domain), agent_id
def continue_call(self, agent_id, asr_info, domainString=None):
'''
wrapper for continue_call for the specific Agent() instance identified by agent_id
:param agent_id: agent id
:type agent_id: string
:param asr_info: information fetched from the asr
:type asr_info: list
:param domainString: domain name
:type domainString: string
:return: string -- the system's response
'''
prompt_str = self.agents[agent_id].continue_call(asr_info, domainString)
return prompt_str
def end_call(self, agent_id=None, session_id=None, noTraining=False):
'''
Can pass session_id or agent_id as we use this in cases
1) normally ending a dialogue, (via agent_id)
2) cleaning a hung up call (via session_id)
:param agent_id: agent id
:type agent_id: string
:param session_id: session_id
:type session_id: string
:return: None
'''
# 1. find the agent if only given session_id
if agent_id is None: # implicitly assume session_id is given then
agent_id = self.retrieve_agent(session_id)
logger.info('Ending agents %s call' % agent_id)
# 2. remove session from active list
session_id = self.agents[agent_id].session_id
del self.session2agent[session_id]
# 3. end agents call
self.agents[agent_id].end_call(noTraining=noTraining)
# 4. can we also delete agent?
self.kill_agent(agent_id)
def agent2session(self, agent_id):
'''
Gets str describing session_id agent is currently on
:param agent_id: agent id
:type agent_id: string
:return: string -- the session id
'''
return self.agents[agent_id].session_id
def retrieve_agent(self, session_id):
'''
Returns str describing agent_id.
:param session_id: session_id
:type session_id: string
:return: string -- the agent id
'''
if session_id not in list(self.session2agent.keys()):
logger.error('Attempted to get an agent for unknown session %s' % session_id)
return self.session2agent[session_id]
def query_ENDING_DIALOG(self, agent_id):
'''
Wrapper for specific Agent.ENDING_DIALOG() -- with some basic initial checks.
:param agent_id: agent id
:type agent_id: string
:return: bool -- whether to end the dialogue or not
'''
if agent_id is None:
return False
if agent_id not in list(self.agents.keys()):
logger.error('Not an existing agent: '+str(agent_id))
return self.agents[agent_id].ENDING_DIALOG
def new_agent(self):
'''
Creates a new agent to handle some concurrency.
Here deepcopy is used to creat clean copy rather than referencing,
leaving it in a clean state to commence a new call.
:return: string -- the agent id
'''
agent_id = 'Smith' + str(len(self.agents))
# self.agents[agent_id] = copy.deepcopy(self.agents['Smith']) # alternative to copying is a new DialogueAgent() object
self.agents[agent_id] = DialogueAgent(agent_id)
self.agents[agent_id].restart_agent(session_id=None) # VERY IMPORTANT AFTER copying!!
logger.info('Agent {} has been created.'.format(agent_id))
return agent_id
def kill_agent(self, agent_id):
'''
Delete an agent if the total agent number is bigger than self.MAX_AGENTS_RUNNING.
:param agent_id: agent id
:type agent_id: string
:return: None
'''
if agent_id == 'Smith':
return # never kill our primary agent
agent_number = int(agent_id.strip('Smith'))
if agent_number > self.MAX_AGENTS_RUNNING:
del self.agents[agent_id]
# TODO - WHEN LEARNING IS INTRODUCED -- will need to save policy etc before killing
def power_down_factory(self):
'''
Finalise agents, print the evaluation summary and save the policy we close dialogue server.
:return: None
'''
for agent_id in list(self.agents.keys()):
logger.info('Summary of agent: %s' % agent_id)
self.agents[agent_id].evaluation_manager.print_summary()
self.agents[agent_id]._save_policy(FORCE_SAVE=True) #always save at end, can otherwise miss some dialogs by saving every 10
logger.info('Factory handled these sessions: %s' % self.historical_sessions)
class CallValidator(object):
'''
Used to validate calls, e.g., when using PyDial within user experiments.
Calls may be validated after a minimum of length in seconds or turns or if the system offers a venue. The flag isTrainable may be used to distinguish between dialogues whose formal conditions for validity are fulfilled
but who will introduce to much noise in the training process, e.g., if you allow for users to regularly abort the dialogue after 2 minutes but only want to use the dialogue for training if a minimum of 3 turns have
carried out.
'''
def __init__(self):
self.startTime = 0
self.turns = 0
self.isValid = False
self.mindialoguedurationprompt = "You cannot finish the dialogue yet, please try just a bit more." # Prompt when user says bye before miduration and without system having informed
self.mindialogueduration = 0 # Minimun duration length in seconds before giving token. Default is 0 (disabled)
self.mindialogueturns = 0 # Minimum number of turns before giving token. Default is 0 (disabled)
self.isTrainable = False
self.doValidityCheck = False
if Settings.config.has_option('agent', 'mindialoguedurationprompt'):
self.mindialoguedurationprompt = Settings.config.get('agent', 'mindialoguedurationprompt')
if Settings.config.has_option('agent', 'mindialogueturns'):
self.mindialogueturns = Settings.config.getint('agent', 'mindialogueturns')
if Settings.config.has_option('agent', 'mindialogueduration'):
self.mindialogueduration = Settings.config.getint('agent', 'mindialogueduration')
if self.mindialogueduration > 0 or self.mindialogueturns > 0:
self.doValidityCheck = True
def init(self):
self.startTime = time.time()
self.turns = 0
self.isValid = False
self.isTrainable = False
def validate(self, sys_act = None):
timePassed = time.time() - self.startTime
timeStatus = timePassed >= self.mindialogueduration
sysActStatus = False
if sys_act is not None:
self.turns += 1
sys_act_string = sys_act.to_string()
sysActStatus = 'bye' in sys_act_string or 'inform' in sys_act_string # if system says goodbye (eg if maxTurns reached) or sys provides one result (needs not to be the correct one)
turnStatus = self.turns >= self.mindialogueturns
if timeStatus:
if self.doValidityCheck:
logger.info("Call is valid due to time ({} sec passed).".format(timePassed))
self.isValid = True
self.isTrainable = True
if sysActStatus:
if self.doValidityCheck:
logger.info("Call is valid due to system act.")
self.isValid = True
self.isTrainable = True
if turnStatus:
if self.doValidityCheck:
logger.info("Call is valid due to number of turns ({} turns).".format(self.turns))
self.isValid = True
self.isTrainable = True
return self.isValid
def getNonValidPrompt(self):
return self.mindialoguedurationprompt
def check_if_user_bye(self,obs):
"""
Checks using a regular expression heuristic if the user said good bye. In accordance with C++ system, prob of respective n-best entry must be > 0.85.
"""
for ob in obs:
# ASR / Texthub input
if isinstance(ob, tuple):
#sentence,sentence_prob = ob[0],ob[1]
sentence,_ = ob[0],ob[1]
# simulated user input
elif isinstance(ob,DiaAct):
sentence = ob.act
elif isinstance(ob,str):
sentence,_ = ob, None
rBYE = "(\b|^|\ )(bye|goodbye|that'*s*\ (is\ )*all)(\s|$|\ |\.)"
if self._check(re.search(rBYE,sentence, re.I)):
# if sentence_prob > 0.85:
return True # one best input so prob is not relevant
return False
def _check(self,re_object):
"""
"""
if re_object is None:
return False
for o in re_object.groups():
if o is not None:
return True
return False
#END OF FILE
|
[
"vniekerk.carel@gmail.com"
] |
vniekerk.carel@gmail.com
|
9572d51080f3e0d4a2e4fd2c2797f68aad570234
|
54f352a242a8ad6ff5516703e91da61e08d9a9e6
|
/Source Codes/AtCoder/agc008/A/4477587.py
|
33c83b3d83148c59e95a3d44b657c2337fe85681
|
[] |
no_license
|
Kawser-nerd/CLCDSA
|
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
|
aee32551795763b54acb26856ab239370cac4e75
|
refs/heads/master
| 2022-02-09T11:08:56.588303
| 2022-01-26T18:53:40
| 2022-01-26T18:53:40
| 211,783,197
| 23
| 9
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 243
|
py
|
input_nums = [int(c) for c in input().split(" ")]
x = input_nums[0]
y = input_nums[1]
ad = 0
if x > y:
ad = 2
if (x < 0 and y > 0) or (x >= 0 and y <= 0):
ad = 1
if x == y:
ad = 0
x, y = abs(x), abs(y)
print(abs(x-y)+ad)
|
[
"kwnafi@yahoo.com"
] |
kwnafi@yahoo.com
|
62e35b9ebf411796b9dd999dcb02c0e95be91ff5
|
cb9bd4b6a5a395cd3437bb2ed068efafa8d61cd4
|
/pyxb_114/bundles/saml20/x500.py
|
bea7ecb1ea6bd32ffb46234f4cddbb87367f0275
|
[
"Apache-2.0"
] |
permissive
|
msherry/PyXB-1.1.4
|
bf4b137e51642f62afa898464c431c28386cbe99
|
08fba3ed97c3ecdfea260da0253d6e6718a2ce62
|
refs/heads/master
| 2021-03-12T20:26:08.120442
| 2013-09-18T01:33:06
| 2013-09-18T01:33:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 47
|
py
|
from pyxb_114.bundles.saml20.raw.x500 import *
|
[
"msherry@gmail.com"
] |
msherry@gmail.com
|
edb19e55cbbf04a11adcf045e2cf3a1d654039db
|
0a349f3c8348b48d3c3fb8a73508212437867e16
|
/SA-ThreatIntelligence/contrib/stix/utils/nsparser.py
|
e46cb35698d82c631cb956da287d0730109942c3
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
reza/es_eventgens
|
2c78a0cdb89b414e3a4f45d2b0c465696edd7695
|
70689c54d1a67e809bf134dd586b2ea05ff4c431
|
refs/heads/master
| 2021-06-15T00:41:31.564158
| 2017-02-11T04:13:44
| 2017-02-11T04:13:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,941
|
py
|
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import mixbox.namespaces
Namespace = mixbox.namespaces.Namespace
NS_CAMPAIGN_OBJECT = Namespace("http://stix.mitre.org/Campaign-1", "campaign", "http://stix.mitre.org/XMLSchema/campaign/1.2/campaign.xsd")
NS_CAPEC_OBJECT = Namespace("http://capec.mitre.org/capec-2", "capec", "")
NS_CIQIDENTITY_OBJECT = Namespace("http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1", "ciqIdentity", "http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.2/ciq_3.0_identity.xsd")
NS_COA_OBJECT = Namespace("http://stix.mitre.org/CourseOfAction-1", "coa", "http://stix.mitre.org/XMLSchema/course_of_action/1.2/course_of_action.xsd")
NS_CVRF_OBJECT = Namespace("http://www.icasi.org/CVRF/schema/cvrf/1.1", "cvrf", "")
NS_ET_OBJECT = Namespace("http://stix.mitre.org/ExploitTarget-1", "et", "http://stix.mitre.org/XMLSchema/exploit_target/1.2/exploit_target.xsd")
NS_GENERICSTRUCTUREDCOA_OBJECT = Namespace("http://stix.mitre.org/extensions/StructuredCOA#Generic-1", "genericStructuredCOA", "http://stix.mitre.org/XMLSchema/extensions/structured_coa/generic/1.2/generic_structured_coa.xsd")
NS_GENERICTM_OBJECT = Namespace("http://stix.mitre.org/extensions/TestMechanism#Generic-1", "genericTM", "http://stix.mitre.org/XMLSchema/extensions/test_mechanism/generic/1.2/generic_test_mechanism.xsd")
NS_INCIDENT_OBJECT = Namespace("http://stix.mitre.org/Incident-1", "incident", "http://stix.mitre.org/XMLSchema/incident/1.2/incident.xsd")
NS_INDICATOR_OBJECT = Namespace("http://stix.mitre.org/Indicator-2", "indicator", "http://stix.mitre.org/XMLSchema/indicator/2.2/indicator.xsd")
NS_IOC_OBJECT = Namespace("http://schemas.mandiant.com/2010/ioc", "ioc", "")
NS_IOCTR_OBJECT = Namespace("http://schemas.mandiant.com/2010/ioc/TR/", "ioc-tr", "")
NS_MARKING_OBJECT = Namespace("http://data-marking.mitre.org/Marking-1", "marking", "http://stix.mitre.org/XMLSchema/data_marking/1.2/data_marking.xsd")
NS_OVALDEF_OBJECT = Namespace("http://oval.mitre.org/XMLSchema/oval-definitions-5", "oval-def", "")
NS_OVALVAR_OBJECT = Namespace("http://oval.mitre.org/XMLSchema/oval-variables-5", "oval-var", "")
NS_REPORT_OBJECT = Namespace("http://stix.mitre.org/Report-1", "report", "http://stix.mitre.org/XMLSchema/report/1.0/report.xsd")
NS_SIMPLEMARKING_OBJECT = Namespace("http://data-marking.mitre.org/extensions/MarkingStructure#Simple-1", "simpleMarking", "http://stix.mitre.org/XMLSchema/extensions/marking/simple/1.2/simple_marking.xsd")
NS_SNORTTM_OBJECT = Namespace("http://stix.mitre.org/extensions/TestMechanism#Snort-1", "snortTM", "http://stix.mitre.org/XMLSchema/extensions/test_mechanism/snort/1.2/snort_test_mechanism.xsd")
NS_STIX_OBJECT = Namespace("http://stix.mitre.org/stix-1", "stix", "http://stix.mitre.org/XMLSchema/core/1.2/stix_core.xsd")
NS_STIXCAPEC_OBJECT = Namespace("http://stix.mitre.org/extensions/AP#CAPEC2.7-1", "stix-capec", "http://stix.mitre.org/XMLSchema/extensions/attack_pattern/capec_2.7/1.1/capec_2.7_attack_pattern.xsd")
NS_STIXCIQADDRESS_OBJECT = Namespace("http://stix.mitre.org/extensions/Address#CIQAddress3.0-1", "stix-ciqaddress", "http://stix.mitre.org/XMLSchema/extensions/address/ciq_3.0/1.2/ciq_3.0_address.xsd")
NS_STIXCVRF_OBJECT = Namespace("http://stix.mitre.org/extensions/Vulnerability#CVRF-1", "stix-cvrf", "http://stix.mitre.org/XMLSchema/extensions/vulnerability/cvrf_1.1/1.2/cvrf_1.1_vulnerability.xsd")
NS_STIXMAEC_OBJECT = Namespace("http://stix.mitre.org/extensions/Malware#MAEC4.1-1", "stix-maec", "http://stix.mitre.org/XMLSchema/extensions/malware/maec_4.1/1.1/maec_4.1_malware.xsd")
NS_STIXOPENIOC_OBJECT = Namespace("http://stix.mitre.org/extensions/TestMechanism#OpenIOC2010-1", "stix-openioc", "http://stix.mitre.org/XMLSchema/extensions/test_mechanism/open_ioc_2010/1.2/open_ioc_2010_test_mechanism.xsd")
NS_STIXOVAL_OBJECT = Namespace("http://stix.mitre.org/extensions/TestMechanism#OVAL5.10-1", "stix-oval", "http://stix.mitre.org/XMLSchema/extensions/test_mechanism/oval_5.10/1.2/oval_5.10_test_mechanism.xsd")
NS_STIXCOMMON_OBJECT = Namespace("http://stix.mitre.org/common-1", "stixCommon", "http://stix.mitre.org/XMLSchema/common/1.2/stix_common.xsd")
NS_STIXVOCABS_OBJECT = Namespace("http://stix.mitre.org/default_vocabularies-1", "stixVocabs", "http://stix.mitre.org/XMLSchema/default_vocabularies/1.2.0/stix_default_vocabularies.xsd")
NS_TA_OBJECT = Namespace("http://stix.mitre.org/ThreatActor-1", "ta", "http://stix.mitre.org/XMLSchema/threat_actor/1.2/threat_actor.xsd")
NS_TLPMARKING_OBJECT = Namespace("http://data-marking.mitre.org/extensions/MarkingStructure#TLP-1", "tlpMarking", "http://stix.mitre.org/XMLSchema/extensions/marking/tlp/1.2/tlp_marking.xsd")
NS_TOUMARKING_OBJECT = Namespace("http://data-marking.mitre.org/extensions/MarkingStructure#Terms_Of_Use-1", "TOUMarking", "http://stix.mitre.org/XMLSchema/extensions/marking/terms_of_use/1.1/terms_of_use_marking.xsd")
NS_TTP_OBJECT = Namespace("http://stix.mitre.org/TTP-1", "ttp", "http://stix.mitre.org/XMLSchema/ttp/1.2/ttp.xsd")
NS_XAL_OBJECT = Namespace("urn:oasis:names:tc:ciq:xal:3", "xal", "http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd")
NS_XNL_OBJECT = Namespace("urn:oasis:names:tc:ciq:xnl:3", "xnl", "http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd")
NS_XPIL_OBJECT = Namespace("urn:oasis:names:tc:ciq:xpil:3", "xpil", "http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd")
NS_YARATM_OBJECT = Namespace("http://stix.mitre.org/extensions/TestMechanism#YARA-1", "yaraTM", "http://stix.mitre.org/XMLSchema/extensions/test_mechanism/yara/1.2/yara_test_mechanism.xsd")
STIX_NAMESPACES = mixbox.namespaces.NamespaceSet()
# Magic to automatically register all Namespaces defined in this module.
for k, v in list(globals().items()):
if k.startswith('NS_'):
mixbox.namespaces.register_namespace(v)
STIX_NAMESPACES.add_namespace(v)
|
[
"dratcliffe75@gmail.com"
] |
dratcliffe75@gmail.com
|
20b54cc32aad3ffaa89957e1125c4fd5d224f5f1
|
9b5b1557d411e617605362a05b92c03b586dc51b
|
/project_name/settings.py
|
9fe2982480bf855a2cf7b85aa54c5785fd68ca8f
|
[] |
no_license
|
barseven/django-starter
|
91cc106f22cd1f74e8f607c00b9d8848dd0cecc1
|
950a32bf65f29f9106d26e999f5cd3beff78bd02
|
refs/heads/main
| 2023-03-03T21:40:58.312676
| 2021-02-13T23:39:54
| 2021-02-13T23:39:54
| 337,296,404
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,785
|
py
|
"""
Django settings for {{project_name}} project.
Generated by 'django-admin startproject' using Django 3.1.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '{{secret_key}}'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'accounts',
]
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 = '{{project_name}}.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 = '{{project_name}}.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_USER_MODEL = 'accounts.CustomUser'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
|
[
"bogdan.rogalski@gmail.com"
] |
bogdan.rogalski@gmail.com
|
b1d86e5c5160527d3b172eada1c3209629b45175
|
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
|
/indices/nnsmyth.py
|
b3a6be273349815fc12361bead6fd914e96835b8
|
[] |
no_license
|
psdh/WhatsintheVector
|
e8aabacc054a88b4cb25303548980af9a10c12a8
|
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
|
refs/heads/master
| 2021-01-25T10:34:22.651619
| 2015-09-23T11:54:06
| 2015-09-23T11:54:06
| 42,749,205
| 2
| 3
| null | 2015-09-23T11:54:07
| 2015-09-18T22:06:38
|
Python
|
UTF-8
|
Python
| false
| false
| 200
|
py
|
ii = [('PettTHE.py', 6), ('WilbRLW2.py', 4), ('ClarGE2.py', 3), ('LyelCPG.py', 9), ('DaltJMA.py', 7), ('WadeJEB.py', 1), ('BackGNE.py', 17), ('FitzRNS.py', 18), ('WilbRLW3.py', 10), ('BrewDTO.py', 1)]
|
[
"varunwachaspati@gmail.com"
] |
varunwachaspati@gmail.com
|
9c719a90de7b6677637c5c4acef4588235ff14fc
|
b55279f01cddc093875c258424b2648f22b4e19e
|
/euler1.py
|
5df32ed36f88b63eb3340e2d2cf9eb6ddb218083
|
[] |
no_license
|
charlotteel/go-leonhard
|
9291f4fef8cd110c7b73dfc635e02a64d3e20cc1
|
e5bb25e3b2d4111fb571af706e90e00203e2b947
|
refs/heads/master
| 2019-01-02T03:42:59.261068
| 2014-11-13T00:18:24
| 2014-11-13T00:18:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 201
|
py
|
def firsteuler(argu):
total = 0
for i in range(0,len(argu)):
if i % 3 == 0:
total = total + i
elif i % 5 == 0:
total = total + i
return total
list1 = range(0,1000)
print firsteuler(list1)
|
[
"shiningsilver@gmail.com"
] |
shiningsilver@gmail.com
|
d22e4d3127780f496ed99b92a7c7ae3020d5daf6
|
3437e4d6914e2a52bb0d94ffb1f622cf15d809b3
|
/venv/Scripts/easy_install-3.7-script.py
|
6919baa32ad939eeb53bdb09d1de88aa6687ce95
|
[] |
no_license
|
gaswita/PY_Project1
|
78cdcd5029a890472a06f8ad06917bf5882c2e94
|
e6143ccb78c569a3c380cf85af45c85d1519be07
|
refs/heads/master
| 2022-09-29T09:04:06.484426
| 2020-06-08T08:19:48
| 2020-06-08T08:19:48
| 270,583,542
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 462
|
py
|
#!C:\Users\TEST23\PycharmProjects\PY_Project\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.7')()
)
|
[
"g_aswita@connect.ite.edu.sg"
] |
g_aswita@connect.ite.edu.sg
|
ba3fc925d09eb53f83eff481d3cd355c60072ad2
|
2b16db46fe37d0443ecd3cf697e57b19fe101117
|
/python/finite_differences/derivatives_for_example_functions_plot.py
|
6511f513f3cad9f10fd5bea628dd669b431225ad
|
[] |
no_license
|
anneaux/wave-equations
|
f53b32d94109eb05a9ff863472a2886e0143d0a3
|
af6b57feab0f024aeab290b41291a3a2c9ff0f67
|
refs/heads/master
| 2023-03-28T04:29:35.358688
| 2021-03-24T12:04:08
| 2021-03-24T12:04:08
| 302,150,146
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,216
|
py
|
import numpy as np
import matplotlib.pyplot as plt
import finite_differences_o2 as dvo2
import finite_differences_o4 as dvo4
import example_functions as ex
#####################################################
#list of functions
func = ex.func
#list of 1st analyitcal function derivatives
func_1st_deriv = ex.func_1st_deriv
#list of 2nd analyitcal function derivatives
func_2nd_deriv = ex.func_2nd_deriv
#list of functions tex strings
tex_f = ex.tex_f
############ set grid ###############################
n=20 #grid points
h=1/n #grid spacing
x = np.linspace(0,1,n)
#function selection, input options = 0, 1, 2, 3, 4, 5(for g_a)
ex.a =1
fs = 5
############ calculating ##########################
y = func[fs](x)
y_prime = func_1st_deriv[fs](x)
y_prime_prime = func_2nd_deriv[fs](x)
dydx = dvo2.derivative_1_c(func[fs],x,h=h) #calculate 1st derivative
dy2dx2 = dvo2.derivative_2_c(func[fs],x,h=h) #calculate 2nd derivative
print(dydx)
Delta_1 = y_prime - dydx #analytical-difference 1st order
Delta_2 = y_prime_prime - dy2dx2 #analytical-difference 2nd order
################ plots ###################
#plt.rc('text', usetex=True)
fig, (ax1, ax2) = plt.subplots(2,figsize=(10, 9))
ax1.set_ylabel('')
#ax1.set_xlabel('x',loc='center')
ax1.plot(x,y,label='$f_%d(x)$' %(fs+1))
ax1.plot(x,y_prime,linestyle='dashed',
label="Analytical 1st Derivative $f_%d^{(1)}(x)$" %(fs+1))
ax1.plot(x,dydx,marker = 'o',linestyle='dotted',
label="Central 1st Difference $D^1_h f_%d(x)$" %(fs+1))
ax1.plot(x,y_prime_prime, linestyle='dashed',
label="Analytical 2nd Derivative $f_%d^{(2)}(x)$" %(fs+1))
ax1.plot(x,dy2dx2,marker = 'o',linestyle='dotted',
label="Central 2nd Difference $D^2_h f_%d(x)$" %(fs+1))
ax1.set_title('function and derivatives for ' '%s' %(tex_f[fs]))
ax1.legend( title='grid size n=%d' % (n) )
ax1.grid(color = 'gainsboro')
ax2.set_ylabel('analytical - finite difference stencil')
ax2.set_xlabel('x',loc='center')
ax2.plot(x,Delta_1,marker = 'o', color = 'cyan', label=' 1st order')
ax2.plot(x,Delta_2, marker = 'o', color= 'hotpink', label=' 2nd order')
ax2.set_title('derivative difference')
ax2.legend()
ax2.grid(color = 'gainsboro')
plt.show()
|
[
"49444603+johanickl@users.noreply.github.com"
] |
49444603+johanickl@users.noreply.github.com
|
f731452c06bfcefbcd45b679f57e87a08798d960
|
d90ceef091c722fde61b3f98d566a933d72ecf9c
|
/app/users/__init__.py
|
4673b3d50bcd442a734fb3063486ee595a10bf1c
|
[] |
no_license
|
alexiuasse/Gerenciamento-de-Salao-Beleza
|
3ff4a5dd9f49c7658d6e9f255bb9fde9b024bd66
|
3c05021adc01bc8ed0fe5f9be70b0bcd222eb349
|
refs/heads/master
| 2023-06-15T06:44:46.730926
| 2021-07-15T23:38:35
| 2021-07-15T23:38:35
| 288,178,307
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 160
|
py
|
# Created by Alex Matos Iuasse.
# Copyright (c) 2020. All rights reserved.
# Last modified 04/09/2020 11:47.
default_app_config = 'users.apps.UsersConfig'
|
[
"alexiuasse@gmail.com"
] |
alexiuasse@gmail.com
|
c38a8272425c61418ee2fb3a36725e300dafa0b5
|
7944c3824451551185c8d8fc305cb51628e0d2e2
|
/src/models/encoder.py
|
bb6ebbff9ff05de6323c4012a3789691be28b165
|
[
"MIT"
] |
permissive
|
convergence-lab/SPADE-PyTorch
|
a4ef4aeaad00f8e482746903be2f8ef480bb71dd
|
75c420d1b38f94a5fec7cdcb41f6cc3b45f7a19e
|
refs/heads/master
| 2020-09-11T08:17:38.852276
| 2019-11-17T04:15:38
| 2019-11-17T04:15:38
| 222,002,773
| 0
| 0
| null | 2019-11-15T21:03:29
| 2019-11-15T21:03:29
| null |
UTF-8
|
Python
| false
| false
| 1,058
|
py
|
import torch
import torch.nn as nn
def conv_inst_lrelu(in_chan, out_chan):
return nn.Sequential(
nn.Conv2d(in_chan, out_chan, kernel_size=(3,3), stride=2, bias=False, padding=1),
nn.InstanceNorm2d(out_chan),
nn.LeakyReLU(inplace=True)
)
class SPADEEncoder(nn.Module):
def __init__(self, args):
super().__init__()
self.layer1 = conv_inst_lrelu(3, 64)
self.layer2 = conv_inst_lrelu(64, 128)
self.layer3 = conv_inst_lrelu(128, 256)
self.layer4 = conv_inst_lrelu(256, 512)
self.layer5 = conv_inst_lrelu(512, 512)
self.layer6 = conv_inst_lrelu(512, 512)
self.linear_mean = nn.Linear(8192, args.gen_input_size)
self.linear_var = nn.Linear(8192, args.gen_input_size)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.layer5(x)
x = self.layer6(x)
x = x.view(x.size(0), -1)
return self.linear_mean(x), self.linear_var(x)
|
[
"kushajreal@gmail.com"
] |
kushajreal@gmail.com
|
3251353b6b34f6003b4888b65db65ef1b661c47e
|
7f858765cdd6226c1870bf09a956c18c81ae1417
|
/work/migrations/0056_auto_20191205_1554.py
|
8d4a54bce8b3535b4148a09b0daf399e84ebbcc8
|
[] |
no_license
|
webclinic017/saubhagya
|
719d7a491b1910780973a8aecebaf51558d39df9
|
b78b4c4313e2035322e7d0eea03e71a1144ea262
|
refs/heads/master
| 2023-06-27T06:01:16.513161
| 2021-07-31T08:31:38
| 2021-07-31T08:31:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 681
|
py
|
# Generated by Django 2.2.6 on 2019-12-05 15:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0055_auto_20191205_1551'),
]
operations = [
migrations.AddField(
model_name='progressqty',
name='review',
field=models.CharField(blank=True, choices=[('ok', 'ok'), ('issue', 'issue')], max_length=50, null=True),
),
migrations.AddField(
model_name='progressqtyextra',
name='review',
field=models.CharField(blank=True, choices=[('ok', 'ok'), ('issue', 'issue')], max_length=50, null=True),
),
]
|
[
"rons.ubm@gmail.com"
] |
rons.ubm@gmail.com
|
b2174447b7dd28ccb2cc2533decb14032eddebc3
|
df1e2fda7568d2d17005839f2c3b789564ba0266
|
/strategy.py
|
0d594fd6c8db52cb07d24a24692695ebf21db5eb
|
[] |
no_license
|
ElliotVilhelm/Binance-Trading-Bot
|
b679da335bf2c234825566558c86e2a40582dc3f
|
79940733dec12a9e9dd59c77eba47029900527a9
|
refs/heads/master
| 2020-04-04T18:54:05.421988
| 2019-01-27T06:49:12
| 2019-01-27T06:49:12
| 156,184,338
| 15
| 10
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,995
|
py
|
from binance.enums import *
from utils import float_to_str
from math import ceil
import logging
logging.basicConfig(filename='output.log', level=logging.INFO)
from trade import Trade
class MovingAverage:
def __init__(self, bot, trade_coin, backtest=False):
self.bot = bot
self.sell_gamma = 1.0
self.buy_gamma = 1.0
self.long_exit_gamma = 1.0
self.short_exit_gamma = 1.0
self.two_step_buy = 0
self.two_step_sell = 0
self.prices = []
self.moving_avg_length = 100
self.quantity = 10
self.orders = 0
self.trade_placed = False
self.trade_type = False
self.order = False
self.trade_coin = trade_coin
self.trades = []
self.backtest = backtest
def moving_avg(self, ask_price=None, last_price=None, base_coin_balance=0, trade_coin_balance=0):
if not self.backtest:
ticker = self.bot.client.get_ticker(symbol=self.trade_coin + self.bot.base_coin)
ask_price = float(ticker['askPrice'])
last_price = float(ticker['lastPrice'])
trade_coin_balance = float(self.bot.client.get_asset_balance(asset=self.trade_coin)['free'])
base_coin_balance = float(self.bot.client.get_asset_balance(asset=self.bot.base_coin)['free'])
bid_price = ticker['bidPrice']
min_quantity = ceil(.001 / float(ticker['bidPrice']))
else:
# bid_price = (ask_price + last_price) / 2
bid_price = ask_price
min_quantity = ceil(.001 / bid_price)
trade = None
self.prices.append(ask_price)
active_avg = sum(self.prices) / len(self.prices)
# print(f"ask: {ask_price} last: {last_price}")
# print("*"*50)
# print("Trade Placed: ", self.trade_placed)
# print(f"sell criteria:\n"
# f"ask_price/active_avg: {ask_price/active_avg} > 1.0?\n"
# f"ask_price/last_price: {ask_price/last_price} < 1.0?")
# print("*"*50)
# print(f"buy criteria:\n"
# f"ask_price/active_avg: {ask_price/active_avg} < 1.0?\n"
# f"ask_price/last_price: {ask_price/last_price} > 1.0?")
# print("*"*50)
if not self.trade_placed:
# SELL
if ask_price/active_avg > self.sell_gamma and ask_price/last_price < self.sell_gamma:
logging.info(f"min quant sell: {min_quantity} coin: {self.trade_coin}")
if trade_coin_balance > min_quantity:
if not self.backtest:
self.order = self.bot.client.create_order(
symbol=self.trade_coin + self.bot.base_coin,
side=SIDE_SELL,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=min_quantity,
price=bid_price)
trade = Trade(bid_price, min_quantity, "short", self.trade_coin + self.bot.base_coin)
# print("sell -> bid price * min_quantity", bid_price * min_quantity)
base_coin_balance += float(bid_price) * min_quantity
trade_coin_balance -= min_quantity
self.trades.append(trade)
if not self.backtest:
logging.info(f"SELL {self.trade_coin} PRICE: {ticker['bidPrice']} QUANTITY: {min_quantity}")
self.trade_placed = True
self.trade_type = 'short'
# BUY
elif ask_price/active_avg < self.buy_gamma and ask_price/last_price > self.buy_gamma:
min_quantity = ceil(.001 / float(ask_price))
self.two_step_buy += 1
if base_coin_balance > min_quantity * ask_price and self.two_step_buy >= 2:
if not self.backtest:
self.order = self.bot.client.create_order(
symbol=self.trade_coin + self.bot.base_coin,
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=min_quantity,
price=ticker['askPrice'])
base_coin_balance -= float(bid_price) * min_quantity
trade_coin_balance += min_quantity # trade coin balance in BTC
trade = Trade(bid_price, min_quantity, "long", self.trade_coin + self.bot.base_coin)
# print("buy -> bid price * min_quantity", bid_price * min_quantity)
self.trades.append(trade)
if not self.backtest:
logging.info(f"BUY {self.trade_coin} PRICE: {ticker['askPrice']} QUANTITY: {min_quantity}")
self.two_step_buy = 0
self.trade_placed = True
self.trade_type = 'long'
elif self.trade_type == "short":
if ask_price/active_avg < self.short_exit_gamma:
logging.info(f"Exit Trade {self.trade_coin}")
# print("Exit Short Trade")
if self.trade_placed:
try:
self.bot.client.cancel_order(symbol=self.trade_coin + self.bot.base_coin, orderId=self.order)
self.trade_placed = False
self.trade_type = False
except:
pass
if self.backtest:
# pass
self.trade_placed = False
self.trade_type = False
elif self.trade_type == 'long':
if ask_price/active_avg > self.long_exit_gamma:
# print("Exit Long Trade")
logging.info(f"Exit Trade {self.trade_coin}")
if self.trade_placed and not self.backtest:
try:
self.bot.client.cancel_order(symbol=self.trade_coin + self.bot.base_coin, orderId=self.order)
self.trade_placed = False
self.trade_type = False
except:
pass
if self.backtest:
# pass
self.trade_placed = False
self.trade_type = False
self.prices = self.prices[-self.moving_avg_length:]
logging.info(f"Ticker: {self.trade_coin + self.bot.base_coin} Moving Average: {float_to_str(active_avg)} Ask Price: {float_to_str(ask_price)} Last Price: {float_to_str(last_price)}")
return trade, base_coin_balance, trade_coin_balance
# holding 50.0 btc
# exchange rate .1 btc for 1 xrp
# btc: $5,000
# xrp: $200
# btc: 1
# xrp: 10
# BUY 1 xrp at .1
# btc: .9
# xrp: 1
# exchange rate .2 btc for 1 xrp
# 1 XRP -> .000088266 BTC
# amount of XRP in BTC = exchange * quantity
|
[
"elliot@pourmand.com"
] |
elliot@pourmand.com
|
385bd65062e64638ba3c4ea483d9cdbe5105c17e
|
34acedc935b3632c0119e37117c92a9bd514f8c9
|
/Robot/locators/extractors/cube/green_cube_extractor.py
|
294a9b0b1876564ac12c881f56d379b1084c95c7
|
[] |
no_license
|
jsbed/Design-III-Robot
|
ec4f9408a0a5298bcc73d3d82bf4ff6442024a0f
|
10e79954a3725efd4120ad14ad6c07191f2ff9fa
|
refs/heads/master
| 2021-05-28T13:34:05.313169
| 2015-04-15T08:04:27
| 2015-04-15T08:04:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 610
|
py
|
from Robot.configuration.config import Config
from Robot.locators.extractors.cube.cube_extractor import CubeExtractor
from Robot.locators.segmentation.cube.cube_segmentation import CubeSegmentor
class GreenCubeExtractor(CubeExtractor):
def __init__(self):
self._cube_segmentor = CubeSegmentor()
self._cube_segmentor.set_lower_hsv_values(
Config().get_cube_low_green_hsv_values())
self._cube_segmentor.set_upper_hsv_values(
Config().get_cube_high_green_hsv_values())
def extract_cube(self, img):
return self._cube_segmentor.segment_cube(img)
|
[
"bedardjs97@hotmail.com"
] |
bedardjs97@hotmail.com
|
83eaaf89ba18f0580d739c36b0ae58707cbe0ddd
|
a052aeb9db57d38509134dc38c156d5fc9ec974d
|
/venv/Scripts/easy_install-3.6-script.py
|
733a761791c22d71142d7b89956db78b29289228
|
[] |
no_license
|
qMotillon/projetSwann
|
60bea0cfd8a0baa9aee9f09a387502b07ec6b83a
|
0f1f9ac37c373c3f29b90e8323d122a4a058ce8b
|
refs/heads/master
| 2020-03-22T06:25:52.776515
| 2018-07-15T14:26:35
| 2018-07-15T14:26:35
| 139,633,340
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 468
|
py
|
#!E:\Users\Gildarytzs\Documents\GitHub\projetSwann\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.6')()
)
|
[
"memepasenreve@hotmail.fr"
] |
memepasenreve@hotmail.fr
|
b0cf348572d22f252e08c8818ed4bd80e799b148
|
2ba9529053985a47164e617d759e8d4ba6c16df3
|
/homeassistant/components/screenlogic/climate.py
|
d289c00228c5e19b7fd6ac73a96d0589b00e0b3c
|
[
"Apache-2.0"
] |
permissive
|
UJStudio/core
|
44dee82f8fa0c2699c4c9c87db0299beac71099c
|
6023105c6a3b69ffb2338c494246802c086aaee4
|
refs/heads/dev
| 2023-03-30T15:41:16.794294
| 2021-03-29T11:06:44
| 2021-03-29T11:06:44
| 285,370,318
| 0
| 0
|
Apache-2.0
| 2020-10-28T20:05:10
| 2020-08-05T18:18:24
|
Python
|
UTF-8
|
Python
| false
| false
| 7,184
|
py
|
"""Support for a ScreenLogic heating device."""
import logging
from screenlogicpy.const import EQUIPMENT, HEAT_MODE
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_PRESET_MODE,
CURRENT_HVAC_HEAT,
CURRENT_HVAC_IDLE,
CURRENT_HVAC_OFF,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.restore_state import RestoreEntity
from . import ScreenlogicEntity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SUPPORTED_FEATURES = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
SUPPORTED_MODES = [HVAC_MODE_OFF, HVAC_MODE_HEAT]
SUPPORTED_PRESETS = [
HEAT_MODE.SOLAR,
HEAT_MODE.SOLAR_PREFERRED,
HEAT_MODE.HEATER,
]
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up entry."""
entities = []
data = hass.data[DOMAIN][config_entry.entry_id]
coordinator = data["coordinator"]
for body in data["devices"]["body"]:
entities.append(ScreenLogicClimate(coordinator, body))
async_add_entities(entities)
class ScreenLogicClimate(ScreenlogicEntity, ClimateEntity, RestoreEntity):
"""Represents a ScreenLogic climate entity."""
def __init__(self, coordinator, body):
"""Initialize a ScreenLogic climate entity."""
super().__init__(coordinator, body)
self._configured_heat_modes = []
# Is solar listed as available equipment?
if self.coordinator.data["config"]["equipment_flags"] & EQUIPMENT.FLAG_SOLAR:
self._configured_heat_modes.extend(
[HEAT_MODE.SOLAR, HEAT_MODE.SOLAR_PREFERRED]
)
self._configured_heat_modes.append(HEAT_MODE.HEATER)
self._last_preset = None
@property
def name(self) -> str:
"""Name of the heater."""
ent_name = self.body["heat_status"]["name"]
return f"{self.gateway_name} {ent_name}"
@property
def min_temp(self) -> float:
"""Minimum allowed temperature."""
return self.body["min_set_point"]["value"]
@property
def max_temp(self) -> float:
"""Maximum allowed temperature."""
return self.body["max_set_point"]["value"]
@property
def current_temperature(self) -> float:
"""Return water temperature."""
return self.body["last_temperature"]["value"]
@property
def target_temperature(self) -> float:
"""Target temperature."""
return self.body["heat_set_point"]["value"]
@property
def temperature_unit(self) -> str:
"""Return the unit of measurement."""
if self.config_data["is_celcius"]["value"] == 1:
return TEMP_CELSIUS
return TEMP_FAHRENHEIT
@property
def hvac_mode(self) -> str:
"""Return the current hvac mode."""
if self.body["heat_mode"]["value"] > 0:
return HVAC_MODE_HEAT
return HVAC_MODE_OFF
@property
def hvac_modes(self):
"""Return th supported hvac modes."""
return SUPPORTED_MODES
@property
def hvac_action(self) -> str:
"""Return the current action of the heater."""
if self.body["heat_status"]["value"] > 0:
return CURRENT_HVAC_HEAT
if self.hvac_mode == HVAC_MODE_HEAT:
return CURRENT_HVAC_IDLE
return CURRENT_HVAC_OFF
@property
def preset_mode(self) -> str:
"""Return current/last preset mode."""
if self.hvac_mode == HVAC_MODE_OFF:
return HEAT_MODE.NAME_FOR_NUM[self._last_preset]
return HEAT_MODE.NAME_FOR_NUM[self.body["heat_mode"]["value"]]
@property
def preset_modes(self):
"""All available presets."""
return [
HEAT_MODE.NAME_FOR_NUM[mode_num] for mode_num in self._configured_heat_modes
]
@property
def supported_features(self):
"""Supported features of the heater."""
return SUPPORTED_FEATURES
async def async_set_temperature(self, **kwargs) -> None:
"""Change the setpoint of the heater."""
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
raise ValueError(f"Expected attribute {ATTR_TEMPERATURE}")
if await self.hass.async_add_executor_job(
self.gateway.set_heat_temp, int(self._data_key), int(temperature)
):
await self.coordinator.async_request_refresh()
else:
raise HomeAssistantError(
f"Failed to set_temperature {temperature} on body {self.body['body_type']['value']}"
)
async def async_set_hvac_mode(self, hvac_mode) -> None:
"""Set the operation mode."""
if hvac_mode == HVAC_MODE_OFF:
mode = HEAT_MODE.OFF
else:
mode = HEAT_MODE.NUM_FOR_NAME[self.preset_mode]
if await self.hass.async_add_executor_job(
self.gateway.set_heat_mode, int(self._data_key), int(mode)
):
await self.coordinator.async_request_refresh()
else:
raise HomeAssistantError(
f"Failed to set_hvac_mode {mode} on body {self.body['body_type']['value']}"
)
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode."""
_LOGGER.debug("Setting last_preset to %s", HEAT_MODE.NUM_FOR_NAME[preset_mode])
self._last_preset = mode = HEAT_MODE.NUM_FOR_NAME[preset_mode]
if self.hvac_mode == HVAC_MODE_OFF:
return
if await self.hass.async_add_executor_job(
self.gateway.set_heat_mode, int(self._data_key), int(mode)
):
await self.coordinator.async_request_refresh()
else:
raise HomeAssistantError(
f"Failed to set_preset_mode {mode} on body {self.body['body_type']['value']}"
)
async def async_added_to_hass(self):
"""Run when entity is about to be added."""
await super().async_added_to_hass()
_LOGGER.debug("Startup last preset is %s", self._last_preset)
if self._last_preset is not None:
return
prev_state = await self.async_get_last_state()
if (
prev_state is not None
and prev_state.attributes.get(ATTR_PRESET_MODE) is not None
):
_LOGGER.debug(
"Startup setting last_preset to %s from prev_state",
HEAT_MODE.NUM_FOR_NAME[prev_state.attributes.get(ATTR_PRESET_MODE)],
)
self._last_preset = HEAT_MODE.NUM_FOR_NAME[
prev_state.attributes.get(ATTR_PRESET_MODE)
]
else:
_LOGGER.debug(
"Startup setting last_preset to default (%s)",
self._configured_heat_modes[0],
)
self._last_preset = self._configured_heat_modes[0]
@property
def body(self):
"""Shortcut to access body data."""
return self.coordinator.data["bodies"][self._data_key]
|
[
"noreply@github.com"
] |
UJStudio.noreply@github.com
|
4668ecf294a0f848de49878d360092d258fe0a7e
|
aa1bb860e8697d56efab402c6226fc81074dc4a4
|
/Entradanumeros.py
|
de47027e347c137bfbb0f4475f0c7de1065d63f5
|
[] |
no_license
|
Jogas12/PR-CTICAS-PYTH-N
|
10124085cde2d164bac04e8081e0e6fe430215bb
|
a22f1d41d6e76c009cc1a7f8682e01eeceb5ee76
|
refs/heads/master
| 2020-04-28T13:22:33.760425
| 2019-03-20T00:05:07
| 2019-03-20T00:05:07
| 175,304,973
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 353
|
py
|
número1= int(input("ingresar un numero: ")) #int nos sirve para válidar números enteros, ya que sino lo tomaria como texto al número
número2= int(input("ingresar un numero: ")) #El int al principio nos dice que el número que vamos a ingresar va ser un núnero y no un texto
resultado = número1 + número2
print (f"El resultado es: {resultado}")
|
[
"gasparcaamal12@gmail.com"
] |
gasparcaamal12@gmail.com
|
e205bab1677ba2e57dcff13bd8fa5eaf732db0ad
|
ee3cd3addb1c48622ed171feaa25b3363ad1a521
|
/Sablenkbot.py
|
1d754353577058880852ad981369c6e15ceadadd
|
[] |
no_license
|
teguhstya37/GINGSULSABLENK
|
89e49e698a6144cd7a0e3a3c0a2d3d1349f7c327
|
7c9eb5424320fe9e70a80af6afb2481566c361e5
|
refs/heads/master
| 2020-04-04T19:13:17.029403
| 2018-11-05T10:23:14
| 2018-11-05T10:23:14
| 156,196,938
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 219,528
|
py
|
#Eww -*- coding: utf-8 -*-
import LINETCR
import requests
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
from bs4 import BeautifulSoup
#import time,random,sys,json,codecs,threading,glob,urllib,urllib2
import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,subprocess
cl = LINETCR.LINE()
#cl.login(token="EyW8mMdmmgnYBHQdlmp0.9q2iIcfJltjghJCvoSD1Wa.uWZ+XbAkBO6TPSHaAgpkfWnsGt7sE54yCUc74sXW5Ow=")
cl.login(token="Eyz1kwi73BRZcoFVBEK0.9q2iIcfJltjghJCvoSD1Wa.zCNFiVh6PIUqTDW5kGR3ZAhdRHOGDIEmRpmpD3uC/uQ=")
cl.loginResult()
ki = LINETCR.LINE()
#ki.login(token="Eyfg6QGFHBFUFC8ZtkZ5.BAbZE0umy2dUOSbpoBpzPq.lXD2kRtVC24dED2mukQS8SWJq69jiPdbdSwYttfrEQg=")
ki.login(token="Ey5zEYs1k42GfcgwuFW5.BAbZE0umy2dUOSbpoBpzPq.aFuBDRob29mHEyqomrfwZhECZCgV1I7at4jtu9+5C2M=")
ki.loginResult()
kk = LINETCR.LINE()
#kk.login(token="Ey870DEVeRttxWG0kULc.YCFgbMZPhmkVN+eVj380ta.iJVSxeD+bc4PA1LUDs7vsCeCDLPRUCzX4+9TVC4HQfE=")
kk.login(token="EyBieZ7K3xdyXDgP8hDc.z4y1C6W70neuRJnWGivNZa.iQid3lx838b4OOb33QkRqEARrg/vj1YSPB+Xuz71pao=")
kk.loginResult()
kc = LINETCR.LINE()
#kc.login(token="EyAO2wLu8PnLKEIxWZQf.jcKRHQZO/ZUdXspu91JKJW.qIV6DwN1HjPrUW6pq0JghQDflEV0c/mlCsPIn3SG/zM=")
kc.login(token="EyJEERgQG8sj1AQbPd8f.jcKRHQZO/ZUdXspu91JKJW.94iJHWkW8o79IeHE1pnXbIE87UmVnQmQntfvKxboSSg=")
kc.loginResult()
kb = LINETCR.LINE()
#kb.login(token="EyCivT3oBbQGe4azowY2.a3wwcrKoF7GSYZK8iLIneG.P2ZAwWDZRfny1TV8lUIguyLE+N19zD7Fb6KPLEv/H3w=")
kb.login(token="EyPqBkFf4G4FsNhNrpv2.a3wwcrKoF7GSYZK8iLIneG.ydIzh4POaZqf5fHxgiJyLmfs3QL6IcW7RShb6BaTL44=")
kb.loginResult()
kd = LINETCR.LINE()
#kd.login(token="EyHnUCm4FRj6OhuMDFpc.lRANtBt0XNe7AUiARUwHRa.KjwS09ZHV20cUlfGjeQEDjdt6fANy5XL7lrj0gUj/uY=")
kd.login(token="Ey3we54LwAJJzj05l65c.lRANtBt0XNe7AUiARUwHRa.n7ksQ75kI0dhkcB53lZvK6tJZn2uvS4YxlcHCIjKuIs=")
kd.loginResult()
sw = LINETCR.LINE()
#sw.login(token="
sw.login(token="EyBVx2zRkqE7nEjFjwH9.pzD1VRZEG6ip2fZxru4LIq.OcZpWnlyFqGd5a7KQwd7R2X1ZZPWj1YiCGrg+XuSrUA=")
sw.loginResult()
print u"login success"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""
~🔰👻SABLENK BOTS👻🔰~~~
👻🔰SABLENK BOTS TEAM🔰👻
╔══════════════
╠ 🔰👻✮Ginfo
╠ 🔰👻✮Botcancel
╠ 🔰👻✮Say「Text」
╠ 🔰👻✮ Gn:「Name GC
╠ 🔰👻✮Mymid「mid me」
╠ 🔰👻✮Welcome on
╠ 🔰👻✮Welcome off
╠ 🔰👻✮ Lurkers
| 🔰👻Mybot
╠ 🔰👻✮View
╠ 🔰👻✮Creator
╚═════════════
🔰👻SABLENK BOTS👻🔰
╔═════════════
╠ 🔰👻Ghost absen
╠ 🔰👻Say 「Text」
╠ 🔰👻@. /buat masukin bot
╠ 🔰👻@, /buat kluarin bot
╠ 🔰👻Sablebk copy 「@」
╠ 🔰👻Sablenk kembali 「@」
╠ 🔰👻Sablenk kick「Mid」
╠ 🔰👻Sablebk invite「Mid」
╠ 🔰👻Ghost setting 「View」
╠ 🔰👻Sablenk bot 「Cek bots」
╠ 🔰👻S cancel「Cancel pending」
╠ 🔰👻S link 「on / off」
╠ 🔰👻S bir 「Buat ratain group
╠ 🔰👻Clearall 「Cleanse group」
╠ 🔰👻Sb 「BL all member」
╠ 🔰👻Sd「Unban all member」
╠ 🔰👻Ginfo 「View group info」
╠ 🔰👻Gcreator 「Melihat pembuat」
╠ 🔰👻All mid 「Melihat mid bot」
╠ 🔰👻Mymid 「mid sndiri」
╠ 🔰👻Gift 「Gift1,Gift2,Gift3」
╠ 🔰👻Spam「on / off」1\ Text
╠ 🔰👻Creator 「Cek pembuat bot」
╠ 🔰👻Gurl 「View group link」
╠ 🔰👻Mentions 「Tag all member」
╠ 🔰👻All: 「Rename all bot」
╠ 🔰👻Allbio: 「Change all bio bot」
╠ 🔰👻Mid 「@」
╠ 🔰👻Bc: 「Text」
╠ 🔰👻Admin on/off 「@」
╠ 🔰👻 List admin
╠ 🔰👻Spam to 「@」
╠ 🔰👻 Speed
╠ 🔰👻Respon
╠ 🔰👻Lurkers
╠ 🔰👻View
╠ 🔰👻Fuck
╠ 🔰👻Sayang「@」
╠ 🔰👻Mk「@」
╠ 🔰👻Nk 「@」
╠ 🔰👻Ban 「@」
╠ 🔰👻Unban「@」
╠ 🔰👻Ciakk 「@」
╠ 🔰👻Ban:on「Send contact」
╠ 🔰👻Unban:on「Send Contact」
╠ 🔰👻Banlist
╠ 🔰👻Kick ban
╠ 🔰👻╬═Mimic on/off
╠ 🔰👻╬═Mimic:add 「@」
╠ 🔰👻╬═Mimic:del 「@」
╠ 🔰👻╬═Reject「Cancel undangn]
╠ 🔰👻╬═InviteMeTo:[group id]
╠ 🔰👻╬═Invite [invite mmber]
╠ 🔰👻╬═TD leaveAllGc
╠ 🔰👻╬═Music[jaran goyang]
╠ 🔰👻╬═S:Bc [Bc taks all]
╚════════════
❧🔰👻SABLENK BOTS👻🔰 ❧
╚════════════
🔰👻SABLENK👻🔰
penting...!!!: SALAM SANTUN
SABLENK BOTS
╚════════════"""
helpMessage1 =""" *** Set Group ***
╔════════════
╠🔐 Auto cancel「on / off」
╠🔐 Contact 「on / off」
╠🔐 Allprotect 「on / off」
╠🔐 Auto like 「on / off」
╠🔐 Auto leave 「on / off」
╠🔐 Backup 「on / off」
╠🔐 Welcome 「on / off」
╚════════════
*** Set Group ***"""
KAC=[cl,ki,kk,kc,kb,kd,sw]
mid = cl.getProfile().mid
Amid = ki.getProfile().mid
Bmid = kk.getProfile().mid
Cmid = kc.getProfile().mid
Dmid = kb.getProfile().mid
Emid = kd.getProfile().mid
Lmid = sw.getProfile().mid
Bots = [mid,Amid,Bmid,Cmid,Dmid,Emid,Lmid]
admin = ["uf50d888821632d32461e37153ac775c0"]
staff = ["uf50d888821632d32461e37153ac775c0"]
owner = ["uf50d888821632d32461e37153ac775c0"]
adminMID = 'uf50d888821632d32461e37153ac775c0'
wait ={
'contact':False,
'autoJoin':True,
'autoCancel':{"on":True,"members":1},
'leaveRoom':False,
'timeline':False,
'autoAdd':False,
'message':"Thanks for add Created by Bank ger",
"lang":"JP",
"comment":" TEAM SABLENK BOTS•\n\nsKilers:\n[☆] BANK GER [☆]\n[✯] thē_sablenk-bots\nhttps://line.me.ti/p~gerhanaselatan",
"likeOn":True,
"commentOn":True,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cName":" ",
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":False,
"Protectgroupname":False,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
"protectJoin":False,
"Backup":True,
"welcome":False,
"goodbye":False,
"TDinvite":False,
}
wait2 = {
'readPoint':{},
'readMember':{},
'setTime':{},
'ROM':{},
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{},
}
setTime = {}
setTime = wait2['setTime']
blacklistFile='blacklist.txt'
pendinglistFile='pendinglist.txt'
setTime = {}
setTime = wait2["setTime"]
contact = cl.getProfile()
backup = cl.getProfile()
backup.displayName = contact.displayName
backup.statusMessage = contact.statusMessage
backup.pictureStatus = contact.pictureStatus
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def mention(to,name):
aa = ""
bb = ""
strt = int(12)
akh = int(12)
nm = name
print nm
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x98\xbb @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.from_ = cl.getProfile.mid
msg.text = "[MENTION]\n"+bb
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print msg
try:
cl.sendMessage(msg)
except Exception as error:
print error
def NOTIFIED_KICKOUT_FROM_GROUP(op):
try:
cl.sendText(op.param1, cl.getContact(op.param3).displayName + " Jangan main kick ")
except Exception as e:
print e
print ("\n\nNOTIFIED_KICKOUT_FROM_GROUP\n\n")
return
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
cl.findAndAddContactsByMid(op.param1)
if (wait["message"] in [""," ","\n",None]):
pass
else:
cl.sendText(op.param1,str(wait["message"]))
#------------------------Auto Join-------------------------------
if op.type == 13:
if mid in op.param3:
G = cl.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
kk.acceptGroupInvitationByTicket(op.param1,Ticket)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
# ke.acceptGroupInvitationByTicket(op.param1,Ticket)
# kg.acceptGroupInvitationByTicket(op.param1,Ticket)
# kh.acceptGroupInvitationByTicket(op.param1,Ticket)
# kl.acceptGroupInvitationByTicket(op.param1,Ticket)
# kt.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
#cl.updateGroup(G)
else:
cl.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
cl.cancelGroupInvitation(op.param1, matched_list)
if op.type == 13:
if Bmid in op.param3:
G = kk.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kk.rejectGroupInvitation(op.param1)
else:
kk.acceptGroupInvitation(op.param1)
else:
kk.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kk.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
kk.cancelGroupInvitation(op.param1, matched_list)
if op.type == 13:
if op.param3 in mid:
if op.param2 in Amid:
G = Amid.getGroup(op.param1)
G.preventJoinByTicket = False
Amid.updateGroup(G)
Ticket = Amid.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
Amid.updateGroup(G)
Ticket = Amid.reissueGroupTicket(op.param1)
if op.param3 in Amid:
if op.param2 in mid:
X = cl.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
if op.param3 in Amid:
if op.param2 in Fmid:
X = kd.getGroup(op.param1)
X.preventJoinByTicket = False
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param3 in Bmid:
if op.param2 in Emid:
X = ke.getGroup(op.param1)
X.preventJoinByTicket = False
ke.updateGroup(X)
Ti = ke.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
if op.param3 in Dmid:
if op.param2 in Imid:
X = ki.getGroup(op.param1)
X.preventJoinByTicket = False
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param3 in Cmid:
if op.param2 in Bmid:
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
kk.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param3 in Dmid:
if op.param2 in Cmid:
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
if op.param3 in Dmid:
if op.param2 in Cmid:
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
if op.param3 in Emid:
if op.param2 in Dmid:
X = kb.getGroup(op.param1)
X.preventJoinByTicket = False
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
if op.param3 in Fmid:
if op.param2 in Emid:
X = kd.getGroup(op.param1)
X.preventJoinByTicket = False
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
if op.param3 in Emid:
if op.param2 in Amid:
X = kd.getGroup(op.param1)
X.preventJoinByTicket = False
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
if op.param3 in Amid:
if op.param2 in Cmid:
X = ki.getGroup(op.param1)
X.preventJoinByTicket = False
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param3 in Lmid:
if op.param2 in mid:
X = sw.getGroup(op.param1)
X.preventJoinByTicket = False
sw.updateGroup(X)
Ti = sw.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
if op.param3 in Amid:
if op.param2 in mid:
X = ki.getGroup(op.param1)
X.preventJoinByTicket = False
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid:
X = cl.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
Ti = ki.reissueGroupTicket(op.param1)
if op.param3 in Cmid:
if op.param2 in Dmid:
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
Ti = kb.reissueGroupTicket(op.param1)
if op.param3 in Dmid:
if op.param2 in Emid:
X = kb.getGroup(op.param1)
X.preventJoinByTicket = False
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
Ti = kd.reissueGroupTicket(op.param1)
if op.param3 in Dmid:
if op.param2 in Bmid:
X = kb.getGroup(op.param1)
X.preventJoinByTicket = False
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
Ti = kk.reissueGroupTicket(op.param1)
if op.param3 in Bmid:
if op.param2 in Lmid:
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
kk.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
X.preventJoinByTicket = True
Ti = sw.reissueGroupTicket(op.param1)
if op.type == 13:
print op.param1
print op.param2
print op.param3
if mid in op.param3:
G = cl.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
cl.cancelGroupInvitation(op.param1, matched_list)
#_____________
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
#_____________________________
#-------------------------------------------------------------------
if op.type == 11:
if not op.param2 in Bots:
try:
gs = ki.getGroup(op.param1)
targets = [op.param2]
for target in targets:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
pass
except Exception, e:
print e
#--------------------------------------------------------------------------------------------
if op.type == 19:
if not op.param2 in Bots:
try:
gs = cl.getGroup(op.param1)
targets = [op.param2]
for target in targets:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
pass
except Exception, e:
print e
if not op.param2 in Bots:
if wait["Backup"] == True:
try:
klist=[ki,kk,kc,kd,kb,cl]
kicker = random.choice(klist)
kicker.inviteIntoGroup(op.param1, [op.param3])
except Exception, e:
print e
if not op.param2 in Bots:
if op.param2 not in Bots:
if wait["protect"] == True:
try:
klist=[cl,ki,kk,kc,kb,kd,cl]
kicker=random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = False
kicker.updateGroup(G)
invsend = 0
Ticket = kicker.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
X = kicker.getGroup(op.param1)
X.preventJoinByTicket = True
kb.kickoutFromGroup(op.param1,[op.param2])
kicker.kickoutFromGroup(op.param1,[op.param2])
kb.leaveGroup(op.param1)
kicker.updateGroup(X)
except Exception, e:
print e
if not op.param2 in Bots:
if op.param2 not in Bots:
if wait["protect"] == True:
try:
klist=[cl,ki,kk,kc,kb,kd,cl]
kicker=random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = False
kicker.updateGroup(G)
invsend = 0
Ticket = kicker.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
X = kicker.getGroup(op.param1)
X.preventJoinByTicket = True
kd.kickoutFromGroup(op.param1,[op.param2])
kicker.kickoutFromGroup(op.param1,[op.param2])
kd.leaveGroup(op.param1)
kicker.updateGroup(X)
except Exception, e:
print e
if not op.param2 in Bots:
if op.param2 not in Bots:
if wait["protect"] == True:
try:
klist=[cl,ki,kk,kc,kb,kd,cl]
kicker=random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = False
kicker.updateGroup(G)
invsend = 0
Ticket = kicker.reissueGroupTicket(op.param1)
sw.acceptGroupInvitationByTicket(op.param1,Ticket)
X = kicker.getGroup(op.param1)
X.preventJoinByTicket = True
sw.kickoutFromGroup(op.param1,[op.param2])
kicker.kickoutFromGroup(op.param1,[op.param2])
sw.leaveGroup(op.param1)
kicker.updateGroup(X)
except Exception, e:
print e
#--------------------------------------------------------------------------------------------
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
try:
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
G = kc.getGroup(op.param1)
G.preventJoinByTicket = False
kc.updateGroup(G)
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
#ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
#kh.acceptGroupInvitationByTicket(op.param1,Ti)
#kl.acceptGroupInvitationByTicket(op.param1,Ti)
#kt.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
X = kc.getGroup(op.param1)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid in op.param3:
if op.param2 in Bots:
pass
try:
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
kk.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
#ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = kk.getGroup(op.param1)
G.preventJoinByTicket = True
kk.updateGroup(G)
Ticket = kk.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Bmid in op.param3:
if op.param2 in Bots:
pass
try:
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
# kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
#kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = kc.getGroup(op.param1)
G.preventJoinByTicket = True
kc.updateGroup(G)
Ticket = kc.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Cmid in op.param3:
if op.param2 in Bots:
pass
try:
kb.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kb.getGroup(op.param1)
X.preventJoinByTicket = False
kb.updateGroup(X)
Ti = kb.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
#kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = kb.getGroup(op.param1)
G.preventJoinByTicket = True
kb.updateGroup(G)
Ticket = kb.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Dmid in op.param3:
if op.param2 in Bots:
pass
try:
kd.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kd.getGroup(op.param1)
X.preventJoinByTicket = False
kd.updateGroup(X)
Ti = kd.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
#ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = kd.getGroup(op.param1)
G.preventJoinByTicket = True
kd.updateGroup(G)
Ticket = kd.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Emid in op.param3:
if op.param2 in Bots:
pass
try:
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
kk.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = kk.getGroup(op.param1)
G.preventJoinByTicket = True
kk.updateGroup(G)
Ticket = kk.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Fmid in op.param3:
if op.param2 in Bots:
pass
try:
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Because there is no kick regulation or group,\n["+op.param1+"]\nof\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki.getGroup(op.param1)
X.preventJoinByTicket = False
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
#kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
#kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
G = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Gmid in op.param3:
if op.param2 in Bots:
pass
try:
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nI could not kick.\nAdd it to the black list.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
G = kc.getGroup(op.param1)
G.preventJoinByTicket = False
kc.updateGroup(G)
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
X = kc.getGroup(op.param1)
X.preventJoinByTicket = True
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Hmid in op.param3:
if op.param2 in Bots:
pass
try:
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).KickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
G = ki.getGroup(op.param1)
G.preventJoinByTicket = False
ki.updateGroup(G)
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kj.acceptGroupInvitationByTicket(op.param1,Ti)
# kf.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
# km.acceptGroupInvitationByTicket(op.param1,Ti)
# kn.acceptGroupInvitationByTicket(op.param1,Ti)
# ko.acceptGroupInvitationByTicket(op.param1,Ti)
# kp.acceptGroupInvitationByTicket(op.param1,Ti)
# kq.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki.getGroup(op.param1)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
#____________~_~~~~_~___~~~~~~~~~~~~___~~~~~~
if op.type == 19:
if op.param2 not in Bots:
if op.param3 in admin:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,admin)
else:
pass
if op.type == 19:
if op.param2 not in Bots:
if op.param2 not in admin:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
print "kicker kicked"
else:
pass
if op.type == 19:
if op.param2 not in Bots:
if mid in op.param3:
if op.param2 in Bots:
pass
try:
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group¡¢\n["+op.param1+"]\n¤Î\n["+op.param2+"]\n¤òõí¤ëʤ¬¤Ç¤¤Þ¤»¤ó¤Ç¤·¤¿¡£\n¥Ö¥é¥Ã¥¯¥ê¥¹¥È¤Ë×·¼Ó¤·¤Þ¤¹¡£")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
G = ki.getGroup(op.param1)
G.preventJoinByTicket = False
ki.updateGroup(G)
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
#kg.acceptGroupInvitationByTicket(op.param1,Ti)
#kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
X = cl.getGroup(op.param1)
X.preventJoinByTicket = True
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid in op.param3:
if op.param2 in Bots:
pass
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client¤¬õí¤êÒŽÖÆor¥°¥ë©`¥×¤Ë´æÔÚ¤·¤Ê¤¤žé¡¢\n["+op.param1+"]\n¤Î\n["+op.param2+"]\n¤òõí¤ëʤ¬¤Ç¤¤Þ¤»¤ó¤Ç¤·¤¿¡£\n¥Ö¥é¥Ã¥¯¥ê¥¹¥È¤Ë×·¼Ó¤·¤Þ¤¹¡£")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
#ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
G = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Bmid in op.param3:
if op.param2 in Bots:
pass
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client¤¬õí¤êÒŽÖÆor¥°¥ë©`¥×¤Ë´æÔÚ¤·¤Ê¤¤žé¡¢\n["+op.param1+"]\n¤Î\n["+op.param2+"]\n¤òõí¤ëʤ¬¤Ç¤¤Þ¤»¤ó¤Ç¤·¤¿¡£\n¥Ö¥é¥Ã¥¯¥ê¥¹¥È¤Ë×·¼Ó¤·¤Þ¤¹¡£")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
G = kk.getGroup(op.param1)
G.preventJoinByTicket = True
kk.updateGroup(G)
Ticket = kk.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Cmid in op.param3:
if op.param2 in Bots:
pass
try:
cl.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client¤¬õí¤êÒŽÖÆor¥°¥ë©`¥×¤Ë´æÔÚ¤·¤Ê¤¤žé¡¢\n["+op.param1+"]\n¤Î\n["+op.param2+"]\n¤òõí¤ëʤ¬¤Ç¤¤Þ¤»¤ó¤Ç¤·¤¿¡£\n¥Ö¥é¥Ã¥¯¥ê¥¹¥È¤Ë×·¼Ó¤·¤Þ¤¹¡£")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = cl.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kb.acceptGroupInvitationByTicket(op.param1,Ti)
kd.acceptGroupInvitationByTicket(op.param1,Ti)
# ke.acceptGroupInvitationByTicket(op.param1,Ti)
# kg.acceptGroupInvitationByTicket(op.param1,Ti)
# kh.acceptGroupInvitationByTicket(op.param1,Ti)
# kl.acceptGroupInvitationByTicket(op.param1,Ti)
G = kc.getGroup(op.param1)
G.preventJoinByTicket = True
kc.updateGroup(G)
Ticket = kc.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
#~~~~~~~__~____~~~__________~~___
#----------------Welcome---------------------------------------------
if op.type == 15:
if wait["goodbye"] == True:
cl.sendText(op.param1, "Nah kq leave,,,Baper yee?")
print op.param3 + "has left the group"
if op.type == 11:
if op.param2 not in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "Please don't play qr")
print "Update group"
if op.type == 17:
if wait["welcome"] == True:
group = cl.getGroup(op.param1)
cb = Message()
cb.to = op.param1
cb.text = cl.getContact(op.param2).displayName + " Welcome to [ " + group.name + " ]\nCreator grup => [ " + group.creator.displayName + " ]"
cl.sendMessage(cb)
#-----------------------------------------------------------------
if op.type == 13:
if mid in op.param3:
klist=[cl,ki,kk,kc,kb,kd,kl]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kicker.rejectGroupInvitation(op.param1)
else:
kicker.acceptGroupInvitation(op.param1)
else:
kicker.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kicker.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
kicker.cancelGroupInvitation(op.param1, matched_list)
if op.type == 22:
if wait["leaveRoom"] == True:
cl.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
cl.leaveRoom(op.param1)
if op.type == 25:
msg = op.message
if msg.toType == 0:
msg.to = msg.from_
if msg.from_ == admin:
if "join:" in msg.text:
list_ = msg.text.split(":")
try:
cl.acceptGroupInvitationByTicket(list_[1],list_[2])
X = cl.getGroup(list_[1])
X.preventJoinByTicket = True
cl.updateGroup(X)
except:
cl.sendText(msg.to,"error")
if msg.toType == 1:
if wait["leaveRoom"] == True:
cl.leaveRoom(msg.to)
if msg.contentType == 16:
url = msg.contentMetadata("line://home/post?userMid="+mid+"&postId="+"new_post")
cl.like(url[25:58], url[66:], likeType=1001)
if op.type == 32:
if op.param2 not in Bots:
if op.param2 not in admin:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
if op.type == 25:
msg = op.message
if msg.contentType == 13:
if wait["Sablenkinvite"] == True:
if msg.from_ in admin:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = cl.getGroup(msg.to)
pending = groups.invite
targets = []
for s in groups.members:
if _name in s.displayName:
cl.sendText(msg.to,"[×]" + _name + " Sudah di grup ini😉")
break
elif invite in wait["blacklist"]:
cl.sendText(msg.to,"Sorry 😉 " + _name + " Ada di daftar Blacklist")
cl.sendText(msg.to,"Call my gerhana to use command !, \n➡Unban: " + invite)
break
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
cl.findAndAddContactsByMid(target)
cl.inviteIntoGroup(msg.to,[target])
cl.sendText(msg.to,"Succes : \n➡" + _name)
wait["Sablenkinvite"] = False
break
except:
try:
ki.findAndAddContactsByMid(invite)
ki.inviteIntoGroup(op.param1,[invite])
wait["Sablenkinvite"] = False
except:
cl.sendText(msg.to,"Sorry i can't invite this contact")
wait["Sablenkinvite"] = False
break
if wait["Sablenknvite"] == True:
if msg.from_ in admin:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = cl.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
ki.sendText(msg.to,"-> " + _name + " was here")
break
elif invite in wait["blacklist"]:
ki.sendText(msg.to,"Sorry, " + _name + " On Blacklist")
ki.sendText(msg.to,"Call my Gerhana to use command !, \n➡ Unban: " + invite)
break
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
ki.findAndAddContactsByMid(target)
ki.inviteIntoGroup(msg.to,[target])
random.choice(KAC).sendText(msg.to,"✍⎯ٴ☬⟿Admin kece☬ Invited: \n➡ " + _name)
wait["akaInvite"] = False
break
except:
cl.sendText(msg.to,"Negative, Err0r Detected")
wait["akaInvite"] = False
break
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
cl.sendText(msg.to,"Telah ditambahkan ke daftar hitam")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
cl.sendText(msg.to,"decided not to comment")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"deleted")
wait["dblack"] = False
else:
wait["dblack"] = False
cl.sendText(msg.to,"It is not in the black list")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
cl.sendText(msg.to,"Telah ditambahkan di daftar hitam")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
cl.sendText(msg.to,"Succes")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"deleted")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
cl.sendText(msg.to,"It is not in the black list")
elif wait["contact"] == True:
msg.contentType = 0
cl.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"🔹Name 》\n" + msg.contentMetadata["displayName"] + "\n🔹Mid 》\n" + msg.contentMetadata["mid"] + "\n🔹Status 》\n" + contact.statusMessage + "\n🔹Picture status 》\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n🔹CoverURL:\n" + str(cu))
else:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"🔹[NAME]:\n" + msg.contentMetadata["displayName"] + "\n🔹[MID]:\n" + msg.contentMetadata["mid"] + "\n🔹[STATUS]:\n" + contact.statusMessage + "\n🔹[PICTURE STATUS]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n🔹[CoverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait["timeline"] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "post URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"]
cl.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text in ["Help","Sw help","Menu","Key","menu"]:
if msg.from_ in admin:
if wait["lang"] == "JP":
cl.sendText(msg.to,helpMessage)
else:
cl.sendText(msg.to,helpt)
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Bot only admin & staff 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif msg.text in ["Set view"]:
if msg.from_ in admin:
if wait["lang"] == "JP":
cl.sendText(msg.to,helpMessage1)
else:
cl.sendText(msg.to,helpt)
elif ("Gn: " in msg.text):
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.name = msg.text.replace("Gn: ","")
cl.updateGroup(X)
else:
cl.sendText(msg.to,"It can't be used besides the group.")
elif "Sablenk kick " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Sablenk kick ","")
cl.kickoutFromGroup(msg.to,[midd])
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif "Kick " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Kick ","")
ki.kickoutFromGroup(msg.to,[midd])
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif msg.text in ["Invite on"]:
if msg.from_ in admin:
wait["Sablenk invite"] = True
cl.sendText(msg.to,"send contact to invite")
elif "Sablenk invite " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Sablenk invite ","")
cl.findAndAddContactsByMid(midd)
cl.inviteIntoGroup(msg.to,[midd])
elif "Sablenk invite " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Sablenk invite ","")
ki.findAndAddContactsByMid(midd)
ki.inviteIntoGroup(msg.to,[midd])
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif msg.text in ["Me"]:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.from_}
cl.sendMessage(msg)
elif msg.text.lower() == 'invite':
if msg.from_ in admin:
if msg.toType == 2:
wait["akaInvite"] = True
ki.sendText(msg.to,"send contact 👻")
elif "Invite:" in msg.text:
midd = msg.text.replace("Invite:","")
cl.findAndAddContactsByMid(midd)
cl.inviteIntoGroup(msg.to,[midd])
elif msg.text in ["Kibar"]:
if msg.from_ in admin:
msg.contentType = 13
msg.contentMetadata = {'mid': Amid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Bmid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Cmid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Dmid}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Emid}
cl.sendMessage(msg)
#msg.contentType = 13
# msg.contentMetadata = {'mid': Fmid}
# cl.sendMessage(msg)
#msg.contentType = 13
# msg.contentMetadata = {'mid': Gmid}
# cl.sendMessage(msg)
# msg.contentType = 13
#msg.contentMetadata = {'mid': Hmid}
# cl.sendMessage(msg)
# msg.contentType = 13
#msg.contentMetadata = {'mid': Imid}
# cl.sendMessage(msg)
# msg.contentType = 13
# msg.contentMetadata = {'mid': Jmid}
# cl.sendMessage(msg)
cl.sendText(msg.to," ASSALAMUALAIKUM \nROOM KALIAN \nDAFTAR PENGGUSURAN \nDALAM TARGET KAMI \n\nNO COMEND \nNO BAPER \nNO BACOT \nNO DESAH \n\n\nWAR!!! WER!!! WOR!!!\nKENAPE LU PADA DIEM\nTANGKIS NYET TANGKIS\n\n\nDASAR ROOM PEA KAGAK BERGUNA\nHAHAHAHHAHAHAHAHAHAHA\nGC LU MAU GUA SITA...!!!\n\n\n[SABLENK BOTS KILLER\n\nHADIR DI ROOM ANDA\n\nRATA GAK RATA YANG PENTING KIBAR \n\n\n>>>>>>BYE BYE <<<<<<\n\n\nDENDAM CARI KAMI\n\n<<<<<<<<<<>>>>>>>>>>\nDari pada mengisap rokok mendingan HISAP PAYUDARA\n1. Payudara wanita yg sering dihisap, keseimbangan sistem kardiovaskular kewanitaannya dpt terjaga ... Apabila lelaki menghisap Payudara wanita dalam waktu yg lama, maka degupan jantung wanita dpt meningkat hingga 110 detak/menit. Hal ini boleh menjadi latihan bagus bagi kesehatan jantung\n2. Hisap Payudara wanita juga dpt membuat berat badan wanita lebih stabil, bahkan berkurang. Hal ini disebabkan, Payudara wanita yg dihisap selama 3 menit dpt membakar lemak sekitar 12 kalori\n3. Ingin wajah lebih kencang? Kalau begitu jangan ragu utk lebih sering dihisap Payudaranya. Dgn dihisap Payudara, maka lebih dari 30 otot wajah wanita bergerak, sehingga berguna utk meningkatkan aliran darah di kulit wajah, dan menghaluskan kulit\n4. Selama ini hisap Payudara wanita dianggap sebagai hal yg kurang sopan/tabu. Tapi pada kenyataanya hisap Payudara wanita dpt membuat wanita lebih awet muda, merupakan obat alami yg merangsang sistem kekebalan tubuh, hasilnya adalah produksi antibodi yg mampu melindungi dari virus. Proses ini disebut cross-imunoterapi\n5. Pada saat Payudara wanita dihisap, biasanya nafas wanita jadi lebih cepat..Rata2 saat hisap Payudara, wanita akan menghirup dan membuang nafas 60 kali dlm satu menit. Padahal dlm keadaan normal hanya 20 kali tiap satu menit. Menghirup dan membuang nafas lebih sering akan mencegah berbagai gangguan diparu\n6. Payudara wanita yg dihisap lebih dari 5 menit akan membuat tubuh wanita lebih santai, dapat menghasilkan rantai kimiawi yg akan menghancurkan berbagai hormon penyebab stress\n7. Kebiasaan menghisap payudara diwaktu pagi saat bangun tidur selama 3 menit dan dilakukan rutin tiap pagi akan membantu mencegah timbulnya kanker payudara\nNah, tunggu apalagi? mudah dan bermanfaat\nAyo para laki-laki tidak perlu sungkan utk kebaikan, dari pada hisap rokok harganya mahal. Selamat Mencoba.\n ~~~~~Yang belum halal jangan di coba ya 😂😂😁😁\nhttps://line.me/ti/p/~gerhanaselatan")
#1. Payudara wanita yg sering dihisap, keseimbangan sistem kardiovaskular kewanitaannya dpt terjaga ... Apabila lelaki menghisap Payudara wanita dalam waktu yg lama, maka degupan jantung wanita dpt meningkat hingga 110 detak/menit. Hal ini boleh menjadi latihan bagus bagi kesehatan jantung")
#2. Hisap Payudara wanita juga dpt membuat berat badan wanita lebih stabil, bahkan berkurang. Hal ini disebabkan, Payudara wanita yg dihisap selama 3 menit dpt membakar lemak sekitar 12 kalori.")
#3. Ingin wajah lebih kencang? Kalau begitu jangan ragu utk lebih sering dihisap Payudaranya. Dgn dihisap Payudara, maka lebih dari 30 otot wajah wanita bergerak, sehingga berguna utk meningkatkan aliran darah di kulit wajah, dan menghaluskan kulit.")
#4. Selama ini hisap Payudara wanita dianggap sebagai hal yg kurang sopan/tabu. Tapi pada kenyataanya hisap Payudara wanita dpt membuat wanita lebih awet muda, merupakan obat alami yg merangsang sistem kekebalan tubuh, hasilnya adalah produksi antibodi yg mampu melindungi dari virus. Proses ini disebut cross-imunoterapi.")
#5. Pada saat Payudara wanita dihisap, biasanya nafas wanita jadi lebih cepat..Rata2 saat hisap Payudara, wanita akan menghirup dan membuang nafas 60 kali dlm satu menit. Padahal dlm keadaan normal hanya 20 kali tiap satu menit. Menghirup dan membuang nafas lebih sering akan mencegah berbagai gangguan diparu.")
#6. Payudara wanita yg dihisap lebih dari 5 menit akan membuat tubuh wanita lebih santai, dapat menghasilkan rantai kimiawi yg akan menghancurkan berbagai hormon penyebab stress.")
#7. Kebiasaan menghisap payudara diwaktu pagi saat bangun tidur selama 3 menit dan dilakukan rutin tiap pagi akan membantu mencegah timbulnya kanker payudara. ")
#----Dr.Boyke Dian Nugraha SpOG----")
#Nah, tunggu apalagi? mudah dan bermanfaat.")
#Ayo para laki-laki tidak perlu sungkan utk kebaikan, dari pada hisap rokok harganya mahal. Selamat Mencoba....")
#Yang belum halal jangan di coba ya 😂😂😁😁")
elif msg.text in ["æ„›ã®ãƒ—レゼント","Gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '2'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["æ„›ã®ãƒ—レゼント","Gift1"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["æ„›ã®ãƒ—レゼント","Gift2"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '6'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["æ„›ã®ãƒ—レゼント","Gift3"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '7'}
msg.text = None
cl.sendMessage(msg)
cl.sendMessage(msg)
elif msg.text in ["Cancel"]:
if msg.from_ in admin:
if msg.toType == 2:
X = cl.getGroup(msg.to)
if X.invitee is not None:
gInviMids = [contact.mid for contact in X.invitee]
cl.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"No one is inviting")
else:
cl.sendText(msg.to,"Sorry, nobody absent")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif msg.text in ["Canc"]:
if msg.toType == 2:
G = kk.getGroup(msg.to)
if G.invitee is not None:
gInviMids = [contact.mid for contact in G.invitee]
kk.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
kk.sendText(msg.to,"No one is inviting")
else:
kk.sendText(msg.to,"Sorry, nobody absent")
else:
if wait["lang"] == "JP":
kk.sendText(msg.to,"Can not be used outside the group")
else:
kk.sendText(msg.to,"Not for use less than group")
elif msg.text in ["Qr on","Ghost link on"]:
if msg.from_ in admin:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done👻")
else:
cl.sendText(msg.to,"already open")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["R1 ourl","R1 link on"]:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
ki.updateGroup(X)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done👻 ")
else:
cl.sendText(msg.to,"already open")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["R2 ourl","R2 link on"]:
if msg.toType == 2:
X = kk.getGroup(msg.to)
X.preventJoinByTicket = False
kk.updateGroup(X)
if wait["lang"] == "JP":
kk.sendText(msg.to,"Done ")
else:
kk.sendText(msg.to,"already open")
else:
if wait["lang"] == "JP":
kk.sendText(msg.to,"Can not be used outside the group")
else:
kk.sendText(msg.to,"Not for use less than group")
elif msg.text in ["Qr off","Sw link off"]:
if msg.from_ in admin:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = True
cl.updateGroup(X)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
cl.sendText(msg.to,"already close")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["R1 curl","R1 link off"]:
if msg.toType == 2:
X = ki.getGroup(msg.to)
X.preventJoinByTicket = True
ki.updateGroup(X)
if wait["lang"] == "JP":
ki.sendText(msg.to,"Done ")
else:
ki.sendText(msg.to,"already close")
else:
if wait["lang"] == "JP":
ki.sendText(msg.to,"Can not be used outside the group")
else:
ki.sendText(msg.to,"Not for use less than group")
elif msg.text in ["R2 curl","R2 link off"]:
if msg.toType == 2:
X = kk.getGroup(msg.to)
X.preventJoinByTicket = True
kk.updateGroup(X)
if wait["lang"] == "JP":
kk.sendText(msg.to,"Done ")
else:
kk.sendText(msg.to,"already close")
else:
if wait["lang"] == "JP":
kk.sendText(msg.to,"Can not be used outside the group")
else:
kk.sendText(msg.to,"Not for use less than group")
elif msg.text in ["Ginfo"]:
ginfo = cl.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
msg.contentType = 13
msg.contentMetadata = {'mid': ginfo.creator.mid}
cl.sendText(msg.to,"➰ NAME GROUP ➰\n" + str(ginfo.name) + "\n\n🔹 Group Id \n" + msg.to + "\n\n🔹Creator \n" + gCreator + "\n\n🔹Status profile \nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n\n~ Anggota :: " + str(len(ginfo.members)) + " Members\n~ Pending :: " + sinvitee + " People\n~ URL :: ")
cl.sendMessage(msg)
# elif "Music" in msg.text.lower():
# songname = msg.text.lower().replace("Music","")
# params = {"songname":" songname"}
# r = requests.get('https://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
# data = r.text
# data = json.loads(data)
# for song in data:
#cl.sendMessage(msg.to,song[4])
# elif "jointicket " in msg.text.lower():
# rplace=msg.text.lower().replace("jointicket ")
# if rplace == "on":
# wait["atjointicket"]=True
# elif rplace == "off":
# wait["atjointicket"]=False
# cl.sendText(msg.to,"Auto Join Group by Ticket is %s" % str(wait["atjointicket"]))
# elif '/ti/g/' in msg.text.lower():
# link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?')
# links = link_re.findall(msg.text)
# n_links=[]
# for l in links:
# if l not in n_links:
# n_links.append(l)
#for ticket_id in n_links:
#if wait["atjointicket"] == True:
# group=cl.findGroupByTicket(ticket_id)
# cl.acceptGroupInvitationByTicket(group.mid,ticket_id)
# cl.sendText(msg.to,"Sukses join ke grup %s" % str(group.name))
elif "Gc" == msg.text:
if msg.from_ in admin:
try:
group = cl.getGroup(msg.to)
GS = group.creator.mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': GS}
cl.sendMessage(M)
except:
W = group.members[0].mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': W}
cl.sendMessage(M)
cl.sendText(msg.to,"old user")
elif "Name: " in msg.text:
if msg.from_ in admin:
string = msg.text.replace("Name: ","")
if len(string.decode('utf-8')) <= 20:
profile = ki.getProfile()
profile.displayName = string
ki.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kk.getProfile()
profile.displayName = string
kk.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kc.getProfile()
profile.displayName = string
kc.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kb.getProfile()
profile.displayName = string
kb.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kd.getProfile()
profile.displayName = string
kd.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ke.getProfile()
profile.displayName = string
ke.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kf.getProfile()
profile.displayName = string
kf.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kg.getProfile()
profile.displayName = string
kg.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kh.getProfile()
profile.displayName = string
kh.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kj.getProfile()
profile.displayName = string
kj.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kl.getProfile()
profile.displayName = string
kl.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = km.getProfile()
profile.displayName = string
km.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = kn.getProfile()
profile.displayName = string
kn.updateProfile(profile)
if len(string.decode('utf-8')) <= 20:
profile = ko.getProfile()
profile.displayName = string
ko.updateProfile(profile)
cl.sendText(msg.to,"Update Name all bot succes")
elif "Mybio: " in msg.text:
if msg.from_ in admin:
string = msg.text.replace("Mybio: ","")
if len(string.decode('utf-8')) <= 500:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Update Bio👉 " + string + " 👈Succes")
elif "Allbio: " in msg.text:
if msg.from_ in admin:
string = msg.text.replace("Allbio: ","")
if len(string.decode('utf-8')) <= 500:
profile = ki.getProfile()
profile.statusMessage = string
ki.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kk.getProfile()
profile.statusMessage = string
kk.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kc.getProfile()
profile.statusMessage = string
kc.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kb.getProfile()
profile.statusMessage = string
kb.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kd.getProfile()
profile.statusMessage = string
kd.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = ke.getProfile()
profile.statusMessage = string
ke.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kl.getProfile()
profile.statusMessage = string
kl.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kg.getProfile()
profile.statusMessage = string
kg.updateProfile(profile)
if len(string.decode('utf-8')) <= 500:
profile = kh.getProfile()
profile.statusMessage = string
kh.updateProfile(profile)
elif "Rename: " in msg.text:
if msg.from_ in admin:
string = msg.text.replace("Rename: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"[●] Update Name👉 " + string + "👈")
elif "Mymid" == msg.text:
cl.sendText(msg.to, msg.from_)
elif "TL: " in msg.text:
if msg.from_ in admin:
tl_text = msg.text.replace("TL: ","")
cl.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+cl.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
elif ("Cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = cl.getProfile()
X = msg.text.replace("Cn: ","")
profile.displayName = X
cl.updateProfile(profile)
cl.sendText(msg.to,"Name ~ " + X + " Done")
else:
cl.sendText(msg.to,"Failed")
elif ("2cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = ki.getProfile()
X = msg.text.replace("2cn: ","")
profile.displayName = X
ki.updateProfile(profile)
ki.sendText(msg.to,"name " + X + " done")
else:
ki.sendText(msg.to,"Failed")
elif ("3cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kk.getProfile()
X = msg.text.replace("3cn: ","")
profile.displayName = X
kk.updateProfile(profile)
kk.sendText(msg.to,"name " + X + " done")
else:
kk.sendText(msg.to,"Failed")
elif ("4cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kc.getProfile()
X = msg.text.replace("4cn: ","")
profile.displayName = X
kc.updateProfile(profile)
kc.sendText(msg.to,"name " + X + " done")
else:
kc.sendText(msg.to,"Failed")
elif ("5cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kb.getProfile()
X = msg.text.replace("5cn: ","")
profile.displayName = X
kb.updateProfile(profile)
kb.sendText(msg.to,"name " + X + " done")
else:
kb.sendText(msg.to,"Failed")
elif ("6cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kd.getProfile()
X = msg.text.replace("6cn: ","")
profile.displayName = X
kd.updateProfile(profile)
kd.sendText(msg.to,"name " + X + " done")
else:
kd.sendText(msg.to,"Failed")
elif ("7cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = ke.getProfile()
X = msg.text.replace("7cn: ","")
profile.displayName = X
ke.updateProfile(profile)
ke.sendText(msg.to,"name " + X + " done")
else:
ke.sendText(msg.to,"Failed")
elif ("8cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kg.getProfile()
X = msg.text.replace("8cn: ","")
profile.displayName = X
kg.updateProfile(profile)
kg.sendText(msg.to,"name " + X + " done")
else:
kg.sendText(msg.to,"Failed")
elif ("9cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kh.getProfile()
X = msg.text.replace("9cn: ","")
profile.displayName = X
kh.updateProfile(profile)
kh.sendText(msg.to,"name " + X + " done")
else:
kh.sendText(msg.to,"Failed")
elif ("10cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = sw.getProfile()
X = msg.text.replace("10cn: ","")
profile.displayName = X
sw.updateProfile(profile)
sw.sendText(msg.to,"name " + X + " done")
else:
sw.sendText(msg.to,"Failed")
elif ("Last: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = kf.getProfile()
X = msg.text.replace("Last: ","")
profile.displayName = X
kf.updateProfile(profile)
kf.sendText(msg.to,"name " + X + " done")
else:
kf.sendText(msg.to,"Failed")
elif ("11cn: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
profile = sw.getProfile()
X = msg.text.replace("11cn: ","")
profile.displayName = X
sw.updateProfile(profile)
sw.sendText(msg.to,"Changed ==[ " + X + " ]== Succes")
else:
sw.sendText(msg.to,"Failed")
elif ("Mid " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
cl.sendText(msg.to,key1)
elif ("Mid: " in msg.text):
if msg.from_ in admin:
mmid = msg.replace("Mid: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":mmid}
cl.sendMessage(msg)
#---------------------------------------------------------------------------------------------
elif msg.text in ["Protect on"]:
if msg.from_ in admin:
if wait["protect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Already on")
else:
cl.sendText(msg.to,"Already on")
else:
wait["protect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already on")
elif msg.text in ["Protect qr on"]:
if msg.from_ in admin:
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"QR protect already on")
else:
cl.sendText(msg.to,"Already on")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On")
elif msg.text in ["Protect invite on"]:
if msg.from_ in admin:
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect invite already on")
else:
cl.sendText(msg.to,"Already on")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On")
elif msg.text in ["Cancelprotect on"]:
if msg.from_ in admin:
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect cancel already on")
else:
cl.sendText(msg.to,"Already on")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already ON")
else:
cl.sendText(msg.to,"It is already On")
elif msg.text in ["Gnamelock on"]:
if msg.from_ in admin:
if wait["Protectgroupname"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect group name on")
else:
cl.sendText(msg.to,"Protect group name on")
else:
wait["Protectgroupname"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Gnamelock already on")
else:
cl.sendText(msg.to,"Gnamelock already on")
elif msg.text in ["Gnamelock off"]:
if msg.from_ in admin:
if wait["Protectgroupname"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect group name off")
else:
cl.sendText(msg.to,"Protect group name off")
else:
wait["Protectgroupname"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Gnamelock already off")
else:
cl.sendText(msg.to,"Gnamelock already off")
#---------------------------------------------------------------------------------------------
elif msg.text in ["Allprotect on","Sw on","S on"]:
if msg.from_ in admin:
if wait["protectJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect join already on")
else:
cl.sendText(msg.to,"Protect join already ON")
else:
wait["protectJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Kick Join already On")
else:
cl.sendText(msg.to,"done")
if wait["protect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Already on")
else:
cl.sendText(msg.to,"Protection already on")
else:
wait["protect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection already ON")
else:
cl.sendText(msg.to,"Protection already On")
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectQR Already on")
else:
cl.sendText(msg.to,"ProtectQR already on")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectQR Already On")
else:
cl.sendText(msg.to,"ProtectQR already On")
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectInvite Already On")
else:
cl.sendText(msg.to,"ProtectInvite Already ON")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectInvite already ON")
else:
cl.sendText(msg.to,"ProtectInvite already On")
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"CancelProtect Already On")
else:
cl.sendText(msg.to,"CancelProtect already On")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"CancelProtect already ON")
else:
cl.sendText(msg.to,"CancelProtect already On")
#-----------------------------------------------------------------------------------------
elif msg.text in ["Allprotect off","Sw off","S off"]:
if msg.from_ in admin:
if wait["protectJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protect join already Off")
else:
cl.sendText(msg.to,"Protect join already Off")
else:
wait["protectJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"kick Join already Off")
else:
cl.sendText(msg.to,"done")
if wait["protect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Already off")
else:
cl.sendText(msg.to,"Protection Already off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection already Off")
else:
cl.sendText(msg.to,"Protection already off")
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectQR Already off")
else:
cl.sendText(msg.to,"ProtectQR Already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectQR already off")
else:
cl.sendText(msg.to,"ProtectQR already Off")
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectInvite Already off")
else:
cl.sendText(msg.to,"ProtectInvite Already off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"ProtectInvite already off")
else:
cl.sendText(msg.to,"ProtectInvite already off")
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"CancelProtect Already off")
else:
cl.sendText(msg.to,"CancelProtect Already off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"CancelProtect already off")
else:
cl.sendText(msg.to,"CancelProtect already off")
#----------------------------------------------------------------------------------------------
elif msg.text in ["連絡先:オン","K on","Contact on","顯示:開"]:
if msg.from_ in admin:
if wait["contact"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["contact"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
elif msg.text in ["連絡先:オフ","K off","Contact off","顯示:關"]:
if msg.from_ in admin:
if wait["contact"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done ")
else:
wait["contact"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
elif msg.text in ["Join on","Auto join:on"]:
if msg.from_ in admin:
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["autoJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Join off","Auto join:off"]:
if msg.from_ in admin:
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["autoJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
elif ("Auto cancel:" in msg.text):
if msg.from_ in admin:
try:
strnum = msg.text.replace("Auto cancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,strnum + " The group of people and below decided to automatically refuse invitation")
except:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Value is wrong")
else:
cl.sendText(msg.to,"Bizarre ratings")
elif msg.text in ["強制自動退出:オン","Leave on","Auto leave:on","強制自動退出:開"]:
if msg.from_ in admin:
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["leaveRoom"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å¼€ã€‚")
elif msg.text in ["強制自動退出:オフ","Leave off","Auto leave:off","強制自動退出:關"]:
if msg.from_ in admin:
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["leaveRoom"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"already")
elif msg.text in ["共有:オン","Share:on","Share on"]:
if msg.from_ in admin:
if wait["timeline"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["timeline"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å¼€ã€‚")
elif msg.text in ["共有:オフ","Share:off","Share off"]:
if msg.from_ in admin:
if wait["timeline"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["timeline"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å…³æ–。")
elif msg.text in ["Sablenk setting","Set","Set view","Setting"]:
if msg.from_ in admin:
md = " ✮🔰「 SABLENK SETING 」🔰✮\n\n╔══════════════\n"
if wait["contact"] == True: md+="🔹 Contact → on\n"
else: md+="🔹 Contact → off\n"
if wait["autoJoin"] == True: md+="🔹 Auto join → on\n"
else: md +="🔹 Auto join → off\n"
if wait["autoCancel"]["on"] == True: md+="🔹 Auto cancel → "+ str(wait["autoCancel"]["members"]) + "\n"
else: md+= "🔹 Auto cancel → off\n"
if wait["likeOn"] == True: md+="🔹 Auto Like → on\n"
else: md+="🔹 Auto Like → off\n"
if wait["leaveRoom"] == True: md+="🔹 Auto leave → on\n"
else: md+="🔹 Auto leave → off\n"
if wait["Backup"] == True: md+="🔹 Auto backup → on\n"
else:md+="🔹 Auto backup → off\n"
if wait["timeline"] == True: md+="🔹 Share → on\n"
else: md+="🔹 Share → off\n"
if wait["autoAdd"] == True: md+="🔹 Auto add → on\n"
else: md+="🔹 Auto add → off\n"
if wait["commentOn"] == True: md+="🔹 Comment → on\n"
else: md+="🔹 Comment → off\n"
if wait["protect"] == True: md+="🔐 Protect → on\n"
else:md+="🔐 Protect → off\n"
if wait["linkprotect"] == True: md+="🔐 QRProtect → on\n"
else:md+="🔐 QRprotect → off\n"
if wait["inviteprotect"] == True: md+="🔐 Protect invite → on\n"
else:md+="🔐 Protect invite → off \n"
if wait["Protectgroupname"] == True: md+="🔐 Gnamelock → on\n"
else:md+="🔐 Gnamelock → off \n"
if wait["cancelprotect"] == True: md+="🔐 Protect cancel → on\n"
else:md+="🔐 Protect cancel → off\n"
if wait["protectJoin"] == True: md+="🔐 Protectjoin → on\n"
else:md+="🔐 Protect join → off\n"
cl.sendText(msg.to,md + "╚═════════════\n\n 🔐 🔰SABLENK BOTS🔰「👻」")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif msg.text in ["Group id","List group"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "[🔹] %s \n" % (cl.getGroup(i).name + " :::: " + str(len (cl.getGroup(i).members)))
cl.sendText(msg.to, "==== [GROUPS] ====\n\n"+ h +"\n[●] TOTAL GROUPS : " +str(len(gid)))
elif msg.text in ["Reject"]:
if msg.from_ in admin:
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"All invitations have been refused")
else:
cl.sendText(msg.to,"æ‹’ç»äº†å…¨éƒ¨çš„邀请。")
elif msg.text in ["Cancelall1"]:
if msg.from_ in admin:
gid = ki.getGroupIdsInvited()
for i in gid:
ki.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki.sendText(msg.to,"All invitations have been refused")
else:
ki.sendText(msg.to,"æ‹’ç»äº†å…¨éƒ¨çš„邀请。")
elif msg.text in ["Cancelall2"]:
if msg.from_ in admin:
gid = kk.getGroupIdsInvited()
for i in gid:
kk.rejectGroupInvitation(i)
if wait["lang"] == "JP":
kk.sendText(msg.to,"All invitations have been refused")
else:
kk.sendText(msg.to,"æ‹’ç»äº†å…¨éƒ¨çš„邀请。")
elif msg.text in ["Backup on","Auto backup on"]:
if msg.from_ in admin:
if wait["Backup"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already On")
else:
cl.sendText(msg.to,"Backup already On")
else:
wait["Backup"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup already On")
else:
cl.sendText(msg.to,"already on")
elif msg.text in ["Backup off","Auto backup off"]:
if msg.from_ in admin:
if wait["Backup"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already off")
else:
cl.sendText(msg.to,"Backup already Off")
else:
wait["Backup"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup already Off")
else:
cl.sendText(msg.to,"Already off")
elif msg.text in ["Auto like on"]:
if msg.from_ in admin:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already on")
elif msg.text in ["Auto like off"]:
if msg.from_ in admin:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already off")
elif msg.text in ["è‡ªå‹•è¿½åŠ :オン","Add on","Auto add:on","è‡ªå‹•è¿½åŠ ï¼šé–‹"]:
if msg.from_ in admin:
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å¼€ã€‚")
elif msg.text in ["è‡ªå‹•è¿½åŠ :オフ","Add off","Auto add:off","è‡ªå‹•è¿½åŠ ï¼šé—œ"]:
if msg.from_ in admin:
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å…³æ–。")
elif "Cek msg" in msg.text:
if msg.from_ in admin:
cl.sendText(msg.to,"Your message ⤵\n\n" + str(wait["message"]))
elif "Message set: " in msg.text:
if msg.from_ in admin:
m = msg.text.replace("Message set: ","")
if m in [""," ","\n",None]:
cl.sendText(msg.to,"Error")
else:
wait["message"] = m
cl.sendText(msg.to,"Changed ⤵\n\n" + m)
elif "Comment set: " in msg.text:
if msg.from_ in admin:
c = msg.text.replace("Comment set: ","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"Error")
else:
wait["comment"] = c
cl.sendText(msg.to,"Changed ⤵\n\n" + c)
elif msg.text in ["Comment on","Comment:on","自動首é 留言:開"]:
if msg.from_ in admin:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"already on")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å¼€ã€‚")
elif msg.text in ["コメント:オフ","Comment:off","Comment off","自動首é 留言:關"]:
if msg.from_ in admin:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"already off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"è¦äº†å…³æ–。")
elif msg.text in ["Welcome on"]:
if wait["welcome"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Welcome already off")
else:
wait["welcome"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Welcome already on")
if wait["goodbye"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Message goodbye already on")
else:
wait["goodbye"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Message goodbye already on")
elif msg.text in ["Welcome off"]:
if wait["welcome"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Welcome already off")
else:
wait["welcome"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Welcome already off")
if wait["goodbye"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Message goodbye off")
else:
wait["goodbye"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Message goodbye off")
elif msg.text in ["Cek comment"]:
if msg.from_ in admin:
cl.sendText(msg.to,"Your comment ⤵\n\n" + str(wait["comment"]))
elif msg.text in ["Bot creator","Creator"]:
msg.contentType = 13
msg.contentMetadata = {'mid': 'uf50d888821632d32461e37153ac775c0'}
cl.sendMessage(msg)
elif msg.text in ["Gurl"]:
if msg.from_ in admin:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
cl.updateGroup(x)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can't be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["1gurl"]:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
ki.updateGroup(x)
gurl = ki.reissueGroupTicket(msg.to)
ki.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can't be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["2gurl"]:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
kk.updateGroup(x)
gurl = kk.reissueGroupTicket(msg.to)
kk.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can't be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["Comment bl "]:
if msg.from_ in admin:
wait["wblack"] = True
cl.sendText(msg.to,"add to comment bl")
elif msg.text in ["Comment wl "]:
wait["dblack"] = True
cl.sendText(msg.to,"wl to comment bl")
elif msg.text in ["Comment bl confirm"]:
if wait["commentBlack"] == {}:
cl.sendText(msg.to,"confirmed")
else:
cl.sendText(msg.to,"Blacklist")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "[]" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text in ["Check"]:
if msg.from_ in admin:
if wait["commentBlack"] == {}:
cl.sendText(msg.to,"Nothing a blacklist")
else:
cl.sendText(msg.to,"Blacklist user")
kontak = cl.getContact(commentBlack)
num=1
msgs="Blacklist user\n"
for ids in kontak:
msgs+="\n%si. %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n\n[●] Total %i blacklist user(s)" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["Jam on"]:
if msg.from_ in admin:
if wait["clock"] == True:
cl.sendText(msg.to,"already on")
else:
wait["clock"] = True
now2 = datetime.now()
nowT = datetime.strftime(now2,"(%H:%M)")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
cl.sendText(msg.to,"done")
elif msg.text in ["Jam off"]:
if msg.from_ in admin:
if wait["clock"] == False:
cl.sendText(msg.to,"already off")
else:
wait["clock"] = False
cl.sendText(msg.to,"done")
elif msg.text in ["Change clock "]:
if msg.from_ in admin:
n = msg.text.replace("Change clock ","")
if len(n.decode("utf-8")) > 13:
cl.sendText(msg.to,"changed")
else:
wait["cName"] = n
cl.sendText(msg.to,"changed to\n\n" + n)
elif msg.text in ["Up"]:
if msg.from_ in admin:
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"(%H:%M)")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
cl.sendText(msg.to,".")
else:
cl.sendText(msg.to,"Please turn on the name clock.")
#-----------------------------------------------------------------------
elif 'youtube ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
cl.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
cl.sendText(msg.to,"Could not find it")
# elif "Remove chat" in msg.text:
#if msg.from_ in admin:
#try:
# cl.removeAllMessages(op.param2)
# ki.removeAllMessages(op.param2)
#kc.removeAllMessages(op.param2)
# kb.removeAllMessages(op.param2)
#kd.removeAllMessages(op.param2)
#ke.removeAllMessages(op.param2)
#kg.removeAllMessages(op.param2)
#h.removeAllMessages(op.param2)
#print "Success Remove Chat"
# except:
# try:
# cl.sendText(msg.to,"Chat telah dihapus")
# pass
#-----------------------------------------------------------------------
elif msg.text in ["Lurkers"]:
cl.sendText(msg.to, "Waiting in lurkers Har Har")
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
now2 = datetime.now()
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime("%Y-%m-%d %H:%M")
wait2['ROM'][msg.to] = {}
print wait2
elif msg.text in ["View"]:
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2["ROM"][msg.to].items():
print rom
chiya += rom[1] + "\n"
cl.sendText(msg.to, "╔════════════\n%s\n\n╠═══════════\n\n%s\n╠═════════════\n║Reading point creation:\n║ [%s]\n╚══════════════" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
else:
cl.sendText(msg.to, "Ketik「Lurkers」dulu pekok ahhh Har Har")
#-------------------------------------------------
elif "Spam to @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Spam to @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
cl.sendText(msg.to,"Wating in progres...")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
kb.sendText(g.mid,"Your Account Has Been Spammed !")
kd.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ke.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kk.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
kh.sendText(g.mid,"Your Account Has Been Spammed !")
kg.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
ki.sendText(g.mid,"Your Account Has Been Spammed !")
kc.sendText(g.mid,"Your Account Has Been Spammed !")
cl.sendText(msg.to, "Succes")
print " Spammed !"
#--------------------------------------------------------------------------
elif "Admin on @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff add executing"
_name = msg.text.replace("Admin on @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.append(target)
cl.sendText(msg.to,"Admin Ditambahkan di perangkat Bot")
except:
pass
print "[Command]Staff add executed"
else:
cl.sendText(msg.to,"Command tidak bisa")
cl.sendText(msg.to,"Bot ready in admin only")
elif "Admin off @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff remove executing"
_name = msg.text.replace("Admin off @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.remove(target)
cl.sendText(msg.to,"Admin Dihapus dari perangkat Bot")
except:
pass
print "[Command]Staff remove executed"
else:
cl.sendText(msg.to,"Command tidak bisa")
cl.sendText(msg.to,"Bot ready in admin only")
elif msg.text in ["Admin list","List admin"]:
if admin == []:
cl.sendText(msg.to,"The admin is empty")
else:
cl.sendText(msg.to,"This is admin bot")
mc = ""
for mi_d in admin:
mc += "[●] " + cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
print "[Command]Stafflist executed"
#~~~~~~___________________________________________________________
#------------------------------------------------------------------------------
elif msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
cl.sendText(msg.to,text)
else:
if msg.contentType == 7:
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "6",
"STKPKGID": "1",
"STKVER": "100" }
cl.sendMessage(msg)
elif msg.contentType == 13:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.contentMetadata["mid"]}
cl.sendMessage(msg)
elif "Mimic:" in msg.text:
if msg.from_ in admin:
cmd = msg.text.replace("Mimic:","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
cl.sendText(msg.to,"Mimic on")
else:
cl.sendText(msg.to,"Mimic already on")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
cl.sendText(msg.to,"Mimic off")
else:
cl.sendText(msg.to,"Mimic already off")
elif "add " in cmd:
target0 = msg.text.replace("Mimic:add ","")
target1 = target0.lstrip()
target2 = target1.replace("@","")
target3 = target2.rstrip()
_name = target3
gInfo = cl.getGroup(msg.to)
targets = []
for a in gInfo.members:
if _name == a.displayName:
targets.append(a.mid)
if targets == []:
cl.sendText(msg.to,"No targets")
else:
for target in targets:
try:
mimic["target"][target] = True
cl.sendText(msg.to,"Success added target")
mid.sendMessageWithMention(msg.to,target)
break
except:
mid.sendText(msg.to,)
break
elif "del " in cmd:
target0 = msg.text.replace("Mimic:del ","")
target1 = target0.lstrip()
target2 = target1.replace("@","")
target3 = target2.rstrip()
_name = target3
gInfo = cl.getGroup(msg.to)
targets = []
for a in gInfo.members:
if _name == a.displayName:
targets.append(a.mid)
if targets == []:
cl.sendText(msg.to,"No targets")
else:
for target in targets:
try:
del mimic["target"][target]
cl.sendText(msg.to,"Success deleted target")
mid.sendMessageWithMention(msg.to,target)
break
except:
mid.sendText(msg.to,)
break
elif "target" in cmd:
if mimic["target"] == {}:
ki.sendText(msg.to,"No target")
else:
lst = "List Target"
total = len(mimic["target"])
for a in mimic["target"]:
if mimic["target"][a] == True:
stat = "On"
else:
stat = "Off"
lst += "\n->" + me.getContact(a).displayName + " | " + start
ki.sendText(msg.to,lst + "\nTotal:" + total)
#----------------------------------------------------------------------------
elif "Staff on @" in msg.text:
if msg.from_ in admin:
print "[Command]Staff add executing"
_name = msg.text.replace("Staff on @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
staff.append(target)
cl.sendText(msg.to,"Staff Ditambahkan diperangkat bot")
except:
pass
print "[Command]Staff add executed"
else:
cl.sendText(msg.to,"Command denied.")
cl.sendText(msg.to,"Admin & staff permission required.")
elif "Staff off @" in msg.text:
if msg.from_ in admin:
print "[Command]Staff remove executing"
_name = msg.text.replace("Staff off @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
staff.remove(target)
cl.sendText(msg.to,"Staff Dihapus dari perangkat bot")
except:
pass
print "[Command]Staff remove executed"
else:
cl.sendText(msg.to,"Command denied.")
cl.sendText(msg.to,"Admin & staff permission required.")
elif msg.text in ["Staff list"]:
if staff == []:
cl.sendText(msg.to,"The stafflist is empty")
else:
cl.sendText(msg.to,"Staff in bot")
mc = ""
for mi_d in staff:
mc += "[●]" + cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
print "[Command]Stafflist executed"
#-------------------------------------------------------------------------------
elif "Dorr " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Dorr ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
sw.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
sw.kickoutFromGroup(msg.to,[target])
sw.leaveGroup(msg.to)
cl.updateGroup(G)
print (msg.to,[g.mid])
except:
ki.sendText(msg.to,"Succes ")
kk.sendText(msg.to,"Bye")
elif "Nk " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Nk ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki.kickoutFromGroup(msg.to,[target])
ki.leaveGroup(msg.to)
cl.updateGroup(G)
print (msg.to,[g.mid])
except:
ki.sendText(msg.to,"Succes ")
kk.sendText(msg.to,"Bye")
#-----------------------------------------------
elif msg.text in ["."]:
if msg.from_ in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kk.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kb.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kd.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ke.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kg.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kh.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
cl.updateGroup(G)
print "kicker ok"
elif msg.text in ["Sablenk 1"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kk.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kb.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kd.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ke.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kg.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kh.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = ki.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(msg.to)
elif msg.text in ["Sw 2"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
kj.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kf.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kl.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
km.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kn.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
ko.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kp.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kq.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = ko.getGroup(msg.to)
G.preventJoinByTicket = True
ko.updateGroup(G)
Ticket = ko.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy3"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kc.acceptGroupInvitationByTicket(msg.to,Ti)
G = kc.getGroup(msg.to)
G.preventJoinByTicket = True
kc.updateGroup(G)
Ticket = kc.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy4"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kb.acceptGroupInvitationByTicket(msg.to,Ti)
G = kb.getGroup(msg.to)
G.preventJoinByTicket = True
kb.updateGroup(G)
Ticket = kb.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy5"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kd.acceptGroupInvitationByTicket(msg.to,Ti)
G = kd.getGroup(msg.to)
G.preventJoinByTicket = True
kd.updateGroup(G)
Ticket = kd.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy6"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
ke.acceptGroupInvitationByTicket(msg.to,Ti)
G = ke.getGroup(msg.to)
G.preventJoinByTicket = True
ke.updateGroup(G)
Ticket = ke.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy7"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kg.acceptGroupInvitationByTicket(msg.to,Ti)
G = kg.getGroup(msg.to)
G.preventJoinByTicket = True
kg.updateGroup(G)
Ticket = kg.reissueGroupTicket(msg.to)
elif msg.text in ["Kuy8"]:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kh.acceptGroupInvitationByTicket(msg.to,Ti)
G = kh.getGroup(msg.to)
G.preventJoinByTicket = True
kh.updateGroup(G)
Ticket = kh.reissueGroupTicket(msg.to)
elif msg.text in ["Ghost"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
sw.acceptGroupInvitationByTicket(msg.to,Ti)
G = sw.getGroup(msg.to)
G.preventJoinByTicket = True
sw.updateGroup(G)
Ticket = sw.reissueGroupTicket(msg.to)
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
#-----------------------------------------------
elif msg.text in ["Mentions","Tag","Mek"]:
if msg.from_ in admin:
group = cl.getGroup(msg.to)
k = len(group.members)//100
for j in xrange(k+1):
msg = Message(to=msg.to)
txt = u''
s=0
d=[]
for i in group.members[j*100 : (j+1)*100]:
d.append({"S":str(s), "E" :str(s+8), "M":i.mid})
s += 9
txt += u'@Krampus\n'
msg.text = txt
msg.contentMetadata = {u'MENTION':json.dumps({"MENTIONEES":d})}
cl.sendMessage(msg)
else:
cl.sendText(msg.to,noticeMessage)
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😊\nKetik 「Creator」for contact admin")
#-----------------------------------------------
elif msg.text in ["Out"]:
gid = cl.getGroupIdsJoined()
gid = ki.getGroupIdsJoined()
gid = kk.getGroupIdsJoined()
gid = kc.getGroupIdsJoined()
gid = kb.getGroupIdsJoined()
gid = kd.getGroupIdsJoined()
gid = ke.getGroupIdsJoined()
gid = kg.getGroupIdsJoined()
gid = kh.getGroupIdsJoined()
gid = kl.getGroupIdsJoined()
for i in gid:
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
kb.leaveGroup(i)
kd.leaveGroup(i)
ke.leaveGroup(i)
kg.leaveGroup(i)
kh.leaveGroup(i)
kl.leaveGroup(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Bot sudah keluar dari semua grup")
else:
cl.sendText(msg.to,"He declined all invitations")
elif msg.text in [","]:
if msg.from_ in admin:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.sendText(msg.to,"Bye bye " + str(ginfo.name) + "")
ki.leaveGroup(msg.to)
kk.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
kb.leaveGroup(msg.to)
kd.leaveGroup(msg.to)
ke.leaveGroup(msg.to)
kg.leaveGroup(msg.to)
kh.leaveGroup(msg.to)
kl.leaveGroup(msg.to)
except:
pass
elif msg.text in [","]:
if msg.from_ in admin:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
#ki.sendText(msg.to,"Bye Bye " + str(ginfo.name) + "")
ki.leaveGroup(msg.to)
#kk.sendText(msg.to,"Bye Bye " + str(ginfo.name) + "")
kk.leaveGroup(msg.to)
#kc.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kc.leaveGroup(msg.to)
#kb.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kb.leaveGroup(msg.to)
#kd.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kd.leaveGroup(msg.to)
#ke.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
ke.leaveGroup(msg.to)
#kg.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kg.leaveGroup(msg.to)
#kh.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kh.leaveGroup(msg.to)
#kl.sendText(msg.to,"Bye Bye😘 " + str(ginfo.name) + "")
kl.leaveGroup(msg.to)
except:
pass
elif msg.text in ["Leave"]:
if msg.from_ in admin:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
elif msg.text in ["Bye"]:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
sw.leaveGroup(msg.to)
except:
pass
#------------------------[Copy]-------------------------
elif msg.text in ["Sablenk kembali"]:
if msg.from_ in admin:
try:
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.sendText(msg.to,"Backup done")
except Exception as e:
cl.sendText(msg.to, str (e))
elif "kedapkedip " in msg.text.lower():
txt = msg.text.replace("kedapkedip ", "")
cl.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Sablenk:Bc " in msg.text:
bctxt = msg.text.replace("Sablenk:Bc ", "")
a = cl.getAllContactIds()
for manusia in a:
cl.sendText(manusia, (bctxt))
elif "Sablenk:Bc " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Sablenk:Bc ", "")
b = ki.getAllContactIds()
for manusia in b:
ki.sendText(manusia, (bctxt))
c = kk.getAllContactIds()
for manusia in c:
kk.sendText(manusia, (bctxt))
d = kc.getAllContactIds()
for manusia in d:
kc.sendText(manusia, (bctxt))
e = kb.getAllContactIds()
for manusia in e:
kb.sendText(manusia, (bctxt))
f = kd.getAllContactIds()
for manusia in f:
kd.sendText(manusia, (bctxt))
g = ke.getAllContactIds()
for manusia in g:
ke.sendText(manusia, (bctxt))
h = kg.getAllContactIds()
for manusia in h:
kg.sendText(manusia, (bctxt))
i = kh.getAllContactIds()
for manusia in i:
kh.sendText(manusia, (bctxt))
j = sw.getAllContactIds()
for manusia in j:
sw.sendText(manusia, (bctxt))
#_______________
elif "InviteMeTo: " in msg.text:
if msg.from_ in owner:
gid = msg.text.replace("InviteMeTo: ","")
if gid == "":
cl.sendText(msg.to,"Invalid group id")
else:
try:
cl.findAndAddContactsByMid(msg.from_)
cl.inviteIntoGroup(gid,[msg.from_])
except:
cl.sendText(msg.to,"Mungkin saya tidak di dalaam grup itu")
elif msg.text in ["Sablenk leaveAllGc"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
gid = ki.getGroupIdsJoined()
gid = kk.getGroupIdsJoined()
gid = kc.getGroupIdsJoined()
gid = kb.getGroupIdsJoined()
gid = kd.getGroupIdsJoined()
gid = ke.getGroupIdsJoined()
gid = kg.getGroupIdsJoined()
gid = kh.getGroupIdsJoined()
gid = kl.getGroupIdsJoined()
gid = kt.getGroupIdsJoined()
gid = kz.getGroupIdsJoined()
gid = sw.getGroupIdsJoined()
for i in gid:
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
kb.leaveGroup(i)
kd.leaveGroup(i)
ke.leaveGroup(i)
kg.leaveGroup(i)
kh.leaveGroup(i)
kl.leaveGroup(i)
kt.leaveGroup(i)
kz.leaveGroup(i)
sw.leaveGroup(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Bot Sudah Keluar Di semua grup")
else:
cl.sendText(msg.to,"He declined all invitations")
elif msg.text in ["Sw1 kembali"]:
if msg.from_ in admin:
try:
kc.updateDisplayPicture(backup.pictureStatus)
kc.updateProfile(backup)
kc.sendText(msg.to,"Backup done")
except Exception as e:
kc.sendText(msg.to, str (e))
elif "S copy @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "[Copy]"
_name = msg.text.replace("S copy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Not Found")
else:
for target in targets:
try:
cl.CloneContactProfile(target)
cl.sendText(msg.to, "Succes copy")
except Exception as e:
print e
elif "S clone @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "[Copy]"
_name = msg.text.replace("S clone @","")
_nametarget = _name.rstrip(' ')
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kc.sendText(msg.to, "Not Found")
else:
for target in targets:
try:
kc.CloneContactProfile(target)
kc.sendText(msg.to, "Succes clone")
except Exception as e:
print e
#=====TRANSLATE===========
elif "/translate-en " in msg.text:
txt = msg.text.replace("/translate-en ","")
try:
gs = goslate.Goslate()
trs = gs.translate(txt,'en')
cl.sendText(msg.to,trs)
print '[Command] Translate EN'
except:
cl.sendText(msg.to,'Error.')
elif "/translate-id " in msg.text:
txt = msg.text.replace("/translate-id ","")
try:
gs = goslate.Goslate()
trs = gs.translate(txt,'id')
cl.sendText(msg.to,trs)
print '[Command] Translate ID'
except:
cl.sendText(msg.to,'Error.')
#-----------------------------------------------
elif "Glist" in msg.text:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "=> %s \n" % (cl.getGroup(i).name + " | Members : [ " + str(len (cl.getGroup(i).members))+" ]")
cl.sendText(msg.to, "#[List Grup]# \n"+ h +"Total Group : " +"[ "+str(len(gid))+" ]")
elif msg.text.lower() == 'group id':
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "[%s]:%s\n" % (cl.getGroup(i).name,i)
cl.sendText(msg.to,h)
elif msg.text in ["Fuck"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
ki.sendText(msg.to,"Bye")
return
for jj in matched_list:
try:
random.choice(KAC).kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
elif "Clearall" in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Clearall","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("all","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Tidak Ada Member")
pass
else:
for target in targets:
if not target in Bots and admin:
try:
cl.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
cl.sendText(msg.to,"Salam kenal hehehe...")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif "S bir" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("S bir","")
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
gs = kb.getGroup(msg.to)
gs = kd.getGroup(msg.to)
gs = ke.getGroup(msg.to)
gs = kg.getGroup(msg.to)
gs = kh.getGroup(msg.to)
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Not found.")
kk.sendText(msg.to,"Not found.")
else:
for target in targets:
if not target in Bots and admin:
try:
klist=[cl,ki,kk,kc,kb,kd,ke,kg,kh]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
cl.sendText(msg,to,"Group cleanse")
cl.sendText(msg,to,"Group cleanse")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
#-------------------------------------------------------------------
# elif "kibar" in msg.text:
# if msg._from in admin:
# if msg.toType == 2:
# print "ok"
# _name = msg.text.replace("Kibar","")
# gs = ki.getGroup(msg.to)
# gs = kk.getGroup(msg.to)
#gs = kc.getGroup(msg.to)
# gs = kb.getGroup(msg.to)
# gs = kd.getGroup(msg.to)
# gs = ke.getGroup(msg.to)
# gs = kg.getGroup(msg.to)
# gs = kh.getGroup(msg.to)
# targets = []
# for g in gs.members:
# if _name in g.displayName:
# targets.append(g.mid)
# if targets == []:
# kk.sendText(msg.to,"Not found.")
# cl.sendContact(to, mid)
# cl.sendContact(to, Amid)
# cl.sendContact(to, Bmid)
# cl.sendContact(to, Cmid)
# cl.sendContact(to, Dmid)
#cl.sendContact(to, Emid)
# cl.sendMessage(msg.to, "ASSALAMUALAIKUM \nROOM KALIAN \nDAFTAR ..PENGGUSURAN \nDALAM TARGET KAMI \n\nNO COMEND \nNO BAPER \nNO BACOT \nNO DESAH \n\n\nWAR!!! WER!!! WOR!!!\nKENAPE LU PADA DIEM\nTANGKIS >NYET TANGKIS\n\n\nDASAR ROOM PEA KAGAK BERGUNA\nHAHAHAHHAHAHAHAHAHAHA\nGC LU MAU GUA SITA...!!!\n\n\n[SK]SOAK KILLER\n\nHADIR DI ROOM ANDA\n\nRATA GAK RATA YANG PENTING KIBAR \n\n\n>>>>>>BYE BYE <<<<<<\n\n\nDENDAM CARI KAMI\n\n<<<<<<<<<<>>>>>>>>>>\n\nhttp://line.me/ti/p/afr1z4l\nhttp://line.me/ti/p/~noto_ati2122")
# else:
# for target in targets:
# if not target in Bots and admin:
# try:
# klist=[cl,ki,kk,kc,kb,kd,ke,kg,kh]
# kicker=random.choice(klist)
# kicker.kickoutFromGroup(msg.to,[target])
# print (msg.to,[g.mid])
# except:
# cl.sendText(msg,to,"Group cleanse")
#.........................#..............##
elif "Mk " in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Mk ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
if not target in Bots and admin:
try:
cl.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
ki.sendText(msg.to,"Succes ")
kk.sendText(msg.to,"Bye")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
#-----------------------------------------------------------------------
elif "BL @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("BL @","")
_kicktarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _kicktarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found")
else:
for target in targets:
if not target in Bots and admin:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
cl.sendText(msg.to,"Succes ")
except:
cl.sendText(msg.to,"error")
elif "Sd" in msg.text:
if msg.from_ in admin:
wait["blacklist"] = {}
cl.sendText(msg.to,"Blacklist user succes dibersihkan")
elif "Sb" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
ban0 = msg.text.replace("Sb","")
ban1 = ban0.lstrip()
ban2 = ban1.replace("@","")
ban3 = ban2.rstrip()
_name = ban3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
cl.sendText(msg.to,"user does not exist")
pass
else:
for target in targets:
if not target in Bots and admin:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
cl.sendText(msg.to,"ヽ( ^ω^)ノ Success")
elif "Spam" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Spam ","")
_nametarget = _name.rstrip(' ')
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+ " ","")
tulisan = jmlh * (teks+"\n")
if txt[1] == "on":
if jmlh <= 10000:
for x in range(jmlh):
cl.sendText(msg.to, teks)
else:
cl.sendText(msg.to, "Melebihi Batas!!! ")
elif txt[1] == "off":
if jmlh <= 10000:
cl.sendText(msg.to, tulisan)
else:
cl.sendText(msg.to, "Melebihi Batas!!! ")
elif "Anjuu" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "Fuck"
_name = msg.text.replace("Anjuu","")
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found.")
else:
for target in targets:
if not target in Bots and admin:
try:
cl.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
pass
elif "Ban @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
ban0 = msg.text.replace("Ban @","")
ban1 = ban0.lstrip()
ban2 = ban1.replace("@","")
ban3 = ban2.rstrip()
_name = ban3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
cl.sendText(msg.to,"This contact can't is a blacklist")
pass
else:
for target in targets:
if not target in Bots and admin:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
cl.sendText(msg.to,"Done blacklist")
except:
cl.sendText(msg.to,"Done blacklist")
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😊\nKetik 「Creator」for contact admin")
#---------------------------------------------------------------------------------
elif "Js" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Js","")
gs = cl.getGroup(msg.to)
cl.sendText(msg.to,"「 mayhem ���\nmayhem is STARTING♪\n abort to abort♪")
cl.sendText(msg.to,"「 mayhem 」\nAll victims shall yell hul·la·ba·loo♪\nhələbəˈlo͞o hələbəˌlo͞o")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not Found")
else:
for target in targets:
if target not in Bots and admin:
try:
klist=[cl,ki,kk,kc,kb,kd,ke,kf,kg,kh,kj,kl,km,kn,ko,kp,kq]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
cl.sendText(msg.to,"Mayhem done")
#----------------------------------------------------------------------------------
elif "Ciak" in msg.text:
if msg.from_ in admin:
if msg.contentMetadata is not None:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
except:
cl.kickoutFromGroup(msg.to,[target])
else:
pass
elif "Sayang" in msg.text:
if msg.from_ in admin:
if msg.contentMetadata is not None:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
ki.kickoutFromGroup(msg.to,[target])
except:
ki.kickoutFromGroup(msg.to,[target])
else:
pass
#-----------------------------------------------
elif "Say " in msg.text:
if msg.from_ in admin:
string = msg.text.replace("Say ","")
if len(string.decode('utf-8')) <= 50:
ki.sendText(msg.to," " + string + " ")
kk.sendText(msg.to," " + string + " ")
kc.sendText(msg.to," " + string + " ")
kb.sendText(msg.to," " + string + " ")
kd.sendText(msg.to," " + string + " ")
ke.sendText(msg.to," " + string + " ")
kg.sendText(msg.to," " + string + " ")
kh.sendText(msg.to," " + string + " ")
kl.sendText(msg.to," " + string + " ")
elif "Bc: " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Bc: ","")
A = cl.getProfile()
n = cl.getGroupIdsJoined()
for manusia in n:
cl.sendText(manusia, (bctxt) + "\n\nBroadcast by : " + (A.displayName))
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😆\nKetik 「Creator」 for contact admin")
print "COMMENT DENIED"
elif "Respon" in msg.text:
if msg.from_ in admin:
s = cl.getProfile()
s1 = ki.getProfile()
s2 = kk.getProfile()
s3 = kc.getProfile()
s4 = kb.getProfile()
s5 = kd.getProfile()
s6 = ke.getProfile()
s7 = kg.getProfile()
s8 = kh.getProfile()
s9 = kl.getProfile()
cl.sendText(msg.to, s.displayName + " ready Har Har")
ki.sendText(msg.to, s1.displayName + " ready Har Har")
kk.sendText(msg.to, s2.displayName + " ready Har Har")
kc.sendText(msg.to, s3.displayName + " ready Har Har")
kb.sendText(msg.to, s4.displayName + " ready Har Har")
kd.sendText(msg.to, s5.displayName + " ready Har Har")
ke.sendText(msg.to, s6.displayName + " ready Har Har")
kg.sendText(msg.to, s7.displayName + " ready Har Har")
kh.sendText(msg.to, s8.displayName + " ready Har Har")
kl.sendText(msg.to, s9.displayName + " ready Har Har�")
#-----------------------------------------------
elif "Pict @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Pict @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
#-----------------------------------------------
elif msg.text in ["Respon"]:
if msg.from_ in admin:
cl.sendText(msg.to,"Hadirr")
ki.sendText(msg.to,"Hadiirrr")
kk.sendText(msg.to,"Hadirr")
kc.sendText(msg.to,"Hadirr")
kb.sendText(msg.to,"Hadiirrr")
kd.sendText(msg.to,"Hadirr")
ke.sendText(msg.to,"Hadirr")
kg.sendText(msg.to,"Hadiirrr")
kh.sendText(msg.to,"Hadirr")
kl.sendText(msg.to,"Hadirr Semua boooss..siap nikung Ampe anu,,")
#-----------------------------------------------
elif "Sp" in msg.text:
if msg.from_ in admin:
start = time.time()
cl.sendText(msg.to, "Progress ...")
elapsed_time = time.time() - start
cl.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
ki.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kk.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kc.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kb.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kd.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
ke.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kg.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kh.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
kl.sendText(msg.to, "%sseconds double thumbs up�" % (elapsed_time))
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😊\nKetik 「Creator」for contact admin")
print "COMMEND DENIED"
elif "speed" in msg.text:
if msg.from_ in admin:
start = time.time()
cl.sendText(msg.to, "Progress ...")
elapsed_time = time.time() - start
cl.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
ki.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
kk.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
kc.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
kb.sendText(msg.to, "%sseconds double thumbs up" % (elapsed_time))
else:
msg.contentType = 13
msg.contentMetadata = {"mid": msg.from_}
cl.sendMessage(msg)
cl.sendText(msg.to, "Acces denied for you 😊\nKetik 「Creator」for contact admin")
print "COMMEND DENIED"
elif "Cbc: " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Cbc: ", "")
contact = cl.getAllContactIds()
for cbc in contact:
cl.sendText(cbc,(bctxt))
#------------------------------------------------------------------
elif msg.text in ["Ban:on"]:
if msg.from_ in admin:
wait["wblacklist"] = True
cl.sendText(msg.to,"send contact to blacklist")
elif msg.text in ["Unban:on"]:
if msg.from_ in admin:
wait["dblacklist"] = True
cl.sendText(msg.to,"send contact to unblacklist")
elif msg.text in ["Banlist"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Nothing a blacklist user")
else:
cl.sendText(msg.to,"Blacklist user")
mc = "[●]「Blacklist User」[●]\n\n"
for mi_d in wait["blacklist"]:
mc += "~ " +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text in ["Cek ban"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
cocoa = ""
for mm in matched_list:
cocoa += mm + "\n"
cl.sendText(msg.to,cocoa + "")
elif msg.text in ["Kick ban"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
group = ki.getGroup(msg.to)
group = kk.getGroup(msg.to)
group = kc.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
cl.sendText(msg.to,"There was no blacklist user")
ki.sendText(msg.to,"There was no blacklist user")
kk.sendText(msg.to,"There was no blacklist user")
kc.sendText(msg.to,"There was no blacklist user")
return
for jj in matched_list:
cl.kickoutFromGroup(msg.to,[jj])
ki.kickoutFromGroup(msg.to,[jj])
kk.kickoutFromGroup(msg.to,[jj])
kc.kickoutFromGroup(msg.to,[jj])
cl.sendText(msg.to,"Blacklist user")
ki.sendText(msg.to,"Blacklist user")
kk.sendText(msg.to,"Blacklist user")
elif msg.text in [".."]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
cl.cancelGroupInvitation(msg.to,[_mid])
cl.sendText(msg.to,"")
#-----------------------------------------------------------------
if op.param3 == "1":
if op.param1 in Protectgroupmame:
group = cl.getGroup(op.param1)
try:
group.name = wait["Protectgrouname"][op.param1]
cl.updateGroup(group)
cl.sendText(op.param1, "Groupname protect now")
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except Exception as e:
print e
pass
if op.type == 17:
if wait["protectJoin"] == True:
if op.param2 not in Bots:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
if wait["protect"] == True:
if wait["blacklist"][op.param2] == True:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G = random.choice(KAC).getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
pass
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G = random.choice(KAC).getGroup(op.param1)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
pass
elif op.param2 not in admin + Bots:
random.choice(KAC).sendText(op.param1,"Welcome. Don't Play Bots. I can kick you!")
else:
pass
if op.type == 11:
if op.param3 == '1':
if op.param1 in wait['Gnamelock']:
try:
G = cl.getGroup(op.param1)
except:
try:
G = ki.getGroup(op.param1)
except:
try:
G = kk.getGroup(op.param1)
except:
try:
G = kb.getGroup(op.param1)
except:
try:
G = ki.getGroup(op.param1)
except:
try:
G = kc.getGroup(op.param1)
except:
pass
G.name = wait['Gnamelock'][op.param1]
try:
cl.updateGroup(G)
except:
try:
ki.updateGroup(G)
except:
try:
kk.updateGroup(G)
except:
try:
ke.updateGroup(G)
except:
try:
kc.updateGroup(G)
except:
try:
ke.updateGroup(G)
except:
pass
if op.param2 in Bots:
pass
else:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
kb.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ke.kickoutFromGroup(op.param1,[op.param2])
except:
pass
cl.sendText(op.param1,"Gnamelock")
ki.sendText(op.param1,"Haddeuh dikunci Pe'a")
kk.sendText(op.param1,"Wekawekaweka Har Har")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
cl.sendMessage(c)
if op.type == 17:
if op.param2 not in Bots:
joinblacklist = op.param2.replace(".",',')
joinblacklistX = joinblacklist.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, joinblacklistX)
if matched_list == []:
pass
else:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in wait["blacklist"]:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#--------------------------------------------------------------------------------
if op.type == 19:
if op.param3 in admin and op.param2 in Bots:
random.choice(KAC).inviteIntoGroup(op.param3)
random.choice(KAC).findAndAddContactsByMid(op.param3)
if op.type == 19:
if op.param3 in admin:
cl.inviteIntoGroup(op.param1,admin)
if op.type == 19:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["protect"] == True:
wait ["blacklist"][op.param2] = True
G = cl.getGroup(op.param1)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
else:
cl.sendText(op.param1,"Please contact admin for invite member")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3])
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
if op.type == 11:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["linkprotect"] == True:
wait ["blacklist"][op.param2] = True
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
Ticket = cl.reissueGroupTicket(op.param1)
sw.acceptGroupInvitationByTicket(op.param1,Ticket)
sw.kickoutFromGroup(op.param1,[op.param2])
cl.updateGroup(G)
sw.leaveGroup(op.param1)
else:
cl.sendText(op.param1,"")
else:
cl.sendText(op.param1,"")
#-----------------------------------------------------------------------------
if op.type == 46:
if op.param2 in Bots:
cl.removeAllMessages()
ki.removeAllMessages()
kk.removeAllMessages()
kc.removeAllMessages()
kb.removeAllMessages()
kd.removeAllMessages()
ke.removeAllMessages()
kg.removeAllMessages()
kh.removeAllMessages()
# kj.removeAllMessages()
#------------------------------------------------------------------------------
if op.type == 55:
print "NOTIFIED_READ_MESSAGE"
try:
if op.param1 in wait2['readPoint']:
Name = cl.getContact(op.param2).displayName
if Name in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += "\n• " + Name
wait2['ROM'][op.param1][op.param2] = "• " + Name
wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
else:
cl.sendText
except:
pass
if op.type == 59:
print op
except Exception as error:
print error
def autoSta():
count = 1
while True:
try:
for posts in cl.activity(1)["result"]["posts"]:
if posts["postInfo"]["liked"] is False:
if wait["likeOn"] == True:
cl.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ki.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kk.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kc.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kb.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kd.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
ke.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kg.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
kh.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
#kj.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# kf.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
#kl.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# km.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# kn.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# ko.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# kp.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
# kq.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
if wait["commentOn"] == True:
if posts["userInfo"]["writerMid"] in wait["commentBlack"]:
pass
else:
cl.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["Owner Guntur ponya selera I like you"])
except:
count += 1
if(count == 50):
sys.exit(0)
else:
pass
thread1 = threading.Thread(target=autoSta)
thread1.daemon = True
thread1.start()
def a2():
now2 = datetime.now()
nowT = datetime.strftime(now2,"%M")
if nowT[14:] in ["10","20","30","40","50","00"]:
return False
else:
return True
def nameUpdate():
while True:
try:
#while a2():
pass
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"(%H:%M)")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
time.sleep(500)
except:
pass
thread2 = threading.Thread(target=nameUpdate)
thread2.daemon = True
thread2.start()
while True:
try:
Ops = cl.fetchOps(cl.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(cl.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
cl.Poll.rev = max(cl.Poll.rev, Op.revision)
bot(Op)
|
[
"noreply@github.com"
] |
teguhstya37.noreply@github.com
|
447d207030446b3cd91cb058f6fe105dcbacf512
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02409/s416602191.py
|
dee7b6c05f16bb6a860e18a9b3312b8efc6cc907
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 617
|
py
|
rooms = []
rooms.append([[0 for i in range(10)] for j in range(3)])
rooms.append([[0 for i in range(10)] for j in range(3)])
rooms.append([[0 for i in range(10)] for j in range(3)])
rooms.append([[0 for i in range(10)] for j in range(3)])
num = int(raw_input())
for i in range(num):
b,f,r,v = map(int, raw_input().split())
rooms[b-1][f-1][r-1] += v
for number, room in enumerate(rooms):
for row in room:
print " %d %d %d %d %d %d %d %d %d %d" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9])
if len(rooms) - 1 > number:
print('####################')
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
bc55befbeb0cc497e41cb7b0ddb9dd914234680e
|
1abdbf49bf7c75ebf75f6d30e6c04747c84b927d
|
/utils/error_handlers.py
|
d0150925c3e8dc77dce4c4d5d018aa90ede0777c
|
[] |
no_license
|
JoseMOrellana/neuro_app_api
|
160577a0de1efa20934c1ee150d34abb591295ee
|
46797375afc66392452a08f28ee6ebee716d8c14
|
refs/heads/master
| 2022-11-20T01:18:46.880451
| 2020-07-24T13:33:07
| 2020-07-24T13:33:07
| 262,230,151
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 530
|
py
|
def handle_validation_error(err):
return { "success": False, "errors": err.messages}, 400
def handle_resource_exists_error(err):
return { "success": False, "errors": err.field}, 400
def handle_invalid_cred_error(err):
return { "success": False, "errors": "Contraseña invalida"}, 401
def handle_resource_not_found_error(err):
return { "success": False, "errors": "Recurso no encontrado"}, 404
def handle_authorization_error(err):
return { "success": False, "errors": "No tienes acceso a este recurso"}, 401
|
[
"jose.mom.1304@gmail.com"
] |
jose.mom.1304@gmail.com
|
f1cacd7bbdf2880bc9ac63c6488ca0063f980d24
|
b18c06ebabc4891543a19b9a5e52ea5162835f7e
|
/account/migrations/0067_auto_20180526_0457.py
|
986e99a506a3e23773490c473f76cb942f400ff7
|
[] |
no_license
|
hackerdem/Myshop
|
38456f3a8daac9e18d55ca1961dc3b8a3ff8b917
|
78ffc3c9b274896f35e65dbe0b55eb92411791d6
|
refs/heads/master
| 2021-06-06T10:56:22.962607
| 2018-11-27T04:01:54
| 2018-11-27T04:01:54
| 129,862,123
| 0
| 0
| null | 2020-06-05T18:23:54
| 2018-04-17T07:12:55
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 463
|
py
|
# Generated by Django 2.0.5 on 2018-05-25 18:57
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0066_auto_20180526_0457'),
]
operations = [
migrations.AlterField(
model_name='useractivation',
name='expire_date',
field=models.DateTimeField(default=datetime.datetime(2018, 5, 26, 4, 57, 17, 305701)),
),
]
|
[
"werdem@gmail.com"
] |
werdem@gmail.com
|
958c30491a26eb436963c2c28b757c4584545ed9
|
c73a1f4c46cff357b1967044fc840646b2034863
|
/test/functional/zerocoin_valid_public_spend.py
|
0a18308b1a8b53b7f9e44208484f15a5c4dbc081
|
[
"MIT"
] |
permissive
|
Palem1988/ion
|
2c493ac33b7d2cc067d971973db7c5e0bdd7b02a
|
1c522cacbf63ebff3e6e52d4a9e2b5be425b86af
|
refs/heads/master
| 2020-08-05T07:48:54.758982
| 2019-09-04T11:12:18
| 2019-09-04T11:12:18
| 212,452,545
| 0
| 1
|
MIT
| 2019-10-02T22:25:26
| 2019-10-02T22:25:19
| null |
UTF-8
|
Python
| false
| false
| 3,683
|
py
|
#!/usr/bin/env python3
# Copyright (c) 2019 The ion Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Covers the 'Wrapped Serials Attack' scenario
'''
import random
from time import sleep
from test_framework.authproxy import JSONRPCException
from test_framework.util import assert_equal, assert_greater_than
from fake_stake.base_test import ION_FakeStakeTest
class xIONValidCoinSpendTest(ION_FakeStakeTest):
def run_test(self):
self.description = "Covers the 'valid publicCoinSpend spend' scenario."
self.init_test()
INITAL_MINED_BLOCKS = 301 # Blocks mined before minting
MORE_MINED_BLOCKS = 52 # Blocks mined after minting (before spending)
DENOM_TO_USE = 1 # zc denomination used for double spending attack
# 1) Start mining blocks
self.log.info("Mining %d first blocks..." % INITAL_MINED_BLOCKS)
self.node.generate(INITAL_MINED_BLOCKS)
sleep(2)
# 2) Mint zerocoins
self.log.info("Minting %d-denom xIONs..." % DENOM_TO_USE)
self.node.mintzerocoin(DENOM_TO_USE)
self.node.generate(1)
sleep(2)
self.node.mintzerocoin(DENOM_TO_USE)
sleep(2)
# 3) Mine more blocks and collect the mint
self.log.info("Mining %d more blocks..." % MORE_MINED_BLOCKS)
self.node.generate(MORE_MINED_BLOCKS)
sleep(2)
list = self.node.listmintedzerocoins(True, True)
mint = list[0]
# 4) Get the raw zerocoin data
exported_zerocoins = self.node.exportzerocoins(False)
zc = [x for x in exported_zerocoins if mint["serial hash"] == x["id"]]
if len(zc) == 0:
raise AssertionError("mint not found")
# 5) Spend the minted coin (mine six more blocks)
self.log.info("Spending the minted coin with serial %s and mining six more blocks..." % zc[0]["s"])
txid = self.node.spendzerocoinmints([mint["serial hash"]])['txid']
self.log.info("Spent on tx %s" % txid)
self.node.generate(6)
sleep(2)
rawTx = self.node.getrawtransaction(txid, 1)
if rawTx is None:
self.log.warning("rawTx is: %s" % rawTx)
raise AssertionError("TEST FAILED")
else:
assert (rawTx["confirmations"] == 6)
self.log.info("%s VALID PUBLIC COIN SPEND PASSED" % self.__class__.__name__)
self.log.info("%s Trying to spend the serial twice now" % self.__class__.__name__)
serial = zc[0]["s"]
randomness = zc[0]["r"]
privkey = zc[0]["k"]
tx = None
try:
tx = self.node.spendrawzerocoin(serial, randomness, DENOM_TO_USE, privkey)
except JSONRPCException as e:
self.log.info("GOOD: Transaction did not verify")
if tx is not None:
self.log.warning("Tx is: %s" % tx)
raise AssertionError("TEST FAILED")
self.log.info("%s DOUBLE SPENT SERIAL NOT VERIFIED, TEST PASSED" % self.__class__.__name__)
self.log.info("%s Trying to spend using the old coin spend method.." % self.__class__.__name__)
tx = None
try:
tx = self.node.spendzerocoin(DENOM_TO_USE, False, False, "", False)
raise AssertionError("TEST FAILED, old coinSpend spent")
except JSONRPCException as e:
self.log.info("GOOD: spendzerocoin old spend did not verify")
self.log.info("%s OLD COIN SPEND NON USABLE ANYMORE, TEST PASSED" % self.__class__.__name__)
if __name__ == '__main__':
xIONValidCoinSpendTest().main()
|
[
"fornaxa@servitising.org"
] |
fornaxa@servitising.org
|
03b0a19df17d2da31bf136b854c693146421f2c4
|
42bef12a3128fb79676a91d57595ca6abec96544
|
/django_orm/Dojo_Ninjas/Dojo_Ninjas/settings.py
|
d3ace3fea2ef9ffc360933bb47fd29e15749b917
|
[] |
no_license
|
chizakirov/django
|
c8bea894d355a72977ecfe86192b7b827fb1f3ea
|
b297b21c38b06d4bc9cd1a248a2ee7626c317cee
|
refs/heads/master
| 2020-04-14T21:50:28.093270
| 2019-01-04T18:48:23
| 2019-01-04T18:48:23
| 164,142,083
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,134
|
py
|
"""
Django settings for Dojo_Ninjas project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x1x7%!a=2lq_4uq6d(3th#)to2i_0lh7d#vc#(g2j@6eo379rk'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'apps.ninjas_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'Dojo_Ninjas.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 = 'Dojo_Ninjas.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/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.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
|
[
"nguyen.chi.byu@gmail.com"
] |
nguyen.chi.byu@gmail.com
|
29b139a3fbb741b9ce9c518d7ab92bcfbd1b268b
|
c67e91c805b70768011ee810f0beddd8aee65210
|
/src/src/prueva.py
|
a943ca9b05452e063700c08d00579ea929e7343b
|
[] |
no_license
|
alu0100791303/Grupo1-C
|
167197d01f972f75c82730cadcda194a573821c8
|
c1ab20ac48c665ff524a9dd22b23bb7393bb3e95
|
refs/heads/master
| 2021-01-18T23:11:06.078096
| 2013-04-05T12:30:28
| 2013-04-05T12:30:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 22
|
py
|
print ("modificacion")
|
[
"alu0100776324@ull.edu.es"
] |
alu0100776324@ull.edu.es
|
af0320af67bf194e80a879ac34b379701b54d5de
|
32983b56175f7b7f54cbd90acaaf344d62fb9828
|
/EDEN_PROGRAMS/drawplayer.py
|
b73492216c7c8ae6379f165bb7a458666f6d19dd
|
[] |
no_license
|
NEIGHFAN/idk4
|
1f808148b49f6d3bf655c09244631f87970bae51
|
c00b571f94b7e88b22f0fbdd47443948e4867388
|
refs/heads/main
| 2023-01-28T15:48:39.360910
| 2020-12-01T09:53:51
| 2020-12-01T09:53:51
| 317,488,638
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,688
|
py
|
def go():
import pygame,time,Eden,os,random
global P,player
P = Eden.PF
pygame.init()
## foot1 = pygame.mixer.Sound('foot1.wav')
## foot2 = pygame.mixer.Sound('foot2.wav')
## foot3 = pygame.mixer.Sound('foot3.wav')
## foot4 = pygame.mixer.Sound('foot4.wav')
## foot5 = pygame.mixer.Sound('foot5.wav')
feet = [foot1,foot2,foot3,foot4,foot5]
foot = feet[random.randint(0,4)]
FACE = (255,0,0,255)
EYES = (0,127,255,255)
HAT = (255,0,255,255)
HAIR = (127,0,255,255)
FHAIR = (255,255,0,255)
HATS = (255,0,127,255)
HATB = (0,255,127,255)
BODY = (0,0,255,255)
SHOULDERS = (127,0,0,255)
ARMS = (127,0,127,255)
GLOVES = (0,0,0,255)
LEGS = (0,255,0,255)
DRESS = (127,255,0,255)
SHOES = (0,255,255,255)
cred = Eden.cred
cgreen = Eden.cgreen
cblue = Eden.cblue
face = (cred[0],cgreen[0],cblue[0],255)
hat = (cred[1],cgreen[1],cblue[1],255)
hats = (cred[2],cgreen[2],cblue[2],255)
hair = (cred[3],cgreen[3],cblue[3],255)
body = (cred[4],cgreen[4],cblue[4],255)
arms = (cred[5],cgreen[5],cblue[5],255)
legs = (cred[6],cgreen[6],cblue[6],255)
shoes = (cred[7],cgreen[7],cblue[7],255)
gloves = (cred[8],cgreen[8],cblue[8],255)
shoulders = (cred[9],cgreen[9],cblue[9],255)
os.chdir('../EDEN_PICS')
pI = pygame.image.load('playerB-i.png')
pB = pygame.image.load('playerB.png')
pB1 = pygame.image.load('playerB-r1.png')
pB2 = pygame.image.load('playerB-r2.png')
pB3 = pygame.transform.flip(pB1,True,False)
pB4 = pygame.transform.flip(pB2,True,False)
pw = [pB,pB1,pB2,pB1,pB,pB3,pB4,pB3]
pF = pygame.image.load('playerF.png')
pF1 = pygame.image.load('playerF-r1.png')
pF2 = pygame.image.load('playerF-r2.png')
pF3 = pygame.transform.flip(pF1,True,False)
pF4 = pygame.transform.flip(pF2,True,False)
ps = [pF,pF1,pF2,pF1,pF,pF3,pF4,pF3]
pL = pygame.image.load('playerS.png')
pL1 = pygame.image.load('playerS-r1.png')
pL2 = pygame.image.load('playerS-r2.png')
pL3 = pygame.image.load('playerS-r3.png')
pL4 = pygame.image.load('playerS-r4.png')
pa = [pL,pL1,pL2,pL1,pL,pL3,pL4,pL3]
pR = pygame.transform.flip(pL,True,False)
pR1 = pygame.transform.flip(pL1,True,False)
pR2 = pygame.transform.flip(pL2,True,False)
pR3 = pygame.transform.flip(pL3,True,False)
pR4 = pygame.transform.flip(pL4,True,False)
pd = [pR,pR1,pR2,pR1,pR,pR3,pR4,pR3]
if Eden.player_direction == 0:
player = pB
if Eden.W == 1 and Eden.moveup == 1:
player = pw[P]
if P == (2 or 6):
Eden.channel2.play(foot)
P += 1
if P >= len(pw):
P = 0
elif Eden.player_direction == 1:
player = pF
if Eden.S == 1 and Eden.movedown == 1:
player = ps[P]
if P == (2 or 6):
Eden.channel2.play(foot)
P += 1
if P >= len(ps):
P = 0
elif Eden.player_direction == 2:
player = pR
if Eden.D == 1 and Eden.moveright == 1:
player = pd[P]
if P == (2 or 6):
Eden.channel2.play(foot)
P += 1
if P >= len(pd):
P = 0
elif Eden.player_direction == 3:
player = pL
if Eden.A == 1 and Eden.moveleft == 1:
player = pa[P]
if P == (2 or 6):
Eden.channel2.play(foot)
P += 1
if P >= len(pa):
P = 0
if Eden.doing == 1:
if Eden.igrid[Eden.gy][Eden.gx] == 1:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 2:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 3:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 4:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 5:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 6:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 7:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 8:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 9:
player = pI
Eden.player_direction = 0
elif Eden.igrid[Eden.gy][Eden.gx] == 10:
player = pI
Eden.player_direction = 0
bplayer = player
col = []
for i in range(30):
col.append(0)
row = []
for i in range(30):
row.append(col)
for i in range(30):
for j in range(30):
row[i][j] = (player.get_at((i,j)))
if row[i][j] == FACE:
player.set_at((i,j),face)
elif row[i][j] == HAT:
if Eden.Hat == 1:
player.set_at((i,j),hat)
else:
player.set_at((i,j),hair)
elif row[i][j] == HATS:
if Eden.Hat == 1:
player.set_at((i,j),hats)
else:
player.set_at((i,j),hair)
elif row[i][j] == HATB:
if Eden.Hat == 1:
player.set_at((i,j),hat)
else:
player.set_at((i,j),(0,0,0,0))
elif row[i][j] == HAIR:
player.set_at((i,j),hair)
elif row[i][j] == FHAIR:
if Eden.Fhair == 1:
player.set_at((i,j),hair)
else:
player.set_at((i,j),face)
elif row[i][j] == BODY:
player.set_at((i,j),body)
elif row[i][j] == SHOULDERS:
player.set_at((i,j),shoulders)
elif row[i][j] == ARMS:
player.set_at((i,j),arms)
elif row[i][j] == GLOVES:
player.set_at((i,j),gloves)
elif row[i][j] == LEGS:
player.set_at((i,j),legs)
elif row[i][j] == DRESS:
if Eden.Dress == 1:
player.set_at((i,j),legs)
else:
player.set_at((i,j),(0,0,0,0))
elif row[i][j] == SHOES:
player.set_at((i,j),shoes)
elif row[i][j] == EYES:
player.set_at((i,j),(0,0,0,255))
else:
player.set_at((i,j),(0,0,0,0))
#if player.get_at((0,0)) == (0,0,0,255):
# go()
if Eden.custom == 1:
player = pygame.transform.scale(player, (300, 300))
Eden.screen.blit(player,(390,225))
elif Eden.custom == 0:
Eden.screen.blit(player,(360,360))
## bplayer.set_colorkey((255,255,255,255))
## print(bplayer.get_at((0,0)))
## col = []
## for i in range(30):
## col.append(0)
## row = []
## for i in range(30):
## row.append(col)
## for i in range(30):
## for j in range(30):
## row[i][j] = (bplayer.get_at((i,j)))
## if row[i][j] != (255,255,255):
## bplayer.set_at((i,j),(0,0,0,Eden.shade))
## Eden.screen.blit(bplayer,(360,360))
Eden.PF = P
|
[
"noreply@github.com"
] |
NEIGHFAN.noreply@github.com
|
f13404af12d2c8daaff902941c02cd497a4d467d
|
34ea37d52888e33511ad243989231f653b7622e2
|
/citizen_code/02_datascience_report1/lassoCV.py
|
c632e4f0a7d7253c48c5aa1cd764d70731a5a370
|
[] |
no_license
|
whcitizen/citizen_code
|
45364dd4a7ba64f0f29265c215470deecbd3158d
|
c19033000394c9e07b83e061890dc9b4e07fbd92
|
refs/heads/master
| 2021-09-11T19:05:55.799800
| 2018-04-11T06:15:43
| 2018-04-11T06:15:43
| 111,392,702
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,074
|
py
|
import numpy as np
import pandas as pd
from sklearn import linear_model
N = 10000
nfeat = 53
train_data = pd.read_csv("train.csv", header=None)
test_data = pd.read_csv("test.csv", header=None)
Train_X = train_data.iloc[:N, 0:nfeat].values
Test_X = train_data.iloc[N:, 0:nfeat].values
Train_Y = train_data.iloc[:N, 53].values.T
Test_Y = train_data.iloc[N:, 53].values.T
lasso_cv = linear_model.LassoCV()
lasso_cv.fit(Train_X, Train_Y)
lasso = linear_model.Lasso(alpha=lasso_cv.alpha_)
lasso.fit(Train_X, Train_Y)
c = np.array(lasso.coef_)
yHatTrain = np.dot(Train_X, c)
for i in range(0, len(yHatTrain)):
if yHatTrain[i] < 0:
yHatTrain[i] = 0
yHatVal = np.dot(Test_X, c)
for i in range(0, len(yHatVal)):
if yHatVal[i] < 0:
yHatVal[i] = 0
print("Training error ", np.mean(np.abs(Train_Y - yHatTrain.T)))
print("Validation error ", np.mean(np.abs(Test_Y - yHatVal.T)))
"""
yHatTest = np.dot(np.array(test_data), c)
for i in range(0, len(yHatTest)):
if yHatTest[i] < 0:
yHatTest[i] = 0
np.savetxt('result_lassoCV.txt', yHatTest)
"""
|
[
"33275297+whcitizen@users.noreply.github.com"
] |
33275297+whcitizen@users.noreply.github.com
|
ecb09c7da625691534c85f7cacc5cec490fda3e9
|
5f0357530eca8f2ad57f914bc471fb83c91cee5b
|
/examples/power-supplies/hp54501a-cem.py
|
94aaa57f0a78cbda92b2ba5d5cad7378fd8e250f
|
[] |
no_license
|
liujin142703/anccontrol_github
|
279283ace975e55b8804dfa919dca313c2377e81
|
7274ef4228e1ed23252dce28f0958c8266c95614
|
refs/heads/master
| 2023-02-27T00:33:56.379866
| 2021-02-06T15:58:54
| 2021-02-06T15:58:54
| 334,120,047
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,373
|
py
|
# r# ================
# r# CEM Simulation
# r# ================
# r# This example show a CEM simulation.
# Fixme: retrieve PDF reference and complete
####################################################################################################
import matplotlib.pyplot as plt
####################################################################################################
import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()
####################################################################################################
from PySpice.Doc.ExampleTools import find_libraries
from PySpice.Probe.Plot import plot
from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit import *
####################################################################################################
libraries_path = find_libraries()
spice_library = SpiceLibrary(libraries_path)
####################################################################################################
from HP54501A import HP54501A
#f# literal_include('HP54501A.py')
####################################################################################################
circuit = Circuit('HP54501A CEM')
circuit.include(spice_library['1N4148'])
diode_model = '1N4148'
ac_line = circuit.AcLine('input', 'input', circuit.gnd, rms_voltage=230 @ u_V, frequency=50 @ u_Hz)
# circuit.subcircuit(HP54501A(diode_model='1N4148'))
# circuit.X('hp54501a', 'HP54501A', 'input', circuit.gnd)
circuit.C(1, 'input', circuit.gnd, 1 @ u_uF)
circuit.X('D1', diode_model, 'line_plus', 'top')
circuit.X('D2', diode_model, 'scope_ground', 'input')
circuit.X('D3', diode_model, circuit.gnd, 'top')
circuit.X('D4', diode_model, 'scope_ground', circuit.gnd)
circuit.R(1, 'top', 'output', 10 @ u_Ω)
circuit.C(2, 'output', 'scope_ground', 50 @ u_uF)
circuit.R(2, 'output', 'scope_ground', 900 @u_Ω)
simulator = circuit.simulator(temperature=25, nominal_temperature=25)
analysis = simulator.transient(step_time=ac_line.period / 100, end_time=ac_line.period*3)
figure = plt.figure(None, (20, 6))
plot(analysis.input)
plot(analysis.Vinput)
plot(analysis.output - analysis.scope_ground)
plt.legend(('Vin [V]', 'I [A]'), loc=(.8,.8))
plt.grid()
plt.xlabel('t [s]')
plt.ylabel('[V]')
plt.show()
#f# save_figure('figure', 'hp54501a-cem.png')
|
[
"liu.jin@zgmicro.com"
] |
liu.jin@zgmicro.com
|
680307ba370397cf8fb88357befe4cbb004b55f8
|
d725e34490665a222654ac5bdde93a689a647844
|
/utils/nms.py
|
b8ffc118832765d10dced0754ec55f188e9c2f59
|
[] |
no_license
|
Zumbalamambo/tfmtcnn
|
e271cf0814c4f4f93d5ca2dcf28743587fb69365
|
24f5b8462589ebd654ac3bce04fa9351dc3a2d5f
|
refs/heads/master
| 2020-03-23T16:45:08.744242
| 2018-05-03T03:56:32
| 2018-05-03T03:56:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,044
|
py
|
# MIT License
#
# Copyright (c) 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import numpy as np
def py_nms(dets, thresh, mode="Union"):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
if mode == "Union":
ovr = inter / (areas[i] + areas[order[1:]] - inter)
elif mode == "Minimum":
ovr = inter / np.minimum(areas[i], areas[order[1:]])
#keep
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return( keep )
|
[
"pritam.shete@gmail.com"
] |
pritam.shete@gmail.com
|
81db00d0c17b0a8ea2f7b5e61632ee140d81b62a
|
28bdb23378998474e9ad2185fa310f203bdedb90
|
/501/lab5.py
|
77ba5b8a24320b70db61889295a1d5ca8cbc017e
|
[] |
no_license
|
Audakel/byu_cs
|
cf15d813fe876df5b0527230315253bba54d2c16
|
3a62f586d9f8a855ac96fc2bc5dfc67fbaacfb12
|
refs/heads/master
| 2021-01-18T20:25:12.529927
| 2017-03-12T01:57:28
| 2017-03-12T01:57:28
| 72,134,053
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,215
|
py
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A very simple MNIST classifier.
See extensive documentation at
http://tensorflow.org/tutorials/mnist/beginners/index.md
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import data
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import time
start = time.time()
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
sess = tf.InteractiveSession()
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# Train
tf.initialize_all_variables().run()
for i in range(50001):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x: batch_xs, y_: batch_ys})
if i % 10000 == 0:
print('@', "{:,}".format(i), 'epochs')
# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('accuracy: ', accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
end = time.time()
print('elapsed time: ', end - start, ' seconds')
|
[
"audakel@gmail.com"
] |
audakel@gmail.com
|
5af654857f3cf6065a8ec90dc0778f42d1ba1560
|
fc97f415df3fba0f29a52ac151b6120fdfe1eb58
|
/scripts/fileserver
|
63a9c1e28752deff67c54e88ff61c02fc16d7489
|
[
"MIT"
] |
permissive
|
HiPERCAM/hcam-drivers
|
ab4045eea3f4a7a82474e4d2ae69dfbeff028032
|
c183be2ea29462e3fd76bdef8865a11e75c67402
|
refs/heads/master
| 2023-08-11T04:13:56.868218
| 2023-07-27T20:27:06
| 2023-07-27T20:27:06
| 73,546,291
| 0
| 0
|
MIT
| 2023-07-27T20:27:08
| 2016-11-12T10:33:00
|
Python
|
UTF-8
|
Python
| false
| false
| 4,411
|
#!/usr/bin/env python
from __future__ import print_function, division, unicode_literals
import glob
import os
import tornado.ioloop
from tornado.web import Application, url
from tornado import websocket
import json
from hcam_drivers.utils.web import BaseHandler, FastFITSPipe
class MainHandler(BaseHandler):
def initialize(self, db):
self.db = db
def get(self, path):
try:
action = self.get_argument('action')
except:
raise tornado.web.HTTPError(400)
if action == "dir":
self.list_dir(self.db['dir'], path)
else:
raise tornado.web.HTTPError(400)
def list_dir(self, root, stub):
path = os.path.abspath(os.path.join(root, stub, "*.fits"))
files = [os.path.splitext(
os.path.basename(file))[0] for file in glob.glob(path)]
self.write("\n".join(files))
class RunHandler(websocket.WebSocketHandler):
def initialize(self, db):
self.db = db
def check_origin(self, origin):
# allow cross-origin connections
return True
def open(self, run_id):
print('Connection opened to access {}'.format(run_id))
self.run_id = run_id
try:
self.ffp = self.get_ffp(run_id)
self.write_message({'status': 'OK'})
except IOError:
print('No such run: ', run_id)
self.write_message({'status': 'no such run'})
self.close(reason='no such run')
def on_message(self, message):
msg = json.loads(message)
action = msg['action']
if action == 'get_frame':
self.get_frame(msg['frame_number'])
elif action == 'get_hdr':
self.get_main_header()
elif action == 'get_next':
self.get_next_frame()
elif action == 'get_nframes':
self.get_nframes()
elif action == 'get_last':
self.get_last_frame()
def on_close(self):
print('Socket closed')
if hasattr(self, 'ffp'):
self.ffp._fileobj.close()
def get_ffp(self, run_id):
fname = '{}.fits'.format(run_id)
path = os.path.join(self.db['dir'], fname)
return FastFITSPipe(open(path, 'rb'))
def get_main_header(self):
"""
Send main FITS HDU as txt
"""
hdr = self.ffp.hdr
self.write_message(hdr.tostring())
def get_frame(self, frame_id):
"""
Read data from HDU in FITS file and send FITS HDUs as binary data
"""
try:
self.ffp.seek_frame(frame_id)
except IOError:
print('No such frame: ', frame_id)
self.write_message({'status': 'no such frame'})
self.close(reason='no such frame')
self._send_frame()
def get_last_frame(self):
self.get_frame(self.ffp.num_frames)
def get_nframes(self):
"""
Return current number of frames
"""
self.write_message({'nframes': self.ffp.num_frames})
def _send_frame(self):
try:
fits_bytes = self.ffp.read_frame_bytes()
except EOFError:
# frame is not ready yet, so send empty bytes
fits_bytes = b''
# write the stuff
self.write_message(fits_bytes, binary=True)
def get_next_frame(self):
self._send_frame()
def make_app(db, debug):
return Application([
# url routing. look for runXXX pattern first, assume everything else
# is a directory for e.g uls
url(r"/(.*run[0-9]+)", RunHandler, dict(db=db)),
url(r"/(.*)", MainHandler, dict(db=db), name="path")
], debug=debug)
def run_fileserver(dir, debug):
# we pass around current run and reference to open fits object
# to minimise the overheads associated with each request.
# this will break if the fileserver is run with multiple processes!
db = {'dir': dir}
app = make_app(db, debug)
app.listen(8007)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="HiPERCAM FileServer")
parser.add_argument('--dir', action='store', default='.', help="directory to serve")
parser.add_argument('--debug', action='store_true', help="debug fileserver")
args = parser.parse_args()
run_fileserver(os.path.abspath(args.dir), args.debug)
|
[
"s.littlefair@shef.ac.uk"
] |
s.littlefair@shef.ac.uk
|
|
9cc1666c64b9a661eff286387e88873b682126e0
|
d67de89260ea46ed62546b657d2087da3aa04b1d
|
/hr1.py
|
33e730db010ee47eedd50624e056948339b3ed63
|
[] |
no_license
|
jefinagilbert/problemSolving
|
534455fd2df56e8a12744571ab24a0254d85d336
|
9f3d165866dd82a9b08119e65f2eeb66bae3c434
|
refs/heads/main
| 2023-06-14T15:17:58.938962
| 2021-07-10T18:02:30
| 2021-07-10T18:02:30
| 366,144,499
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 635
|
py
|
if __name__ == '__main__':
N = int(input())
l = []
k = 0
entry = input().split()
rc = entry[0]
while N > k:
if "append" == rc:
l.append(entry[1])
elif "insert" == rc:
l.insert(int(entry[1]),int(entry[2]))
elif "remove" == rc:
l.remove(int(entry[1]))
elif "reverse" == rc:
l.reverse()
elif "pop" == rc:
l.pop()
elif "print" == rc:
print(l)
elif "sort" == rc:
l.sort()
else:
print("invalid")
k += 1
|
[
"noreply@github.com"
] |
jefinagilbert.noreply@github.com
|
ed5d414bf4400b0c909b6d42dcc8f93d0848c144
|
13514a2b5e567aaed826c1822a1835cddef6f622
|
/Variables.py
|
ee99bc9223321a648abd32f695aede78f5f4d6e8
|
[] |
no_license
|
Rishav190895/Python_Basics
|
86bdd8a9d01f73320c2fe7802d94386e4b745032
|
e6188645bfc7aaa154e0068f913c2f6b32c441f9
|
refs/heads/master
| 2020-08-23T23:55:57.126689
| 2019-09-29T13:08:43
| 2019-09-29T13:08:43
| 216,727,905
| 0
| 0
| null | 2019-10-22T05:10:37
| 2019-10-22T05:10:36
| null |
UTF-8
|
Python
| false
| false
| 611
|
py
|
#------------------Variables-------------------
var_str1 = "hello world " #string variables
var_str2 ="john wick"
variable_int = 45 #integer variable
variable_flot = 23.988 #float_varibale
print(var_str1+var_str2) #concatinating two stings
print(variable_int+variable_flot) #adding int and float value
#-------------adding_two_numbers------------------------
""" uncomment the single line comment for given below to run the program"""
# number2=int(input("Please Enter the 1st number: "))
# number1=int(input("please Enter the 2nd number: "))
# print(f"the sum of given numbers is {number1+number2}")
|
[
"noreply@github.com"
] |
Rishav190895.noreply@github.com
|
ad283e8c2c7c8ad34472eafefef19795d0688c5e
|
9053bc7a81b319cff00aff73ea2d138739a3050d
|
/test.py
|
1e7bf466809154bebb57e457f21cdec191972e83
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
itoshikihiro/BioSPPy
|
e49af6340477c003d8e80785f7abba36d16976ba
|
dfb324527cdeffcdc1e2f6943c391c6109e64c85
|
refs/heads/master
| 2020-03-28T06:30:22.535961
| 2018-09-13T01:59:24
| 2018-09-13T01:59:24
| 147,839,625
| 0
| 0
| null | 2018-09-07T15:08:59
| 2018-09-07T15:08:59
| null |
UTF-8
|
Python
| false
| false
| 4,720
|
py
|
from biosppy import storage
from biosppy.signals import ecg
from biosppy.signals import bvp
from biosppy.signals import eda
from biosppy.signals import resp
from biosppy.signals import emg
from multiprocessing import Process
# THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING
# A TUTOR OR CODE WRITTEN BY OTHER STUDENTS - Jie Lin
# Python 3
#coding=utf-8
"""
@version: 1.1
@author: Jie Lin
@Mail: jlin246@emory.edu
@file: test.py
@time: 09/11/2018 12:39am
@purpose: this is a test file to try out different methods in Bioppy
@code environment: ubuntu 18.01
"""
# plot a graph of ecg
def plotEcg(ecgSignal):
print();
# to tell user what should be done if they want to continue
print("plotting the graph. Close the graph windows to continue in order to continue this program");
# process it and plot
# signal is equal to raw ecg data, which is passed from main method
# the rest parameters are set to default
ecgGraph = ecg.ecg(signal=ecgSignal);
# plot a graph of bvp
def plotBvp(bvpSignal):
print();
# to tell user what should be done if they want to continue
print("plotting the graph. Close the graph windows to continue in order to continue this program");
# process it and plot
# signal is equal to bvp data, which is passed from main method
# the rest parameters are set to default
bvpGraph = bvp.bvp(signal=bvpSignal);
# plot a graph of eda
def plotEda(edaSignal):
print();
# to tell user what should be done if they want to continue
print("plotting the graph. Close the graph windows to continue in order to continue this program");
# process it and plot
# signal is equal to eda data, which is passed from main method
# the rest parameters are set to default
edaGraph = eda.eda(signal=edaSignal);
# plot a graph of resp
def plotResp(respSignal):
print();
# to tell user what should be done if they want to continue
print("plotting the graph. Close the graph windows to continue in order to continue this program");
# process it and plot
# signal is equal to resp data, which is passed from main method
# the rest parameters are set to default
respGraph = resp.resp(signal=respSignal);
# plot a graph of emg
def plotEmg(emgSignal):
print();
# to tell user what should be done if they want to continue
print("plotting the graph. Close the graph windows to continue in order to continue this program");
# process it and plot
# signal is equal to emg data, which is passed from main method
# the rest parameters are set to default
emgGraph = emg.emg(signal=emgSignal);
#show two emg plotting, for user to compare them easily
def compareEmgs(emgSignal1, emgSignal2):
print();
processEmgPlot1 = Process(target=plotEmg, args=(emgSignal1,));
processEmgPlot2 = Process(target=plotEmg, args=(emgSignal2,));
#start processes
processEmgPlot1.start();
processEmgPlot2.start();
#join to main process
processEmgPlot1.join();
processEmgPlot2.join();
#the main method
if __name__ == '__main__':
# load raw ECG signal
# ecgSignal stores the actual ecg data. ecgMdata stores what is commented in the ect.txt
ecgSignal, ecgMdata = storage.load_txt('./examples/ecg.txt');
# load raw bvp signal
bvpSignal, bvpMdata = storage.load_txt('./examples/bvp.txt');
# load eda signal
edaSignal, edaMdata = storage.load_txt('./examples/eda.txt');
# load resp signal
respSignal, respMdata = storage.load_txt('./examples/resp.txt');
# load emg signal
emgSignal1, emgMdata1 = storage.load_txt('./examples/emg.txt');
# load emg_1 signal
emgSignal2, emgMdata2 = storage.load_txt('./examples/emg_1.txt');
#start multi processing, because I want to see both graphs at the same time
# processEcgPlot = Process(target=plotEcg, args=(ecgSignal,));
# processBvpPlot = Process(target=plotBvp, args=(bvpSignal,));
# processEdaPlot = Process(target=plotEda, args=(edaSignal,));
# processRespPlot = Process(target=plotResp, args=(respSignal,));
# processEmgPlot1 = Process(target=plotEmg, args=(emgSignal1,));
# processEmgPlot2 = Process(target=plotEmg, args=(emgSignal2,));
# #
# #
# # #start threads
# processEcgPlot.start();
# processBvpPlot.start();
# processEdaPlot.start();
# processRespPlot.start();
# processEmgPlot1.start();
# processEmgPlot2.start();
# #
# # #join thread to the main thread
# processEcgPlot.join();
# processBvpPlot.join();
# processEdaPlot.join();
# processRespPlot.join();
# processEmgPlot1.join();
# processEmgPlot2.join();
compareEmgs(emgSignal1,emgSignal2);
|
[
"jlin246@emory.edu"
] |
jlin246@emory.edu
|
36e962e903c70e96aec834a4a1a6cc7e2c3dd42f
|
a09a988c92c82d43e58db91fd75f56706399b36b
|
/src/niwi/feeds.py
|
ab71da3a8b4954027c1cf41b1def5d8553f50f8f
|
[
"BSD-2-Clause"
] |
permissive
|
jespino/niwi-web
|
2fbf4d6452af96a5182af5217cb986b92b399c49
|
116952687669ef8511bb9d052f5a6c9a41960e97
|
refs/heads/master
| 2021-01-18T07:58:05.015043
| 2011-10-26T20:08:41
| 2011-10-26T20:08:41
| 2,393,976
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 702
|
py
|
# -*- coding: utf-8 -*-
# Thanks to Vladimir Epifanov <voldmar@voldmar.ru>
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from django.contrib.markup.templatetags.markup import markdown
from django.utils.translation import ugettext_lazy as _
from niwi.models import Post, Page
class LatestPostsFeed(Feed):
feed_type = Atom1Feed
title = _(u'Ultimas entradas')
link = '/'
def items(self):
return Post.objects.filter(status="public").order_by('-created_date')[:10]
def item_title(self, item):
return item.title
def item_description(self, item):
# TODO: fix this
return markdown(item.content)
|
[
"niwi@niwi.be"
] |
niwi@niwi.be
|
f9c94419fc5018394e09af6a1bb8bcc6f7b84521
|
e36910a24fd202d1b9364380411dd0cbecde4d09
|
/wiki/documents/admin.py
|
ac10fb185ed9c007bcdc4f7bacbf56fcd70321aa
|
[] |
no_license
|
neharamakanth/Passfort-Assignment
|
b9edb55c7dc95c4164cd7da7b12593b2ce6f18c3
|
817c51d35f38b96721a9474216c51aecc99c11f1
|
refs/heads/master
| 2022-12-18T22:50:17.836638
| 2020-09-20T15:22:04
| 2020-09-20T15:22:04
| 297,099,127
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 425
|
py
|
from django.contrib import admin
from .forms import DocumentForm
from .models import Document
# Register your models here.
class DocumentAdmin(admin.ModelAdmin):
list_display=["title","content",'version',"author","modified_timestamp","created_timestamp"]
list_filter=['title']
form=DocumentForm
# class Meta():
# model=Status
# Register your models here.
admin.site.register(Document,DocumentAdmin)
|
[
"nayana.ramakanth@gmail.com"
] |
nayana.ramakanth@gmail.com
|
a2da771246e7c91061f27992313962e02f9dcaa0
|
2054446dd26c7b1361e4eee6908e00c72e5b0325
|
/scripts/gn_lib/gn_io/clk.py
|
8f6379db7aa1c2a1f3716916dbe5d67a9a3730d6
|
[
"Apache-2.0"
] |
permissive
|
mengruizu/ginan
|
65ad2cda89151cfe6e115da95d0c5ef0ea7a6621
|
598cfff85be52c53c4a03bca7c0540a9200b1ee3
|
refs/heads/main
| 2023-07-28T12:21:40.147648
| 2021-08-06T07:14:32
| 2021-08-06T07:14:32
| 409,628,081
| 1
| 1
|
NOASSERTION
| 2021-09-23T14:35:45
| 2021-09-23T14:35:45
| null |
UTF-8
|
Python
| false
| false
| 1,560
|
py
|
'''RINEX CLK file parsing function'''
import sys as _sys
from io import BytesIO as _BytesIO
import numpy as _np
import pandas as _pd
from ..gn_datetime import _J2000_ORIGIN
from .common import path2bytes
PYGINANPATH = '/data/acs/pea/python/source/'
if PYGINANPATH not in _sys.path:
_sys.path.insert(0, PYGINANPATH)
CLK_TYPE_CATEGORY = _pd.CategoricalDtype(['CR','DR','AR','AS','MS'])
def read_clk(clk_path):
content = path2bytes(str(clk_path))
data_b = content.find(b'END OF HEADER')+13
data_b += content[data_b:data_b+20].find(b'\n') + 1
# header = content[:data_b]
clk_df = _pd.read_csv(_BytesIO(content[data_b:]),
delim_whitespace=True,header=None,usecols=[0,1,2,3,4,5,6,7,9,10],
names = ['A', 'CODE', 'Y', 'M', 'D', 'h', 'm', 's', 'EST', 'STD'],
dtype = {'A':CLK_TYPE_CATEGORY,'CODE':object,
'Y':_np.uint16,'M':_np.uint16,'D':_np.uint16,
'h':_np.int32,'m':_np.int32,'s':_np.float_,}
)
date = (((clk_df.Y.values - 1970).astype('datetime64[Y]').astype('datetime64[M]')
+ clk_df.M.values - 1).astype('datetime64[D]')
+ clk_df.D.values - 1)
time = (clk_df.h.values * 3600 + clk_df.m.values * 60 + clk_df.s.values).astype('timedelta64[s]')
j2000time = (date + time - _J2000_ORIGIN).astype(int)
clk_df.drop(columns=['Y','M','D','h','m','s'],inplace=True)
clk_df.set_index(['A',j2000time,'CODE'],inplace=True)
clk_df.index.names = ([None,None,None])
return clk_df
|
[
"john.donovan@ga.gov.au"
] |
john.donovan@ga.gov.au
|
772ebe0e48e44ce7f40861d41ebddad75e094c45
|
bf4eb36a60a17cfa8f8c289dffc6dc12702d9818
|
/Programming assignments/Programming Assignment 4.py
|
353a482d2df0ef1b82ec827ddf1da4f5ca70e78d
|
[] |
no_license
|
JanhaviBorsarkar/Ineuron-Assignments
|
8a8fb14cfdb281ed3c7d44f91d87728207c1da21
|
b1fcabc45e8380d6267b1ea52287b5744dd24bba
|
refs/heads/main
| 2023-06-26T16:46:45.988616
| 2021-07-29T03:54:30
| 2021-07-29T03:54:30
| 390,317,122
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,825
|
py
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# Q1. Write a Python Program to Find the Factorial of a Number
n = int(input("Enter a number: "))
fact = 1
if n < 0:
print("Please enter a positive integer")
elif n == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, n + 1):
fact = fact * i
print("Factorial of {0} is {1}" .format(n , fact))
# In[3]:
# Q2. Write a Python Program to Display the multiplication Table
n = int(input("Enter a number: "))
for i in range(1,11):
print(n * i)
# In[4]:
# Q3. Write a Python Program to Print the Fibonacci sequence
n = int(input("How many numbers? "))
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
# In[5]:
# Q4. Write a Python Program to Check Armstrong Number
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
# In[6]:
# Q5. Write a Python Program to Find Armstrong Number in an Interval
lower = 100
upper = 2000
for num in range(lower, upper + 1):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
# In[7]:
# Q6. Write a Python Program to Find the Sum of Natural Numbers
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
# In[ ]:
|
[
"noreply@github.com"
] |
JanhaviBorsarkar.noreply@github.com
|
c8afc42409188b6dbaa70cff0a6b38710fadc5df
|
4b45adb7ff5fa0f347057796cccb5f8388d558c1
|
/idealog/model/collection.py
|
dfd3c4bef197b112a85789f366fae32ebe8a022c
|
[] |
no_license
|
HyJan-go/idealog
|
22d2f73ea5ad31e3ce17809dee0e6e6e510ec0a6
|
0636155bdeff4c1569920a9424e016a7ea554a57
|
refs/heads/master
| 2022-11-27T19:29:17.195673
| 2020-08-12T02:02:59
| 2020-08-12T02:02:59
| 286,891,649
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,041
|
py
|
from sqlalchemy import inspect
from model.user import db
# 收藏文章表(顺序id,用户id,用户头像地址,收藏文章id,收藏文章标题,收藏时间)
class Collection(db.Model):
# '标签id',
collection_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# '用户id(收藏者)',
user_id = db.Column(db.Integer, nullable=False)
# '文章id'
article_id = db.Column(db.Integer, nullable=False)
# '收藏时间'
collection_time = db.Column(db.DateTime, default='null')
def __init__(self, user_id, article_id, collection_time):
self.user_id = user_id
self.article_id = article_id
self.collection_time = collection_time
# 提供输出接口,后期根据需要改
def __repr__(self):
return '<Collection_Article %r>' % self.collection_id
def serialize(self):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
@staticmethod
def serialize_list(l):
return [m.serialize() for m in l]
|
[
"hejian@52tt.com"
] |
hejian@52tt.com
|
0d5204f791006b7bfb4f02036903d8c1795c3f30
|
bd92bf830b66dc40fc3fe00958265ee87260d4ae
|
/sda2_tp1_python/insertionSort.py
|
d11b47c6d34c8fdc86694fb809eb198ee5222b15
|
[] |
no_license
|
dugiwarc/sda-2
|
55313643f286373f3862d65a27f665b48075f426
|
a6e5f6d627427144f137b34bfbaa744682e01560
|
refs/heads/master
| 2021-02-14T04:56:11.375393
| 2020-03-10T17:36:18
| 2020-03-10T17:36:18
| 244,771,169
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 391
|
py
|
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print("% d" % arr[i])
|
[
"gicubotnaru@gmail.com"
] |
gicubotnaru@gmail.com
|
8dda90de2d863085f330782f743aa206f695db63
|
c15437b98d99bdbf05b3ceef2f6eaa6e827ff71c
|
/POO_Algoritmos_con_Python/descomposicion.py
|
ce42719b873aaf74a8876337b9831cab5562a2b7
|
[] |
no_license
|
Dave-dev-ceo/Data_Science
|
92c5d88ba7ea3dbbd75e3c48ffec51619e3beb65
|
ae15f0eac4f1934367aab8122014e105c9160fc8
|
refs/heads/master
| 2022-11-08T05:05:17.421493
| 2020-06-25T14:16:32
| 2020-06-25T14:16:32
| 272,722,800
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 739
|
py
|
class Automovil:
def __init__(self, modelo, marca, color):
self.modelo = modelo
self.marca = marca
self.color = color
#Cuando se inicia con underscor es una variable privada por convencion
self._estado = 'en_reposo'
self._motor = Motor(cilindros=4)
def acelerar(self, tipo ='despacio'):
if tipo == 'rapido':
self._motor.inyecta_gasolina(10)
else:
self._motor.inyecta_gasolina(3)
self._estado ='movimiento'
class Motor:
def __init__(self,cilindros, tipo ='gasolina'):
self.cilindros = cilindros
self.tipo = tipo
self._temperatura = 0
def inyecta_gasolina(self, cantidad):
pass
|
[
"upro.ceo@gmail.com"
] |
upro.ceo@gmail.com
|
862fbab88286582f9d38167db835ab185312fac1
|
afca5997ede5f044d76a6b3bacdda360ddc953f9
|
/Analysis/RUAnalysis/Analysis/scripts/plotJECUnc.py
|
51fcfbb0a12ea2dff88d8f8a0a08cdb061f41925
|
[] |
no_license
|
jgonski/usercode
|
ef6e62006195c52769edbbe91f90147728863d29
|
090ab6e74313b6ff8b050aa1854f215281b94354
|
refs/heads/master
| 2020-12-03T00:05:53.296750
| 2013-10-21T15:04:02
| 2013-10-21T15:04:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 52,926
|
py
|
# Pass 1st argument as "log" to get log scale plots
from __future__ import division
from tdrStyle import *
from math import sqrt
from ROOT import *
import sys
canvases = []
scanvases = []
counter = 0
asymrange = 0.5
logscale = 0
if (len(sys.argv) >= 2):
logarg = sys.argv[1]
if (logarg == "log"):
logscale = 1
def plotMttbar():
tdrstyle = setTDRStyle();
gStyle.SetHatchesSpacing(1.0);
# gStyle.SetOptStat("emri"); # Print integral & usual stuff
lumi = 2400;
oldLumi = 2400;
scale = lumi / oldLumi;
qcdScale = {'default':1.72, 'withMETAndAsymJets': 3.03};
# data = TFile.Open("samples/mc2012_QCD_HT250-Inf_Summer12_8TeV_4pt80_6pt60_geqB_RelXsec_2p4fb_k1p16_Aug15_GeneralDist.root");
data = TFile.Open("samples/oldjecnonofficial/data2012_MultiJet_Quad50_Quad60_Di20_Json0601_2400pb_4pt80_6pt60_geqB_Aug15.root");
ttbar = TFile.Open("samples/oldjecnonofficial/mc2012_TTJets_Summer12_8TeV_TLBSM52xv3_4pt80_6pt60_geqB_Aug15.root");
stsusy300 = TFile.Open("samples/oldjecnonofficial/stsusy300.root");
stsusy300_v2 = TFile.Open("samples/oldjecnonofficial/stsusy300_53x_v2a.root");
jecnone = TFile.Open("samples/RUOfficial/jecdec/mc_RPV_M400_112_BtagMap_Officialpu206940jecstd.root");
jecup = TFile.Open("samples/RUOfficial/jecdec/mc_RPV_M400_112_BtagMap_Officialpu206940jecup.root");
jecdown = TFile.Open("samples/RUOfficial/jecdec/mc_RPV_M400_112_BtagMap_Officialpu206940jecdown.root");
jecdownpriv = TFile.Open("samples/oldjecnonofficial/rpv400_53x_v2a.root");
# ttbar = TFile.Open("TT_Tune_4000pb_PFElectron_PF2PATJets_PFMET.root");
# wjets = TFile.Open("WJetsToLNu_5000pb_PFElectron_PF2PATJets_PFMET.root");
# wjets = TFile.Open("WToENu_4000pb_PFElectron_PF2PATJets_PFMET.root");
# zjets = TFile.Open("DYJetsToLL_4000pb_PFElectron_PF2PATJets_PFMET.root");
# bce1 = TFile.Open("QCD_Pt-20to30_BCtoE_4000pb_PFElectron_PF2PATJets_PFMET.root");
# bce2 = TFile.Open("QCD_Pt-30to80_BCtoE_4000pb_PFElectron_PF2PATJets_PFMET.root");
# bce3 = TFile.Open("QCD_Pt-80to170_BCtoE_4000pb_PFElectron_PF2PATJets_PFMET.root");
# enri1 = TFile.Open("QCD_Pt-20to30_EMEnriched_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# enri2 = TFile.Open("QCD_Pt-30to80_EMEnriched_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# enri3 = TFile.Open("QCD_Pt-80to170_EMEnriched_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# zjets = TFile.Open("DYJets_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime500 = TFile.Open("Zprime_M500GeV_W50GeV_4000pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime1500 = TFile.Open("Zprime_M1500GeV_W15GeV_4000pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime750 = TFile.Open("Zprime_M750GeV_W7500MeV_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime1000 = TFile.Open("Zprime_M1000GeV_W10GeV_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime2000 = TFile.Open("Zprime_M2000GeV_W20GeV_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# Zprime4000 = TFile.Open("Zprime_M4000GeV_W400GeV_4000pb_PFElectron_PF2PATJets_PFMET.root");
# Tprime300 = TFile.Open("TprimeToWb_M300_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# Tprime350 = TFile.Open("TprimeToWb_M350_35.9pb_PFElectron_PF2PATJets_PFMET.root");
# WprimeTToTTD_M400 = TFile.Open("WprimeTToTTD_M400_5000pb_PFElectron_PF2PATJets_PFMET.root");
# WprimeTToTTD_M600 = TFile.Open("WprimeTToTTD_M600_5000pb_PFElectron_PF2PATJets_PFMET.root");
# WprimeTToTTD_M800 = TFile.Open("WprimeTToTTD_M800_5000pb_PFElectron_PF2PATJets_PFMET.root");
# WprimeTToTTD_M1000 = TFile.Open("WprimeTToTTD_M1000_5000pb_PFElectron_PF2PATJets_PFMET.root");
# WprimeToTTBbar_M1000 = TFile.Open("WprimeToTBbar_M-1000_4000pb_PFElectron_PF2PATJets_PFMET.root");
# pj1 = TFile.Open("pj1_36.145pb_PFElectron_PF2PATJets_PFMET.root");
# pj2 = TFile.Open("pj2_36.145pb_PFElectron_PF2PATJets_PFMET.root");
# pj3 = TFile.Open("pj3_36.145pb_PFElectron_PF2PATJets_PFMET.root");
# tW = TFile.Open("tW_36.145pb_PFElectron_PF2PATJets_PFMET.root");
# tchan = TFile.Open("tchan_36.145pb_PFElectron_PF2PATJets_PFMET.root");
# vqq = TFile.Open("vqq_7.22pb_V4PFCalo.root__fullSetOfVars.root");
# Zprime1250 = TFile.Open("/storage/workspace/BristolAnalysisTools/outputfiles/Zprime_M1250GeV_W12500MeV_36.135pb.root");
# Zprime1500 = TFile.Open("/storage/workspace/BristolAnalysisTools/outputfiles/Zprime_M1500GeV_W15GeV_36.135pb.root");
hists = [];
hists.append("Triplets/nBJet35_EvtSel");
hists.append("Triplets/HT_EvtSel");
hists.append("Triplets/nJet35_EvtSel");
hists.append("Triplets/Jet0_EvtSel");
hists.append("Triplets/Jet1_EvtSel");
hists.append("Triplets/Jet2_EvtSel");
hists.append("Triplets/Jet3_EvtSel");
hists.append("Triplets/Jet4_EvtSel");
hists.append("Triplets/Jet5_EvtSel");
hists.append("Triplets/Jet6_EvtSel");
hists.append("Triplets/MET_EvtSel");
hists.append("Events/nBJet35");
hists.append("Events/HT");
hists.append("Events/nJet35");
hists.append("Events/Jet0");
hists.append("Events/Jet1");
hists.append("Events/Jet2");
hists.append("Events/Jet3");
hists.append("Events/Jet4");
hists.append("Events/Jet5");
# hists.append("Events/Jet6");
hists.append("Events/MET");
hists.append("Events/nTruePileUp");
hists.append("Triplets/bjet_0/jetpt_60/Mjjj_bjet0_pt60_diag110_GE6jet");
print hists
gcd = gROOT.cd
for histname in hists:
gcd()
print histname
hist_data = data.Get(histname);
# hist_data2;
# if (histname == "mttbar_rebinned")
# hist_data2 = data2.Get(histname);
# else
# hist_data2 = TH1F(*hist_data);
# hist_data.Sumw2();
# hist_data2.Sumw2();
hist_ttbar = ttbar.Get(histname);
hist_stsusy300 = stsusy300.Get(histname);
hist_stsusy300_v2 = stsusy300_v2.Get(histname);
hist_jecnone = jecnone.Get(histname);
hist_jecup = jecup.Get(histname);
hist_jecdown = jecdown.Get(histname);
hist_jecdownpriv = jecdownpriv.Get(histname);
# hist_zjets = zjets.Get(histname);
# hist_bce1 = bce1.Get(histname);
# hist_bce2 = bce2.Get(histname);
# hist_bce3 = bce3.Get(histname);
# hist_enri1 = enri1.Get(histname);
# hist_enri2 = enri2.Get(histname);
# hist_enri3 = enri3.Get(histname);
# # hist_pj1 = pj1.Get(histname);
# # hist_pj2 = pj2.Get(histname);
# hist_pj3 = pj3.Get(histname);
# hist_singleTop = tW.Get(histname)
# hist_singleTop.Add(tchan.Get(histname))
# hist_Zprime500 = Zprime500.Get(histname);
# hist_Zprime750 = Zprime750.Get(histname);
# hist_Zprime1000 = Zprime1000.Get(histname);
# hist_Zprime1500 = Zprime1500.Get(histname);
# hist_Zprime2000 = Zprime2000.Get(histname);
# hist_Zprime4000 = Zprime4000.Get(histname);
# hist_Tprime300 = Tprime300.Get(histname);
# hist_Tprime350 = Tprime350.Get(histname);
# # hist_Zprime1250 = Zprime1250.Get(histname);
# hist_wpm400 = WprimeTToTTD_M400.Get(histname);
# hist_wpm600 = WprimeTToTTD_M600.Get(histname);
# hist_wpm800 = WprimeTToTTD_M800.Get(histname);
# hist_wpm1000 = WprimeTToTTD_M1000.Get(histname);
# hist_wptb1000 = WprimeToTTBbar_M1000.Get(histname);
# hist_ttbar.Sumw2(); # No good, must be done before filling
# if ('iso' in histname or 'jetmultip' in histname or 'DeltaR' in histname or ('num' in histname and 'Top' in histname)):
if (false and logscale == 0):
numevts = hist_ttbar.Integral();
if (numevts > 0):
hist_ttbar.Scale(1.0/numevts);
numevts = hist_stsusy300.Integral();
hist_stsusy300.Scale(1.0/numevts);
numevts = hist_stsusy300_v2.Integral();
hist_stsusy300_v2.Scale(1.0/numevts);
numevts = hist_data.Integral();
hist_data.Scale(1.0/numevts);
numevts = hist_jecnone.Integral();
hist_jecnone.Scale(1.0/numevts);
numevts = hist_jecup.Integral();
hist_jecup.Scale(1.0/numevts);
numevts = hist_jecdown.Integral();
hist_jecdown.Scale(1.0/numevts);
numevts = hist_jecdownpriv.Integral();
hist_jecdownpriv.Scale(1.0/numevts);
# numevts = hist_wpm800.Integral();
# hist_wpm800.Scale(1.0/numevts);
# numevts = hist_wpm1000.Integral();
# hist_wpm1000.Scale(1.0/numevts);
else:
scale = 225.0 * lumi / 1203373.0;
# num evts = 1203373;
hist_ttbar.Scale(scale);
scale = 1.1 * lumi / 98600.0;
hist_stsusy300.Scale(scale);
hist_stsusy300_v2.Scale(scale);
scale = 0.045 * lumi / 107800.0;
# hist_jecnone.Scale(scale);
# scale = 140.0 * lumi / 93500.0;
# scale = 495.0 * lumi / 40500.0 # Incomplete PATtuple
# scale = 495.0 * lumi / 101250.0;
# hist_jecup.Scale(scale);
# scale = 7.94 * lumi / 100000.0;
# hist_jecdown.Scale(scale);
scale = 7.94 * lumi / 101250.0;
hist_jecdownpriv.Scale(scale);
# hist_wpm400.Scale(scale);
# hist_wpm600.Scale(scale);
# hist_wpm1000.Scale(scale);
# hist_wpm800.Scale(scale);
# hist_wjets.Scale(scale);
# hist_wjets.Scale(scale);
# hist_zjets.Scale(scale);
# hist_bce1.Scale(scale);
# hist_bce2.Scale(scale);
# hist_bce3.Scale(scale);
# hist_enri1.Scale(scale);
# hist_enri2.Scale(scale);
# hist_enri3.Scale(scale);
# hist_pj1.Scale(scale);
# hist_pj2.Scale(scale);
# hist_pj3.Scale(scale);
# scale = scale * 10.0;
# hist_Zprime500.Scale(scale);
# hist_Zprime750.Scale(scale);
# hist_Zprime1000.Scale(scale);
# hist_Zprime2000.Scale(scale);
# hist_Zprime1500.Scale(scale);
# hist_Zprime4000.Scale(scale);
# hist_Tprime300.Scale(scale);
# hist_Tprime350.Scale(scale);
# hist_Zprime1250.Scale(scale);
# hist_wptb1000.Scale(scale);
# hist_qcd = hist_bce1.Clone("qcd")#TH1F(*hist_bce1);
# hist_qcd.Add(hist_bce2);
# hist_qcd.Add(hist_bce3);
# hist_qcd.Add(hist_enri1);
# hist_qcd.Add(hist_enri2);
# hist_qcd.Add(hist_enri3);
# hist_qcd.Add(hist_pj1);
# hist_qcd.Add(hist_pj2);
# hist_qcd.Add(hist_pj3);
# hist_qcd.Scale(qcdScale[currentSelection]);
# ndata = hist_data.Integral();
# ntop = hist_ttbar.Integral();
# nwj = hist_wjets.Integral();
# nzj = hist_zjets.Integral();
# nqcd = hist_qcd.Integral();
# sumMC = ntop + nwj + nzj + nqcd;
# cout << ndata << " " << sumMC << endl;
# hist_wjets.Scale(ndata / sumMC);
# hist_ttbar.Scale(ndata / sumMC);
# hist_zjets.Scale(ndata / sumMC);
# hist_qcd.Scale(ndata / sumMC);
# mttbars = ['mttbar_' + suffix for suffix in suffixes]
# mttbars2 = ['mttbar_withMETAndAsymJets_' + suffix for suffix in suffixes]
# if histname in mttbars or histname in mttbars2:
# print "taking QCD shape from DATA"
# name = histname.replace('mttbar', 'mttbar_conversions')
# hist_qcd = data.Get(name)
# if( hist_qcd.Integral() > 0):
# hist_qcd.Scale(nqcd/hist_qcd.Integral())
# hist_mc = hist_qcd.Clone("all_mc")
# hist_mc.Add(hist_ttbar);
# hist_mc.Add(hist_zjets);
# hist_mc.Add(hist_wjets);
# hist_mc.Add(hist_singleTop);
hist_data = hist_jecnone.Clone("test");
rebin = 1;
Urange = (0,5000)
Yrange = (0,0)
if ("nBJet35" in histname):
hist_data.SetXTitle("Number of b jets");
hist_data.SetYTitle("Events");
Urange = (0, 6)
elif ("HT" in histname):
hist_data.SetXTitle("HT [GeV]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 5;
Urange = (400, 3500)
elif ("MET" in histname):
hist_data.SetXTitle("MET [GeV]");
hist_data.SetYTitle("Events/(5 GeV)");
# rebin = 2;
Urange = (0, 250)
elif ("nJet35" in histname):
hist_data.SetXTitle("Number of jets");
hist_data.SetYTitle("Events");
Urange = (4, 15)
elif ("Jet0" in histname):
hist_data.SetXTitle("Leading jet p_{T}");
hist_data.SetYTitle("Events/(25 GeV)");
rebin = 5;
Urange = (50, 1000)
elif ("Jet1" in histname):
hist_data.SetXTitle("2nd jet p_{T}");
hist_data.SetYTitle("Events/(25 GeV)");
rebin = 5;
Urange = (50, 800)
elif ("Jet2" in histname):
hist_data.SetXTitle("3rd jet p_{T}");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 2;
Urange = (50, 600)
elif ("Jet3" in histname):
hist_data.SetXTitle("4th jet p_{T}");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 2;
Urange = (50, 400)
elif ("Jet4" in histname):
hist_data.SetXTitle("5th jet p_{T}");
hist_data.SetYTitle("Events/(5 GeV)");
#rebin = 2;
Urange = (30, 300)
elif ("Jet5" in histname):
hist_data.SetXTitle("6th jet p_{T}");
hist_data.SetYTitle("Events/(5 GeV)");
# rebin = 2;
Urange = (30, 200)
elif ("Jet6" in histname):
hist_data.SetXTitle("7th jet p_{T}");
hist_data.SetYTitle("Events/(5 GeV)");
# rebin = 2;
Urange = (30, 150)
elif ("PileUp" in histname):
hist_data.SetXTitle("Number of pile-up events");
hist_data.SetYTitle("Events");
rebin = 5;
Urange = (0, 70)
elif ("Mjjj" in histname):
hist_data.SetXTitle("Triplet mass [GeV]");
hist_data.SetYTitle("Events/(100 GeV)");
rebin = 20;
Urange = (0, 1000)
elif (histname == "electron_et"):
hist_data.SetXTitle("electron E_{T} [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 300)
elif (histname == "electron_pt" or histname == "electminus_pt" or histname == "positron_pt"):
hist_data.SetXTitle("electron p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 300)
elif (histname == "muon_et"):
hist_data.SetXTitle("muon E_{T} [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 300)
elif (histname == "muon_pt"):
hist_data.SetXTitle("muon p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 300)
elif ("ttbar_pt" in histname):
hist_data.SetXTitle("p_{T} of t#bar{t} system [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 500)
elif ("ttbar_px" in histname):
hist_data.SetXTitle("p_{x} of t#bar{t} system [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 500)
elif ("ttbar_py" in histname):
hist_data.SetXTitle("p_{y} of t#bar{t} system [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 500)
elif ("ttbar_pz" in histname):
hist_data.SetXTitle("p_{z} of t#bar{t} system [GeV]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 2000)
elif ("METpt_ltop" in histname):
hist_data.SetXTitle("MET p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 400)
elif ("tPrime_pt" in histname):
hist_data.SetXTitle("p_{T} of T' system [GeV]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 200)
elif ("tPrime_px" in histname):
hist_data.SetXTitle("p_{x} of T' system [GeV]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 200)
elif ("tPrime_py" in histname):
hist_data.SetXTitle("p_{y} of T' system [GeV]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 200)
elif ("tPrime_pz" in histname):
hist_data.SetXTitle("p_{z} of T' system [GeV]");
hist_data.SetYTitle("Events/(100 GeV)");
rebin = 200;
Urange = (0, 1800)
elif ("HT_" in histname):
hist_data.SetXTitle("#Sigma p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 2000)
elif ("ST" in histname):
hist_data.SetXTitle("ST [GeV]");
hist_data.SetYTitle("Events/(30 GeV/c)");
rebin = 30;
Urange = (0, 1000)
elif ("HT3jet_ltop" in histname):
hist_data.SetXTitle("#Sigma p_{T} of leading 3 jets [GeV]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 1000)
elif ("HT4jet_ltop" in histname):
hist_data.SetXTitle("#Sigma p_{T} of leading 4 jets [GeV]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 1200)
elif (histname == "numberOfJets"):
hist_data.SetXTitle("number of jets");
hist_data.SetYTitle("Events");
elif (histname == "numberOfBJets"):
hist_data.SetXTitle("number of b-tagged jets (SSVHE medium)");
hist_data.SetYTitle("Events");
elif ('MET_' in histname and 'MET_ltop' not in histname):
hist_data.SetXTitle("MET [GeV]");
hist_data.SetYTitle("Events/(5 GeV)");
rebin = 5;
Urange = (0, 400)
elif ('MET_ltop' in histname):
hist_data.SetXTitle("MET [GeV]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (0, 400)
elif ("leadingJetMass" in histname):
hist_data.SetXTitle("leading jet mass [GeV/c^2]");
hist_data.SetYTitle("Events/(5 GeV)");
rebin = 5;
Urange = (0, 150)
elif ("mtW" in histname):
hist_data.SetXTitle("transverse W-boson mass [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
elif ("both" in histname or "plus" in histname or "minus" in histname):
hist_data.SetXTitle("transverse mass [GeV]");
hist_data.SetYTitle("Events/(100 GeV)");
rebin = 100;
Urange = (0, 2000)
elif ("transMasslm1b" in histname):
hist_data.SetXTitle("M_{T} (lep+MET+1b) [GeV]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 700)
elif ("electronD0" in histname):
hist_data.SetXTitle("electron d_{0} / cm");
hist_data.SetYTitle("Events/(0.001 cm)");
rebin = 10;
elif ("angleTops" in histname or "deltaPhiTops" in histname):
hist_data.SetXTitle("angle between top quarks");
hist_data.SetYTitle("Events/(0.1 rad)");
rebin = 10;
elif ( "deltaphilep" in histname):
hist_data.SetXTitle("angle between lepton & leading jet");
hist_data.SetYTitle("Events/(0.2 rad)");
rebin = 20;
elif ("lepb_angle" in histname):
hist_data.SetXTitle("angle between electron and b jet");
hist_data.SetYTitle("Events/(0.1 rad)");
rebin = 10;
elif ("angleHadTopD" in histname):
hist_data.SetXTitle("angle between hadronic top and light jet");
hist_data.SetYTitle("Events/(0.2 rad)");
rebin = 20;
elif ("METtopangle_ltop" in histname):
hist_data.SetXTitle("angle between MET and top p_{T}");
hist_data.SetYTitle("Events/(0.1 rad)");
rebin = 10;
Urange = (-2, 2)
elif ("qkjet_eta" in histname):
hist_data.SetXTitle("#eta of b jet");
hist_data.SetYTitle("Events/(0.1 rad)");
Urange = (-3, 3)
rebin = 10;
elif ("_rap" in histname):
hist_data.SetXTitle("Jet Rapidity");
hist_data.SetYTitle("Events/(0.1 rad)");
Urange = (-3, 3)
rebin = 20;
elif ("neutrino_pz" in histname):
hist_data.SetXTitle("neutrino p_{Z} [GeV/c]");
hist_data.SetYTitle("Events/(20 GeV)");
rebin = 20;
Urange = (-500, 500)
elif ('mHadTopLoneNM' in histname):
hist_data.SetXTitle("top mass [GeV/c^2]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 400)
elif ('mass4jets' in histname):
hist_data.SetXTitle("4-jet mass [GeV]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 1500)
elif ('mLepTopLoneNM' in histname):
hist_data.SetXTitle("top mass [GeV]");
hist_data.SetYTitle("Events/(10 GeV)");
rebin = 10;
Urange = (0, 400)
elif ('chiHadronicTop' in histname or 'chiLeptonicTop' in histname):
hist_data.SetXTitle("top #chi^{2} [GeV]");
hist_data.SetYTitle("Events/(1)");
rebin = 1;
Urange = (0, 30)
elif ('chiGlobal' in histname or 'chiTotal' in histname):
hist_data.SetXTitle("Event #chi^{2} [GeV]");
hist_data.SetYTitle("Events/(100)");
rebin = 100;
elif ('numHadTopMCMatches' in histname or 'numLepTopMCMatches' in histname):
hist_data.SetXTitle("Number of Exact Decay-Chain Matches");
hist_data.SetYTitle("Events");
Yrange = (0, 1.1)
elif ('numHadTopDauMCMatches' in histname or 'numLepTopDauMCMatches' in histname):
hist_data.SetXTitle("Number of Top Daughter Matches");
hist_data.SetYTitle("Events");
Yrange = (0, 1.1)
elif ('numHadTopCorrectID' in histname or 'numLepTopCorrectID' in histname):
hist_data.SetXTitle("Number of Reco Candidates Matched to MC-Truth Particles");
hist_data.SetYTitle("Events");
Yrange = (0, 1.1)
elif ('lepTopDeltaR' in histname or 'hadTopDeltaR' in histname):
hist_data.SetXTitle("#Delta R of MC truth top");
hist_data.SetYTitle("Events");
rebin = 20;
# Urange = (0, 4)
elif ('lepTopLep' in histname or 'hadTopHad' in histname):
hist_data.SetXTitle("top MC truth identity");
hist_data.SetYTitle("Events");
Urange = (0, 2)
elif ('mHadTopLone' in histname or 'mHadronicTop' in histname or 'mAllTop' in histname):
hist_data.SetXTitle("top mass [GeV/c^2]");
hist_data.SetYTitle("Events/(15 GeV)");
rebin = 15;
Urange = (0, 700)
elif ('mLepTopLone' in histname or 'mLeptonicTop' in histname):
hist_data.SetXTitle("top mass [GeV/c^2]");
hist_data.SetYTitle("Events/(15 GeV)");
rebin = 15;
Urange = (0, 700)
elif ('pt_' in histname and 'Top' in histname):
hist_data.SetXTitle("top p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 500)
elif ('trailingJetPt' in histname):
hist_data.SetXTitle("Jet p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(25 GeV)");
rebin = 30;
Urange = (0, 270)
elif ('JetPt' in histname):
hist_data.SetXTitle("Jet p_{T} [GeV/c]");
hist_data.SetYTitle("Events/(50 GeV)");
rebin = 50;
Urange = (0, 600)
elif('QCDest_CombRelIso' in histname):
hist_data.SetXTitle("relative isolation");
hist_data.SetYTitle("Events/(0.1)");
rebin = 10;
Urange = (0, 2)
elif('QCDest_PFIsolation' in histname):
hist_data.SetXTitle("ParticleFlow isolation");
hist_data.SetYTitle("Events/(0.1)");
rebin = 10
Urange = (0, 2)
elif('iso' in histname):
hist_data.SetXTitle("ParticleFlow Isolation");
hist_data.SetYTitle("Events/(0.02)");
rebin = 4
Urange = (0, 0.5)
elif('vertdist' in histname):
hist_data.SetXTitle("Steps from PV");
hist_data.SetYTitle("Events");
# rebin = 200
Urange = (0, 2)
elif('jetmultip' in histname):
hist_data.SetXTitle("Number of jets");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (0, 11)
elif('chargemis' in histname):
hist_data.SetXTitle("Correct charge");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (-1, 2)
elif('tausInJets' in histname):
hist_data.SetXTitle("Number of tau jets");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (0, 3)
elif('numTaus' in histname):
hist_data.SetXTitle("Number of taus");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (0, 15)
elif('numGenJets' in histname):
hist_data.SetXTitle("Number of GenJets");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (3, 15)
elif('numDiffJets' in histname):
hist_data.SetXTitle("Difference between Reco Jets & GenJets");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (-7, 4)
elif('miss' in histname and 'Jets' in histname):
if('miss' in histname and 'missGenJets' in histname):
hist_data.SetXTitle("Number of Unmatched Reco Jets");
else:
hist_data.SetXTitle("Number of Unmatched GenJets");
hist_data.SetYTitle("Events");
# rebin = 60
Urange = (0, 8)
hist_data.SetTitleOffset(1.5, "Y");
if ('jet1' in histname):
hist_data.Rebin2D();
hist_ttbar.Rebin2D();
hist_Tprime300.Rebin2D();
hist_Tprime350.Rebin2D();
hist_data.SetAxisRange(0, 600, "X");
hist_data.SetAxisRange(0, 600, "Y");
hist_ttbar.SetAxisRange(0, 600, "X");
hist_ttbar.SetAxisRange(0, 600, "Y");
# hist_Tprime300.SetAxisRange(0, 600, "X");
# hist_Tprime300.SetAxisRange(0, 600, "Y");
# hist_Tprime350.SetAxisRange(0, 600, "X");
# hist_Tprime350.SetAxisRange(0, 600, "Y");
else:
hist_data.Rebin(rebin);
hist_ttbar.Rebin(rebin);
hist_stsusy300.Rebin(rebin);
hist_stsusy300_v2.Rebin(rebin);
hist_jecnone.Rebin(rebin);
hist_jecup.Rebin(rebin);
hist_jecdown.Rebin(rebin);
hist_jecdownpriv.Rebin(rebin);
# hist_zjets.Rebin(rebin);
# hist_qcd.Rebin(rebin);
# hist_Zprime500.Rebin(rebin);
# hist_Zprime1500.Rebin(rebin);
# hist_Zprime750.Rebin(rebin);
# hist_Zprime1000.Rebin(rebin);
# hist_Zprime2000.Rebin(rebin);
# hist_Zprime4000.Rebin(rebin);
# hist_Tprime300.Rebin(rebin);
# hist_Tprime350.Rebin(rebin);
# hist_singleTop.Rebin(rebin)
# hist_wpm400.Rebin(rebin);
# hist_wpm600.Rebin(rebin);
# hist_wpm800.Rebin(rebin);
# hist_wpm1000.Rebin(rebin);
# hist_wptb1000.Rebin(rebin);
hist_data.SetAxisRange(Urange[0], Urange[1]);
hist_ttbar.SetAxisRange(Urange[0], Urange[1]);
hist_stsusy300.SetAxisRange(Urange[0], Urange[1]);
hist_stsusy300_v2.SetAxisRange(Urange[0], Urange[1]);
# print "high range ", Urange[1];
hist_jecnone.SetAxisRange(Urange[0], Urange[1]);
hist_jecup.SetAxisRange(Urange[0], Urange[1]);
hist_jecdown.SetAxisRange(Urange[0], Urange[1]);
hist_jecdownpriv.SetAxisRange(Urange[0], Urange[1]);
# hist_wjets.SetAxisRange(Urange[0], Urange[1]);
# hist_zjets.SetAxisRange(Urange[0], Urange[1]);
# hist_qcd.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime500.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime750.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime1000.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime1500.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime2000.SetAxisRange(Urange[0], Urange[1]);
# hist_Zprime4000.SetAxisRange(Urange[0], Urange[1]);
# hist_Tprime300.SetAxisRange(Urange[0], Urange[1]);
# hist_Tprime350.SetAxisRange(Urange[0], Urange[1]);
# hist_singleTop.SetAxisRange(Urange[0], Urange[1]);
# hist_wpm400.SetAxisRange(Urange[0], Urange[1]);
# hist_wpm600.SetAxisRange(Urange[0], Urange[1]);
# hist_wpm800.SetAxisRange(Urange[0], Urange[1]);
# hist_wpm1000.SetAxisRange(Urange[0], Urange[1]);
# hist_wptb1000.SetAxisRange(Urange[0], Urange[1]);
hist_data.SetMarkerStyle(8);
hist_data.SetMarkerSize(1.5);
# hist_data.SetMarkerSize(0.1);
# hist_data.SetFillStyle(1001);
# hist_data.SetFillColor(kRed);
# hist_ttbar.SetFillStyle(1001);
# hist_ttbar.SetFillColor(kRed);
# hist_wjets.SetFillStyle(1001);
# hist_wjets.SetFillColor(4);
# hist_zjets.SetFillStyle(1001);
# hist_zjets.SetFillColor(8);
# hist_qcd.SetFillStyle(1001);
# hist_qcd.SetFillColor(kYellow);
# hist_qcd.SetFillColor(12);
# hist_singleTop.SetFillStyle(1001);
# hist_singleTop.SetFillColor(kMagenta)
# nbins = hist_qcd.GetXaxis().GetNbins();
# binwidth = (hist_qcd.GetXaxis().GetXmax() - hist_qcd.GetXaxis().GetXmin()) / nbins;
# for i in range(1, nbins + 1):
# yvalue = hist_qcd.GetBinContent(i);
# # float xvalue = hist_qcd.GetBinCenter(i);
# # float ymin = yvalue - yvalue*0.5;
# # float ymax = yvalue + yvalue*0.5;
# # float xmin = xvalue - 0.5*binwidth;
# # float xmax = xvalue + 0.5*binwidth;
# error = yvalue * 0.5;
# hist_mc.SetBinError(i, error);
# # qcdUncert.SetPointError(i, xmin, xmax, ymin, ymax);
#
# qcdUncert = TGraphAsymmErrors(hist_mc);
linewidth = 3;
# hist_Zprime500.SetLineColor(6);
# hist_Zprime500.SetLineWidth(linewidth);
# hist_Zprime500.SetFillStyle(0);
# hist_Zprime500.SetFillColor(kWhite);
# hist_Zprime750.SetLineColor(5);
# hist_Zprime750.SetLineWidth(linewidth);
# hist_Zprime750.SetFillStyle(0);
# hist_Zprime750.SetFillColor(kWhite);
# hist_Zprime1000.SetLineColor(7);
# hist_Zprime1000.SetLineWidth(linewidth);
# hist_Zprime1000.SetFillStyle(0);
# hist_Zprime1000.SetFillColor(kWhite);
# hist_Zprime2000.SetLineColor(42);
# hist_Zprime2000.SetLineWidth(linewidth);
# hist_Zprime2000.SetFillStyle(0);
# hist_Zprime2000.SetFillColor(kWhite);
# # hist_Zprime4000.SetLineColor(50);
# hist_Zprime4000.SetLineWidth(linewidth);
# hist_Zprime4000.SetFillStyle(0);
# hist_Zprime4000.SetFillColor(kWhite);
# hist_Tprime300.SetLineColor(kOrange + 1);
# hist_Tprime300.SetLineWidth(linewidth);
# hist_Tprime350.SetLineColor(kGray + 3);
# hist_Tprime350.SetLineWidth(linewidth);
#
# hist_Zprime1250.SetLineColor(kCyan - 5);
# hist_Zprime1250.SetLineWidth(linewidth);
# hist_Zprime1250.SetFillStyle(0);
# hist_Zprime1250.SetFillColor(kWhite);
#
# hist_Zprime1500.SetLineColor(42);
# hist_Zprime1500.SetLineWidth(linewidth);
# hist_Zprime1500.SetFillStyle(0);
# hist_Zprime1500.SetFillColor(kWhite);
hist_ttbar.SetLineColor(kRed);
hist_ttbar.SetLineWidth(linewidth);
hist_stsusy300.SetLineColor(kGreen + 1);
hist_stsusy300.SetLineWidth(linewidth);
hist_stsusy300_v2.SetLineColor(kOrange + 1);
hist_stsusy300_v2.SetLineWidth(linewidth);
hist_jecnone.SetMarkerColor(kBlack);
hist_jecnone.SetLineColor(kBlack);
hist_jecnone.SetLineWidth(linewidth);
hist_jecnone.SetMarkerStyle(8);
hist_jecnone.SetMarkerSize(1.0);
# hist_jecup.SetMarkerColor(kGreen + 3);
hist_jecup.SetLineColor(kGreen + 3);
hist_jecup.SetLineWidth(linewidth);
# hist_jecup.SetMarkerStyle(24);
# hist_jecup.SetMarkerSize(1.5);
# hist_jecdown.SetMarkerColor(kOrange + 1);
hist_jecdown.SetLineColor(kOrange + 1);
hist_jecdown.SetLineWidth(linewidth);
# hist_jecdown.SetMarkerStyle(21);
# hist_jecdown.SetMarkerSize(1.5);
hist_jecdownpriv.SetMarkerColor(kGray + 3);
hist_jecdownpriv.SetLineColor(kGray + 3);
hist_jecdownpriv.SetLineWidth(linewidth);
hist_jecdownpriv.SetMarkerStyle(22);
hist_jecdownpriv.SetMarkerSize(2.0);
# hist_wpm400.SetLineColor(kGreen + 1);
# hist_wpm400.SetLineWidth(linewidth);
# hist_wpm600.SetLineColor(kGray + 3);
# hist_wpm600.SetLineWidth(linewidth);
# hist_wpm800.SetLineColor(kCyan);
# hist_wpm800.SetLineWidth(linewidth);
# hist_wpm1000.SetLineColor(kOrange + 1);
# hist_wpm1000.SetLineWidth(linewidth);
# hist_wptb1000.SetLineColor(kCyan);
# hist_wptb1000.SetLineWidth(linewidth);
# qcdUncert.SetFillColor(kGray + 3);
# qcdUncert.SetFillStyle(3003);
leg = TLegend(0.72, 0.6, 0.98, 0.85);
leg.SetBorderSize(0);
leg.SetLineStyle(0);
leg.SetTextFont(42);
leg.SetFillStyle(0);
# leg.AddEntry(hist_data, "QCD", "P");
# leg.AddEntry(hist_data2, "data(no HLT)", "P");
# leg.AddEntry(hist_ttbar, "t#bar{t}", "L");
# leg.AddEntry(hist_jecnone, "StSUSY 500", "P");
# leg.AddEntry(hist_jecup, "StSUSY 500 up", "L");
# leg.AddEntry(hist_jecdown, "StSUSY 500 down", "L");
leg.AddEntry(hist_jecnone, "RPV LF 400", "P");
leg.AddEntry(hist_jecup, "RPV LF 400 up", "L");
leg.AddEntry(hist_jecdown, "RPV LF 400 down", "L");
# leg.AddEntry(hist_jecdownpriv, "RPV 400 Private", "P");
# leg.AddEntry(hist_stsusy300, "StealthSUSY 300 v1", "L");
# leg.AddEntry(hist_stsusy300_v2, "StealthSUSY 300 v2", "L");
# leg.AddEntry(hist_wjets, "W#rightarrowl#nu", "f");
# leg.AddEntry(hist_zjets, "Z/#gamma*#rightarrowl^{+}l^{-}", "f");
# leg.AddEntry(hist_qcd, "QCD", "F");
# leg.AddEntry(hist_qcd, "QCD/#gamma + jets");
# leg.AddEntry(hist_singleTop, "Single-Top")
# leg.AddEntry(hist_Zprime500, "Z' 0.5TeV (50 pb)", "L");
# leg.AddEntry(hist_Zprime750, "Z' 0.75TeV", "L");
# leg.AddEntry(hist_Zprime1000, "Z' 1TeV", "L");
# leg.AddEntry(hist_Zprime1500, "Z' 1.5TeV (50 pb)", "L");
# leg.AddEntry(hist_Zprime2000, "Z' 2TeV", "L");
# leg.AddEntry(hist_Zprime4000, "Z' 4TeV (50 pb)", "L");
# leg.AddEntry(hist_Tprime300, "T' 300GeV", "L");
# leg.AddEntry(hist_Tprime350, "T' 350GeV", "L");
# leg.AddEntry(hist_Zprime1250, "Z' 1.25TeV");
# if (not 'num' in histname or not 'Top' in histname):
# leg.AddEntry(hist_wpm400, "W't .4TeV (32 pb)", "L");
# leg.AddEntry(hist_wpm600, "W't .6TeV (8 pb)", "L");
# if (not 'num' in histname or not 'Top' in histname):
# leg.AddEntry(hist_wpm800, "W't .8TeV (2.2 pb)", "L");
# leg.AddEntry(hist_wpm1000, "W't 1TeV (0.72 pb)", "L");
# leg.AddEntry(hist_wptb1000, "W'-> tb 1TeV (8 pb)", "L");
canvases.append(TCanvas("cname" + histname, histname, 1200, 900))
# if ('iso' in histname or 'jetmultip' in histname or 'num' in histname and 'Top' in histname):
canvases[-1].SetGrid();
canvases[-1].cd().SetRightMargin(0.04);
if ('jet1' in histname):
hist_data.SetMarkerStyle(8);
hist_ttbar.SetMarkerStyle(21);
hist_ttbar.SetMarkerColor(kRed);
hist_Tprime300.SetMarkerColor(kOrange + 1);
hist_Tprime300.SetMarkerStyle(22);
hist_Tprime350.SetMarkerColor(kGray + 3);
hist_Tprime350.SetMarkerStyle(3);
else:
hs = THStack("MC", "MC");
# hs.Add(hist_qcd);
# hs.Add(hist_zjets);
# hs.Add(hist_wjets);
# hs.Add(hist_singleTop);
hs.Add(hist_ttbar);
max = 0
if hist_jecdown.GetMaximum() > hist_jecnone.GetMaximum():
max = hist_jecdown.GetMaximum()*1.1
else:
max = hist_data.GetMaximum()*1.1
if hist_jecup.GetMaximum() > max :
max = hist_jecup.GetMaximum() * 1.1
# if hist_wpm400.GetMaximum() > max :
# max = hist_wpm400.GetMaximum() * 1.1
if (false and 'wp1topmass' in histname):
hist_data.GetYaxis().SetRangeUser(0, 310);
elif (false and 'mLepTopLone' in histname):
hist_data.GetYaxis().SetRangeUser(0, 510);
elif (false and 'mHadTopLone' in histname):
hist_data.GetYaxis().SetRangeUser(0, 400);
elif ('jetmultip' in histname):
hist_data.GetYaxis().SetRangeUser(0, 1600);
elif ('looseeleciso' in histname):
hist_data.GetYaxis().SetRangeUser(0, 0.2);
else:
hist_data.GetYaxis().SetRangeUser(0.01, max);
if (logscale):
canvases[-1].SetLogy();
hist_data.SetStats(1);
# hist_data.Draw('error hist');
hist_data.Draw('axis');
# hist_data.Draw("hist");
hist_data.SetMarkerStyle(8);
if ('jet1' in histname):
hist_ttbar.Draw("same");
else:
# hs.Draw("hist same");
# hist_ttbar.Draw("hist same");
# hist_stsusy300.Draw("hist same");
# hist_stsusy300_v2.Draw("hist same");
hist_jecup.Draw("hist error same");
hist_jecdown.Draw("hist error same");
hist_jecnone.Draw("hist error same");
# hist_jecdownpriv.Draw("hist error same");
# hist_Zprime500.Draw("same");
# hist_Zprime750.Draw("same");
# hist_Zprime1000.Draw("same");
# hist_Zprime2000.Draw("same");
# hist_Zprime4000.Draw("same");
# hist_Tprime300.Draw("same");
# hist_Tprime350.Draw("same");
# hist_Zprime1250.Draw("same");
# hist_Zprime1500.Draw("same");
# hist_wpm600.Draw("hist same");
# if (not 'num' in histname or not 'Top' in histname):
#hist_wpm400.Draw("hist same");
# hist_wpm800.Draw("hist same");
# hist_wpm1000.Draw("hist same");
# hist_wptb1000.Draw("same");
# qcdUncert.Draw("1 same");
# hist_data2.Draw("error same");
# hist_data.Draw("error same");
# hist_data.Draw("same");
leg.Draw();
text1 = TLatex(3.570061, 23.08044, "CMS Preliminary");
text1.SetNDC();
text1.SetTextAlign(13);
text1.SetX(0.38);
text1.SetY(0.938);
#text1.SetLineWidth(2);
text1.SetTextFont(42);
text1.SetTextSizePixels(24);# dflt=28
text1.SetTextSize(0.02);
text1.Draw();
# text2 = TLatex(3.570061, 23.08044, "#sqrt{s} = 8 TeV");
text2 = TLatex(3.570061, 23.08044, "%d pb^{-1} at #sqrt{s} = 8 TeV" % lumi);
text2.SetNDC();
text2.SetTextAlign(13);
text2.SetX(0.38);
text2.SetY(0.89);
#text2.SetLineWidth(2);
text2.SetTextFont(42);
text2.SetTextSizePixels(24);# dflt=28
text2.SetTextSize(0.02);
# text2.Draw();
# canvases[-1].SaveAs('plots/' + histname + '.png')
if (false and 'iso' in histname):
canvases[-1].SaveAs('plots/' + histname + '.root')
else:
canvases[-1].SaveAs('plots/' + histname + '.png')
# canvases[-1].SaveAs('plots/' + histname + '.png')
# canvases[-1].SaveAs('/storage/results/' + histname + '.png')
cu_hist_data = getCumulativePlot(hist_data, "data");
cu_hist_ttbar = getCumulativePlot(hist_ttbar, "ttbar");
cu_hist_stsusy300 = getCumulativePlot(hist_stsusy300, "stsusy300");
cu_hist_stsusy300_v2 = getCumulativePlot(hist_stsusy300_v2, "stsusy300");
cu_hist_jecnone = getCumulativePlot(hist_jecnone, "rvp200");
cu_hist_jecup = getCumulativePlot(hist_jecup, "rvp200");
cu_hist_jecdown = getCumulativePlot(hist_jecdown, "rvp400");
cu_hist_jecdownpriv = getCumulativePlot(hist_jecdownpriv, "rvp400");
# cu_hist_qcd = getCumulativePlot(hist_qcd, "qcd");
# cu_hist_singleTop = getCumulativePlot(hist_singleTop, "singleTop");
# cu_hist_wpm400 = getCumulativePlot(hist_wpm400, "Wprimet400");
# cu_hist_wpm600 = getCumulativePlot(hist_wpm600, "Wprimet600");
# cu_hist_wpm800 = getCumulativePlot(hist_wpm800, "Wprimet800");
# cu_hist_wpm1000 = getCumulativePlot(hist_wpm1000, "Wprimet1000");
# cu_hist_wptb1000 = getCumulativePlot(hist_wptb1000, "Wprimetb1000");
# cu_hist_Zprime500 = getCumulativePlot(hist_Zprime500, "Zprime500");
# cu_hist_Zprime750 = getCumulativePlot(hist_Zprime750, "Zprime750");
# cu_hist_Zprime1000 = getCumulativePlot(hist_Zprime1000, "Zprime1000");
# cu_hist_Zprime2000 = getCumulativePlot(hist_Zprime2000, "Zprime2000");
# cu_hist_Zprime4000 = getCumulativePlot(hist_Zprime4000, "Zprime4000");
# cu_hist_Tprime300 = getCumulativePlot(hist_Tprime300, "Tprime300");
# cu_hist_Tprime350 = getCumulativePlot(hist_Tprime350, "Tprime350");
## cu_hist_Zprime1250 = getCumulativePlot(hist_Zprime1250, "Zprime1250");
## cu_hist_Zprime1500 = getCumulativePlot(hist_Zprime1500, "Zprime1500");
cu_hist_data.SetTitleSize(0.04, "X");
cu_hist_data.SetTitleSize(0.04, "Y");
cu_hist_data.SetYTitle("Integrated Events");
cu_hist_data.SetTitleOffset(1.3, "X");
cu_hist_data.SetTitleOffset(1.7, "Y");
##
#
cu_hist_data.SetAxisRange(Urange[0], Urange[1]);
cu_hist_ttbar.SetAxisRange(Urange[0], Urange[1]);
cu_hist_stsusy300.SetAxisRange(Urange[0], Urange[1]);
cu_hist_stsusy300_v2.SetAxisRange(Urange[0], Urange[1]);
cu_hist_jecnone.SetAxisRange(Urange[0], Urange[1]);
cu_hist_jecup.SetAxisRange(Urange[0], Urange[1]);
cu_hist_jecdown.SetAxisRange(Urange[0], Urange[1]);
cu_hist_jecdownpriv.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_qcd.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_singleTop.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_wpm400.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_wpm600.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_wpm800.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_wpm1000.SetAxisRange(Urange[0], Urange[1]);
# cu_hist_wptb1000.SetAxisRange(Urange[0], Urange[1]);
if (Yrange[1] > 0):
cu_hist_data.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_ttbar.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_stsusy300.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_stsusy300_v2.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_jecnone.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_jecup.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_jecdown.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hist_jecdownpriv.SetAxisRange(Yrange[0], Yrange[1], "Y");
cu_hs = THStack("cu_MC", "cu_MC");
# cu_hs.Add(cu_hist_qcd);
# cu_hs.Add(cu_hist_zjets);
# cu_hs.Add(cu_hist_wjets);
cu_hs.Add(cu_hist_ttbar);
scanvases.append(TCanvas("cu_cname" + histname, histname + "(cu)", 1200, 900))
# if ('iso' in histname or 'jetmultip' in histname or 'num' in histname and 'Top' in histname):
scanvases[-1].SetGrid();
# if ('muiso' in histname):
# scanvases[-1].SetLogy();
scanvases[-1].cd().SetRightMargin(0.04);
# cu_hist_data.Draw("error");
# cu_hist_data.Draw("axis");
cu_hist_data.SetStats(0);
if (logscale):
scanvases[-1].SetLogy();
# cu_hist_data.Draw("hist");
cu_hist_data.Draw("axis");
# cu_hist_data.Draw("p same");
# cu_hist_ttbar.Draw("hist same");
# cu_hist_stsusy300.Draw("hist same");
# cu_hist_stsusy300_v2.Draw("hist same");
cu_hist_jecnone.Draw("same");
cu_hist_jecup.Draw("same");
cu_hist_jecdown.Draw("same");
cu_hist_jecdownpriv.Draw("same");
# if (not 'num' in histname or not 'Top' in histname):
# cu_hist_wpm400.Draw("same");
# cu_hist_wpm800.Draw("same");
# cu_hist_wpm1000.Draw("same");
# cu_hist_wptb1000.Draw("same");
# cu_hist_Zprime500.Draw("same");
# cu_hist_Zprime750.Draw("same");
# cu_hist_Zprime1000.Draw("same");
# cu_hist_Zprime2000.Draw("same");
# cu_hist_Zprime4000.Draw("same");
# cu_hist_Tprime300.Draw("same");
# cu_hist_Tprime350.Draw("same");
### cu_hist_Zprime1250.Draw("same");
### cu_hist_Zprime1500.Draw("same");
## # cu_hist_data2.Draw("error same");
# cu_hist_data.Draw("error same");
leg.Draw();
##
text1.Draw();
##
text2.Draw();
# scanvases[-1].SaveAs('/storage/results/' + histname + '_integrated.png')
scanvases[-1].SaveAs('plots/' + histname + '_integrated.png')
# tdrGrid: Turns the grid lines on (true) or off (false)
#def tdrGrid(bool gridOn):
# tdrStyle.SetPadGridX(gridOn);
# tdrStyle.SetPadGridY(gridOn);
#
# fixOverlay: Redraws the axis
def setCorrErrs(hist_good, hist_bad, hist_diff):
nbins = hist_diff.GetXaxis().GetNbins();
goodval = hist_good.GetBinContent(i);
badval = hist_bad.GetBinContent(i);
gooderr = hist_good.GetBinError(i);
baderr = hist_bad.GetBinError(i);
errsum = goodval + badval;
for i in range(1, nbins):
if errsum > 0:
# print 'evts err ', goodval, gooderr;
goodprod = goodval * baderr;
badprod = gooderr * badval;
tot = (goodprod * goodprod) + (badprod * badprod);
# Assume 90% correlation
tot = tot - (1.8 * goodprod * badprod);
if tot > 0:
tot = 4.0 * sqrt(tot) / (errsum * errsum);
hist_diff.SetBinError(i, tot);
def setUncorrErrs(hist_good, hist_bad, hist_diff):
nbins = hist_diff.GetXaxis().GetNbins();
for i in range(1, nbins):
goodval = hist_good.GetBinContent(i);
badval = hist_bad.GetBinContent(i);
err = goodval + badval;
err = err * err * err;
if err > 0:
err = 4.0 * sqrt((goodval * badval) / err);
hist_diff.SetBinError(i, err);
def asymmetryplot(hist_good, hist_bad, histname):
hist_total = hist_good.Clone("test");
# hist_total.Sumw2();
hist_total.Add(hist_bad);
hist_diff = hist_good.Clone("test");
# hist_diff.Sumw2();
hist_diff.Add(hist_bad, -1);
hist_total.Scale(0.5);
hist_diff.Divide(hist_total);
# setCorrErrs(hist_good, hist_bad, hist_diff);
hist_diff.SetXTitle("W' mass [GeV]");
hist_diff.SetYTitle("Asymmetry");
hist_diff.SetAxisRange(200, 1100);
hist_diff.SetLineWidth(4);
# hist_diff.SetFillStyle(1001);
hist_diff.SetFillStyle(3001);
hist_diff.SetFillColor(kRed);
canvases[-1].SetGridy();
hist_diff.GetYaxis().SetRangeUser(-asymrange, asymrange);
hist_diff.Draw("hist E1");
canvases[-1].SaveAs('plots/' + histname + '.png')
def asymmetry2plot(ttbar_good, ttbar_bad, wp_good, wp_bad, histname):
hist_total = ttbar_good.Clone("test");
# hist_total.Sumw2();
hist_total.Add(ttbar_bad);
hist_total.Add(wp_good);
hist_total.Add(wp_bad);
hist_total.Scale(0.5);
hist_diff = ttbar_good.Clone("test");
# hist_diff.Sumw2();
hist_diff.Add(wp_good);
hist_diff.Add(ttbar_bad, -1);
hist_diff.Add(wp_bad, -1);
hist_diff.Divide(hist_total);
# nbins = hist_diff.GetXaxis().GetNbins();
hist_good = ttbar_good.Clone("test");
hist_good.Add(wp_good);
hist_bad = ttbar_bad.Clone("test");
hist_bad.Add(wp_bad);
# setCorrErrs(hist_good, hist_bad, hist_diff);
hist_diff.SetXTitle("W' mass [GeV]");
hist_diff.SetYTitle("Asymmetry");
hist_diff.SetAxisRange(200, 1100);
hist_diff.SetLineWidth(4);
# hist_diff.SetFillStyle(1001);
hist_diff.SetFillStyle(3001);
hist_diff.SetFillColor(kRed);
canvases[-1].SetGridy();
hist_diff.GetYaxis().SetRangeUser(-asymrange, asymrange);
hist_diff.Draw("hist E1");
canvases[-1].SaveAs('plots/' + histname + '.png')
def plusminuscmp(hist_pos, hist_neg, hist_name, sign):
hist_neg.SetXTitle("Reco W' mass [GeV]");
hist_neg.SetYTitle("Events/(60 GeV)");
hist_pos.SetLineColor(kGray + 3);
hist_neg.SetLineColor(kRed);
hist_neg.SetFillStyle(0);
hist_pos.SetFillStyle(0);
linewidth = 6;
hist_pos.SetLineWidth(linewidth);
hist_neg.SetLineWidth(linewidth);
leg = TLegend(0.696, 0.35, 0.95, 0.92);
leg.SetBorderSize(0);
leg.SetLineStyle(0);
leg.SetTextFont(42);
leg.SetFillStyle(0);
if sign == 1:
leg.AddEntry(hist_pos, "W't+ .6TeV (8 pb)", "L");
leg.AddEntry(hist_neg, "W't- .6TeV (8 pb)", "L");
else:
leg.AddEntry(hist_pos, "W't bad .6TeV (8 pb)", "L");
leg.AddEntry(hist_neg, "W't good .6TeV (8 pb)", "L");
hist_pos.SetStats(1);
hist_neg.Draw("hist E1");
hist_pos.Draw("hist same");
leg.Draw();
canvases[-1].SaveAs('plots/' + hist_name + '.png')
def fixOverlay():
gPad.RedrawAxis();
def getCumulativePlot(initial, type):
global counter
counter = counter + 1;
name = initial.GetName()
name = "cu_" + name + "_" + type + str(counter);
title = initial.GetTitle()
title = "cu_" + title + "_" + type;
xaxis = initial.GetXaxis().GetTitle();
yaxis = initial.GetYaxis().GetTitle();
nBins = initial.GetNbinsX();
cu = TH1F(name, title, nBins, initial.GetXaxis().GetXmin(), initial.GetXaxis().GetXmax());
for bin in range(1,nBins+1):
cu.SetBinContent(bin, initial.Integral(bin, nBins));
cu.SetFillStyle(initial.GetFillStyle());
cu.SetFillColor(initial.GetFillColor());
cu.SetLineColor(initial.GetLineColor());
cu.SetMarkerSize(initial.GetMarkerSize());
cu.SetMarkerStyle(initial.GetMarkerStyle());
cu.SetMarkerColor(initial.GetMarkerColor());
cu.SetLineWidth(initial.GetLineWidth());
cu.GetXaxis().SetTitle(xaxis);
cu.GetYaxis().SetTitle(yaxis);
return cu;
if __name__ == "__main__":
gROOT.SetBatch(True)
gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')
plotMttbar()
# print "press enter to quit"
# a = raw_input()
|
[
""
] | |
5ccecde465c4907dc159e2a15899f49c43186f9a
|
462446cba06fc05bd307a99884bd924ed73d90f1
|
/channel_data_ytAPI.py
|
314b1c3d4aca2dbcbd2efdac0afbb371aa9cbe45
|
[] |
no_license
|
follperson/youtube-transcript-scraper
|
6281505eb2676c8dd75a3f54538640cb09ff3c3a
|
9c0fa937c063ea377647b75b188ce1fe8aa4d6ca
|
refs/heads/master
| 2020-08-26T15:43:57.778236
| 2019-12-16T00:50:02
| 2019-12-16T00:50:02
| 217,059,933
| 1
| 0
| null | 2019-10-23T13:08:14
| 2019-10-23T13:08:14
| null |
UTF-8
|
Python
| false
| false
| 5,846
|
py
|
# This program is used to read your channelId list, and then access the YouTube API
# to get links for the most recent videos uploaded by that channel.
# an also use prespecified PlaylistID instead of channelId, in case you need to only review one playlist instead of
# all content from a given channel.
import credentials as cred
import pandas as pd
import googleapiclient.discovery
import googleapiclient.errors
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
version = '20191202' # filename for you output file
channels_csv = 'channels.csv'
channel_id_col = 'channelId'
video_id_col = 'videoId'
playlist_id_col = 'playlistId'
playlist_csv = 'playlist.csv'
max_videos_per_playlist_channel = 300
def get_youtube_api_connection():
api_service_name = "youtube"
api_version = "v3"
# Get credentials and create an API client
youtube = googleapiclient.discovery.build(
api_service_name, api_version, developerKey=cred.api_key)
return youtube
def get_data_from_api(channel_id, youtube=None, get_video=True):
if youtube is None:
# create a new YouTube API connection
youtube = get_youtube_api_connection()
# get our channel data an the playlist id for the channel uploads
upload_id, channel_data = get_channel_info(channel_id, youtube)
video_data = {}
if get_video: # we want to download videos as well as the channel data
video_data = get_videos_from_playist_id(upload_id, youtube)
return channel_data, video_data
def get_channel_info(channel_id, youtube):
channel_request = youtube.channels().list(
part='contentDetails,statistics,snippet',
id=channel_id
)
channel_response = channel_request.execute()
# Only way to get the videos uploaded by the channel is via the uploads playlist
upload_id = channel_response['items'][0]['contentDetails']['relatedPlaylists']['uploads']
# get some channel level statistics
stats = channel_response['items'][0]['statistics']
channel_cols = ['viewCount','commentCount','subscriberCount','videoCount']
channel_data = {col: stats[col] for col in channel_cols}
info = channel_response['items'][0]['snippet']
channel_info_cols = ['title', 'description', 'customUrl', 'publishedAt']
channel_data.update({col: info[col] for col in channel_info_cols if col in info})
return upload_id, channel_data
def get_videos_from_playist_id(playlist_id, youtube):
"""
take in the
:param playlist_id:
:param youtube:
:return:
"""
# youtube api parameters
part = 'snippet'
max_results = 50
playlist_request = youtube.playlistItems().list(playlistId=playlist_id, part=part, maxResults=max_results)
playlist_response = playlist_request.execute()
# video data points to collect
video_info_cols = ['publishedAt','channelId','title','description','channelTitle']
all_video_data = {}
max_steps = max_videos_per_playlist_channel // 50
steps = 0
# iterate thru the current response and collect the video data
for item in playlist_response['items']:
video_id = item['snippet']['resourceId']['videoId']
all_video_data[video_id] = {col: item['snippet'][col] for col in video_info_cols}
# get the next chunk of videos
while 'nextPageToken' in playlist_response and steps < max_steps:
next_token = playlist_response['nextPageToken']
playlist_request = youtube.playlistItems().list(playlistId=playlist_id, part=part, maxResults=max_results,
pageToken=next_token)
playlist_response = playlist_request.execute()
for item in playlist_response['items']:
video_id = item['snippet']['resourceId']['videoId']
all_video_data[video_id] = {col: item['snippet'][col] for col in video_info_cols}
steps += 1
# tag on the playlist source so we can merge later on!
for video in all_video_data:
all_video_data[video].update({'playlistId': playlist_id})
return all_video_data
def download_channel_data_and_videos():
# load our channel ids
df = pd.read_csv(channels_csv, encoding='utf-8')
channel_data = {}
video_data = {}
# start the youtube api connection
youtube = get_youtube_api_connection()
for i in df.index:
print(df.loc[i, :])
channel_id = df.loc[i, channel_id_col]
c_data, v_data = get_data_from_api(channel_id, youtube, True)
channel_data.update({channel_id: c_data})
video_data.update(v_data)
# save and write our data
df_channel = pd.DataFrame(channel_data).T.reset_index().rename(columns={'index':channel_id_col})
df_video = pd.DataFrame.from_dict(video_data).T.reset_index().rename(columns={'index':video_id_col})
df_channel.to_csv('data/channel_data_ytapi_{}.csv'.format(version), index=False)
df_video.to_csv('data/video_data_ytapi_{}.csv'.format(version), index=False)
df_video.to_csv('data/video_data_ytapi_{}-inflight.csv'.format(version), index=False)
def download_playlist_videos():
df = pd.read_csv(playlist_csv, encoding='utf-8')
video_data = {}
youtube = get_youtube_api_connection()
for i in df.index:
print(df.loc[i, :])
playlist_id = df.loc[i, playlist_id_col]
v_data = get_videos_from_playist_id(playlist_id, youtube)
video_data.update(v_data)
df_video = pd.DataFrame.from_dict(video_data).T.reset_index().rename(columns={'index': video_id_col})
df_video.to_csv('data/video_data_ytapi_{}_playlist.csv'.format(version), index=False)
df_video.to_csv('data/video_data_ytapi_{}_playlist-inflight.csv'.format(version), index=False)
def main():
# download_channel_data_and_videos()
# download_playlist_videos()
pass
if __name__ == '__main__':
main()
|
[
"follmann.andrew@gmail.com"
] |
follmann.andrew@gmail.com
|
d5e68d3530c7eb13296b055ac0a26e38fb84e1fe
|
267cca3d3ff54012748fcb3dd3bbc90e1900ca51
|
/read_file.py
|
e87a055af807701d2042ff484b7603f38870a79a
|
[] |
no_license
|
sishui198/python_code_snippet
|
32b18d1a50260122985aaf7f395ebaf75b32a6e1
|
effdd5358c6730c6c703ffc8f4b467f7bd02feee
|
refs/heads/master
| 2020-03-19T07:19:01.108546
| 2017-12-13T02:34:42
| 2017-12-13T02:34:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 186
|
py
|
file_object = open('re.py')
try:
file_context = file_object.read()
print type(file_context)
# file_context = open(file).read().splitlines()
finally:
file_object.close()
|
[
"xishengbo@baidu.com"
] |
xishengbo@baidu.com
|
7d1f869180858e3a91a90f69ad6d69b93258516f
|
42b756d466716ba1bdc67e7a2211263774a1409a
|
/sql.py
|
ec4ad65389140a50ca1f07a41d61e6776355a8c5
|
[] |
no_license
|
lurkerzhang/SqlSimulated
|
74f12155f916b43057ead1307fc5793d4ffc0b1a
|
11a19972d7863103f25104fe666cc45291c3f590
|
refs/heads/master
| 2020-04-10T00:00:12.231269
| 2018-12-12T08:14:11
| 2018-12-12T08:14:11
| 160,673,120
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,476
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/25 08:12
# @Author : lurkerzhang
# @File : sql.py
# @Descript: 员工信息增删改查程序,须支持如下语法:
# 1.find name,age from staff_table where age > 22
# 2.find * from staff_table where dept = "IT"
# 3.find * from staff_table where enroll_date like "2013"
# 4.add staff_table Alex Li,25,134435344,IT,2015‐10‐29
# 5.del from staff_table where id=3
# 6.UPDATE staff_table SET dept="Market" WHERE dept = "IT" 把所有dept=IT的纪录的dept改成Market
# 7.UPDATE staff_table SET age=25 WHERE name = "Alex Li" 把name=Alex Li的纪录的年龄改成25
# 注:以上每条语名执行完毕后,要显示这条语句影响了多少条纪录。 比如查询语句 就显示 查询出了多少条、
# 修改语句就显示修改了多少条等。
import os
# 连接数据文件(数据表)
def collect_table(table_name):
try:
table = []
with open(table_name, 'r', encoding='utf-8') as t:
for r in t:
r = r.strip().split(',')
r[0], r[2] = int(r[0]), int(r[2])
table.append(r)
return table
except IOError:
print('操作的数据表不存在')
return None
# 定义员工数据表头
def table_header():
return ['id', 'name', 'age', 'phone', 'dept', 'enroll_date']
# 定义sql语句类别
def sql_types():
return ['find', 'add', 'update', 'del']
# 定义sql语句关键词
def sql_keywords():
return ['find', 'add', 'update', 'del', 'where', 'set', 'like']
# 将sql语句关键字变成小写
def list_lower(l):
l_lower = []
for i in l:
if isinstance(i, str) and i.lower() in sql_keywords():
i = i.lower()
l_lower.append(i)
return l_lower
# sql语句结构化字典(find,add,update,del)
def sql_to_dic(sql):
sql_list = list(filter(None, list_lower(sql.split(' '))))
# 添加where默认,支持find * from staff_table语句查询所有数据
if sql_list[0] == 'find' and 'where' not in sql_list:
sql_list.extend(['where', '', ''])
# 定义find语句结构的关键字
find_dic = {
'type': sql_find,
'k1': 'find',
'k2': 'from',
'k3': 'where',
}
# 定义add语句结构的关键字
add_dic = {
'type': sql_add,
'k1': 'add',
'k2': 'line',
}
# 定义update语句结构的关键字
update_dic = {
'type': sql_update,
'k1': 'update',
'k2': 'set',
'k3': 'where',
}
# 定del语名的关键字
del_dic = {
'type': sql_del,
'k1': 'del',
'k2': 'from',
'k3': 'where',
}
sql_type = sql_classify(sql)
try:
sql_struct = eval('{0}_dic'.format(sql_type))
except:
print('语法错误')
return 0
sql_dic = {}
try:
if sql_type:
# 根据定义的不同类型的sql语句结构组装成sql语句成字典
if sql_type == 'add':
sql_dic = {
'sql_exec': sql_struct['type'],
sql_struct['k1']: ' '.join(sql_list[1:2]),
sql_struct['k2']: (' '.join(sql_list[2:])),
}
else:
# 获取sql语句关键字段的切片位置
k1_l, k1_r = 1, sql_list.index(sql_struct['k2'])
k2_l, k2_r = sql_list.index(sql_struct['k2']) + 1, sql_list.index(sql_struct['k3'])
k3_l = sql_list.index(sql_struct['k3']) + 1
# 结构化sql语句为字典
k1_val = sql_list[k1_l:k1_r]
k1_val = ' '.join(k1_val).strip()
k2_val = sql_list[k2_l:k2_r]
k2_val = ' '.join(k2_val).strip()
k3_val = sql_list[k3_l:]
k3_val = ' '.join(k3_val).strip()
sql_dic = {
'sql_exec': sql_struct['type'],
sql_struct['k1']: k1_val,
sql_struct['k2']: k2_val,
sql_struct['k3']: k3_val,
}
return sql_dic
except:
print('语法错误1')
return 0
# where字段转换成列表
def parse_to_list(where_s):
cal = ['>', '<', '=', '>=', '<=', 'like']
l = []
for i in cal:
if i in where_s:
l = where_s.split(i)
l.insert(1, i)
where_l = []
for i in l:
i = i.strip()
where_l.append(i)
return where_l
# 解析匹配where字段,满足条件返回True,否则返回False
def match_where(where_s, line_l):
line_dic = dict(zip(table_header(), line_l))
# 将where字段转换成python语句where_excec
where_l = parse_to_list(where_s)
try:
where_l[0] = "line_dic['%s']" % where_l[0]
except:
return 0
where_exec = ''
if where_l[1] == 'like':
# 如果是like语法,将比较值都转小写,提高模糊查询精度
where_exec = ' '.join(["'%s'" % str(where_l[2]).lower(), 'in', "'%s'" % eval(where_l[0]).lower()])
elif where_l[1] == '=':
if not where_l[2].isdigit():
where_l[2] = "'%s'" % where_l[2]
where_exec = ' '.join([where_l[0], '==', where_l[2]])
else:
where_l[2] = "%s" % where_l[2]
where_exec = ' '.join([where_l[0], '==', where_l[2]])
elif where_l[1] in ['>', '<', '>=', '<=']:
where_exec = ' '.join(where_l)
else:
return False
return eval(where_exec)
# 判断sql语句类别:find,add,update,del
def sql_classify(sql):
s = sql.split(' ')
if s[0].lower() in sql_types():
return s[0].lower()
else:
return False
# 判断phone值是否重复
def is_phone_unique(table, phone):
is_unique = True
for i in table:
if i[3] == str(phone):
is_unique = False
return is_unique
# 操作结果显示
def show_result(res):
if res:
print('%s%s' % (res['result'], res['record']))
else:
print('操作失败')
# 查询数据
def sql_find(sql_dic):
rt, rd = '', ''
table = collect_table(sql_dic['from'])
# 格式化修改字段
while_s = format_s(sql_dic['where'])
if not table:
return False
find_l = []
record = 0
sql_dic['find'] = sql_dic['find'].replace(' ', '').split(',')
sql_dic['find'] = table_header() if sql_dic['find'] == ['*'] else sql_dic['find']
for i in table:
try:
if not while_s:
j = dict(zip(table_header(), i))
find_l.append(j)
record += 1
else:
if match_where(while_s, i):
j = dict(zip(table_header(), i))
find_l.append(j)
record += 1
except:
rt = '未查询到符合条件的记录'
rd = ''
if find_l:
head = ''
for i in sql_dic['find']:
head = head + '{:^15}'.format(i)
print(head)
for i in find_l:
line = ''
for k in sql_dic['find']:
i[k] = str(i[k]) if isinstance(i[k], int) else i[k]
line = line + '{:^15}'.format(i[k])
print(line)
rt = '查询成功!'
rd = '查询到符合条件的记录%s条' % record
else:
rt = '未查询到符合条件的记录'
rd = ''
return {'result': rt, 'record': rd}
# 增加数据
def sql_add(sql_dic):
rt, rd = '', ''
table = collect_table(sql_dic['add'])
if not table:
rt = '数据表操作错误'
rd = ''
else:
line = sql_dic['line'].split(',')
if is_phone_unique(table, line[2]):
with open(sql_dic['add'], 'a', encoding='utf-8') as t:
line.insert(0, len(table) + 1)
t.write('\n' + ','.join(list(map(lambda j: str(j) if isinstance(j, int) else j, line))))
rt = '增加成功!'
rd = '成功增加1条记录'
else:
rt = '增加失败!'
rd = '电话号码重复'
return {'result': rt, 'record': rd}
# 改数据
def sql_update(sql_dic):
# 修改结果变量
rt, rd = '', ''
record = 0
table = collect_table(sql_dic['update'])
if not table:
return False
else:
# 格式化修改字段
while_s = format_s(sql_dic['where'])
set_l = parse_to_list(sql_dic['set'])
set_l[2] = format_s(set_l[2])
set_l[2] = int(set_l[2]) if set_l[2].isdigit() else set_l[2]
# 如果修改的是phone字段,判断phone是否重复
if set_l[0] == 'phone' and not is_phone_unique(table, set_l[2]):
rt = '修改失败,电话号码已存在数据表中不能重复'
rd = ''
else:
index = (table_header().index(set_l[0])) # 获取数据行要修改的位置
count = 0
try:
with open('new', 'w', encoding='utf-8') as f:
for i in table:
count += 1
if match_where(while_s, i):
i[index] = set_l[2]
write_to_file(i, f)
record += 1
if count < len(table):
f.write('\n')
else:
write_to_file(i, f)
if count < len(table):
f.write('\n')
# 判断如果修改的是phone,修改记录大于1条,禁止保存
if set_l[0] == 'phone' and record > 1:
rt = '修改失败!修改的记录大于1条,号码重复,禁止修改'
rd = ''
elif record == 0:
rt = '修改失败!'
rd = '符合条件的数据为0'
else:
rt = '修改成功!'
rd = '修改数据%s条' % record
os.replace('new', 'staff_table')
except:
rt = '语法错误!'
rd = ''
return {'result': rt, 'record': rd}
# 删数据
def sql_del(sql_dic):
rt, rd = '', ''
record = 0
table = collect_table(sql_dic['from'])
while_s = format_s(sql_dic['where'])
if not table:
return False
else:
count = 0
new_id = 1
with open('new', 'w', encoding='utf-8') as f:
for i in table:
count += 1
if match_where(while_s, i):
record += 1
else:
i[0] = new_id
write_to_file(i, f)
if count < len(table):
f.write('\n')
new_id += 1
if record == 0:
rt = '删除失败!未找到符合条件的数据'
rd = ''
else:
rt = '删除成功!'
rd = '删除数据%s条,数据表ID已重新排序' % record
os.replace('new', 'staff_table')
return {'result': rt, 'record': rd}
# 格式化字符串
def format_s(s):
return s.replace('\'', '').replace('\"', '').strip()
# 把数据列写到文件
def write_to_file(i, f):
f.write(','.join(list(map(lambda j: str(j) if isinstance(j, int) else j, i))))
# 为测试打印的语句示例
def test_sql():
sqls = ''' ----------------测试语句示例------------
1.find * from staff_table
2.find name,age from staff_table where age> 22
3.find * from staff_table where dept ="IT"
4.find * from staff_table where enroll_date like "2013"
5.add staff_table Alex Li,25,134435344,IT,2015‐10‐29
6.del from staff_table where id=3
7.UPDATE staff_table SET dept="Market" WHERE dept = "IT"
8.UPDATE staff_table SET age=25 WHERE name ="Alex Li"
----------------------------------------'''
print(sqls)
def main():
test_sql()
while True:
sql = input("请输入sql语句(输入'Q'退出)>>>")
if sql.strip() in ['q', 'Q']:
exit('bye')
else:
sql_dic = sql_to_dic(sql)
if sql_dic:
result = sql_dic['sql_exec'](sql_dic)
show_result(result)
if __name__ == '__main__':
main()
|
[
"lurkerzhang@foxmail.com"
] |
lurkerzhang@foxmail.com
|
310126961dc54e2b1256524faee1e3c32addc4c5
|
b4e41521e761c10caf6f8855da7569fb6c8217dd
|
/lesson7.py
|
3eaa6ce36e0069620f85cf9a05263a7e35ded993
|
[] |
no_license
|
mrVovster/Geek_brains_python
|
1f5adb970384211916c5386cd22b97693e65b42e
|
90b80201c283d416b5d16e4de7f16b332e635f78
|
refs/heads/main
| 2023-08-18T10:37:01.804476
| 2021-10-20T18:14:01
| 2021-10-20T18:14:01
| 410,644,767
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 9,156
|
py
|
"""
Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()), который должен
принимать данные (список списков) для формирования матрицы. Подсказка: матрица — система некоторых математических
величин, расположенных в виде прямоугольной схемы. Примеры матриц вы найдете в методичке. Следующий шаг — реализовать
перегрузку метода __str__() для вывода матрицы в привычном виде. Далее реализовать перегрузку метода __add__() для
реализации операции сложения двух объектов класса Matrix (двух матриц). Результатом сложения должна быть новая
матрица. Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы
складываем с первым элементом первой строки второй матрицы и т.д.
"""
from typing import List
class Matrix:
def __init__(self, matrix_data: List[List]):
self.__matrix = matrix_data
m_rows = len(self.__matrix)
self.__matrix_size = frozenset([(m_rows, len(row)) for row in self.__matrix])
if len(self.__matrix_size) != 1:
raise ValueError("Invalid matrix size")
def __add__(self, other: "Matrix") -> "Matrix":
if not isinstance(other, Matrix):
raise TypeError(f"'{other.__class__.__name__}' "
f"incompatible object type")
if self.__matrix_size != other.__matrix_size:
raise ValueError(f"Matrix sizes difference")
result = []
for item in zip(self.__matrix, other.__matrix):
result.append([sum([j, k]) for j, k in zip(*item)])
return Matrix(result)
def __str__(self) -> str:
return '\n'.join(['\t'.join(map(str, row)) for row in self.__matrix])
if __name__ == '__main__':
matrix1 = Matrix([[1, 2], [3, 4]])
print(matrix1, '\n')
matrix2 = Matrix([[10, 20], [30, 40]])
print(matrix2, '\n')
print(matrix1 + matrix2)
"""
Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная сущность (класс) этого
проекта — одежда, которая может иметь определенное название. К типам одежды в этом проекте относятся пальто и костюм.
У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма). Это могут быть обычные числа: V и
H, соответственно. Для определения расхода ткани по каждому типу одежды использовать формулы: для пальто (V/6.5 +
0.5), для костюма (2 * H + 0.3). Проверить работу этих методов на реальных данных. Реализовать общий подсчет расхода
ткани. Проверить на практике полученные на этом уроке знания: реализовать абстрактные классы для основных классов
проекта, проверить на практике работу декоратора @property.
"""
class Textile:
def __init__(self, width, height):
self.width = width
self.height = height
def get_square_c(self):
return self.width / 6.5 + 0.5
def get_square_j(self):
return self.height * 2 + 0.3
@property
def get_sq_full(self):
return str(f'Площадь общая ткани \n'
f' {(self.width / 6.5 + 0.5) + (self.height * 2 + 0.3)}')
class Coat(Textile):
def __init__(self, width, height):
super().__init__(width, height)
self.square_c = round(self.width / 6.5 + 0.5)
def __str__(self):
return f'Площадь на пальто {self.square_c}'
class Jacket(Textile):
def __init__(self, width, height):
super().__init__(width, height)
self.square_j = round(self.height * 2 + 0.3)
def __str__(self):
return f'Площадь на костюм {self.square_j}'
coat = Coat(2, 4)
jacket = Jacket(1, 2)
print(coat)
print(jacket)
print(coat.get_sq_full)
print(jacket.get_sq_full)
print(jacket.get_square_c())
print(jacket.get_square_j())
"""
Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка. В его конструкторе
инициализировать параметр, соответствующий количеству клеток (целое число). В классе должны быть реализованы методы
перегрузки арифметических операторов: сложение (__add__()), вычитание (__sub__()), умножение (__mul__()),
деление (__truediv__()).Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение,
умножение и обычное (не целочисленное) деление клеток, соответственно. В методе деления должно осуществляться
округление значения до целого числа. Сложение. Объединение двух клеток. При этом число ячеек общей клетки должно
равняться сумме ячеек исходных двух клеток. Вычитание. Участвуют две клетки. Операцию необходимо выполнять только
если разность количества ячеек двух клеток больше нуля, иначе выводить соответствующее сообщение. Умножение.
Создается общая клетка из двух. Число ячеек общей клетки определяется как произведение количества ячеек этих двух
клеток. Деление. Создается общая клетка из двух. Число ячеек общей клетки определяется как целочисленное деление
количества ячеек этих двух клеток. В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и
количество ячеек в ряду. Данный метод позволяет организовать ячейки по рядам. Метод должен возвращать строку вида
*****\n*****\n*****..., где количество ячеек между \n равно переданному аргументу. Если ячеек на формирование ряда не
хватает, то в последний ряд записываются все оставшиеся. Например, количество ячеек клетки равняется 12, количество
ячеек в ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n**. Или, количество ячеек клетки равняется
15, количество ячеек в ряду — 5. Тогда метод make_order() вернет строку: *****\n*****\n*****.
"""
class Cell:
def __init__(self, quantity):
self.quantity = int(quantity)
def __str__(self):
return f'Результат операции {self.quantity * "*"}'
def __add__(self, other):
return Cell(self.quantity + other.quantity)
def __sub__(self, other):
return self.quantity - other.quantity if (self.quantity - other.quantity) > 0 else print('Отрицательно!')
def __mul__(self, other):
return Cell(int(self.quantity * other.quantity))
def __truediv__(self, other):
return Cell(round(self.quantity // other.quantity))
def make_order(self, cells_in_row):
row = ''
for i in range(int(self.quantity / cells_in_row)):
row += f'{"*" * cells_in_row} \\n'
row += f'{"*" * (self.quantity % cells_in_row)}'
return row
cells1 = Cell(33)
cells2 = Cell(9)
print(cells1)
print(cells1 + cells2)
print(cells2 - cells1)
print(cells2.make_order(5))
print(cells1.make_order(10))
print(cells1 / cells2)
|
[
"egorov941@gmail.com"
] |
egorov941@gmail.com
|
1bd5c0967f9f9e3846fcd377bab507a9cecf4e05
|
f9e80e63263712bc44cdb0ae267f9d161f9c3fc9
|
/main_app/migrations/0007_remove_restaurant_rating.py
|
f7a40f9b484088a0c4009c3786b557dafed5084e
|
[] |
no_license
|
crnguyen/FoodFuse
|
cb99fc1487d6587fb40c95091996a8e06e945c80
|
c5d985321d3e150a5314a88d0f40a5f266bb98a5
|
refs/heads/master
| 2023-04-13T03:51:10.130073
| 2021-04-13T20:04:12
| 2021-04-13T20:04:12
| 298,864,589
| 1
| 0
| null | 2020-10-05T15:47:44
| 2020-09-26T17:23:24
|
Python
|
UTF-8
|
Python
| false
| false
| 333
|
py
|
# Generated by Django 3.1.1 on 2020-10-01 07:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main_app', '0006_auto_20201001_0553'),
]
operations = [
migrations.RemoveField(
model_name='restaurant',
name='rating',
),
]
|
[
"cristinanguyen@MacBook-Pro.local"
] |
cristinanguyen@MacBook-Pro.local
|
0db8341373ab692fc767c2641a48c1d668f667da
|
f59b18dcb0255a20542167069968cb799f9271c1
|
/similarity_scoring/umbc_scoring.py
|
7b51c6128e2f2f3f57a88f926903b71f7c2bd07c
|
[] |
no_license
|
happinesstaker/FYP
|
d36a17ff69ba153cbbe318d6d4ceb098f8f6bb82
|
a59815b7481a295bb0bb2ede80ae62fe566a1e93
|
refs/heads/master
| 2021-01-21T13:57:43.143457
| 2016-05-13T08:34:10
| 2016-05-13T08:34:10
| 45,525,925
| 0
| 0
| null | 2015-12-31T10:09:47
| 2015-11-04T08:40:21
|
Python
|
UTF-8
|
Python
| false
| false
| 6,742
|
py
|
from datetime import date, timedelta
from math import log1p, exp
from nltk.corpus import wordnet as wn
from nltk.tokenize import MWETokenizer
import nltk
import DBOperation
import FYPsetting
from lsa_matrix import LSAMatrix
from tfcos_scoring import TfSim
from wordnet_boosting import WordNet_boosting
from datetime import datetime
import re
import numpy as np
existing_articles = {}
lsa_mat = LSAMatrix(0, 0)
wn_bst = WordNet_boosting()
#tf_sim = TfSim()
def sim (token1, pos1, token2, pos2):
'''
calculate the term similarity between two terms
in LSA, by doing word vectorization first and combine vecotrs
in WordNet Boosting, term similarity is already contained
ignored the proposed weighing method for path edge
should add the LSA measurement later
:return: a the similarity score
'''
lsa_sim = lsa_mat.term_similarity(token1, token2)
wn_sim = wn_bst.term_similarity(token1, pos1, token2, pos2)
simi = 0
if token1 == token2 and pos1 == pos2:
simi = 1.0
elif lsa_sim>0.1:
simi = lsa_sim + wn_sim
elif lsa_sim <0.1:
simi = 0
else:
simi = lsa_sim
# set the ceiling as mentioned in the paper
if simi>1:
simi = 1
return simi
def inverse_log_fq(token, sent):
'''
calculate the penalty for the token's inverse log frequency
:param token:
:param sent:
:return:
'''
fdist = nltk.FreqDist(sent)
if log1p(fdist[token]):
return 1/log1p(fdist[token])
else:
return 0
def pos_weight(pos):
'''
assign POS weight to the token according to the rule written in umbc paper
1 for noun, verb, pronoun, and number; 0.5 for others
:param pos:
:return:
'''
# choose the prefix as there are detailed categories defined under NN, VB etc.
if pos[:2]=='NN' or pos[:2]=='VB' or pos[:3]=='PRP' or pos=='CD' or pos[:2]=='WP':
return 1
else:
return 0.5
def umbc_penalty(token, pos, sent, simi, counterpart):
'''
calcualte the penalty for every single token
consisting of two situations for penalty
A. very unsimilar
B. antonym
:param token:
:param pos:
:param sent:
:param simi:
:param counterpart:
:return:
'''
penalty = 0
if simi<0.2:
penalty += simi+inverse_log_fq(token, sent)*pos_weight(pos)
tag = wn_bst.get_wordnet_pos(pos)
s = wn.synsets(token, tag)
if not s==[]:
#try:
for y in range(len(s)):
ant = s[y].lemmas()[0].antonyms()
if not ant == []:
for x in range (len(ant)):
if ant[x].name() == counterpart:
penalty += (simi+0.5)
#print datetime.now(), " ", token, ": antonyms found."
#except:
#pass
return penalty
def umbc_sum(sim_dict):
'''
sum up the similarity score of every single token
:param sim_dict:
:return:
'''
sum = 0
for result in sim_dict:
sum+=sim_dict[result]['sim']
sum-=sim_dict[result]['p']
return sum
def umbc_sim (title1, title2):
'''
compares the similarity of title1 and title2
:param title1:
:param title2:
:return: a bool value, 0 for similar, 1 for not similar
'''
#print datetime.now(), " Preprocessing titles..."
title1 = title_prepocessing(title1)
title2 = title_prepocessing(title2)
#print datetime.now(), " Tokenization and parsing starts..."
tokenizer = MWETokenizer(wn_bst.multi_words_xpn())
tokens1 = tokenizer.tokenize(title1.split())
#print datetime.now(), " First title tokenized."
tagged1 = nltk.pos_tag(tokens1)
#print datetime.now(), " First title parsed."
tokens2 = tokenizer.tokenize(title2.split())
#print datetime.now(), " Second title tokenized."
tagged2 = nltk.pos_tag(tokens2)
#print datetime.now(), " Second title parsed."
# remove tokens that are not supported by WordNet
tagged1 = [x for x in tagged1 if not wn_bst.get_wordnet_pos(x[1])=='']
tagged2 = [x for x in tagged2 if not wn_bst.get_wordnet_pos(x[1])=='']
#print datetime.now(), " Tokens cleaned."
# use a matrix to store the result for later use
#print datetime.now(), " Building matrix..."
len1 = len(tagged1)
len2 = len(tagged2)
Matrix = np.zeros((len2,len1))
result1 = {}
result2 = {}
for x in range(len1):
token1=tagged1[x][0]
pos1 = tagged1[x][1]
simi = 0
counterpart1 = ''
for y in range(len2):
token2 = tagged2[y][0]
pos2 = tagged2[y][1]
Matrix[y, x] = sim(token1, pos1, token2, pos2)
if Matrix[y,x]>simi:
simi = Matrix[y, x]
counterpart1 = token2
penalty1 = umbc_penalty(token1, pos1, tokens1, simi, counterpart1)
result1[token1] = {'sim':simi, 'p':penalty1, 'counter':counterpart1}
#print datetime.now(), " Title1 result calculated..."
for y in range (0, len2):
token2=tagged2[y][0]
pos2 = tagged2[y][1]
simi = 0
counterpart2 = ''
for x in range(0, len1):
if Matrix[y,x]>simi:
simi = Matrix[y,x]
counterpart2 = tagged1[x][0]
#print token2, counterpart2, simi
penalty2 = umbc_penalty(token2, pos2, tokens2, simi, counterpart2)
result2[token2] = {'sim':simi, 'p':penalty2, 'counter':counterpart2}
#print datetime.now(), " Title2 result calculated..."
#print result1
sum1 = umbc_sum(result1)
sum1 = float(sum1)
#print result2
sum2 = umbc_sum(result2)
sum2 = float(sum2)
#print sum1, sum2
score = sum1/(2*len1)+sum2/(2*len2)
#cut upper and lower bound
if score < 0:
score = 0
return score
def title_prepocessing(string):
string = string.lstrip()
string = string.rstrip()
string = string.replace("\'", "")
string = string.replace("\"", "")
string = string.replace(".","")
string = string.replace("!","")
string = string.replace(",","")
string = string.replace("?","")
string = string.replace(":","")
string = string.replace("<","")
string = string.replace(">","")
string = string.replace(";","")
string = string.replace("[","")
string = string.replace("]","")
string = string.replace("{","")
string = string.replace("}","")
string = string.replace("(","")
string = string.replace(")","")
string = string.replace("\\", "")
string = string.replace("\s+"," ")
string = string.replace("\t", " ")
string = string.replace("\n", " ")
string = re.sub(' +',' ',string)
return string
|
[
"sirayshei@gmail.com"
] |
sirayshei@gmail.com
|
d8f23d3040def7fb2e668a8e2bcd270cc1c7b24c
|
6f8d211f6b6033ff54810268b5b7a259fb9af39a
|
/if condition.py
|
dd1f5f02cd3d6533bb034f1941195a01824e79ea
|
[] |
no_license
|
eneopetoku/Learning-Python
|
a2feb4a30b080fbcae2b35c0ab8422a5a02679d7
|
a398b4650d5794546f1115d787668d161908b9cb
|
refs/heads/master
| 2020-04-03T03:17:39.505798
| 2018-11-01T08:44:33
| 2018-11-01T08:44:33
| 154,981,509
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 27
|
py
|
x=5
if x==5:
print(x)
|
[
"petokueneo@gmail.com"
] |
petokueneo@gmail.com
|
54d9b33170e2aba633e6ee72ab93964da50fa1ac
|
0d022860ae5c57bddfe30070776f68dd1bed318b
|
/add_type/add_rev_type.py
|
0f6968499488e992c656799d3e376f95986e62f5
|
[] |
no_license
|
daniel-kurushin/wiki-graph
|
da09f50ab832d33f793c76351b72335ed18fd1ac
|
483013071b65da771b5916c02ffe600c1f8261d5
|
refs/heads/master
| 2023-03-27T19:39:31.656604
| 2021-03-24T11:24:51
| 2021-03-24T11:24:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,437
|
py
|
import re
class RevsWithTypes:
def __init__(self):
pass
def convert_revisions_to_list(self, revisions):
converted = list(map(
lambda x: {
'old_revid': x.old_revid,
'new_revid': x.new_revid,
'lines_diffs': list(map(lambda diff: {'old': diff[0], 'new': diff[1]}, x.lines_diffs))
},
revisions))
return converted
def add_type_to_revision(self, revisions):
revisions_list = self.convert_revisions_to_list(revisions)
links_regex = 'http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
wiki_links_regex = 'http[s]?:\/\/(?:[a-zA-Z])+.wikipedia.org\/'
for dict in revisions_list:
lines_diffs_list = dict['lines_diffs']
for line_numb in range(len(lines_diffs_list)):
line_diffs = lines_diffs_list[line_numb]
if line_diffs['old'] is None:
line_diffs['old'] = 'None'
if line_diffs['new'] is None:
line_diffs['new'] = 'Deleted'
match_link_old = re.search(links_regex, line_diffs['old'], flags=re.IGNORECASE)
match_link_new = re.search(links_regex, line_diffs['new'], flags=re.IGNORECASE)
if match_link_new:
if match_link_old:
if match_link_old.group() == match_link_new.group():
line_diffs['type'] = 'Малая правка'
else:
match_wiki_link = re.search(wiki_links_regex, line_diffs['new'], flags=re.IGNORECASE)
if match_wiki_link:
line_diffs['type'] = 'Перевод вики-страницы'
else:
line_diffs['type'] = 'Ссылка на источник'
else:
match_wiki_link = re.search(wiki_links_regex, line_diffs['new'], flags=re.IGNORECASE)
if match_wiki_link:
line_diffs['type'] = 'Перевод вики-страницы'
else:
line_diffs['type'] = 'Ссылка на источник'
else:
line_diffs['type'] = 'Малая правка'
return revisions_list
|
[
"lorddelivuskraust@gmail.com"
] |
lorddelivuskraust@gmail.com
|
90b60211284014eea983260c23dc16adf0446d99
|
227a34166a070ceca80448e206b54b4b078c401c
|
/src/tar/src/nmt/create_datasets.py
|
dd691643d9ac7cb7e1f2e6171a8606f81a339944
|
[
"MIT",
"CC-BY-4.0",
"GPL-3.0-only"
] |
permissive
|
ccasimiro88/TranslateAlignRetrieve
|
c42d47caa0b0597005b1442920b2cccb198f2e3b
|
c84784219785c1fc05884b26081d9b7b4156c019
|
refs/heads/master
| 2022-12-13T12:45:28.470981
| 2021-02-11T11:41:29
| 2021-02-11T11:41:29
| 213,844,388
| 63
| 15
|
MIT
| 2022-12-08T06:59:47
| 2019-10-09T06:59:44
|
Python
|
UTF-8
|
Python
| false
| false
| 4,247
|
py
|
# This script clean a parallel corpora from sentence that
# are not in the correct source/target language and
# then splits it up into train/dev/test datasets
import fasttext
import argparse
import os
import random
import time
from tqdm import tqdm
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
FASTTEXT_LANG_DETECT_MODEL = SCRIPT_DIR + '/data/fastText/lid.176.bin'
langdetect = fasttext.load_model(FASTTEXT_LANG_DETECT_MODEL)
def check_correct_target_language(text, target_language):
prediction = langdetect.predict(text)
label_language = prediction[0][0]
return label_language.endswith(target_language)
def create_datasets(source_file, target_file, source_lang, target_lang, output_dir, test_size, valid_size):
with open(source_file) as sf, open(target_file) as tf:
source_target_lines = [(s.strip(), t.strip()) for (s, t) in tqdm(zip(sf.readlines(), tf.readlines()))]
# Remove pairs duplicates
source_target_lines = set(source_target_lines)
# Remove pairs containing source or target duplicates
source_seen = set()
target_seen = set()
source_target_lines_clean = set()
for st in tqdm(source_target_lines):
if st[0] not in source_seen and st[1] not in target_seen:
source_seen.add(st[0])
target_seen.add(st[1])
source_target_lines_clean.add(st)
# Remove pairs with wrongly aligned (uncorrect translations)
source_target_lines_clean = [st for st in tqdm(source_target_lines_clean)
if check_correct_target_language(st[0], source_lang)
and check_correct_target_language(st[1], target_lang)
and st[0] != st[1]]
# Shuffle and split
random.seed(10)
random.shuffle(source_target_lines_clean)
source_target_lines_test = source_target_lines_clean[:test_size+1]
source_target_lines_valid = source_target_lines_clean[test_size+1:(valid_size+test_size)+2]
source_target_lines_train = source_target_lines_clean[(valid_size+test_size)+2:]
source_test = os.path.join(output_dir, 'test.{}'.format(source_lang))
target_test = os.path.join(output_dir, 'test.{}'.format(target_lang))
with open(source_test, 'w', encoding='utf8') as sf, open(target_test, 'w') as tf:
sf.writelines('\n'.join(st[0] for st in tqdm(source_target_lines_test)))
tf.writelines('\n'.join(st[1] for st in tqdm(source_target_lines_test)))
source_valid = os.path.join(output_dir, 'valid.{}'.format(source_lang))
target_valid = os.path.join(output_dir, 'valid.{}'.format(target_lang))
with open(source_valid, 'w', encoding='utf8') as sf, open(target_valid, 'w') as tf:
sf.writelines('\n'.join(st[0] for st in tqdm(source_target_lines_valid)))
tf.writelines('\n'.join(st[1] for st in tqdm(source_target_lines_valid)))
source_train = os.path.join(output_dir, 'train.{}'.format(source_lang))
target_train = os.path.join(output_dir, 'train.{}'.format(target_lang))
with open(source_train, 'w', encoding='utf8') as sf, open(target_train, 'w') as tf:
sf.writelines('\n'.join(st[0] for st in tqdm(source_target_lines_train)))
tf.writelines('\n'.join(st[1] for st in tqdm(source_target_lines_train)))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--source_file', type=str, help='Source file')
parser.add_argument('--target_file', type=str, help='Target file')
parser.add_argument('--source_lang', type=str, help='Source lang')
parser.add_argument('--target_lang', type=str, help='Target lang')
parser.add_argument('--output_dir', type=str, help='Output directory')
parser.add_argument('--test_size', type=int, help='Test dataset size')
parser.add_argument('--valid_size', type=int, help='Valid dataset size')
args = parser.parse_args()
if not os.path.isdir(args.output_dir):
os.mkdir(args.output_dir)
start = time.time()
create_datasets(args.source_file, args.target_file, args.source_lang, args.target_lang,
args.output_dir,
args.test_size, args.valid_size)
end = time.time()
print('Total time: {} s'.format(end-start))
|
[
"casimiro.pio.carrino@veue01.tsc.upc.edu"
] |
casimiro.pio.carrino@veue01.tsc.upc.edu
|
98b91872fb890ba158d6727df7d3821cf90836f9
|
8fd152b3ae5deb85087a1d7a503506bbbe4fd406
|
/tel_bot.py
|
2f9686bfc7e86eb216f587a6a3c60a0d0c3c4af7
|
[] |
no_license
|
mal-mel/tel-bot-places
|
a302e41c45e9802665de9f9f433b67dc5f321fa6
|
9d0b6b88a17a4a37e63679d45435d1355cabd0af
|
refs/heads/master
| 2020-05-17T16:22:25.677866
| 2019-04-27T19:59:22
| 2019-04-27T19:59:22
| 183,816,198
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,317
|
py
|
import telebot
import re
from config import token
from telebot import types
from collections import defaultdict
from db import DB
from distance_calculation import calculate
database = DB('users_places.db')
regular = '^[0-9]{,2}\.[0-9]*, [0-9]{,2}\.[0-9]*$'
bot = telebot.TeleBot(token)
START, LOCATION, DESCRIPTION, CONTINUE = range(4)
USER_STATE = defaultdict(lambda: START)
TEMP_LIST = []
def authentication(message):
"""Аутентификация пользователя"""
user_id = message.from_user.id
try:
database.query(f'select user_id from users where user_id={user_id}').fetchall()[0][0]
except IndexError:
database.query(f'insert into users values({user_id}, "{message.from_user.username}")')
def add_place(message, location, description):
"""Добавление места в БД"""
user_id = message.from_user.id
lon = location.longitude
lat = location.latitude
database.query(f'insert into places values("{lon}, {lat}", {user_id}, "{description}")')
def get_state(message):
return USER_STATE[message.chat.id]
def update_state(message, state):
USER_STATE[message.chat.id] = state
def create_keyboard(message):
places = database.query(f'select description from places where user_id={message.from_user.id}').fetchall()
if len(places) > 10:
places = places[-10:]
if len(places) == 0:
return False
keyboard = types.InlineKeyboardMarkup(row_width=2)
buttons = [types.InlineKeyboardButton(text=str(p[0]), callback_data=str(p[0]))
for p in places]
keyboard.add(*buttons)
return keyboard
@bot.message_handler(func=lambda message: get_state(message) == START)
def start_handler(message):
bot.send_message(message.chat.id, 'Привет, я бот умеющий сохранять твои любимые места и показывать их тебе\n'
'при необходимости!\n\n'
'Список доступных команд:\n'
'/add - Добавить место\n'
'/list - Показать твои места\n'
'/reset - Удаление всех мест')
authentication(message)
update_state(message, CONTINUE)
@bot.message_handler(commands=['add'])
def add_handler(message):
bot.send_message(message.chat.id, 'Для того чтобы добавить место, отправь мне его геолокацию\n'
'Или координаты формата: xx.xxxxxx, yy.yyyyyy')
update_state(message, LOCATION)
@bot.message_handler(content_types=['location', 'text'], func=lambda message: get_state(message) == LOCATION)
def location_handler(message):
"""В этом хендлере осуществляется проверка на тип переданных координат"""
if not message.text:
location = message.location
elif re.match(regular, message.text):
location = types.Location
lon, lat = message.text.split(',')
location.longitude = float(lon)
location.latitude = float(lat)
else:
bot.send_message(message.chat.id, 'По всей видимости твое сообщение не соответствует шаблону\n'
'Попробуй еще раз')
return
for i in database.query(f'select coor from places where user_id={message.from_user.id}').fetchall():
temp = i[0].split(',')
if calculate(location.latitude, float(temp[1]), location.longitude, float(temp[0])) <= 500:
place = database.query(f'select description from places where coor="{i[0]}"').fetchall()[0][0]
bot.send_message(message.chat.id,
f'Тут кстати приблизительно в 500 метрах есть одно из твоих любимых мест:\n'
f'{place}')
break
TEMP_LIST.append(message)
TEMP_LIST.append(location)
bot.send_message(message.chat.id, 'Теперь отправь мне название этого места')
update_state(message, DESCRIPTION)
@bot.message_handler(func=lambda message: get_state(message) == DESCRIPTION)
def description_handler(message):
"""Добавление места, используется временный список для хранения нужных значений"""
add_place(TEMP_LIST[0], TEMP_LIST[1], message.text)
TEMP_LIST.clear()
bot.send_message(message.chat.id, 'Место успешно добавлено')
update_state(message, CONTINUE)
@bot.message_handler(commands=['list'], func=lambda message: get_state(message) == CONTINUE)
def list_handler(message):
"""Вывод добавленных мест пользователя"""
keyboard = create_keyboard(message)
if keyboard:
bot.send_message(message.chat.id, 'Список твоих мест:', reply_markup=keyboard)
else:
bot.send_message(message.chat.id, 'Нет добавленных мест')
@bot.callback_query_handler(func=lambda callback: get_state(callback.message) == CONTINUE)
def callback_place(callback):
"""Хендлер для отправки выбранного места, с проверкой на существование этого места в БД"""
message = callback.message
data = callback.data
try:
coor = database.query(
f'select coor from places where user_id={message.chat.id} and description="{data}"').fetchall()
lon, lat = coor[0][0].split(',')
bot.send_message(message.chat.id, f'А вот и {data}')
bot.send_location(message.chat.id, lat, lon)
except IndexError:
bot.send_message(message.chat.id, 'Это место удалено')
@bot.message_handler(commands=['reset'])
def reset(message):
database.query(f'delete from places where user_id={message.from_user.id}')
bot.send_message(message.chat.id, 'Данные успешно удалены')
bot.polling(none_stop=True)
|
[
"olegsvetovidov@gmail.com"
] |
olegsvetovidov@gmail.com
|
63d89e34b7165f5b0082fa3a94a62353504b9136
|
0b468aff5c96ba1f15258220531b4dfc3913b4a6
|
/data/db_con.py
|
6596e41556d675340d1a5d8144545adf39972e91
|
[] |
no_license
|
MugdhaGodse/Trial
|
dcad3abeae8ddc0ca67681806e6ffdf0cc752620
|
7722daf8c614f4ab2a571881e8e53e100e64ef66
|
refs/heads/main
| 2023-04-17T17:59:07.856150
| 2021-04-28T12:24:34
| 2021-04-28T12:24:34
| 362,392,459
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,059
|
py
|
import mysql.connector
def insert_data(uname, passwd):
mysqldb = mysql.connector.connect(host="127.0.0.1", user="root",
passwd="root", database="botproject")
dbcursor = mysqldb.cursor()
sql = 'INSERT INTO login(username, password) VALUES ("{0}","{1}");'.format(uname, passwd)
dbcursor.execute(sql)
mysqldb.commit()
def fetch_data():
mysqldb = mysql.connector.connect(host="127.0.0.1", user="root",
passwd="root", database="botproject")
dbcursor = mysqldb.cursor()
dbcursor.execute("select * from login")
result=dbcursor.fetchall()
return result
def fetch_studentdetails():
mysqldb = mysql.connector.connect(host="127.0.0.1", user="root",
passwd="root", database="botproject")
dbcursor = mysqldb.cursor()
dbcursor.execute("select * from studentdetails,login where studentdetails.Roll_no==login.username")
result=dbcursor.fetchall()
return result
|
[
"noreply@github.com"
] |
MugdhaGodse.noreply@github.com
|
cabcfca1cfebdd1cb0c7dbcdbd736e6a82dad446
|
1044df6c19c990475649a26d056c095164a5b920
|
/pra23.py
|
e66917a42f0cce3c3c8a8d2166e81980174130ee
|
[] |
no_license
|
pengwangbupt/practice100_python
|
735d74bbf6694e937b2bc92eb02406f917a72483
|
447c17771dd417badc3b7ab4467507d87ce0be07
|
refs/heads/master
| 2020-12-25T15:17:44.314115
| 2016-09-03T09:47:41
| 2016-09-03T09:47:41
| 67,229,660
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 456
|
py
|
#!/usr/bin/python
# coding:utf-8
'''
star=['*']
for i in range(7):
print star*(2*i+1)
'''
# 一定要注意python语言的对齐方式
from sys import stdout
for i in range(4):
for j in range(2 - i + 1):
stdout.write(' ')
for k in range(2 * i + 1):
stdout.write('*')
print ' '
for i in range(3):
for j in range(i + 1):
stdout.write(' ')
for k in range(4 - 2 * i + 1):
stdout.write('*')
print ' '
|
[
"jwwbupt@163.com"
] |
jwwbupt@163.com
|
f5e0a8e43ca587db0b6e8ab3f6c3e8884dc1dbb0
|
add72f4d6f9f7af1f437d19213c14efb218b2194
|
/icekit/plugins/slideshow/migrations/0005_auto_20160927_2305.py
|
629c1e819cd89bee8d33d0a226b2688db1d516f6
|
[
"MIT"
] |
permissive
|
ic-labs/django-icekit
|
6abe859f97c709fcf51207b54778501b50436ff7
|
c507ea5b1864303732c53ad7c5800571fca5fa94
|
refs/heads/develop
| 2022-08-08T21:26:04.144852
| 2018-01-08T02:55:17
| 2018-01-08T02:55:17
| 65,470,395
| 53
| 12
|
MIT
| 2022-07-06T19:59:39
| 2016-08-11T13:11:02
|
Python
|
UTF-8
|
Python
| false
| false
| 664
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_plugins_slideshow', '0004_auto_20160821_2140'),
]
operations = [
migrations.AlterModelOptions(
name='slideshow',
options={'verbose_name': 'Image gallery', 'verbose_name_plural': 'Image galleries'},
),
migrations.AlterField(
model_name='slideshowitem',
name='slide_show',
field=models.ForeignKey(help_text='An image gallery.', to='icekit_plugins_slideshow.SlideShow'),
),
]
|
[
"greg@interaction.net.au"
] |
greg@interaction.net.au
|
5031f08805f198609e39be66e32a4ad8f53bc3ff
|
17ac3a89a2d013a9216a19d06c7da0908512c8dd
|
/code/scanner.py
|
84ec2dfc85f9b418278f5dcf017f169d85d4b8a8
|
[] |
no_license
|
CillianM/Runbook
|
28f121cf7b1fd7fe9cf9d4cdf8c42bc9fe314c99
|
5eba0d2eff5ffca9bf244d8da266b5552ee9c2a6
|
refs/heads/master
| 2021-03-16T06:53:39.265410
| 2017-03-29T14:35:41
| 2017-03-29T14:35:41
| 80,838,892
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,057
|
py
|
import ipaddress
import platform
import socket
import subprocess
import threading
import urllib.request
import uuid
import networkx as nx
from PyQt5.QtCore import pyqtSignal
from Connectivity import pingAddress
# Used to generate an image of a Local Area Network
class Scanner():
def __init__(self):
super(Scanner, self).__init__()
self.missingIpNumbers = None
self.graphLocation = None
self.macAddrDict = dict()
self.vendorDict = dict()
# get the ip numbers removed when they were added to graph (for readibility)
def getMissingIpNumbers(self):
return self.missingIpNumbers
# to be called from outside to get vendor
def returnVendor(self,macAddr):
if macAddr in self.vendorDict:
return self.vendorDict[macAddr]
else:
return "N/A"
# to be called from outside to get mac address
def returnMacAddr(self,ipAddr):
if ipAddr in self.macAddrDict:
return self.macAddrDict[ipAddr]
else:
return "N/A"
# return the generated graph
def getGraph(self):
return self.graphLocation
# checks if we're connected to the internet by pinging google
def isConnected(self):
try:
urllib.request.urlopen("https://www.google.ie")
return True
except:
return False
def findLast(self,s, ch):
#builds a list of all the occurences of a character
list = [index for index, currentChar in enumerate(s) if currentChar == ch]
#returns the last index
return list[-1]
# depending on the OS, make the appropriate commands to get the submask for the network
def getSubnetMask(self):
try:
os = platform.system()
myIp = self.getMyIpAddr()
notation = 0
if "Windows" in os:
ipconfig = subprocess.Popen(['ipconfig'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
subnetMask = [line for line in ipconfig.split('\n') if "Subnet Mask" in line][0]
start = subnetMask.index(':') + 1 # from start of subnet mask in ifconfig get the start of address
end = self.findLast(subnetMask, '.') + 4 # get last few digits
subnetMask = subnetMask[start:end].strip()
elif "Linux" in os:
ipconfig = subprocess.Popen(['ifconfig'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
subnetMask = [line for line in ipconfig.split('\n') if myIp in line][0]
start = subnetMask.index("Mask") + 5 # locate where mask starts
end = self.findLast(subnetMask, '.') + 4 # get last few digits
subnetMask = subnetMask[start:end].strip()
elif "Darwin" in os: #mac readout is a bit different as it's in hex
ipconfig = subprocess.Popen(['ifconfig'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
subnetMask = [line for line in ipconfig.split('\n') if myIp in line][0]
start = subnetMask.index("netmask") + 10 # locate where mask starts
end = self.findLast(subnetMask, 'b') # get last few digits
subnetMask = subnetMask[start:end].strip()
tmp = int(subnetMask,16)
tmp = bin(tmp)[2:]
for i in range(0,len(tmp)):
if not tmp[i] is "0":
notation += 1
return "/" + str(notation)
subnetMaskComponents = subnetMask.split('.')
for i in range(0,len(subnetMaskComponents)):
tmp = int(subnetMaskComponents[i])
tmp = bin(tmp)[2:]
if not tmp is "0":
notation += len(tmp)
return "/" + str(notation)
except:
return "/24" #return a default value
# consult arp table for mac addr
def getMacAddr(self,currentIP):
arpTable = self.getArpTable()
currentOS = platform.system()
'''
ensure we're getting the entry for this ip rather than finding it within another
eg. 192.168.1 is in 192.169.10
so by having a ending character we avoid this
'''
macSpace = ':' # linux and mac space mac address with :
if "Windows" in currentOS:
macSpace = '-' # mac addresses spaced with - in windows
currentIP = currentIP + " " #space after end of ip in arp table
else:
currentIP = currentIP + ")" #bracket in linux and mac
try:
arpEntry = [line for line in arpTable.split('\n') if currentIP in line][-1] #get last index of lines found
start = arpEntry.index(macSpace) - 2 # get first 2 characters of mac address
end = self.findLast(arpEntry,macSpace) + 3 #get last 2 characters of mac address
'''
ff-ff-ff-ff-ff-ff
^ ^
ff-ff-ff-ff-ff-ff => 2 and plus 3
^ ^
'''
return arpEntry[start:end].strip()
except:
return "Not in arp table"
# gets my mac address through python command
def getMyMacAddr(self):
# Convert mac address from decimal to hex and add colons for readibility
myMacAddress = hex(uuid.getnode())[2:]
return ":".join(myMacAddress[i:i + 2] for i in range(0, len(myMacAddress), 2))
'''
Contacting https://macvendors.com/ through their API to get vendor for specified mac address
returns the vendor or "vendor not found" otherwise
'''
def getMacVendor(self,macAddr):
if not len(macAddr) == 17:
return "N/A"
#if we have internet connection get it through the API
if self.isConnected():
try:
response = urllib.request.urlopen('http://api.macvendors.com/' + macAddr)
vendor = str(response.read())
return vendor[2:len(vendor) - 1] #just cut out quotes from returned string for neatness
except:
return self.checkMacFile(macAddr) #check locally is there was an error
#otherwise we check our own local file
else:
return self.checkMacFile(macAddr)
#checks for match in our local file
def checkMacFile(self,macAddr):
if not len(macAddr) == 17:
return "N/A"
macAddr = macAddr[:7]
if "-" in macAddr:
macAddr = self.removeMacSeperators(macAddr,"-")
elif ":" in macAddr:
macAddr = self.removeMacSeperators(macAddr,":")
try:
with open('mac_addresses.csv', 'r', encoding='utf-8') as f:
for line in f:
comma = line.index(",")
prefix = line[:comma]
prefix = prefix.lower()
if macAddr in prefix:
return line[comma + 1:].strip('\n')
return "N/A"
except FileNotFoundError:
return "No Local Record Found"
def removeMacSeperators(self,macAddr,signToRemove):
newMacAddr = ""
for i in range(0,len(macAddr)):
if macAddr[i] is not signToRemove:
newMacAddr += macAddr[i]
return newMacAddr
# gets my ip through python command
def getMyIpAddr(self):
ipAddr = socket.gethostbyname(socket.gethostname())
# Issue when using WLan cards, get Loopback instead of actual IP address
if ("127.0" in ipAddr):
ipAddr = self.getIpAddressFix()
return ipAddr
'''
if we can't just pick up IP address we can force a connection
and see what made address made that connection
'''
def getIpAddressFix(self):
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySocket.connect(("136.206.1.4",80))
ip = mySocket.getsockname()[0]
mySocket.close()
return ip
# return the arp table
def getArpTable(self):
return subprocess.Popen(['arp', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
# start a scan of the network from a seperate thread
def scanNetwork(self,callingThread):
try:
self.percentage = 0
myIpAddress = self.getMyIpAddr()
ipAddress = myIpAddress + self.getSubnetMask()
ipNetwork = ipaddress.ip_network(ipAddress, strict=False)
allHosts = list(ipNetwork)
liveIPs = [myIpAddress]
length = len(allHosts)
chunkOne = []
chunkTwo = []
chunkThree = []
chunkFour = []
thread1 = SubScanner(1, myIpAddress, allHosts[0:int((length/4) +1)],chunkOne)
thread1.start()
thread2 = SubScanner(2, myIpAddress, allHosts[int((length/4) +1):int((length / 2) + 1)], chunkTwo)
thread2.start()
thread3 = SubScanner(3, myIpAddress, allHosts[int((length / 2) + 1):int((length / 4) + 1) * 3], chunkThree)
thread3.start()
thread4 = SubScanner(4, myIpAddress, allHosts[int((length / 4) + 1) * 3:length], chunkFour)
thread4.start()
#Small progress update to show them something is happening
callingThread.trigger.emit(5)
thread1.join()
callingThread.trigger.emit(25)
thread2.join()
callingThread.trigger.emit(50)
thread3.join()
callingThread.trigger.emit(75)
thread4.join()
#bring all the found IPs back together
liveIPs.extend(chunkOne)
liveIPs.extend(chunkTwo)
liveIPs.extend(chunkThree)
liveIPs.extend(chunkFour)
callingThread.trigger.emit(90)
G=nx.Graph()
G.add_node(str(myIpAddress))
stringIndex = self.findLast(str(myIpAddress), '.')
#so when we cut it down for the labels we still have what we cut out
self.missingIpNumbers = myIpAddress[0:stringIndex]
global macAddrDict,vendorDict
myMac = self.getMyMacAddr()
self.macAddrDict[myIpAddress] = self.getMyMacAddr()
self.vendorDict[myMac] = self.getMacVendor(myMac)
#Take all of our current IPs and construct the graph along with finding the mac and vendor
for i in range(len(liveIPs)):
if(liveIPs[i] != myIpAddress):
oldIpString = str(liveIPs[i])
newIPIndex = self.findLast(str(liveIPs[i]), '.')
newIpString = oldIpString[newIPIndex:len(str(liveIPs[i])) + 1]
G.add_node(newIpString)
edge = (newIpString, str(myIpAddress))
G.add_edge(*edge)
currentMac = self.getMacAddr(liveIPs[i])
self.macAddrDict[liveIPs[i]] = currentMac
self.vendorDict[currentMac] = self.getMacVendor(currentMac)
callingThread.trigger.emit(100)
self.graphLocation = G
callingThread.trigger.emit(101)
except Exception as e:
print(str(e))
callingThread.trigger.emit(-1)
# Used for pinging LAN devices
class SubScanner(threading.Thread):
trigger = pyqtSignal(int)
def __init__(self, thread_no, myIpAddress, listToScan,listToReturn):
threading.Thread.__init__(self)
self.thread_no = thread_no
self.currentOS = platform.system()
self.myIpAddress = myIpAddress
self.listToScan = listToScan
self.listToReturn = listToReturn
def run(self):
for i in range(len(self.listToScan)):
currentIP = str(self.listToScan[i])
if (currentIP != self.myIpAddress):
if pingAddress(currentIP):
self.listToReturn.append(currentIP)
|
[
"cillianmcneill@gmail.com"
] |
cillianmcneill@gmail.com
|
31aeaae87bfb563d8b390269f63fddd2f6687d6b
|
a7e3b13fb332f355292f86ef0a3f493ea364511c
|
/mapimage/genbbox.py
|
789290f1084e227e5bd4d905ba172d45295d8df1
|
[
"Apache-2.0"
] |
permissive
|
crschmidt/habitationi
|
470850ccc4563b16bcff9dfd9e34b144c527d994
|
2ae88640160e6ad11d5efa45fe13bd45254a80ed
|
refs/heads/master
| 2022-02-03T17:00:36.336034
| 2022-01-25T14:31:19
| 2022-01-25T14:31:19
| 191,000,590
| 1
| 1
|
Apache-2.0
| 2021-02-21T16:00:32
| 2019-06-09T11:56:02
|
Python
|
UTF-8
|
Python
| false
| false
| 949
|
py
|
# Copyright 2019 Christopher Schmidt
#
# 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 fiona
import shapely.geometry
import csv
parcels = fiona.open("ASSESSING_ParcelsFY2019.shp")
done = 0
w = csv.writer(open("parcelbbox.csv", "w"), "excel-tab")
for parcel in parcels:
lot = shapely.geometry.shape(parcel['geometry'])
lot = lot.buffer(100)
w.writerow([parcel['properties']['ML'], ",".join(map(lambda x: "%i" % x, lot.bounds))])
|
[
"crschmidt@crschmidt.net"
] |
crschmidt@crschmidt.net
|
6712f47e67621dcd41357d0a5cfef3b820e6d841
|
895f850ad761fe6caab5fb124cb7aa29e10e5df5
|
/backup_2/dependencies.py
|
18f3cfff79e83e536731f1ad57b308b1e24275ee
|
[] |
no_license
|
m-albert/quantification
|
792ae1927c01070d1bca35fee6aa2f94c475ff90
|
d795e920fd4c5194aab96767665318ab01b4110b
|
refs/heads/master
| 2021-05-31T00:57:34.730886
| 2016-03-21T15:03:31
| 2016-03-21T15:03:31
| 40,670,446
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 608
|
py
|
__author__ = 'malbert'
from imports import *
sys.path.append('/home/malbert/software/trackpy')
import ilastiking,filing,imaging
import tifffile
import trackpy
import pandas
import zeissFusion as zf
from matplotlib import pyplot
import czifile
timestamp = time.localtime()
timestamp = '%02d%02d%02d_%02d%02d%02d' %tuple([timestamp[i] for i in range(6)])
tmpDir = os.path.join('/data/malbert/tmp','quantificationTmpFolder_%s' %timestamp)
os.mkdir(tmpDir)
elastixPath = '/home/malbert/bin/elastix'
import misc
import brain
import objects
import microglia
import fli
import aponeuron
import descriptors
|
[
"marvin.albert@gmail.com"
] |
marvin.albert@gmail.com
|
3d4386193db64c1d359cd107f0990178ad19ba29
|
7735effa4f02d98fcedc57ef4f768b771fc46ac1
|
/mi_oj/62.py
|
04107357f300855889d73b4ee1e25b7ed79820b9
|
[
"Apache-2.0"
] |
permissive
|
ShumaoHou/MyOJ
|
dbda39071a93b94492d76850e5a69fd815cf9875
|
ee92fb657475d998e6c201f222cb20bcbc2bfd64
|
refs/heads/master
| 2023-06-09T16:45:10.303736
| 2019-04-05T03:30:22
| 2019-04-05T03:30:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,143
|
py
|
'''
括号配对
我们知道,在逻辑表达式中广泛使用了括号,而括号都是层次化成对出现的。
也就是任意左括号都应该存在一个在同一逻辑层级的右括号作为对应。 现在我们有一些仅由括号组成的字符串序列,
保证每个字符为大括号”{”,”}”、中括号”[”,”]”和小括号”(”,”)”中的一种。 需要判断给定的的序列是否合法。
输入:一行仅由括号组成的字符串
输出:如果序列合法输出 1,否则输出 0
输入样例
[()]
({[])}
[()]{}
输出样例
1
0
1
小提示
栈的典型应用
'''
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
stack = []
for i in range(len(line)):
if line[i] == "(" or line[i] == "[" or line[i] == "{":
stack.append(line[i])
elif len(stack) == 0:
return 0
elif (line[i] == ")" and stack[-1] == "(") or (line[i] == "]" and stack[-1] == "[") or (line[i] == "}" and stack[-1] == "{"):
stack.pop()
else:
return 0
return 1
print(solution(input()))
|
[
"houshumao@qq.com"
] |
houshumao@qq.com
|
4a5d8f69bef47df572d74e211e83091253252679
|
73ad9af21fd3584a741ee47ce646ea22b6666721
|
/leetcode/RecoverBinarySearchTree2.py
|
00411fa58ee77081ff6f11d6716d400676f9c7a1
|
[] |
no_license
|
zhenggang587/code
|
a70b5004a4afb3e2eb6b4d8f267fd1aed83a4b74
|
fa13c439bcfaad543461b8a8ea397ecb95a066a5
|
refs/heads/master
| 2020-05-02T18:23:18.892197
| 2014-12-14T05:53:13
| 2014-12-14T05:53:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,260
|
py
|
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.pre = None
self.first = None
self.second = None
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
self.traverse(root)
self.first.val, self.second.val = self.second.val, self.first.val
return root
def traverse(self, node):
if not node:
return
self.traverse(node.left)
if self.pre and self.pre.val > node.val:
if not self.first:
self.first = self.pre
self.second = node
self.pre = node
self.traverse(node.right)
def printTree(self, root):
if not root:
return
print root.val
self.printTree(root.left)
self.printTree(root.right)
if __name__ == "__main__":
s = Solution()
node1 = TreeNode(3)
node2 = TreeNode(4)
node3 = TreeNode(5)
node4 = TreeNode(4)
node1.left = node2
node2.left = node3
#node1.right = node3
#node2.right = node4
s.recoverTree(node1)
s.printTree(node1)
|
[
"zhenggang@meituan.com"
] |
zhenggang@meituan.com
|
7b6d84910a093db1582fac3bd6e59ab180f34b2b
|
0182e4f9fae415cb6d209d22f46af91f606ceb89
|
/migrations/versions/e73b0b369a6f_created_contribution_and_transfer_tables.py
|
f387b482a53573ab3dd6f8f7df5d658bac41135c
|
[] |
no_license
|
ouimet51/fundit
|
89242b27827ef8875755d5153fc436e2140f17f7
|
90cb56b7ed60819f80bfbc53065307f660bd287c
|
refs/heads/master
| 2020-03-22T21:02:27.355058
| 2018-07-12T02:49:20
| 2018-07-12T02:49:20
| 140,651,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,893
|
py
|
"""Created Contribution and Transfer tables
Revision ID: e73b0b369a6f
Revises: 6bd9444a2665
Create Date: 2018-07-10 10:11:48.166224
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e73b0b369a6f'
down_revision = '6bd9444a2665'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('transfer',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('value', sa.Integer(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_transfer_timestamp'), 'transfer', ['timestamp'], unique=False)
op.create_table('contribution',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('value', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('fund_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['fund_id'], ['fund.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_contribution_timestamp'), 'contribution', ['timestamp'], unique=False)
op.add_column('user', sa.Column('account', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'account')
op.drop_index(op.f('ix_contribution_timestamp'), table_name='contribution')
op.drop_table('contribution')
op.drop_index(op.f('ix_transfer_timestamp'), table_name='transfer')
op.drop_table('transfer')
# ### end Alembic commands ###
|
[
"ouimet51@gmail.com"
] |
ouimet51@gmail.com
|
7b9c3e167d1ae4c52526a236428f2a93017d2d5a
|
69a3293cc8da5543b7c7fce9d2e074d919ec041c
|
/ISOMAP.py
|
93e21ac1a8a1f5cdfa842dc0001c65ae420b2159
|
[] |
no_license
|
SAAllegri/pca-isomap_algorithm_comparison
|
ae2fa06a07d946d8818c8e51472988e9f12099b3
|
e12ee32c7c03822aad5bca6a1ca1916d36b876bc
|
refs/heads/main
| 2023-08-31T05:03:55.772702
| 2021-10-12T02:07:19
| 2021-10-12T02:07:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,279
|
py
|
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from scipy import spatial, sparse
from sklearn.utils import graph_shortest_path
from sklearn.neighbors import kneighbors_graph
# Initialize the class, load the data with load_data(), and obtain the z-matrix through generate_low_dimensional_representation()
class ISOMAP():
def __init__(self, dimensions=2, neighbor_min=100, epsilon_thresh=0.001, dist_measure='euclidean'):
self.neighbor_min = neighbor_min
self.epsilon_thresh = epsilon_thresh
self.dist_measure = dist_measure
self.dimensions = dimensions
def load_data(self, np_array):
self.data = np_array
self.shape = np_array.shape
def generate_adjacency_matrix(self):
self.distance_matrix = spatial.distance.cdist(self.data, self.data, self.dist_measure)
distance_matrix_temporary = self.distance_matrix.copy()
iso_max = np.max(distance_matrix_temporary)
iso_min = np.min(distance_matrix_temporary)
epsilon = ((iso_max - iso_min) / 2) + (((iso_max - iso_min) / 2) / 2)
prev_epsilon = ((iso_max - iso_min) / 2) - (((iso_max - iso_min) / 2) / 2)
while (np.abs((epsilon - prev_epsilon) / prev_epsilon) > self.epsilon_thresh):
switch = np.inf
for idx in range(self.data.shape[0]):
edge_count = len(distance_matrix_temporary[idx][distance_matrix_temporary[idx] < epsilon])
if edge_count < switch:
switch = edge_count
prev_epsilon_local = epsilon
# +1 to include self
if switch < (self.neighbor_min + 1):
epsilon = epsilon + (np.abs(epsilon - prev_epsilon) / 2)
prev_epsilon = prev_epsilon_local
else:
self.epsilon_outer = epsilon
epsilon = epsilon - (np.abs(epsilon - prev_epsilon) / 2)
prev_epsilon = prev_epsilon_local
for idx in range(self.data.shape[0]):
distance_matrix_temporary[idx][idx] = 0
distance_matrix_temporary[idx][np.where(distance_matrix_temporary[idx] > self.epsilon_outer)] = 0
self.adjacency_matrix = distance_matrix_temporary
def generate_shortest_path_matrix(self):
self.shortest_path = sparse.csgraph.dijkstra(sparse.csr_matrix(self.adjacency_matrix))
def generate_low_dimensional_representation(self):
self.generate_adjacency_matrix()
self.generate_shortest_path_matrix()
h = np.identity(self.shape[0]) - ((1 / self.shape[0]) * np.ones((self.shape[0], self.shape[0])))
self.c_matrix = (-1 / 2) * h.dot(self.shortest_path ** 2).dot(h)
eigenvalues, eigenvectors = np.linalg.eig(self.c_matrix)
idx = eigenvalues.argsort()[::-1]
eigenvalues = eigenvalues[idx].real
eigenvectors = eigenvectors[:, idx].real
reduced_eigenvalues = eigenvalues[:self.dimensions]
reduced_eigenvectors = eigenvectors[:, :self.dimensions]
self.z_matrix = reduced_eigenvectors.dot(np.diag(reduced_eigenvalues ** (-1 / 2)))
|
[
"noreply@github.com"
] |
SAAllegri.noreply@github.com
|
132da27f9f197e2030cf410fcb4add5def5499f4
|
e11494ef821623d11c4987b13eef219d7b45c4a4
|
/bin/SumMech_Basic.py
|
badd2601ffef36df01ebedcc04eedb008a58943f
|
[] |
no_license
|
boboppie/BreakSeq
|
7ee9cdb20324ffab73985014a170d84ceccc86f5
|
0ca8f6237a7e174fa7b4fbd7c18c856fde5b0b22
|
refs/heads/master
| 2021-01-17T13:22:33.224204
| 2013-12-28T06:02:10
| 2013-12-28T06:02:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,321
|
py
|
#!/opt/Python/2.7.3/bin/python
import sys
from collections import defaultdict
from numpy import *
import re
import os
import argparse
from Bio import SeqIO
def usage():
test="name"
message='''
python SumMech_Basic.py --input HEG4.insertion.SV.gff
'''
print message
def fasta_id(fastafile):
fastaid = defaultdict(str)
for record in SeqIO.parse(fastafile,"fasta"):
fastaid[record.id] = 1
return fastaid
'''
Chr1 SVpipe Deletion 66133 66245 . . . INDEL=Deletio "INDEL=Deletion"; Mech "NAHR"; Method=soaps "Method=soapsv"; Seq=GGCGGGCGGGAGAGGCGGGGCGGCGGCCGGCAGGAGAGGAGGCGCGCGGCCGGCGGGCGGGAGAGGAGGCGCGCGGCCGGCGGGCGGCGGGAGAGGGGGCGCGGCGGCGGGC "Seq=GGCGGGCGGGAGAGGCGGGGCGGCGGCCGGCAGGAGAGGAGGCGCGCGGCCGGCGGGCGGGAGAGGAGGCGCGCGGCCGGCGGGCGGCGGGAGAGGGGGCGCGGCGGCGGGCG"; Size=11 "Size=113"
'''
def drawLengthclass(Rfile):
pdf = Rfile.replace('.table', '.pdf')
R = Rfile.replace('.table', '.R')
Rcmd='''
pdf("''' + pdf + '''")
par(mar=c(6,4,4,10))
par(xpd=TRUE)
barlegend <- function(x,y,height,length,name,color){
rect(x,y-0.04*height,x+0.05*length,y,col=color,border=FALSE)
text(x+0.15*length,y-0.02*height,labels=name)
}
x <- read.table("'''+ Rfile +'''", skip = 1, sep = '\\t')
data <- rbind(x[,3]/x[,2],x[,4]/x[,2],x[,5]/x[,2],x[,6]/x[,2],x[,7]/x[,2],x[,8]/x[,2])
xx <- barplot(data,ylab="Proportion",border=FALSE,space=1,ylim=c(0,1),col=c("blue","orange","#A0522D","green","gray","black"))
axis(1,c(0.9,max(xx)+0.6),line=0,labels=c("",""))
text(xx,rep(-0.08,6),offset=2,labels=x[,1],srt=55,xpd=TRUE)
legend(10,0.8,bty="n",lty=c(0,0),border="NA",cex=1.2,c("NHR","NAHR","VNTR","MTEI","STEI","UNSURE"),fill=c("blue","orange","#A0522D","green","gray","black"))
#barlegend(10,0.7,1,10,"CDS","red")
mtext("Indel Length (bp)",side=1, at=5.2,line=4)
dev.off()
'''
ofile = open (R, 'w')
print >> ofile, Rcmd
ofile.close()
os.system('cat %s | R --slave' % (R))
def drawPie(Rfile):
pdf = Rfile.replace('.table', '.pdf')
R = Rfile.replace('.table', '.R')
Rcmd='''
pdf("''' + pdf + '''")
options(digits=2)
read.table("''' + Rfile + '''",skip=1,sep='\\t') -> anno
pie(anno[,3],border = NA, init.angle = 40,labels=anno[,1],radius=0.8,col=c("#FA8072","orange","green","blue","gray","black")) -> x
#legend(0.6,1,cex=1,anno[,1],bty="n",fill=c("#FFA07A","orange","green","blue","gray","black"))
dev.off()
'''
ofile = open (R, 'w')
print >> ofile, Rcmd
ofile.close()
os.system('cat %s | R --slave' % (R))
def sumMech(infile, outfile):
data = defaultdict(int)
lengthclass = defaultdict(lambda : defaultdict(int))
total = 0
s = re.compile(r'Mech \"(\w+)\".*\"Size=(\d+)\"')
with open (infile, 'r') as filehd:
for line in filehd:
line = line.rstrip()
if len(line) > 2 or not line.startswith('#'):
unit = re.split(r'\t',line)
m = s.search(unit[8])
if m:
mech = m.groups(0)[0].replace('_EXT','')
size = m.groups(0)[1]
data[mech] = data[mech] + 1
total = total + 1
if int(size) <= 100:
lengthclass['50'][mech] = lengthclass['50'][mech] + 1
elif int(size) <= 500:
lengthclass['100'][mech] = lengthclass['100'][mech] + 1
elif int(size) <= 1000:
lengthclass['500'][mech] = lengthclass['500'][mech] + 1
elif int(size) <= 5000:
lengthclass['1000'][mech] = lengthclass['1000'][mech] + 1
else:
lengthclass['5000'][mech] = lengthclass['5000'][mech] + 1
mechs = ['NHR', 'NAHR', 'VNTR', 'MTEI', 'STEI', 'UNSURE']
ofile = open(outfile + '.Pie.table', 'w')
print >> ofile, 'Mechanism Percent% Number#'
for mech in mechs:
if data.has_key(mech):
print >> ofile, '%s %d%%\t%s\t%s' % (mech, int(100.00*float(data[mech])/float(total)), data[mech], float(data[mech])/float(total))
ofile.close()
drawPie(outfile + '.Pie.table')
lengths = {'50':'50-100', '100':'100-500', '500':'500-1000', '1000':'1000-5000', '5000':'>5000'}
ofile = open (outfile + '.LengthClass.table', 'w')
print >> ofile, 'Lenth #Total #NHR #NAHR #VNTR #MTEI #STEI #UNSURE'
for length in sorted(lengthclass.keys(), key=int):
line = lengths[length]
temp = []
suml = 0
for mech in mechs:
num = lengthclass[length][mech] if lengthclass[length][mech] > 0 else 0
suml = suml + num
temp.append(str(num))
line = line + '\t' + str(suml) + '\t' + '\t'.join(temp)
print >> ofile, line
ofile.close()
drawLengthclass(outfile + '.LengthClass.table')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
args = parser.parse_args()
try:
len(args.input) > 0
except:
usage()
sys.exit(2)
if args.output is None:
args.output = 'Mech.Basic'
sumMech(args.input, args.output)
if __name__ == '__main__':
main()
|
[
"jinfeng7chen@gmail.com"
] |
jinfeng7chen@gmail.com
|
170f33819fc06dd241d4282cac0a9db64f20011d
|
89b2f5b08c441d4af0a63ed2ec1a5889bc92f0f7
|
/Python OOP 2020/OOP_2020_exam_prep/Python OOP - Exam Preparation - 2 April 2020/tests/test_magic_card.py
|
06cbd102595dba8bc793126df0fcbdd7196beffc
|
[] |
no_license
|
KoliosterNikolayIliev/Softuni_education
|
68d7ded9564861f2bbf1bef0dab9ba4a788aa8dd
|
18f1572d81ad9eb7edd04300deb8c81bde05d76b
|
refs/heads/master
| 2023-07-18T09:29:36.139360
| 2021-08-27T15:04:38
| 2021-08-27T15:04:38
| 291,744,823
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 836
|
py
|
import unittest
from project.card.magic_card import MagicCard
class TestMagicCard(unittest.TestCase):
def setUp(self):
self.magic_card = MagicCard("mali")
def test_magic_card_creation(self):
self.assertEqual(self.magic_card.name, "mali")
self.assertEqual(self.magic_card.damage_points, 5)
self.assertEqual(self.magic_card.health_points, 80)
def test_name_empty_string(self):
with self.assertRaises(ValueError):
self.magic_card.name = ""
def test_set_health_points_ValueError(self):
with self.assertRaises(ValueError):
self.magic_card.health_points = -1
def test_set_damage_points_ValueError(self):
with self.assertRaises(ValueError):
self.magic_card.damage_points = -1
if __name__ == "__main__":
unittest.main()
|
[
"65191727+KoliosterNikolayIliev@users.noreply.github.com"
] |
65191727+KoliosterNikolayIliev@users.noreply.github.com
|
1de63eb112ee1189f20ebfb0f7282898150ec5f9
|
87b12ec1bea4008b0f51ed2c2be632e3121a0d04
|
/0x0F-python-object_relational_mapping/7-model_state_fetch_all.py
|
408ca717b2bf171a9845d9e0542a8858ee387b6c
|
[] |
no_license
|
jbathel/holbertonschool-higher_level_programming
|
181d24de8df362842ee3b3a632dd49c38966a662
|
10afef612d8544e55a7c295ba90b1b0e2f2171b8
|
refs/heads/master
| 2020-07-22T23:51:09.947518
| 2020-02-14T06:42:04
| 2020-02-14T06:42:04
| 207,372,715
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 622
|
py
|
#!/usr/bin/python3
# Script that lists all states from the database hbtn_0e_0_usa
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import sys
from model_state import Base, State
if __name__ == "__main__":
engine = create_engine(
'mysql+mysqldb://{}:{}@localhost/{}'.format(
sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True)
Base.metadata.create_all(engine)
Session = sessionmaker(engine)
session = Session()
for state in session.query(State).order_by(State.id).all():
print("{}: {}".format(state.id, state.name))
session.close()
|
[
"811@holbertonschool.com"
] |
811@holbertonschool.com
|
773c777deb8b4b5f7be364eed2eb8f5fe4a74960
|
ff61a27e80cde560cdc308f203e134698fe71cad
|
/PerceptronMultiCapaService.py
|
9c3931da72a443a3c924daacf26ab95ad264391b
|
[] |
no_license
|
Piton007/TB2-IA
|
e7ecca352223520019360ee9416a90a645e84202
|
e053c3ae16ecb3369862e0e777d95aff16d32b60
|
refs/heads/master
| 2020-09-04T04:37:48.359259
| 2019-11-07T15:30:28
| 2019-11-07T15:30:28
| 219,659,281
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,468
|
py
|
from PerceptronMultiCapaCore import PerceptronMulticapa
class PerceptronMulticapaService():
def __init__(self):
self.perceptron_multicapa=""
self.resultados=""
def configurar_perceptron(self,neuronas_entrada,neuronas_escondidas,neuronas_salida,coeficiente_aprendizaje,limite_error_cuadratico):
del self.perceptron_multicapa
self.perceptron_multicapa=PerceptronMulticapa(neuronas_entrada,neuronas_escondidas,neuronas_salida,coeficiente_aprendizaje,limite_error_cuadratico)
def entrenar_perceptron(self):
return self.perceptron_multicapa.entrenar()
def obtener_pesos(self):
return dict(pesos_ocultos=self.perceptron_multicapa.pesos_ocultos.tolist(),bias_oculta=self.perceptron_multicapa.bias_oculta.tolist(),pesos_salidas=self.perceptron_multicapa.pesos_salidas.tolist(),bias_salida=self.perceptron_multicapa.bias_salida.tolist(),limite=self.perceptron_multicapa.limite_error_cuadratico,
error=self.resultados.get("error"),
resultado=self.resultados.get("resultado")
)
def agregar_patrones(self,patron):
self.perceptron_multicapa.agregar_patron(patron)
def agregar_valor_esperado(self,esperado):
self.perceptron_multicapa.agregar_valor_esperado(esperado)
def obtener_prediccion(self):
return self.perceptron_multicapa.predecir()
def obtener_size_patrones(self):
return self.perceptron_multicapa.get_patrones()
|
[
"jose45321@outlook.com"
] |
jose45321@outlook.com
|
2f9de45caa02b14ba917b1a23e8169da6645b3a4
|
da1ca390feea3caba17cd2c0193f6dedf880824d
|
/UnitTests/mock_tests.py
|
7f7e3605e661ba3845f7d0f41b07fc16ad36677c
|
[] |
no_license
|
stoolrossa/OzriPythonSnippets
|
67b612e3c917119d08c534c45d38030d5fe28e49
|
b1e20672a0a24c5ed52b420044cdeed16a74dbef
|
refs/heads/master
| 2021-01-20T23:16:55.354083
| 2014-10-08T05:21:52
| 2014-10-08T05:21:52
| 24,872,455
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,631
|
py
|
import unittest
from mock import Mock
import datetime
import greeting as grt
class MyMockedTests(unittest.TestCase):
# test the greeting in the morning
def test_morning(self):
# mock the clock such that get_time passes back the time 9:52
clock = grt.Clock()
clock.get_time = Mock(return_value=datetime.datetime(2014, 10, 3, 9, 52))
# inject the mocked clock as a dependency
greeting = grt.Greeting(clock)
# assert that the greeting is correct
result = greeting.say_hello("Todd")
self.assertEqual("Good morning Todd", result)
# test the greeting in the afternoon
def test_afternoon(self):
# mock the clock such that get_time passes back the time 13:23
clock = grt.Clock()
clock.get_time = Mock(return_value=datetime.datetime(2014, 10, 3, 13, 23))
# inject the mocked clock as a dependency
greeting = grt.Greeting(clock)
# assert that the greeting is correct
result = greeting.say_hello("Todd")
self.assertEqual("Good afternoon Todd", result)
# test the greeting in the evening
def test_evening(self):
# mock the clock such that get_time passes back the time 19:12
clock = grt.Clock()
clock.get_time = Mock(return_value=datetime.datetime(2014, 10, 3, 19, 12))
# inject the mocked clock as a dependency
greeting = grt.Greeting(clock)
# assert that the greeting is correct
result = greeting.say_hello("Todd")
self.assertEqual("Good evening Todd", result)
if __name__ == '__main__':
unittest.main()
|
[
"jackson.todd.a@gmail.com"
] |
jackson.todd.a@gmail.com
|
e869f2602078c7b911082e578e8d8902d3b1c006
|
dd116ddf8b7edb0083ff9eeaf5c0b4ecb4199378
|
/mainapp/migrations/0007_auto_20210805_1051.py
|
d278d55f8a1b2a147d0d0a0a0a8fcf090a7eaaed
|
[] |
no_license
|
AllStars123/online_shop_django
|
bd11fabf4cd4d2e026b63e8e97bc9ffbbb8fd770
|
39b8e04d78db2e4a8feab1e67580088e7529e0bf
|
refs/heads/master
| 2023-07-08T22:50:53.754670
| 2021-08-06T21:57:14
| 2021-08-06T21:57:14
| 393,510,483
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 662
|
py
|
# Generated by Django 3.2.5 on 2021-08-05 10:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0006_alter_cart_owner'),
]
operations = [
migrations.AlterField(
model_name='customers',
name='address',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Адрес'),
),
migrations.AlterField(
model_name='customers',
name='phone',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Номер телефона'),
),
]
|
[
"purnov.nikita@yandex.ru"
] |
purnov.nikita@yandex.ru
|
92d3a92569bcf612c5b3bec75f9c3e1e4a38f00f
|
847e4869d0d3a5ab76ca181e9f6037427a7a93e3
|
/Simulation/Train.py
|
81fbb1a66da9addb75ac638989753c2b48a27d2d
|
[] |
no_license
|
HengJiang95/DGSMP
|
07ed1dc888bb7eb6ee83973cf2c58ff927c812cd
|
4a7ab23fb93618ed3bfb6a914e74a9f531455f8e
|
refs/heads/main
| 2023-08-21T21:45:36.831912
| 2021-06-24T13:30:14
| 2021-06-24T13:30:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,942
|
py
|
from Model import HSI_CS
from Dataset import dataset
import torch.utils.data as tud
from torch import optim
from torch.optim.lr_scheduler import MultiStepLR
import time
import datetime
import argparse
from torch.autograd import Variable
from Utils import *
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
if __name__=="__main__":
print("===> New Model")
model = HSI_CS(Ch=28, stages=4)
print("===> Setting GPU")
model = dataparallel(model, 1) # set the number of parallel GPUs
## Initialize weight
for layer in model.modules():
if isinstance(layer, nn.Conv2d):
nn.init.xavier_uniform_(layer.weight)
# nn.init.constant_(layer.bias, 0.0)
if isinstance(layer, nn.ConvTranspose2d):
nn.init.xavier_uniform_(layer.weight)
# nn.init.constant_(layer.bias, 0.0)
## Model Config
parser = argparse.ArgumentParser(description="PyTorch Spectral Compressive Imaging")
parser.add_argument('--data_path', default='./Data/Training_data/', type=str,help='Path of data')
parser.add_argument('--mask_path', default='./Data/mask.mat', type=str,help='Path of mask')
parser.add_argument("--size", default=96, type=int, help='The training image size')
parser.add_argument("--trainset_num", default=20000, type=int, help='The number of training samples of each epoch')
parser.add_argument("--testset_num", default=10, type=int, help='Total number of testset')
parser.add_argument("--seed", default=1, type=int, help='Random_seed')
parser.add_argument("--batch_size", default=4, type=int, help='Batch_size')
parser.add_argument("--isTrain", default=True, type=bool, help='Train or test')
opt = parser.parse_args()
print("Random Seed: ", opt.seed)
torch.manual_seed(opt.seed)
torch.cuda.manual_seed(opt.seed)
print(opt)
## Load training data
key = 'train_list.txt'
file_path = opt.data_path + key
file_list = loadpath(file_path)
HR_HSI = prepare_data(opt.data_path, file_list, 30)
## Load trained model
initial_epoch = findLastCheckpoint(save_dir="./checkpoint") # load the last model in matconvnet style
if initial_epoch > 0:
print('Load model: resuming by loading epoch %03d' % initial_epoch)
model = torch.load(os.path.join("./checkpoint", 'model_%03d.pth' % initial_epoch))
## Loss function
criterion = nn.L1Loss()
## optimizer and scheduler
optimizer = optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.999), eps=1e-8)
scheduler = MultiStepLR(optimizer, milestones=[], gamma=0.1) # learning rates
## pipline of training
for epoch in range(initial_epoch, 500):
model.train()
Dataset = dataset(opt, HR_HSI)
loader_train = tud.DataLoader(Dataset, num_workers=4, batch_size=opt.batch_size, shuffle=True)
scheduler.step(epoch)
epoch_loss = 0
start_time = time.time()
for i, (input, label) in enumerate(loader_train):
input, label = Variable(input), Variable(label)
input, label = input.cuda(), label.cuda()
out = model(input)
loss = criterion(out, label)
epoch_loss += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i % (1000) == 0:
print('%4d %4d / %4d loss = %.10f time = %s' % (
epoch + 1, i, len(Dataset)// opt.batch_size, epoch_loss / ((i+1) * opt.batch_size), datetime.datetime.now()))
elapsed_time = time.time() - start_time
print('epcoh = %4d , loss = %.10f , time = %4.2f s' % (epoch + 1, epoch_loss / len(Dataset), elapsed_time))
np.savetxt('train_result.txt', np.hstack((epoch + 1, epoch_loss / i, elapsed_time)), fmt='%2.4f')
torch.save(model, os.path.join("./checkpoint", 'model_%03d.pth' % (epoch + 1)))
|
[
"noreply@github.com"
] |
HengJiang95.noreply@github.com
|
8a92b2a570c5b6ff4b9342cbca901f64b66eca91
|
e62bc1322ef29535da02cf8040daef0ef9b1227e
|
/14_urllib_handler处理器的基本使用.py
|
01f15c831aed9cd101f3c510715cd8fb4335ae06
|
[] |
no_license
|
JLUVicent/crawler
|
7c291cda13b777397cb35d9a846c804a9928d24a
|
e218d343f6c0abb25486ee358652b3edc5756541
|
refs/heads/master
| 2023-08-28T20:53:03.466878
| 2021-09-17T07:16:06
| 2021-09-17T07:16:06
| 405,664,280
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 754
|
py
|
# 需求:使用handler来访问百度 获取网页源码
import urllib.request
url = 'http://www.baidu.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
}
request = urllib.request.Request(url=url, headers=headers)
# handler build_opener open
# 下面三步就相当于这条命令urllib.request.urlopen(request)
# 使用下面命令可以使用一些代理ip来进行访问
# (1)获取handler对象
handler = urllib.request.HTTPHandler()
# (2)获取opener对象
opener = urllib.request.build_opener(handler)
# (3)调用open方法
response = opener.open(request)
content = response.read().decode('utf-8')
print(content)
|
[
"17390955615@163.com"
] |
17390955615@163.com
|
1efde10d267c0dd29625aafc7b3354f8ddb25286
|
c46a3177866d72d6230016c23db797d207f15ada
|
/scripts/py/form_id_pairs.py
|
8a9dc33fc5edb77f6d5333732cb747d1c8ea599e
|
[] |
no_license
|
nknyazeva/course_work_5
|
4e560eb649a6506d35b1541527e29e0a4b9d2a7f
|
fb633557afc8685ff8c0a924a3f56b48a5134685
|
refs/heads/master
| 2020-07-25T11:33:27.167210
| 2019-11-06T16:52:25
| 2019-11-06T16:52:25
| 208,275,183
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,163
|
py
|
coord_macaca_file = '/home/nknyazeva/courseWork5/data/result/oma_exon_coordinates_macaca.txt'
coord_human_file = '/home/nknyazeva/courseWork5/data/result/oma_exon_coordinates_human.txt'
id_pairs_file = '/home/nknyazeva/courseWork5/data/result/ortho_pairs.txt'
out_file = '/home/nknyazeva/courseWork5/data/result/ortho_pairs_coordinates.txt'
dict_coord_human = {}
with open(coord_human_file, 'r') as coord_human:
for line in coord_human:
line = line.strip()
dict_coord_human[line.split()[0]] = line[11:]
dict_coord_macaca = {}
with open(coord_macaca_file, 'r') as coord_macaca:
for line in coord_macaca:
line = line.strip()
dict_coord_macaca[line.split()[0]] = line[11:]
with open(id_pairs_file, 'r') as id_pairs:
with open(out_file, 'w') as out_file:
for line in id_pairs:
line = line.strip()
human_id = line.split()[0]
macaca_id = line.split()[1]
out_file.write(human_id + '\t')
out_file.write(dict_coord_human[human_id] + '\t')
out_file.write(macaca_id + '\t')
out_file.write(dict_coord_macaca[macaca_id] + '\n')
|
[
"knjasewa-nastja@yandex.ru"
] |
knjasewa-nastja@yandex.ru
|
9772eae5928f6ca9699a8383d0dccc6eca2b1713
|
eb65feb88a0ca04999c33cf06ce3099c688418a5
|
/email_usernames/management.py
|
c086cea982b17b52be7dfb7e69cefe5673d3bb8d
|
[
"BSD-3-Clause"
] |
permissive
|
lucianolev/django-email-usernames
|
8333e8c2c06243f025a50c6c3eabbbe10559dab4
|
d2d2363f921fb9c048e8cb29cc4ad79438fb31c2
|
refs/heads/master
| 2020-12-30T09:38:18.109932
| 2012-11-08T03:09:56
| 2012-11-08T03:09:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,276
|
py
|
from django.db.models.signals import post_syncdb
message = """
'django-email-usernames' has detected that you just installed Django's authentication system (django.auth).
For your convenience, django-email-usernames can alter the user table's username field to allow 75 characters instead
of the default 35 chars. Unless you do this, emails that are longer than 30 characters will be cut off, and this
app will probably not work!
NOTE: this will only work if the SQL user account you have created for django has the privileges
to run ALTER statements.
Do you want django-email-usernames to try to alter the auth_user.username column to allow 75 characters?
(y/N): """
def query_fix_usertable(sender, app, created_models, verbosity, interactive, **kwargs):
model_names = [m.__name__ for m in created_models]
if not interactive or app.__name__ != 'django.contrib.auth.models' or "User" not in model_names:
return
answer = raw_input(message)
while not answer.lower() in ('y', 'n', 'yes', 'no'):
raw_input("You need to either decide yes ('y') or no ('n'). Default is no. (y/N): ")
from django.conf import settings
from django.db import connection
engine = settings.DATABASES['default']['ENGINE']
cursor = connection.cursor()
if 'postgis' in engine or 'postgresql_psycopg2' in engine:
cursor.execute('ALTER TABLE auth_user ALTER username TYPE character varying(75)')
elif 'sqlite3' in engine:
cursor.execute('ALTER TABLE "auth_user" RENAME TO "auth_user_temp"')
cursor.execute('CREATE TABLE "auth_user" ("id" integer NOT NULL PRIMARY KEY,"username" varchar(75) NOT NULL UNIQUE,"first_name" varchar(30) NOT NULL,"last_name" varchar(30) NOT NULL,"email" varchar(75) NOT NULL,"password" varchar(128) NOT NULL,"is_staff" bool NOT NULL,"is_active" bool NOT NULL,"is_superuser" bool NOT NULL,"last_login" datetime NOT NULL,"date_joined" datetime NOT NULL)')
cursor.execute('INSERT INTO "auth_user" SELECT * FROM "auth_user_temp"')
cursor.execute('DROP TABLE "auth_user_temp"')
else:
cursor.execute('ALTER TABLE auth_user MODIFY COLUMN username varchar(75) NOT NULL')
post_syncdb.connect(query_fix_usertable)
|
[
"lleveroni@eryxsoluciones.com.ar"
] |
lleveroni@eryxsoluciones.com.ar
|
9dce82a9bca0995ebad823b26676f483f32f1a9c
|
3e83835028984e8f07cafe40bda25f31f4d9894b
|
/tkmtribe/templates/urls.py
|
fe803d336db6f4511987e6a9a1d2bf1b171d96bc
|
[] |
no_license
|
AJITH-klepsydra/other_repositories
|
e029bd552cf2de3c9dcafa91d4d6905f77bea1da
|
e3c53315920cf093993ba10d4814a9b759f99588
|
refs/heads/main
| 2023-06-22T02:54:36.875236
| 2021-07-19T20:13:29
| 2021-07-19T20:13:29
| 386,726,541
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 796
|
py
|
"""todolist URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('todoapp.urls')),
path('admin/', admin.site.urls),
]
|
[
"ajithpmuralidharan01@gmail.com"
] |
ajithpmuralidharan01@gmail.com
|
7d3f89bf4180dc04215bc135c08b92f84466161e
|
aedc3ee164734a8c42d5c535a02ee1acdf3443fb
|
/Python/Gff2fasta-mito.py
|
1e2e3e09353064d7522b7f2ebb643b24e1778a13
|
[] |
no_license
|
zglu/Scripts_Bioinfo
|
60fdd5fe70b4900d981cc06560595ecb4fb9690e
|
8589ed613868f88ae12b8a629156c0a12b420bbc
|
refs/heads/master
| 2023-01-27T11:13:18.140272
| 2023-01-23T13:19:09
| 2023-01-23T13:19:09
| 96,612,675
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,050
|
py
|
#! /usr/bin/env python
"""
Get dna sequences based on a gff file for features like gene, transcript, cds, exon, and get pep for coding sequences.
SHOULD CHECK THE FEATURE NAME IN YOUR GFF: mRNA or transcript, and change accordingly.
THIS IS A SLIGHT CHANGED SCRIPT FOR PROTEIN SEQUENCES OF MITOCHONDRIAL GENES
Usage: python gff2fasta.py <gff3 file> <genome sequence> <type> > output
last update: 18/11/2017
"""
import sys
import gffutils
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
## ignore biopython warnings
import warnings
from Bio import BiopythonWarning
warnings.simplefilter('ignore', BiopythonWarning)
if len(sys.argv) < 3:
sys.exit("Usage: python gff2fasta.py <gff3 file> <genome sequence> <type> > output")
else:
myGFF = sys.argv[1]
myFasta = sys.argv[2]
seqType = sys.argv[3]
db = gffutils.create_db(myGFF, ':memory:', merge_strategy="create_unique", keep_order=True)
## or create a real database
## import data into database: one-time operation
#db = gffutils.create_db(myGFF, 'myGFF.db', merge_strategy="create_unique", keep_order=True) # ':memory:'
## once created, use the database (donot need gff file anymore)
#db = gffutils.FeatureDB('myGFF.db')
## function to get all gene/transcript(mRNA) sequences
def parent_seq(type):
for p in db.features_of_type(type):
print('>' + p.id)
p_seq = p.sequence(myFasta)
p_seq = Seq(p_seq, generic_dna)
if p.strand == '-':
p_seq = p_seq.reverse_complement()
for i in range(0, len(p_seq), 60): # print 60 bases per line
print(p_seq[i:i+60])
## function to get all cds/exon/intron sequences under the same transcript id
def child_seq(type):
for t in db.features_of_type('mRNA', order_by='start'): # or mRNA depending on the gff
print('>' + t.id + '_' + type)
# print(t.sequence(myFasta))
seq_combined = ''
for i in db.children(t, featuretype=type, order_by='start'): # or exon/intron
seq = i.sequence(myFasta, use_strand=False) # use_strand doesn't work in 0.8; have to revcomp
seq_combined += seq
seq_combined = Seq(seq_combined, generic_dna)
if t.strand == '-':
seq_combined = seq_combined.reverse_complement()
for i in range(0, len(seq_combined), 60):
print(seq_combined[i:i+60])
## function to get all protein sequences under the same transcript id
def pep_seq():
for t in db.features_of_type('mRNA', order_by='start'): # or mRNA depending on the gff
#print(t.sequence(myFasta))
print('>' + t.id)
seq_combined = ''
j = 0
for i in db.children(t, featuretype='CDS', order_by='start'): # or exon/intron
j += 1
if j == 1:
pphase = i[7] # assign phase to the 7th column of first CDS
seq = i.sequence(myFasta, use_strand=False) # use_strand doesn't work; have to revcomp
seq_combined += seq
seq_combined = Seq(seq_combined, generic_dna)
if t.strand == '-':
pphase = i[7] # assign phase to the 7th column of last CDS line
seq_combined = seq_combined.reverse_complement()
#print(seq_combined)
if pphase == "0" or pphase == ".":
seq_transl = seq_combined.translate(table=5) ## select translation table for mitochodrial genes
for i in range(0, len(seq_transl), 60):
print(seq_transl[i:i+60])
elif pphase == "1":
seq_transl = seq_combined[1:].translate()
for i in range(0, len(seq_transl), 60):
print(seq_transl[i:i+60])
elif pphase == "2":
seq_transl = seq_combined[2:].translate()
for i in range(0, len(seq_transl), 60):
print(seq_transl[i:i+60])
if seqType in ['gene', 'mRNA']:
parent_seq(seqType)
elif seqType in ['CDS', 'exon', 'intron']:
child_seq(seqType)
elif seqType == 'pep':
pep_seq()
else:
sys.exit("Supported feature types: gene/mRNA/CDS/pep/exon/intron.")
|
[
"zl@zlzyz.com"
] |
zl@zlzyz.com
|
1902d295e917b79374d5a728c75bdc9e5b4f41af
|
627b76ad17f70cdbaa090d44baf6a8116aae2e64
|
/data structures/doublyLinkedList.py
|
ff5433323f9db9b3c4ca0c9fbb1bf2a12626473b
|
[] |
no_license
|
darumada/alghoritms
|
24125b5cb8b650bb9d7f6219fa2635671ac4ff25
|
48c56209d16b3256df76adc39f13a8547737470f
|
refs/heads/master
| 2022-11-14T05:12:36.262606
| 2020-06-26T23:07:09
| 2020-06-26T23:07:09
| 231,822,381
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,610
|
py
|
class DoublyLinkedList:
class _Node:
def __init__(self, element, next=None, prev=None):
self.element = element
self.next = next
self.prev = prev
def __init__(self):
self._size = 0
self.header = self._Node(None, None, None)
self.trailer = self._Node(None, None, None)
self.header.next = self.trailer
self.trailer.prev = self.header
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def add_first(self, e):
return self.insert_between(e, self.header.next, self.header)
def add_last(self, e):
return self.insert_between(e, self.trailer, self.trailer.prev)
def insert_between(self, e, next, prev):
new_node = self._Node(e, next, prev)
next.prev = new_node
prev.next = new_node
self._size += 1
return new_node
def delete_node(self, node):
prev = node.prev
next = node.next
element = node.element
prev.next = next
next.prev = prev
node.prev = node.next = node.element = None
self._size -= 1
return element
if __name__ == "__main__":
list = DoublyLinkedList()
list.add_first(1)
list.add_first(2)
list.add_first(3)
list.add_first(4)
list.add_last(5)
list.add_last(6)
list.add_last(7)
list.add_last(8)
def traversal(list):
head = list.header.next
while head is not list.trailer:
print(head.element)
head = head.next
traversal(list)
|
[
"maksaturekeshov@gmail.com"
] |
maksaturekeshov@gmail.com
|
9da7a5def4b9c4018ae9cce832eb6b33b5a7c773
|
851250765122fd9b4c75236b8e6e21d6daf8df04
|
/py/04_01_simple_cnn_project.py
|
bf7fcfb891892b0a1064c0e6755b403532c1fb66
|
[] |
no_license
|
younghwani/NLP
|
5e2507a06eb5b530d75d44f914d71fcca76d5cc7
|
abf6a86315743a6c17a4bf7f752396b326afe9e2
|
refs/heads/master
| 2023-03-08T08:13:58.364244
| 2021-02-16T04:33:01
| 2021-02-16T04:33:01
| 332,720,312
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,819
|
py
|
# -*- coding: utf-8 -*-
# EVN
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# 단어 긍정(2), 중립(1), 부정(0) 분류 프로젝트
# 데이터
sentences = [
'나는 오늘 기분이 좋아',
'나는 오늘 우울해'
]
# 출력 정답
labels = [[1, 1, 1, 2],
[1, 1, 0]] # 긍정(2), 중립(1), 부정(0)
# 정답 dic
id_to_label = {0: '부정', 1: '중립', 2: '긍정'}
# Vocabulary
# 각 문장을 띄어쓰기 단위로 분할
words = []
for sentence in sentences:
words.extend(sentence.split())
# 중복 단어 제거
words = list(dict.fromkeys(words))
# 각 단어별 고유한 번호 부여
word_to_id = {'[PAD]': 0, '[UNK]': 1}
for word in words:
word_to_id[word] = len(word_to_id)
# 각 숫자별 단어 부여
id_to_word = {_id:word for word, _id in word_to_id.items()}
print('Id to Word : \n', id_to_word)
# 학습용 입력 데이터 생성
train_inputs = []
for sentence in sentences:
train_inputs.append([word_to_id[word] for word in sentence.split()])
# train label은 labels 사용
train_labels = labels
# 문장의 길이를 모두 동일하게 변경 (최대길이 4)
for row in train_inputs:
row += [0] * (4 - len(row))
# train inputs을 numpy array로 변환
train_inputs = np.array(train_inputs)
# 정답 길이를 모두 동일하게 변경 (최대길이 4)
for row in train_labels:
row += [1] * (4 - len(row))
# 학습용 정답을 numpy array로 변환
train_labels = np.array(train_labels)
# 모델링
# 입력 단어를 vector로 변환
embedding = tf.keras.layers.Embedding(len(word_to_id), 8)
hidden = embedding(train_inputs)
print('After Embedding : \n', hidden)
# embedding weight
weight = embedding.get_weights()[0]
print('weight.shape : ', weight.shape)
# numpy를 이용해서 직접 조회 (두 결과값 비교)
# print(weight[train_inputs], hidden)
# 단어의 vector를 이용해서 긍정(2), 부정(0), 중립(1) 확률값 예측
linear = tf.keras.layers.Dense(3, activation=tf.nn.softmax)
outputs = linear(hidden)
print('After linear : \n', outputs)
# dense의 wieght, bias
weight, bias = linear.get_weights()
# print(weight, bias)
# numpy를 이용한 xW + b
logits = np.matmul(hidden, weight) + bias
# print(logits)
# softmax 계산을 위한 준비 exp(x') / sum(exp(x))
numerator = np.exp(logits)
denominator = np.sum(numerator, axis=2, keepdims=True)
# print(numerator, denominator)
# 두 결과값 비교
probs = numerator / denominator
print('probs : ', probs, '\noutputs : ', outputs)
def build_model(n_vocab, d_model, n_seq, n_out):
"""
동작만 하는 간단한 모델
:param n_vocab: vocabulary 단어 수
:param d_model: 단어를 의미하는 벡터의 차원 수
:param n_seq: 문장길이 (단어 수)
:param n_out: 예측할 class 개수
"""
inputs = tf.keras.layers.Input((n_seq,)) # (bs, n_seq)
embedding = tf.keras.layers.Embedding(n_vocab, d_model) # 입력 단어를 vector로 변환
hidden = embedding(inputs) # (bs, n_seq, d_model)
hidden = tf.keras.layers.Conv1D(64, kernel_size=5, padding='same', activation='relu')(hidden)
hidden = tf.keras.layers.Dense(n_out, activation=tf.nn.softmax)(hidden) # 단어의 vector를 이용해서 정답 확률값 예측 (bs, n_seq, n_out)
model = tf.keras.Model(inputs=inputs, outputs=hidden) # 학습할 모델 선언
return model
# 모델 생성
model = build_model(len(word_to_id), 8, 4, 3)
# 모델 내용 출력
print(model.summary())
# 학습
# 모델 loss, optimizer, metric 정의
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 모델 학습
history = model.fit(train_inputs, train_labels, epochs=100, batch_size=16)
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], 'b-', label='loss')
plt.xlabel('Epoch')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], 'g-', label='accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.show()
# 모델 평가
model.evaluate(train_inputs, train_labels)
# 예측
# 추론할 입력
string = '나는 기분이 우울해'
# 입력을 숫자로 변경
infer_input = [word_to_id[word] for word in string.split()]
# print(infer_input)
# 문장의 길이를 모두 동일하게 변경 (최대길이 4)
infer_input += [0] * (4 - len(infer_input))
# print(infer_input)
# numpy array 변환 (batch size 1 추가)
infer_inputs = np.array([infer_input])
# print(infer_inputs)
# 긍정/부정 추론
y_preds = model.predict(infer_inputs)
print('y_preds : ', y_preds)
# 확률의 max 값을 추론 값으로 결정
y_pred_class = np.argmax(y_preds, axis=2)
print('y_pred_class : ', y_pred_class)
# 각 예측 값에 대한 label string
for row in y_pred_class:
for val in row:
print(val, ':', id_to_label[val])
|
[
"younghwankim624@gmail.com"
] |
younghwankim624@gmail.com
|
782c52d293b6d10df0abe617763dc183609221ad
|
7cf9e036e839562a663c53babdfb1b7ec5172b0e
|
/cat_bookstore/config/asgi.py
|
bc3ca883115d37bc0397eb54297b6ec7a322b748
|
[] |
no_license
|
kKn00077/bookstore_backend_cancled
|
73e81765ab6eaa8afc57ccf011624609815f22b0
|
556e1ae7083fe2dc8131145b966b7bea1741193e
|
refs/heads/main
| 2023-06-15T14:56:41.929712
| 2021-07-15T03:52:43
| 2021-07-15T03:52:43
| 386,153,687
| 0
| 0
| null | 2021-07-15T03:51:28
| 2021-07-15T03:46:31
|
Python
|
UTF-8
|
Python
| false
| false
| 403
|
py
|
"""
ASGI config for cat_bookstore project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cat_bookstore.settings')
application = get_asgi_application()
|
[
"kkn00077@gmail.com"
] |
kkn00077@gmail.com
|
223279549adfb57b8078816158b1509154e88f3d
|
e48aedf65644d3810389b927d28e7043b7b4f043
|
/utils/GlobalVars.py
|
fd45fcd014da84b73cc94a30fb442914755ccd0f
|
[] |
no_license
|
Petersonjoe/pyproject
|
a5ee349b8aa729a200211a9391f338d4b391a4da
|
ce7b3f4af0f87dc6e92a3cb04797909bfd5c6abe
|
refs/heads/master
| 2022-12-13T11:54:45.025505
| 2020-08-12T02:10:56
| 2020-08-12T02:10:56
| 210,077,146
| 1
| 1
| null | 2022-12-08T02:39:51
| 2019-09-22T02:02:42
|
Python
|
UTF-8
|
Python
| false
| false
| 2,959
|
py
|
# -*- coding: utf-8 -*-
#############################################
# @Author: jlei1
# @Date: 2018-07-07
# @Last Modified By: jlei1
# @Last Modified Time: 2018-07-20
#############################################
from distutils.log import warn as printf
import os, sys
''' Pathon的path与运行时文件位置绑定,很恶心,需要注意这一点
os 模块的常用方法
========================================================================================
os.sep可以取代操作系统特定的路径分隔符。windows下为 “\\”
os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
os.getenv()获取一个环境变量,如果没有返回none
os.putenv(key, value)设置一个环境变量值
os.listdir(path)返回指定目录下的所有文件和目录名。
os.remove(path)函数用来删除一个文件。
os.system(command)函数用来运行shell命令。
os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
os.curdir:返回当前目录('.')
os.chdir(dirname):改变工作目录到dirname
========================================================================================
os.path常用方法:
os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
os.path.exists()函数用来检验给出的路径是否真地存在
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(path) :将path分割成目录和文件名二元组返回。
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录;使用“\”连接
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径
os.path.pardir: 当前目录的上一级目录
'''
from .ReadConfig import DecodeConfig
# 注意:这里不要使用任何OS模块相关的函数,因为会导致人“入口依赖”问题
# 例如,par_dir = os.getcwd().replace('\\','/')
# 如果调用的入口文件不在同一个层级,将会返回不同的文件路径
# 如果需要绝对路径,请使用魔术方法:__file__
# 以该文件为参照,获取项目根目录的绝对路径
CUR_ABS_DIR = os.path.split(__file__)[0]
PAR_ABS_DIR = '/'.join(CUR_ABS_DIR.split("\\")[0:-1])
PROJ_ROOT_DIR = PAR_ABS_DIR
# 获取stm的url列表
config_path = PROJ_ROOT_DIR + '/conf/'
config_name = 'global'
config = DecodeConfig()
url_file_loc = config.getConfig(filepath=config_path, filename=config_name)
URL_LIST = config.getCSV(filepath=PROJ_ROOT_DIR + url_file_loc['input_dirs']['stm'],filename=url_file_loc['input_files']['stm'])
# output 目录
OTPT_DIR = PROJ_ROOT_DIR + '/output/'
|
[
"trandg@126.com"
] |
trandg@126.com
|
c621d0a6b55bda68a4519f7026a6b961f9d5f30f
|
25cf6132112ef79eeaf786f71283f440f8790e55
|
/video.py
|
2e1cc365ade987432309e017e2ab5f201b579976
|
[] |
no_license
|
daaguirr/Mandelbrot-Infinite-Zoom-GPU
|
0281eeef17b5bdea5e23aa1e1dadba9e3d8d1303
|
a18b1282ffa02969ae0712ce2f68b01a825301d4
|
refs/heads/master
| 2020-04-12T00:08:20.009952
| 2018-12-26T03:44:22
| 2018-12-26T03:44:22
| 162,190,198
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 903
|
py
|
import imageio
import sys
import datetime
VALID_EXTENSIONS = ('png', 'jpg')
def create_gif(filenames, duration):
images = []
for filename in filenames:
images.append(imageio.imread(filename))
output_file = 'Gif-%s.gif' % datetime.datetime.now().strftime('%Y-%M-%d-%H-%M-%S')
imageio.mimsave(output_file, images, duration=duration)
if __name__ == "__main__":
from os import listdir
from os.path import isfile, join
import os
current_dir = os.getcwd()
path = os.path.join(current_dir, 'results')
filenames = [f for f in listdir(path) if isfile(join(path, f))]
if not all(f.lower().endswith(VALID_EXTENSIONS) for f in filenames):
print('Only png and jpg files allowed')
sys.exit(1)
filenames = [os.path.join(path, f) for f in filenames]
filenames.sort(key=lambda x: x)
print(filenames)
create_gif(filenames, 1/30)
|
[
"dagum95@gmail.com"
] |
dagum95@gmail.com
|
033cb8f01e7ebbaa293f884be0a33fa115b6f18e
|
f342fb3db6654617b7cc18d1647907719e5e215e
|
/test/test12.py
|
5084f4cb2bc8f764a44eaf52072707260649f60f
|
[] |
no_license
|
durgeshn/validations
|
17d0d30283deb6cebda7fe5b5df4601a6a9dfea9
|
79bd47ca380a3c161fcba0eeed3b78d98692cc32
|
refs/heads/master
| 2020-12-30T16:14:42.121372
| 2017-05-11T10:25:57
| 2017-05-11T10:25:57
| 90,967,074
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 18
|
py
|
import maya_batch
|
[
"durgeh.n@philmcgi.com"
] |
durgeh.n@philmcgi.com
|
df36f6d06bf7f69a97d3c71ce44dd114f532d059
|
afa60e28e2d60fb3255fa12bdc327d7e377a7c63
|
/data/multicols/surface_residues.py
|
2805cea0b9a1d3de66d9d8f967ff28fe143790af
|
[
"Apache-2.0"
] |
permissive
|
smoitra87/mrfs
|
19bbd826b409f0d5ec16056096527117507f6aaf
|
49c1de4f98b655cc296bf9c3a9b0e99e1e721056
|
refs/heads/master
| 2016-08-04T17:52:03.484751
| 2015-04-30T15:14:50
| 2015-04-30T15:14:50
| 28,839,144
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 678
|
py
|
'''
http://pymolwiki.org/index.php/FindSurfaceResidues
'''
from pymol import cmd
def findAtomExposure(selection="all"):
"""
DESCRIPTION
Finds those atoms on the surface of a protein
that have at least 'cutoff' exposed A**2 surface area.
USAGE
findSurfaceAtoms [ selection, [ cutoff ]]
SEE ALSO
findSurfaceResidues
"""
tmpObj = cmd.get_unused_name("_tmp")
cmd.create(tmpObj, "(" + selection + ") and polymer", zoom=0)
cmd.set("dot_solvent", 1, tmpObj)
cmd.get_area(selection=tmpObj, load_b=1)
atoms = list()
cmd.iterate(tmpObj, "atoms.append((name,chain,resv,b))", space=locals())
cmd.delete(tmpObj)
return atoms
|
[
"subhodeep.moitra@gmail.com"
] |
subhodeep.moitra@gmail.com
|
128e0c315480ac722dea65aca21dfab20d5aa3c9
|
533f86815dcded10183f623b6ddd552fadd9e38c
|
/Lesson_01/_5_practice.py
|
1420a105c746f316b1fe33e498c58cbd5029339c
|
[] |
no_license
|
DoctorSad/_Course
|
8ab81db218cd9a0bfefb118094912c53b11256d4
|
da5ba4d6904910be033241e3b68c846e883a24fa
|
refs/heads/main
| 2023-04-15T10:26:27.294706
| 2021-05-06T08:59:38
| 2021-05-06T08:59:38
| 351,796,720
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,053
|
py
|
"""
1. Создать переменные var_int, var_float, var_str,
присвоив им 25, 4.5, 'python'
2. Значение var_int увеличьте в 1.5 раза и присвойте переменной var_big
3. Измените значение, хранимое в var_float уменьшив его на единицу
4. Выведите на экран остаток от деления var_big на var_float
5. Измените значение переменной var_str на 'end'
6. Выведите значения всех переменных
"""
# 1
var_int = 25
var_float = 4.5
var_str = "python"
# вариант с множественным присваиванием
var_int, var_float, var_str = 25, 4.5, "python"
# 2
var_big = var_int * 1.5
# 3
var_float = var_float - 1
# с использованием оператора присваивания
# var_float -= 1
# 4
result = var_big % var_float
print(result)
# 5
var_str = "end"
# 6
print(var_big, var_float, var_str)
|
[
"DoctorSad@gmail.com"
] |
DoctorSad@gmail.com
|
917f26898831eae2502f2fba6bcdb7f7de66b64a
|
1941d67b9ec30a338bf8e9a62082c92488f2b534
|
/snake_record_table/settings.py
|
45a593b1dd146a7395705d4ae970759dc9ea9309
|
[] |
no_license
|
kaktus313/snake_records_table_rep
|
e13b53a364ca8c096f800e8a8827e59d52e63fcd
|
656a8bfe49d5bfb700f63a0b2e24a650d27e3b56
|
refs/heads/master
| 2021-05-06T14:26:04.275259
| 2017-12-09T08:26:02
| 2017-12-09T08:26:02
| 113,363,984
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,273
|
py
|
"""
Django settings for snake_record_table project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8^wzbk3+u$$qgal#1%03dyx^=4o9f(16a53mu5^p6139#wo)(l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'kaktus313.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'snake_record_table_app'
]
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 = 'snake_record_table.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 = 'snake_record_table.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
[
"kaktus313z@gmail.com"
] |
kaktus313z@gmail.com
|
98370c87cc80048dc11a1301074e9af579891753
|
65dff28b4bc200d44f36531c7dc34c87a83261e2
|
/tests/base_class.py
|
92ddc22d2afe35798eafe79a1873ea2dda4ccbf6
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
domlysz/python-overpy
|
a96cfb48b48b0323ff4e8742adeb6af1df15a3d6
|
7f4ece2a8b2edee233dee671b1e1cc28b2150df0
|
refs/heads/master
| 2021-01-21T17:57:15.971535
| 2016-07-29T12:38:59
| 2016-07-29T12:38:59
| 63,004,671
| 4
| 0
| null | 2016-07-10T15:14:18
| 2016-07-10T15:14:17
| null |
UTF-8
|
Python
| false
| false
| 9,337
|
py
|
from decimal import Decimal
import os
import pytest
import overpy
from tests import read_file
class BaseTestNodes(object):
def _test_node01(self, result):
assert len(result.nodes) == 3
assert len(result.relations) == 0
assert len(result.ways) == 0
node = result.nodes[0]
assert isinstance(node, overpy.Node)
assert isinstance(node.id, int)
assert isinstance(node.lat, Decimal)
assert isinstance(node.lon, Decimal)
assert node.id == 50878400
assert node.lat == Decimal("50.7461788")
assert node.lon == Decimal("7.1742257")
assert isinstance(node.tags, dict)
assert len(node.tags) == 0
node = result.nodes[1]
assert isinstance(node, overpy.Node)
assert isinstance(node.id, int)
assert isinstance(node.lat, Decimal)
assert isinstance(node.lon, Decimal)
assert node.id == 100793192
assert node.lat == Decimal("50.7468472")
assert node.lon == Decimal("7.1709376")
assert isinstance(node.tags, dict)
assert len(node.tags) == 1
assert node.tags["highway"] == "turning_circle"
node = result.nodes[2]
assert isinstance(node, overpy.Node)
assert isinstance(node.id, int)
assert isinstance(node.lat, Decimal)
assert isinstance(node.lon, Decimal)
assert node.id == 3233854234
assert node.lat == Decimal("50.7494236")
assert node.lon == Decimal("7.1757664")
assert isinstance(node.attributes, dict)
assert len(node.attributes) == 5
# ToDo: fix
# assert node.attributes["changeset"] == 23456789
# assert node.attributes["user"] == "TestUser"
# try to get a single node by id
node = result.get_node(50878400)
assert node.id == 50878400
# try to get a single node by id not available in the result
with pytest.raises(overpy.exception.DataIncomplete):
result.get_node(123456)
# node_ids is an alias for get_node_ids() and should return the same data
for node_ids in (result.node_ids, result.get_node_ids()):
assert len(node_ids) == 3
assert node_ids[0] == 50878400
assert node_ids[1] == 100793192
assert node_ids[2] == 3233854234
assert len(result.relation_ids) == 0
assert len(result.get_relation_ids()) == 0
assert len(result.way_ids) == 0
assert len(result.get_way_ids()) == 0
class BaseTestRelation(object):
def _test_relation01(self, result):
assert len(result.nodes) == 0
assert len(result.relations) == 1
assert len(result.ways) == 0
relation = result.relations[0]
assert isinstance(relation, overpy.Relation)
assert isinstance(relation.id, int)
assert relation.id == 2046898
assert isinstance(relation.tags, dict)
assert len(relation.tags) == 6
assert relation.tags["from"] == "Here"
assert relation.tags["name"] == "Test relation"
assert relation.tags["ref"] == "609"
assert relation.tags["route"] == "bus"
assert relation.tags["to"] == "There"
assert relation.tags["type"] == "route"
assert isinstance(relation.attributes, dict)
assert len(relation.attributes) == 5
assert len(relation.members) == 5
assert isinstance(relation.members[0], overpy.RelationNode)
assert isinstance(relation.members[1], overpy.RelationNode)
assert isinstance(relation.members[2], overpy.RelationNode)
assert isinstance(relation.members[3], overpy.RelationNode)
assert isinstance(relation.members[4], overpy.RelationWay)
def _test_relation02(self, result):
assert len(result.nodes) == 3
assert len(result.relations) == 1
assert len(result.ways) == 1
relation = result.relations[0]
assert isinstance(relation, overpy.Relation)
assert isinstance(relation.id, int)
assert relation.id == 2046898
assert isinstance(relation.tags, dict)
assert len(relation.tags) == 6
assert relation.tags["from"] == "Here"
assert relation.tags["name"] == "Test relation"
assert relation.tags["ref"] == "609"
assert relation.tags["route"] == "bus"
assert relation.tags["to"] == "There"
assert relation.tags["type"] == "route"
assert isinstance(relation.attributes, dict)
assert len(relation.attributes) == 5
assert len(relation.members) == 4
member = relation.members[0]
assert isinstance(member, overpy.RelationNode)
node = member.resolve()
assert isinstance(node, overpy.Node)
assert node.id == 3233854233
assert member.ref == node.id
member = relation.members[1]
assert isinstance(member, overpy.RelationNode)
node = member.resolve()
assert isinstance(node, overpy.Node)
assert node.id == 3233854234
assert member.ref == node.id
member = relation.members[2]
assert isinstance(member, overpy.RelationNode)
node = member.resolve()
assert isinstance(node, overpy.Node)
assert node.id == 3233854235
assert member.ref == node.id
member = relation.members[3]
assert isinstance(member, overpy.RelationWay)
way = member.resolve()
assert isinstance(way, overpy.Way)
assert way.id == 317146078
assert member.ref == way.id
class BaseTestWay(object):
def _test_way01(self, result):
assert len(result.nodes) == 0
assert len(result.relations) == 0
assert len(result.ways) == 2
way = result.ways[0]
assert isinstance(way, overpy.Way)
assert isinstance(way.id, int)
assert way.id == 317146077
assert isinstance(way.tags, dict)
assert len(way.tags) == 1
assert way.tags["building"] == "yes"
assert isinstance(way.attributes, dict)
assert len(way.attributes) == 0
way = result.ways[1]
assert isinstance(way, overpy.Way)
assert isinstance(way.id, int)
assert way.id == 317146078
assert isinstance(way.tags, dict)
assert len(way.tags) == 0
assert isinstance(way.attributes, dict)
assert len(way.attributes) == 5
# ToDo: fix it
# assert way.attributes["uid"] == 345678
# assert way.attributes["user"] == "TestUser"
# assert way.attributes["changeset"] == 23456789
# try to get a single way by id
way = result.get_way(317146077)
assert way.id == 317146077
# try to get a single way by id not available in the result
with pytest.raises(overpy.exception.DataIncomplete):
result.get_way(123456)
assert len(result.node_ids) == 0
assert len(result.get_node_ids()) == 0
assert len(result.relation_ids) == 0
assert len(result.get_relation_ids()) == 0
# way_ids is an alias for get_way_ids() and should return the same data
for way_ids in (result.way_ids, result.get_way_ids()):
assert len(way_ids) == 2
assert way_ids[0] == 317146077
assert way_ids[1] == 317146078
def _test_way02(self, result):
assert len(result.nodes) == 6
assert len(result.relations) == 0
assert len(result.ways) == 1
node = result.nodes[0]
assert isinstance(node, overpy.Node)
assert isinstance(node.id, int)
assert isinstance(node.lat, Decimal)
assert isinstance(node.lon, Decimal)
assert node.id == 3233854233
assert node.lat == Decimal("50.7494187")
assert node.lon == Decimal("7.1758731")
way = result.ways[0]
assert isinstance(way, overpy.Way)
assert isinstance(way.id, int)
assert way.id == 317146077
assert isinstance(way.tags, dict)
assert len(way.tags) == 1
assert way.tags["building"] == "yes"
nodes = way.nodes
assert len(nodes) == 7
node = nodes[0]
assert isinstance(node, overpy.Node)
assert node.id == 3233854241
# try to get a single way by id
way = result.get_way(317146077)
assert way.id == 317146077
# try to get a single way by id not available in the result
with pytest.raises(overpy.exception.DataIncomplete):
result.get_way(123456)
# node_ids is an alias for get_node_ids() and should return the same data
for node_ids in (result.node_ids, result.get_node_ids()):
assert len(node_ids) == 6
assert node_ids[0] == 3233854233
assert node_ids[1] == 3233854234
assert node_ids[2] == 3233854236
assert node_ids[3] == 3233854237
assert node_ids[4] == 3233854238
assert node_ids[5] == 3233854241
assert len(result.relation_ids) == 0
assert len(result.get_relation_ids()) == 0
# way_ids is an alias for get_way_ids() and should return the same data
for way_ids in (result.way_ids, result.get_way_ids()):
assert len(way_ids) == 1
assert way_ids[0] == 317146077
|
[
"phibo@dinotools.org"
] |
phibo@dinotools.org
|
41b75083e16654b4f12be00cf82ecd8b4765021c
|
f47a380e2ff84d53b890095f935b713ddc0c985f
|
/Programming Fundamentals/Lab 7-9/service/serviceEvent.py
|
6544bf2bf813852d6bfcb30c04e1194e62ff5223
|
[] |
no_license
|
crisnita/University
|
155b1855e2cfc20ca9f25558c8a026e6a691817c
|
30e22ffde3ea41c55eb8a4964c8e57041c734d57
|
refs/heads/master
| 2020-05-04T18:35:51.427652
| 2019-05-21T16:57:41
| 2019-05-21T16:57:41
| 179,354,262
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,163
|
py
|
"""
@author: Nita Andrei-Cristian
@email: cristiannita99@yahoo.com
@date: 11/19/2018 14:20
"""
from domain.entities import Event
class ServiceEvent:
def __init__(self, repo, val):
self.__repo = repo
self.__val = val
def createEvent(self, id, date, time, descr):
"""
1) Create event
2) Validate event
3) Store event in repository
:param id:
:param date:
:param time:
:param descr:
:return:
"""
e = Event(id, date, time, descr)
self.__val.validateEvent(e)
self.__repo.storeElem(e)
return e
def getAllEvents(self):
return self.__repo.getAllEvents()
def modEvent(self, id, date, time, descr):
event = Event(id, date, time, descr)
self.__repo.update(event)
def deleteEventFaraRecursivitate(self, id):
allEvents = self.__repo.getAllEvents()
for e in allEvents:
if e.get_id() == id:
self.__repo.deleteEvent(e)
def deleteEvent(self, id):
allPeople = self.__repo.getAllEvents()
lst = []
for pers in allPeople:
lst.append(pers.get_id())
toDelete = self.findEvent(lst, id, 0)
if toDelete == -1:
print('No such event in the list!')
else:
self.__repo.deleteEventWithId(toDelete)
def findEvent(self, lst, id, i):
'''
Metoda recursiva
:param lst:
:param id:
:param i:
:return:
'''
if i >= len(lst):
return -1
if lst[i] == id:
return lst[i]
return self.findEvent(lst, id, i+1)
def printEve(self, id):
return self.__repo.findEvent(id)
def searchInEvent(self, e, secv):
date = e.get_date()
time = e.get_time()
descr = e.get_descr()
if secv in date:
return True
if secv in time:
return True
if secv in descr:
return True
return False
def loadEve(self):
self.__repo.load()
def saveEve(self):
self.__repo.save()
|
[
"cristiannita99@yahoo.com"
] |
cristiannita99@yahoo.com
|
07687717a392cda35c1f43e3f3945fb41d621f94
|
2d792f8949b4081e1104aecb10744645224b02e9
|
/hear_me_code/dict_exercise.py
|
3969dc20dd009ff8d40c376e210e6232599de4ed
|
[] |
no_license
|
lizmeister321/abunchofstuff
|
15a47990fbb89ac3774b2ef11a3676cd12ab2478
|
64f61e5c9cded15f60e500394a24e0fee5aec5df
|
refs/heads/master
| 2021-01-19T12:51:16.956992
| 2021-01-15T15:20:21
| 2021-01-15T15:20:21
| 82,344,174
| 0
| 2
| null | 2021-01-15T15:20:22
| 2017-02-17T22:36:30
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 1,214
|
py
|
schools = {
"geometry": {
"coordinates": [
-81.50572799999999,
39.21675500000001
],
"type": "Point"
},
"properties": {
"address": "300 Campus Drive, Parkersburg, WV 26104",
"marker-color": "#3F3040",
"marker-symbol": "circle",
"name": "West Virginia University at Parkersburg"
},
"type": "Feature"
}
# Example Question: How could you "slice" the dictionary to print "Feature" from line 15?
# Answer: print schools["type"]
# Question 1: What slice will give you a dictionary
# with the key of "coordinates" and a value containing a list
# of two decimal numbers?
#print schools['geometry']
# Question 2: What slice will give you the address of the school?
#print schools['properties']['address']
# Question 3: What slice will give you the name of the school?
#print schools['properties']['name']
# Question 4: What slice will give you the latitude of the school?
# (Hint: the latitude is 39.216...)
#print schools['geometry']['coordinates'][1]
# Question 5 (bonus): What slice will give you the marker-color
# without the hashtag in front?
print schools['properties']['marker-color'][1:]
|
[
"e.geiger.ellis@gmail.com"
] |
e.geiger.ellis@gmail.com
|
9790b58c105c148d65399a28a2045c466d1761b7
|
f159aeec3408fe36a9376c50ebb42a9174d89959
|
/77.Combinations.py
|
a5a4333e228ee0f56a58bfb8d2b3f46049e647d2
|
[
"MIT"
] |
permissive
|
mickey0524/leetcode
|
83b2d11ab226fad5da7198bb37eeedcd8d17635a
|
fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f
|
refs/heads/master
| 2023-09-04T00:01:13.138858
| 2023-08-27T07:43:53
| 2023-08-27T07:43:53
| 140,945,128
| 27
| 9
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 775
|
py
|
# https://leetcode.com/problems/combinations/
#
# algorithms
# Medium (45.24%)
# Total Accepted: 178,657
# Total Submissions: 394,947
# beats 79.55% of python submissions
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = [[]]
def resursive(length, idx, path):
if length == k:
res[0] += path,
return
if k - length > n - idx + 1:
return
for i in xrange(idx, n + 1):
resursive(length + 1, i + 1, path + [i])
resursive(0, 1, [])
return res[0]
|
[
"buptbh@163.com"
] |
buptbh@163.com
|
b93f21e54f0b95c73c2f7533d0bfce90b385dc0f
|
500b7f39baa00b81bd6cac3ae001c9ddd0162bb8
|
/ChatServerLocalTemplate.py
|
eb558fce1fb270400dfe946f5d0ed82fc5a3b63a
|
[] |
no_license
|
planetblix/raspberrypi
|
1e6d57691c028ab526e5c980934974cc9efce50b
|
61975c68edb13060211a7089589e9c1066f7058b
|
refs/heads/master
| 2020-06-06T02:15:18.372271
| 2013-04-26T16:37:00
| 2013-04-26T16:37:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 464
|
py
|
import socket
HOST = '192.168.0.4' #This is the I.P. Address of the machine this code is running on
PORT = 8000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1) # Only accepts 1 x client connection
conn,addr = s.accept()
print "Connected by", addr
i = True
while i is True:
data = conn.recv(1024)
print 'Received', repr(data)
if not data:
break
reply = raw_input("Reply: ")
conn.sendall(reply)
conn.close()
|
[
"binodbista@gmail.com"
] |
binodbista@gmail.com
|
21c9444c2972001bb184608dfffd1927af31eaac
|
c21905c7ade0c313e8adebf08f4b1f481cf57fa5
|
/lstm.py
|
e01b05b750639e83616c45bbe788fa166565ebc5
|
[
"MIT"
] |
permissive
|
zackchase/PyRNN
|
dfe405db1bc0d5c51efcb4fbe22b50c8618cb5c8
|
26687d3e0ebf082e91a5371e996108f697f6b6a7
|
refs/heads/master
| 2016-09-06T17:30:15.833369
| 2015-08-28T04:55:57
| 2015-08-28T04:55:57
| 41,527,570
| 4
| 6
| null | 2016-01-27T08:13:23
| 2015-08-28T04:45:22
|
Python
|
UTF-8
|
Python
| false
| false
| 4,304
|
py
|
import numpy as np
import theano
import theano.tensor as T
from lib import softmax, dropout, floatX, random_weights, zeros
class NNLayer:
def get_params(self):
return self.params
def save_model(self):
return
def load_model(self):
return
def updates(self):
return []
def reset_state(self):
return
class LSTMLayer(NNLayer):
def __init__(self, num_input, num_cells, input_layer=None, name=""):
"""
LSTM Layer
Takes as input sequence of inputs, returns sequence of outputs
"""
self.name = name
self.num_input = num_input
self.num_cells = num_cells
self.X = input_layer.output()
self.h0 = theano.shared(floatX(np.zeros(num_cells)))
self.s0 = theano.shared(floatX(np.zeros(num_cells)))
self.W_gx = random_weights((num_input, num_cells))
self.W_ix = random_weights((num_input, num_cells))
self.W_fx = random_weights((num_input, num_cells))
self.W_ox = random_weights((num_input, num_cells))
self.W_gh = random_weights((num_cells, num_cells))
self.W_ih = random_weights((num_cells, num_cells))
self.W_fh = random_weights((num_cells, num_cells))
self.W_oh = random_weights((num_cells, num_cells))
self.b_g = zeros(num_cells)
self.b_i = zeros(num_cells)
self.b_f = zeros(num_cells)
self.b_o = zeros(num_cells)
self.params = [self.W_gx, self.W_ix, self.W_ox, self.W_fx,
self.W_gh, self.W_ih, self.W_oh, self.W_fh,
self.b_g, self.b_i, self.b_f, self.b_o,
]
def one_step(self, x, h_tm1, s_tm1):
"""
"""
g = T.tanh(T.dot(x, self.W_gx) + T.dot(h_tm1, self.W_gh) + self.b_g)
i = T.nnet.sigmoid(T.dot(x, self.W_ix) + T.dot(h_tm1, self.W_ih) + self.b_i)
f = T.nnet.sigmoid(T.dot(x, self.W_fx) + T.dot(h_tm1, self.W_fh) + self.b_f)
o = T.nnet.sigmoid(T.dot(x, self.W_ox) + T.dot(h_tm1, self.W_oh) + self.b_o)
s = i*g + s_tm1 * f
h = T.tanh(s) * o
return h, s
def output(self):
([outputs, states], updates) = theano.scan(
fn=self.one_step,
sequences=self.X,
outputs_info = [self.h0, self.s0],
)
self.new_s = states[-1]
self.new_h = outputs[-1]
return outputs
def updates(self):
return [(self.s0, self.new_s), (self.h0, self.new_h)]
def reset_state(self):
self.h0 = theano.shared(floatX(np.zeros(self.num_cells)))
self.s0 = theano.shared(floatX(np.zeros(self.num_cells)))
class FullyConnectedLayer(NNLayer):
"""
"""
def __init__self(self, num_input, num_output, input_layer, name=""):
self.X = input_layer.output()
self.num_input = num_input
self.num_output = num_output
self.W = random_weights((num_input, num_output))
self.b = zeros(num_output)
self.params = [self.W, self.B]
def output(self):
return
class InputLayer(NNLayer):
"""
"""
def __init__(self, X, name=""):
self.name = name
self.X = X
self.params=[]
def output(self):
return self.X
class SoftmaxLayer(NNLayer):
"""
"""
def __init__(self, num_input, num_output, input_layer, temperature=1.0, name=""):
self.name = ""
self.X = input_layer.output()
self.params = []
self.temp = temperature
self.W_yh = random_weights((num_input, num_output))
self.b_y = zeros(num_output)
self.params = [self.W_yh, self.b_y]
def output(self):
return softmax((T.dot(self.X, self.W_yh) + self.b_y), temperature=self.temp)
class SigmoidLayer(NNLayer):
def __init__(self, input_layer, name=""):
self.X = input_layer.output()
self.params = []
def output(self):
return sigmoid(self.X)
class DropoutLayer(NNLayer):
def __init__(self, input_layer, name=""):
self.X = input_layer.output()
self.params = []
def output(self):
return dropout(self.X)
class MergeLayer(NNLayer):
def init(self, input_layers):
return
def output(self):
return
|
[
"zachary.chase@gmail.com"
] |
zachary.chase@gmail.com
|
072cf5ced5b0ebfafd0509d2839c7deb21763719
|
e23a4f57ce5474d468258e5e63b9e23fb6011188
|
/125_algorithms/_exercises/templates/_algorithms_challenges/codewar/_CodeWars-Python-master/solutions/Prime_number_decompositions.py
|
98bab5130b9b53c7602161b8d40e494e47c07bfc
|
[] |
no_license
|
syurskyi/Python_Topics
|
52851ecce000cb751a3b986408efe32f0b4c0835
|
be331826b490b73f0a176e6abed86ef68ff2dd2b
|
refs/heads/master
| 2023-06-08T19:29:16.214395
| 2023-05-29T17:09:11
| 2023-05-29T17:09:11
| 220,583,118
| 3
| 2
| null | 2023-02-16T03:08:10
| 2019-11-09T02:58:47
|
Python
|
UTF-8
|
Python
| false
| false
| 964
|
py
|
"""
Prime number decompositions
http://www.codewars.com/kata/prime-number-decompositions/train/python
"""
___ getAllPrimeFactors(n
__ n __ 1:
r.. [1]
result # list
__ isvalidparameter(n
factor 2
w.... n > 1:
w.... n % factor __ 0:
n /= factor
result.a..(factor)
factor += 1
r.. ?
___ getUniquePrimeFactorsWithCount(n
result [[], []]
__ isvalidparameter(n
factors getAllPrimeFactors(n)
___ f __ factors:
__ f __ result[0]:
result[1][-1] += 1
____
result[0].a..(f)
result[1].a..(1)
r.. ?
___ getUniquePrimeFactorsWithProducts(n
result # list
__ isvalidparameter(n
factors getUniquePrimeFactorsWithCount(n)
result m.. l.... x: x[0] ** x[1], z..(factors[0], factors[1]
r.. ?
___ isvalidparameter(n
r.. isi..(n, i..) a.. n > 0
|
[
"sergejyurskyj@yahoo.com"
] |
sergejyurskyj@yahoo.com
|
b0d41d101decf5447cd9b0cf4368c46c3a502ceb
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02598/s996042239.py
|
d46c51b86ccfeeefa731e41af21211b4da2ac6d3
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 484
|
py
|
import sys
def input():
return sys.stdin.readline().rstrip()
def main():
N,K=map(int,input().split())
A=list(map(int,input().split()))
ng =0
ok =10**9+1
while ok -ng >1:
mid = (ok+ng)//2
ans =0
for i in range(N):
ans += A[i]//mid -1
if A[i]%mid !=0:
ans +=1
if ans <=K:
ok =mid
else:
ng =mid
print(ok)
if __name__ == "__main__":
main()
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
841b1b1af1e9355862952d82dea3d905364c811f
|
1630390904e1915dbf340947d8eaf62a2da64a65
|
/ASP_experiments/scripts/generate_template_from_data.py
|
3c92b0a26bec69c0bcb63cd8c319ac2f5a0e0052
|
[] |
no_license
|
wsgan001/KR_Graph_Mining
|
9515555c4886e917e48f95adfc5922851d6da0ce
|
40a5d742cfc50f6a09538494315ffbff0376572b
|
refs/heads/master
| 2020-03-16T23:21:42.856193
| 2017-02-07T18:08:12
| 2017-02-07T18:08:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 996
|
py
|
import re
import random
def extract_graph_id(graph_str):
graph_id = re.search(r'graph\((?P<id>\w+)\)',graph_str).group('id')
return graph_id
def filter_edges_with_id(data, graph_id):
edges_labels = [atom for atom in data if ("edge("+graph_id+",") in atom or ("label("+graph_id+",") in atom]
return edges_labels
def remove_id(atom_str):
prefix, suffix = atom_str.split('(')
elements = suffix.split(",")[1:] # remove id
return prefix+"("+",".join(elements)
def transform_into_template(atoms):
return "\n".join(["t_" + remove_id(atom) for atom in atoms])
def read_dataset():
datasetname = "yoshida"
with open(datasetname,"r") as datafile:
data = datafile.read().splitlines()
graphs = [atom for atom in data if "graph(" in atom]
selected = extract_graph_id(random.choice(graphs))
template = transform_into_template(filter_edges_with_id(data,selected))
print(template)
def main():
read_dataset()
if __name__ == "__main__":
main()
|
[
"sergey.paramonov@phystech.edu"
] |
sergey.paramonov@phystech.edu
|
b962e7e24161f081c2de2326378185a5767191d9
|
dcd83aeb799143b58956612fb0bfc0258d30f229
|
/src/python/StageOut/Impl/HadoopImpl.py
|
b56e0d60ba28ca26ef9b5c680d42dd0ebf835ee0
|
[] |
no_license
|
giffels/PRODAGENT
|
67e3e841cfca7421caa505d03417b663a62d321b
|
c99608e3e349397fdd1b0b5c011bf4f33a1c3aad
|
refs/heads/master
| 2021-01-01T05:51:52.200716
| 2012-10-24T13:22:34
| 2012-10-24T13:22:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,420
|
py
|
#!/usr/bin/env python
"""
_HadoopImpl_
Implementation of StageOutImpl interface for Hadoop
"""
import os
from StageOut.Registry import registerStageOutImpl
from StageOut.StageOutImpl import StageOutImpl
from StageOut.Execute import runCommand
class HadoopImpl(StageOutImpl):
"""
_HadoopImpl_
Implement interface for Hadoop
"""
run = staticmethod(runCommand)
def createSourceName(self, _, pfn):
"""
_createSourceName_
uses pfn
"""
return "%s" % pfn
def createOutputDirectory(self, targetPFN):
"""
_createOutputDirectory_
This is a no-op, as Hadoop automatically creates directories.
"""
def createStageOutCommand(self, sourcePFN, targetPFN, options = None):
"""
_createStageOutCommand_
Build an Hadoop put
"""
original_size = os.stat(sourcePFN)[6]
print "Local File Size is: %s" % original_size
result = "hadoop fs -put "
if options != None:
result += " %s " % options
result += " %s " % sourcePFN
result += " %s " % targetPFN
return result
def removeFile(self, pfnToRemove):
"""
_removeFile_
CleanUp pfn provided
"""
command = "hadoop fs -rm %s" % pfnToRemove
self.executeCommand(command)
registerStageOutImpl("hadoop", HadoopImpl)
|
[
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.