index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
988,400
564f4fe353cbdb604e0efcdf8fc728e45f10f920
''' Created on Jan 3, 2012 @author: eocampo ''' __version__ = '20120224' # DB ERRORS DB_GRAL_ERR = -1 DB_CON_ERR = -101 DB_CON_HDL_ERR = -102 DB_CONSTR_ERR = -103 DB_OPER_ERR = -104 DB_NO_HANDLER = -105 # APP ERRORS INV_LOAD_FILENAME = -200 INV_CRED_TBL_KEY = -201 SNAME_NOT_FOUND = -203 INV_ID_DTYPE = -204 INV_TBL_KEY = -205 INV_SRV_KEY = -206 # I/O Errors FILE_NOT_EXIST = -300 NOT_FILE_OBJ = -301 # INFA ERRORS PMCMD_INV_APP_ARGS = -400 # Missing dict keys for fld,wkfl. PMCMD_INV_SIZE_ARGS = -401 # Empty elememnts keys for fld,wkfl.
988,401
00126e93625db32acb2e2954680642b20bc74d68
import copy import numpy as np import pyfits as pf def expand_fits_header(header, factor): header = header.copy() header['CDELT1']/=factor header['CDELT2']/=factor header['NAXIS1']*=factor header['NAXIS2']*=factor header['CRPIX1']=header['CRPIX1']*factor - factor/2.0 + 0.5 header['CRPIX2']=header['CRPIX2']*factor - factor/2.0 + 0.5 return header def expand_fits_data(data, factor): larger=list(data.shape) larger[0]*=factor larger[1]*=factor larger_data = np.zeros(larger,dtype=data.dtype) for i in range(factor): for j in range(factor): larger_data[i::factor,j::factor] = data def expand_fits(pf,factor,hdu=0): """ Create a new fits file where each pixel is divided into factor**2 more pixels all of equal value. I am not an expert on Fits files and I only think this code works. Also, I have no idea if it would work with 3D data (?). As a rule of thumb, if you use this function, you should probably open the before/after in ds9 and blink them for a while to convince yourself the function worked. """ pf = copy.deepcopy(pf) pf[hdu].header = expand_fits_header(pf[hdu].header) pf[hdu].data=expand_fits_data(pf[hdu].data)
988,402
4dbefc9b0c95d96ee453ecbf271cbbcd8db21c5e
def LCM(a,b): if a>b: z=a else: z=b while(True): if(z%a==0) and (z%b==0): LCM=z break z+=1 return LCM print(LCM(78,45)) print(LCM(4,8))
988,403
908265a0c6ea4e567780ba4b8070c826484c9de5
# WARNING: parser must be called very early on for argcomplete. # argcomplete evaluates the package until the parser is constructed before it # can generate completions. Because of this, the parser must be constructed # before the full package is imported to behave in a usable way. Note that # running # > python3 -m stnet # will actually import the entire package (along with dependencies like # pytorch, numpy, and pandas), before running __main__.py, which takes # about 0.5-1 seconds. # See Performance section of https://argcomplete.readthedocs.io/en/latest/ from .parser import parser parser() import pandas as _ from stnet.__version__ import __version__ from stnet.config import config from stnet.main import main import stnet.datasets as datasets import stnet.cmd as cmd import stnet.utils as utils import stnet.transforms as transforms
988,404
56a5968317d75ac2aaef6b006ee750027eca3e6f
# Generated by Django 3.0.5 on 2020-05-06 18:27 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Clients', '0008_auto_20200506_1803'), ] operations = [ migrations.AlterField( model_name='order', name='customer_id', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Clients.Customer', verbose_name='Company'), ), migrations.AlterField( model_name='product', name='product_price', field=models.DecimalField(decimal_places=2, max_digits=20, validators=[django.core.validators.MinValueValidator(10, message='Minimum value = 10')]), ), migrations.AlterField( model_name='product', name='product_stock', field=models.IntegerField(validators=[django.core.validators.MinValueValidator(1, message='Minimum value = 1')]), ), ]
988,405
6321c50afb7a7dccc04d0be719a9f7b4e121b841
def proc_array_val(array, val): try: return array[int(val)] except (IndexError, TypeError, ValueError): return array[0] def proc_enum_val(array, val): return {"value": val, "str": proc_array_val(array, val)} # set up enum arrays enum_state = [ "unknown", "Unknown", "Other", "NoMgmtSysConn", "NoDialTone", "InvalidNumber", "Ringing", "NoAnswer", "InProgress", "RemoteHold", "ShareLineActive", "InLocalConference", "TerminatedbyError", "LocalHold", "TerminatedNormally", "Answer", "Resume", "Busy", "Pause", "Playback", "Recording" ] enum_termination = [ "unknown", "unknown", "other", "internalError", "localDisconnected", "remoteDisconnected", "networkCongestion", "mediaNegotiationFailure", "securityConfigMismatched", "incompatibleRemoteEndPt", "serviceUnavailable", "remoteTerminatedWithError" ] enum_type = ["unknown", "TelePresence", "Audio Only", "unknown"] enum_mode = ["No Management System", "No Management System", "Managed"] enum_security = [ "unknown", "Non-Secure", "Authenticated", "Secure", "Unknown" ] enum_direction = ["unknown", "Incoming", "Outgoing", "unknown"] enum_remote_call_type = [ "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "PTP", "PTP", "MP", "N/A", "N/A" ] def proc_state_val(val): return proc_enum_val(enum_state, val) def proc_termination_val(val): return proc_enum_val(enum_termination, val) def proc_type_val(val): return proc_enum_val(enum_type, val) def proc_mode_val(val): return proc_enum_val(enum_mode, val) def proc_security_val(val): return proc_enum_val(enum_security, val) def proc_direction_val(val): return proc_enum_val(enum_direction, val) def proc_remote_call_type_val(val): return proc_enum_val(enum_remote_call_type, val) print proc_state_val(0) print proc_termination_val(0) print proc_type_val(0) print proc_mode_val(0) print proc_security_val(0) print proc_direction_val(0) print proc_remote_call_type_val(0)
988,406
9e0c104bc035436e69b11ee738abe92dab5bf709
from tqsdk import TqApi from DataLoader import download_data, read_data from datetime import datetime api = TqApi() quotes = api._data['quotes'] symbols = [] for symbol, item in quotes.items(): if item['ins_class'] == 'FUTURE': symbols.append(symbol) <<<<<<< HEAD print(len(symbols)) download_data(symbols[1500:2500], datetime(2016,1,1), datetime(2020,8,25), "tick") ======= <<<<<<< HEAD print(len(symbols)) download_data(symbols[10:1000], datetime(2016,1,1,0,0), datetime(2020,8,31,0,0), "tick") ======= download_data(symbols[1000:1500], datetime(2016,1,1), datetime(2020,8,25), "tick") >>>>>>> 3431b1e158b6ab39b51f776a5bc40985ad3e402b #download_data(symbols, datetime(2016,1,1), datetime(2020,8,25), "D") >>>>>>> origin/master
988,407
b4b7dfcdeee510b943792357712bab37fd2871ca
from words import w_list #words.py is a file containing a list of words. import random #Function to get a random word from the file "words.py". def get_word(): word = random.choice(w_list) return word.upper() #Function to display the design of the hangman for each stage or try. def display_hangman(life): stages = [ """ ------- | | | O | /|\\ | | | / \\ --- """, """ ------- | | | O | /| | | | / \\ --- """, """ ------- | | | O | | | | | / \\ --- """, """ ------- | | | O | | | | | \\ --- """, """ ------- | | | O | | | | | --- """, """ ------- | | | O | | | | --- """, """ ------- | | | O | | | --- """, """ ------- | | | | | | --- """, """ ------- | | | | | --- """, ] return stages[life] #Function with the actuall game. Records players guesses and state. def play(word): #Initiate all variables. Start of game. #Variable to keep word progress. word_completion = "*" * len(word) #Variable to keep game progress guessed = False #variable to store guessed letters. g_letters = [] #Variable to keep guessed words. g_words = [] #variables for number of tries life = 8 print("\t\t\tLets play hangman!!......\n\t\t\tGuess the district in Kerala") print(display_hangman(life)) print(word_completion) print("\n") while not guessed and life > 0: guess = input("\t\t\tGuess a word or a letter : ").upper() #Consider that the user entered a letter. if len(guess) == 1 and guess.isalpha(): if guess in g_letters: print("\t\t\tYou have already guessed ",guess) elif guess not in word: print("\t\t\t"+guess+" IS NOT in the word") life -= 1 g_letters.append(guess) else: print("\t\t\t"+guess+" IS present in the word") word_as_list = list(word_completion) indices = [i for i, letter in enumerate(word) if letter == guess] for index in indices: word_as_list[index] = guess word_completion = "".join(word_as_list) if "*" not in word_completion: guessed = True #Consider that the user entered a word. elif len(guess) == len(word) and guess.isalpha(): if guess in g_words: print("\t\t\t"+guess+" has already been guessed.") elif guess != word: print("\t\t\t"+guess+" IS NOT the word") life -= 1 g_words.append(guess) else: guessed = True word_completion = word else: print("\t\t\tInvalid Guess!\n") print(display_hangman(life)) print(word_completion) print("\n") if guessed: print("\t\t\tCongratulations! You won!") else: print("\t\t\tYou have run out of tries.\nThe word was "+word+"\nBetter luck next time.") if __name__ == "__main__": word = get_word() play(word) while input("\t\t\tDo you want to play again (Y/N) : ").upper() == "Y": word = get_word() play(word)
988,408
87806f9540664754600a69f9d6e91e3733d7b087
from urllib.parse import parse_qsl from config import cache_config from cache import Cache class CacheMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): cache = Cache(cache_config) cache_control = do_caching(environ.get('Cache-Control', '')) url = "{path}?{query}".format(path=environ.get('PATH_INFO'), query=get_sorted_query(environ.get('QUERY_STRING'))) if url in cache: response = [cache[url]] start_response("200 OK", [('Content-Type', 'text/plain')]) else: response = self.app(environ, start_response) if cache_control: cache[url] = "".join(piece.decode() for piece in response) return response def get_sorted_query(query_string): query_list = parse_qsl(query_string) query_list.sort(key=lambda value: value[0]) return '&'.join(('='.join(pair) for pair in query_list)) def do_caching(header_value): return False if header_value == 'no-cache' else True
988,409
a4a952fc85b89377e8fc83ea32d57cc312a4c6c5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import defaultdict class Node(): def __init__(self,n_node,nchilds, nmetadata): self.nchilds = nchilds self.nmetadata = nmetadata self.n_node = n_node def set_metadata(self,metadata): self.metadata = metadata def set_childs(self,childs): self.childs = childs def get_value(self): if self.nchilds != 0: self.value = 0 for i in self.metadata: if len(self.childs) >= i and i != 0: self.value = self.value + (self.childs[i-1]).get_value() return self.value else: return sum(self.metadata) with open('Day8/input', 'r') as fp: input = list(map(int,fp.read().strip().split(' '))) nodes = [] i=0 n_node = 0 temp_nodes = [] current_child = defaultdict(int) childs = defaultdict(list) while i < len(input): while(temp_nodes): if (current_child[temp_nodes[-1]] == nodes[temp_nodes[-1]].nchilds): metadata = [] for j in range(i, i + nodes[temp_nodes[-1]].nmetadata): metadata.append(input[j]) nodes[temp_nodes[-1]].set_metadata(metadata) i = i + nodes[temp_nodes[-1]].nmetadata nodes[temp_nodes[-1]].set_childs(childs[temp_nodes[-1]]) temp_nodes.pop() else: current_child[temp_nodes[-1]] = current_child[temp_nodes[-1]] + 1 break if (i<len(input)): nchilds = input[i] nmetadata = input[i+1] metadata = [] if (nchilds != 0): temp_nodes.append(n_node) nodes.append(Node(n_node,nchilds,nmetadata)) if (len(temp_nodes) >= 2 and current_child[temp_nodes[-2]] != 0): childs[temp_nodes[-2]].append(nodes[-1]) i = i + 2 else: for j in range(i+2, i + 2 + nmetadata): metadata.append(input[j]) nodes.append(Node(n_node,nchilds,nmetadata)) nodes[-1].set_metadata(metadata) if (current_child[temp_nodes[-1]] != 0): childs[temp_nodes[-1]].append(nodes[-1]) i = i + 2 + nmetadata n_node = n_node + 1 print(sum(sum(i.metadata)for i in nodes)) print(nodes[0].get_value())
988,410
8a2bcbc4928eab529dce9463fa1c63174759427c
"""TENANTS ROUTING routing for tenants zone - all routes use language code prefix (ex: /en/dashboard) """ from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.utils.translation import ugettext_lazy as _ from django.conf.urls.static import static urlpatterns = [ path('api/', include('modules.lists.api_urls', namespace='list_api')), path('api/', include('modules.address_book.api_urls', namespace='addressbook_api')), path('api/', include('modules.profile_page.api_urls', namespace='user_lists_api')), path('api/', include('modules.articles.api_urls', namespace='articles_api')), path('api/', include('modules.branches.api_urls', namespace='branches_api')), path('api/', include('modules.warehouse.api_urls', namespace='warehouses_api')), path('api/', include('modules.settings.api_urls', namespace='settings_api')), url(r'^select2/', include('django_select2.urls')), path('', include('modules.account.urls_inapp')), path('', include('modules.lists.urls_inapp')), path('', include('modules.address_book.urls_inapp', namespace='addressbook')), path('', include('modules.redirections.urls_tenants', namespace='redirections')), path('', include('modules.dashboard.urls', namespace='dashboard')), path('', include('modules.profile_page.urls_inapp', namespace='profile_page')), path('', include('modules.branches.urls_inapp', namespace='branches')), path('', include('modules.articles.urls_inapp', namespace='articles')), path('', include('modules.settings.urls_inapp', namespace='settings')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
988,411
6017647df7e24e81bd8c070c28cde4a78afad6da
import os import django_filters from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.utils.translation import ugettext_lazy as _ from django.views.generic import ListView from django_filters.views import FilterView from django_tables2 import SingleTableMixin, SingleTableView from .forms_lab import LabCheckInForm, LabGenerateBarcodeForm, LabProbeEditForm, LabQueryForm, LabRackResultsForm from .models import Event, Registration, RSAKey, Sample from .serializers import SampleSerializer from .statuses import SampleStatus from .tables import SampleTable from django.views.decorators.csrf import csrf_exempt import json from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated @login_required def index(request): return render(request, "lab/index.html") @login_required def version(request): # Checking where the .git directory is if os.path.isdir("../.git"): git_dir = "../.git" elif os.path.isdir(".git"): git_dir = ".git" else: return HttpResponse("No .git directory found") with open(git_dir + "/HEAD", "r") as head: ref = head.readline().split(" ")[-1].strip() branch_name = ref.split("/")[-1] if "/" in ref: with open(git_dir + "/" + ref, "r") as git_hash: commit_hash = git_hash.readline().strip() else: commit_hash = ref version_str = """ <code> Branch: <a href='https://github.com/anders-biostat/covid-test-web-site/tree/%s'>%s</a><br> Commit: <a href='https://github.com/anders-biostat/covid-test-web-site/commit/%s'>%s</a><br> Short: %s <br> </code> """ return HttpResponse(version_str % (branch_name, branch_name, commit_hash, commit_hash, commit_hash[:7])) @login_required def sample_check_in(request): if request.method == "POST": form = LabCheckInForm(request.POST) if form.is_valid(): barcodes = [x.strip().upper() for x in form.data["barcodes"].split()] rack = form.cleaned_data["rack"].strip().upper() status = form.data["status"] comment = form.data["comment"] barcodes_not_in_db = [] status_not_set = [] rack_not_set = [] successful_barcodes = [] for barcode in barcodes: sample = Sample.objects.filter(barcode=barcode).first() if not sample: barcodes_not_in_db.append(barcode) else: sample.rack = rack sample.save() set_status = sample.set_status(status, comment=comment) if not set_status: status_not_set.append(barcode) else: successful_barcodes.append(barcode) if len(barcodes_not_in_db) > 0: messages.add_message(request, messages.ERROR, _("Einige Barcodes waren nicht in der Datenbank")) if len(status_not_set) > 0: messages.add_message(request, messages.ERROR, _("Einige Status konnten nicht gesetzt werden")) if len(rack_not_set) > 0: messages.add_message(request, messages.ERROR, _("Einige Racks konnten nicht gesetzt werden")) no_success = True if len(rack_not_set) == 0 and len(status_not_set) == 0 and len(barcodes_not_in_db) == 0: no_success = False messages.add_message(request, messages.SUCCESS, _("Proben erfolgreich eingetragen")) return render( request, "lab/sample_check_in.html", { "form": form, "sample": sample, "barcodes_not_in_db": barcodes_not_in_db, "rack_not_set": rack_not_set, "status_not_set": status_not_set, "no_success": no_success, "successful_barcodes": successful_barcodes }, ) else: form = LabCheckInForm() return render(request, "lab/sample_check_in.html", {"form": form, "display_sample": False}) @login_required def sample_edit_rack(request): form = LabRackResultsForm() if request.method == "POST": form = LabRackResultsForm(request.POST) if form.is_valid(): rack = form.cleaned_data["rack"].upper().strip() lamp_positive = form.data["lamp_positive"].split() lamp_inconclusive = form.data["lamp_inconclusive"].split() lamp_failed = form.data["lamp_failed"].split() lamp_positive = [x.replace("\n", "").replace("\r", "").strip() for x in lamp_positive] lamp_inconclusive = [x.replace("\n", "").replace("\r", "").strip() for x in lamp_inconclusive] lamp_failed = [x.replace("\n", "").replace("\r", "").strip() for x in lamp_inconclusive] rack_samples = Sample.objects.filter(rack=rack) if len(rack_samples) > 0: for sample in rack_samples: status = SampleStatus.LAMPNEG if sample.barcode in lamp_positive: status = SampleStatus.LAMPPOS if sample.barcode in lamp_inconclusive: status = SampleStatus.LAMPINC if sample.barcode in lamp_failed: status = SampleStatus.LAMPFAIL set_status = sample.set_status(status, author=request.user.get_username()) barcodes_status_set = [] if not set_status: messages.add_message( request, messages.ERROR, _("Status konnte nicht gesetzt werden: ") + str(sample.barcode) ) else: barcodes_status_set.append(sample.barcode) messages.add_message( request, messages.SUCCESS, _("Ergebnisse hinzugefügt: ") + ", ".join(barcodes_status_set) ) else: messages.add_message(request, messages.ERROR, _("Keine Proben zu Rack gefunden")) return render(request, "lab/sample_rack_results.html", {"form": form}) @login_required def sample_detail(request): form = LabQueryForm() edit_form = LabProbeEditForm() if request.method == "POST": if "search" in request.POST.keys(): form = LabQueryForm(request.POST) if form.is_valid(): search = form.cleaned_data["search"].upper().strip() sample = Sample.objects.filter(barcode=search).first() if not sample: sample = Sample.objects.filter(access_code=search).first() if sample: edit_form = LabProbeEditForm(initial={"rack": sample.rack, "comment": "Status changed in lab interface"}) return render( request, "lab/sample_query.html", {"form": form, "edit_form": edit_form, "sample": sample, "search": search}, ) if "edit" in request.POST.keys(): edit_form = LabProbeEditForm(request.POST) if edit_form.is_valid(): barcode = edit_form.cleaned_data["barcode"].upper().strip() status = edit_form.cleaned_data["status"].upper().strip() rack = edit_form.cleaned_data["rack"].upper().strip() comment = edit_form.cleaned_data["comment"].strip() sample = Sample.objects.filter(barcode=barcode).first() if sample is None: messages.add_message(request, messages.ERROR, _("Sample nicht gefunde")) else: rack_changed = sample.rack != rack if rack_changed: event = Event( sample=sample, status=SampleStatus.INFO, comment="Rack changed in lab interface from "+str(sample.rack)+" to "+str(rack)+"." ) sample.rack = rack sample.save() event.save() messages.add_message(request, messages.SUCCESS, _("Sample rack geupdated")) if status != "-": status = SampleStatus[status] event = Event( sample=sample, status=status.value, comment=comment ) event.save() messages.add_message(request, messages.SUCCESS, _("Status geupdated")) return render( request, "lab/sample_query.html", {"form": form, "edit_form": edit_form, "sample": sample} ) return render(request, "lab/sample_query.html", {"form": form, "edit_form": edit_form}) @api_view(['POST']) @permission_classes([IsAuthenticated]) def update_status(request): if request.method == "POST": body = json.loads(request.body) bc = body['barcode'].strip().upper() bc_ok = [] bc_missing = [] bc_duplicated = [] qset = Sample.objects.filter(barcode=bc) if len(qset) == 0: bc_missing.append(bc) return HttpResponseBadRequest("Barcode %s not found on the server." % bc) if len(qset) > 1: bc_duplicated.append(bc) return HttpResponseBadRequest("Multiple samples with barcode %s found." % bc) if 'status' not in body: return HttpResponseBadRequest("No sample status provided") if 'comment' not in body: comment = "" else: comment = body['comment'] sample = qset.first() if 'rack' in body: sample.rack = body['rack'] sample.save() comment += ". Rack: " + str(body['rack']) sample.events.create(status=body['status'], comment=comment) bc_ok.append(bc) return HttpResponse("Event created successfully", status=201) class SampleFilter(django_filters.FilterSet): class Meta: model = Sample fields = ["barcode", "access_code"] class SampleListView(SingleTableMixin, FilterView): model = Sample table_class = SampleTable template_name = "lab/sample_list.html" filterset_class = SampleFilter @login_required def dashboard(request): count_wait = Event.objects.filter(status="PRINTED").count() dashboard_values = {"count_Samples": Sample.objects.filter().count(), "count_wait": count_wait} return render(request, "lab/dashboard.html", {"dashboard_values": dashboard_values}) @api_view(['POST']) @permission_classes([IsAuthenticated]) def sample_details_snippet(request): sample = Sample.objects.filter(access_code = request.POST.get("access_code")).first() if sample is not None: return render(request, "lab/sample_snippet_for_virusfinder.html", {"sample": sample}) else: return HttpResponse("<i>Access code %s not found</i>" % request.POST.get("access_code"))
988,412
f1ae41d68629efc3239ed3f0156f260f39071118
def counter(path): with open(path) as file: d = file.read() d.replace("," , " ") return len(data.split(" ")) print(counter(path)("b.txt"))
988,413
01e26944b69e95c32bf2fac5aea92b285f333377
# 1.通过索引可以访问序列中的任何元素 # verse = ["圣安东尼奥马刺","洛杉矶湖人","休斯顿火箭","金州勇士"] # print(verse[2]) #输出第3个元素 # print(verse[-1]) #输出最后一个元素 # # # 2.通过切片获取列表n中的第2个到第5个元素,以及第一个、第三个和第五个元素 # n = ['0','1','2','3','4','5','6','7','8'] # print(n[1:5]) #获取第二个到第五个元素 # print(n[0:5:2]) #获取第一个、第三个、第五个元素 # # # 3.使用n关键字检查某个元素是否是序列的成员 # nba = ["圣安东尼奥马刺","洛杉矶湖人","休斯顿火箭","金州勇士"] # print("洛杉矶湖人" in nba) # # # 4 # num = [7,14,21,28,35,42,49,56,63] # # 使用len()函数计算序列num的长度 # print("序列num的长度为",len(num)) # # 使用max()函数计算序列num的最大值 # print("序列",num,"中的最大值为",max(num)) # # 使用min()函数计算序列num的最小值 # print("序列",num,"中的最小值为",min(num)) # # # 5.修改列表中的元素只需要通过索引获取该元素,然后再为其重新赋值 # nmn = ["圣安东尼奥马刺","洛杉矶湖人","休斯顿火箭","金州勇士"] # nmn[1] = "森林狼" #修改列表的第二个元素 # print(nmn) # # # 6.使用del语句删除列表中的指定元素 # dmn = ["圣安东尼奥马刺","洛杉矶湖人","休斯顿火箭","金州勇士"] # del dmn[-1] #删除列表最后一个元素 # print(dmn) # # # 7.使用remove()方法删除元素前,最好先判断该元素是否存在 # fmn = ["圣安东尼奥马刺","洛杉矶湖人","休斯顿火箭","金州勇士"] # value = "金州勇士" #指定要移除的元素 # print(fmn.count(value)) # if fmn.count(value)>0: #判断要删除的元素是否存在 # fmn.remove(value) #移除指定元素 # print(fmn) # 8.sort()方法字符串列表的排序,需要先对大写字母进行排序,然后再对小写字母进行排序。 #如果想要对字符串列表进行排序(不区分大小写),需要指定key参数 # char = ['cat','Tom','Angela','pet'] # char.sort() #默认区分字母大小写 # print(char) # char.sort(key=str.lower) #不区分字母大小写 # print(char) # 9.应用列表推到式生成一个将全部商品价格打5折的列表 # price = [1200,5330,2988,6200,1998,8888] # sale = [int(x*0.5) for x in price] # print(sale) # sale2 = [x for x in price if x>5000] # print(sale2) # 11.使用元组推导式生成一个包含10个随机数的生成器对象,然后将其转换为元组 # import random # randomnumber = (random.randint(10,100) for i in range(10)) # print(randomnumber) # randomnumber = tuple(randomnumber) #转换为元组 # print(randomnumber) # 12.__next__()方法用于遍历生成器对象,通过生成器推导式生成一个包含3个元素的生成器对象number, #然后调用3次__next__()方法输出每个元素 number = (i for i in range(3)) print(number.__next__()) #输出第一个元素 print(number.__next__()) #输出第二个元素 print(number.__next__()) #输出第三个元素 # 13. number = (i for i in range(4)) #生成生成器对象 for i in number: #遍历生成器对象 print(i,end='') #输出每个元素的值
988,414
fb63fcf0236bc9dc15c06817fb40212afa6c3e8e
#-*- coding:utf-8 -*- import sys import os import datetime from time import sleep import shutil ### path pcap_path = "./" accesslog_path = "/server/logs/access.log" ### By G file_list = os.listdir(pcap_path) file_list_py = [file for file in file_list if file.endswith(".pcapng")] def tmp_dir(): try: if not(os.path.isdir('tmp')): os.makedirs(os.path.join('tmp')) except OSError as e: if e.errno != errno.EEXIST: print("Failed to create directory!!!!!") raise while 1: lambda: os.system('cls') print("################################### pcap - http.request") if file_list_py is not None: tmp_dir() for line in file_list_py: os.system('tshark -r %s -Y http.request -o data.show_as_text:TRUE -T fields -e frame.time -e ip.src -e tcp.srcport -e ip.dst -e tcp.dstport -e http.request.method -e http.request.full_uri -e http.user_agent -e text >> request.txt ' %line ) shutil.move(line, 'tmp/'+line) with open('request.txt', 'r') as f: for line in f.readlines()[0:10:-1]: print(line.strip()) f.close() else: with open('request.txt', 'r') as f: for line in f.readlines()[0:10:-1]: print(line.strip()) f.close() print("################################### accesslog") with open(accesslog_path, 'r') as f: for line in f.readlines()[0:10:-1]: print(line.strip()) f.close() time = datetime.datetime.now() print("############################# end time = " + str(time)) sleep(60)
988,415
5869b51439371136198bd4c9644afc69fb69c254
from django.contrib import admin from .models import Specialty, Company, Application class SpecialtyAdmin(admin.ModelAdmin): pass class CompanyAdmin(admin.ModelAdmin): pass class ApplicationAdmin(admin.ModelAdmin): pass admin.site.register(Specialty, SpecialtyAdmin) admin.site.register(Company, CompanyAdmin) admin.site.register(Application, ApplicationAdmin)
988,416
b38e81ce0e2d505f1b341c268ca46807a2646190
def garage(initial, final): initial = initial[::] seq = [] steps = 0 while (initial != final): for i in range(len(initial)): zero = initial.index(0) # print (zero, end=":") if initial[i] != final[i]: initial[i], initial[zero] = initial[zero], initial[i] # print (initial) seq.append(initial[::]) steps += 1 print (seq) print ("-"*15) return steps, seq import time if __name__ == '__main__': initial = [1,2,3,0,4] final = [0,3,2,1,4] bt = time.time() garage(initial, final) et = time.time() print ("running time:", str(et-bt))
988,417
83cf921913bbf70fa582c27bd14fe277500f2101
This is a test for fixing bug. And then we fix it!
988,418
830aefca6c48fbfdcf1acd625c68c7d10d72aa7e
from random import choice from django.contrib.auth.models import User from django.shortcuts import redirect, render from django.urls import reverse from core.models import Game CHOICE = ['Rock', 'Paper', 'Scissors'] def rps_list(request): games = Game.objects.all() user = request.user data = { 'user': user, 'games': games } return render(request, 'rps_list.html', data) def play_user(request, pk): if request.method == 'POST': defender = request.POST.get('defender', None) atk_choice = request.POST.get('atk_choice', None) Game.objects.create( atk_user = User.objects.get(pk=pk), dfn_user = User.objects.get(pk=defender), atk_choice = atk_choice, dfs_choice = '', result = '진행중' ) return redirect(reverse('rps_list')) elif request.method == 'GET': users = User.objects.all().exclude(username=request.user) user = User.objects.get(pk=pk) data = { 'user': user, 'users': users, } return render(request, 'rps_play.html', data) def rps_compete(request, pk): if request.method == 'POST': dfn_choice = request.POST.get('dfn_choice', None) game = Game.objects.get(pk=pk) if game.atk_choice == 'Rock': if dfn_choice == 'Paper': result = str(game.dfn_user) + " Win" elif dfn_choice == 'Scissors': result = str(game.atk_user) + " Win" elif dfn_choice == 'Rock': result = "Tie" elif game.atk_choice == 'Scissors': if dfn_choice == 'Rock': result = str(game.dfn_user) + " Win" elif dfn_choice == 'Paper': result = str(game.atk_user) + " Win" elif dfn_choice == 'Scissors': result = "Tie" elif game.atk_choice == 'Paper': if dfn_choice == 'Scissors': result = str(game.dfn_user) + " Win" elif dfn_choice == 'Rock': result = str(game.atk_user) + " Win" elif dfn_choice == 'Paper': result = "Tie" Game.objects.filter(pk=pk).update(dfs_choice=dfn_choice, result=result) return redirect(reverse('rps_list')) elif request.method == 'GET': users = User.objects.all().exclude(username=request.user) data = { 'users': users, } return render(request, 'rps_compete.html', data) def rps_detail(request, pk): game = Game.objects.get(pk=pk) data={ 'game': game } return render(request, 'rps_detail.html', data) def play_cpu(request, pk): if request.method == 'POST': atk_choice = request.POST.get('atk_choice', None) atk_user = User.objects.get(pk=pk) dfn_choice = choice(CHOICE) if atk_choice == 'Rock': if dfn_choice == 'Paper': result = str(atk_user) + " Lose" elif dfn_choice == 'Scissors': result = str(atk_user) + " Win" elif dfn_choice == 'Rock': result = "Tie" elif atk_choice == 'Scissors': if dfn_choice == 'Rock': result = str(atk_user) + " Lose" elif dfn_choice == 'Paper': result = str(atk_user) + " Win" elif dfn_choice == 'Scissors': result = "Tie" elif atk_choice == 'Paper': if dfn_choice == 'Scissors': result = str(atk_user) + " Lose" elif dfn_choice == 'Rock': result = str(atk_user) + " Win" elif dfn_choice == 'Paper': result = "Tie" Game.objects.create( atk_user = User.objects.get(pk=pk), atk_choice = atk_choice, dfs_choice = dfn_choice, result = result, ) return redirect(reverse('rps_list')) elif request.method == 'GET': user = User.objects.get(pk=pk) data = { 'user': user, } return render(request, 'play_cpu.html', data)
988,419
6653a9143042ba735ec433f20745e05460b15d5c
from plugins.telegram import handlers __all__ = [ 'bot', 'dispatcher', ]
988,420
f72618c0c8a4ead9dd66b216dad9c2078404456e
def remove_vogais(palavra): lista_vogais=['a','e','i','o','u'] sem_vogal='' for i in range(len(palavra)): if palavra[i] not in lista_vogais: sem_vogal.append(palavra[i]) return sem_vogal
988,421
5131b0c1cb3584a9d1d4ee1399fa1e7b6885acfb
""" Author: Ishan Thilina Somasiri E-mail: ishan@ishans.info Web: www.blog.ishans.info Git: https://github.com/ishanthilina/Gnome-Online-Documents-Manager """ class CustomException(Exception): """ Class to create custom exceptions """ def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter)
988,422
286bf00c1f9c5ea48bb632573dfd5f0e75672461
# Import module from flask import Flask, render_template # app devient notre server app = Flask(__name__) # Création d'une route "/" @app.route("/") def helloWorld(): # La fonction de notre route return "Hello, World!" # Notre route "/hello" @app.route("/hello") def hello(): return render_template("index.html") # renvoie de notre page html if __name__ == '__main__': app.run(debug = True)
988,423
545afc3b48d348409a4e9ffac57fd9e58f52728a
from tensorflow import keras from tensorflow.keras import layers def BuildVgg19(): vgg = keras.applications.VGG19(weights='imagenet') outputs = [vgg.layers[i].output for i in range(3, 10)] model = keras.Model([vgg.input], outputs) return model def ResidualBlock(x): filters = 64 kernel_size = 3 momentum = 0.8 padding = 'same' strides = 1 res = layers.Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding)(x) res = layers.Activation('relu')(res) res = layers.BatchNormalization(momentum=0.8)(res) res = layers.Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=padding)(x) res = layers.BatchNormalization(momentum=0.8)(res) res = layers.Add()([res, x]) return res def BuildGenerator(): ResBlocks = 16 momentum = 0.8 input_shape = (224, 224, 3) input_layer = keras.Input(shape=input_shape) gen1 = layers.Conv2D(filters=16, kernel_size=3, strides=1, padding='same', activation='relu')(input_layer) gen2 = layers.Conv2D(filters=32, kernel_size=3, strides=2, padding='same', activation='relu')(gen1) gen3 = layers.Conv2D(filters=64, kernel_size=3, strides=2, padding='same', activation='relu')(gen2) res = ResidualBlock(gen3) for i in range(ResBlocks-1): res = ResidualBlock(res) gen4 = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='same')(res) gen4 = layers.BatchNormalization(momentum=momentum)(gen4) gen5 = layers.Add()([gen4, gen3]) gen6 = layers.UpSampling2D(size=2)(gen5) gen6 = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same')(gen6) gen6 = layers.Activation('relu')(gen6) gen7 = layers.UpSampling2D(size=2)(gen6) gen7 = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same')(gen7) gen7 = layers.Activation('relu')(gen7) gen8 = layers.Conv2D(filters=3, kernel_size=9, strides=1, padding='same')(gen7) output = layers.Activation('tanh')(gen8) model = keras.Model(inputs=[input_layer], outputs=[output], name='generator') return model def BuildDiscriminator(): leakyrelu_alpha = 0.2 momentum = 0.8 input_shape = (224, 224, 3) input_layer = keras.Input(shape=input_shape) dis1 = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='same')(input_layer) dis1 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis1) dis2 = layers.Conv2D(filters=64, kernel_size=3, strides=2, padding='same')(dis1) dis2 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis2) dis2 = layers.BatchNormalization(momentum=momentum)(dis2) dis3 = layers.Conv2D(filters=128, kernel_size=3, strides=1, padding='same')(dis2) dis3 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis3) dis3 = layers.BatchNormalization(momentum=momentum)(dis3) dis4 = layers.Conv2D(filters=128, kernel_size=3, strides=2, padding='same')(dis3) dis4 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis4) dis4 = layers.BatchNormalization(momentum=momentum)(dis4) dis5 = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same')(dis4) dis5 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis5) dis5 = layers.BatchNormalization(momentum=momentum)(dis5) dis6 = layers.Conv2D(filters=256, kernel_size=3, strides=2, padding='same')(dis5) dis6 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis6) dis6 = layers.BatchNormalization(momentum=momentum)(dis6) dis7 = layers.Conv2D(filters=512, kernel_size=3, strides=1, padding='same')(dis6) dis7 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis7) dis7 = layers.BatchNormalization(momentum=momentum)(dis7) dis8 = layers.Conv2D(filters=512, kernel_size=3, strides=2, padding='same')(dis7) dis8 = layers.LeakyReLU(alpha=leakyrelu_alpha)(dis8) dis8 = layers.BatchNormalization(momentum=momentum)(dis8) dis9 = layers.Dense(units=1024)(dis8) dis9 = layers.LeakyReLU(alpha=0.2)(dis9) output = layers.Dense(units=1, activation='sigmoid')(dis9) model = keras.Model(inputs=[input_layer], outputs=[output], name='discriminator') return model
988,424
cf42c316ca5fdad9da7e4134598cddc2d566195c
''' 皮一下 ''' if __name__ == '__main__': print('finish this book!')
988,425
eb2810fe559840ae7f43769be436516c034875cd
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """geometry""" import numpy as np import numba @numba.jit(nopython=False) def surface_equ_3d_jit(polygon_surfaces): """surface equ 3d jit""" # return [a, b, c], d in ax+by+cz+d=0 # polygon_surfaces: [num_polygon, num_surfaces, num_points_of_polygon, 3] surface_vec = polygon_surfaces[:, :, :2, :] - polygon_surfaces[:, :, 1:3, :] # normal_vec: [..., 3] normal_vec = np.cross(surface_vec[:, :, 0, :], surface_vec[:, :, 1, :]) d = np.einsum('aij, aij->ai', normal_vec, polygon_surfaces[:, :, 0, :]) return normal_vec, -d @numba.jit(nopython=False) def points_in_convex_polygon_3d_jit(points, polygon_surfaces, num_surfaces=None): """check points is in 3d convex polygons. Args: points: [num_points, 3] array. polygon_surfaces: [num_polygon, max_num_surfaces, max_num_points_of_surface, 3] array. all surfaces' normal vector must direct to internal. max_num_points_of_surface must at least 3. num_surfaces: [num_polygon] array. indicate how many surfaces a polygon contain Returns: [num_points, num_polygon] bool array. """ max_num_surfaces, _ = polygon_surfaces.shape[1:3] num_points = points.shape[0] num_polygons = polygon_surfaces.shape[0] if num_surfaces is None: num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64) normal_vec, d = surface_equ_3d_jit(polygon_surfaces[:, :, :3, :]) # normal_vec: [num_polygon, max_num_surfaces, 3] # d: [num_polygon, max_num_surfaces] ret = np.ones((num_points, num_polygons), dtype=np.bool_) for i in range(num_points): for j in range(num_polygons): for k in range(max_num_surfaces): if k > num_surfaces[j]: break sign = (points[i, 0] * normal_vec[j, k, 0] + points[i, 1] * normal_vec[j, k, 1] + points[i, 2] * normal_vec[j, k, 2] + d[j, k]) if sign >= 0: ret[i, j] = False break return ret @numba.jit def points_in_convex_polygon_jit(points, polygon, clockwise=True): """check points is in 2d convex polygons. True when point in polygon Args: points: [num_points, 2] array. polygon: [num_polygon, num_points_of_polygon, 2] array. clockwise: bool. indicate polygon is clockwise. Returns: [num_points, num_polygon] bool array. """ # first convert polygon to directed lines num_points_of_polygon = polygon.shape[1] num_points = points.shape[0] num_polygons = polygon.shape[0] vec1 = polygon[:, [num_points_of_polygon - 1] + list(range(num_points_of_polygon - 1)), :] if clockwise: vec1 = polygon - vec1 else: vec1 = vec1 - polygon # vec1: [num_polygon, num_points_of_polygon, 2] ret = np.zeros((num_points, num_polygons), dtype=np.bool_) for i in range(num_points): for j in range(num_polygons): success = True for k in range(num_points_of_polygon): cross = vec1[j, k, 1] * (polygon[j, k, 0] - points[i, 0]) cross -= vec1[j, k, 0] * (polygon[j, k, 1] - points[i, 1]) if cross >= 0: success = False break ret[i, j] = success return ret
988,426
bd2a29d87830fec99d756f57a92efba69aa6ca11
# -*- coding: utf-8 -*- from django.test import TestCase from dedal import ACTIONS, ACTION_CREATE from dedal.site import site, Dedal from dedal.decorators import crud from dedal.exceptions import ModelIsNotInRegisterError from example.blog.models import Post class FooModel(object): class _meta: # noqa model_name = 'foo' class TestDedalSiteRegistry(TestCase): def setUp(self): self.Model = crud(FooModel) def test_model_should_register_when_decorated(self): self.assertTrue(site.is_registered(self.Model)) def test_model_should_unregister_when_registered(self): self.assertTrue(site.unregister(self.Model)) self.assertFalse(site.is_registered(self.Model)) def test_unregister_should_raise_error_when_not_in_register(self): site.unregister(self.Model) with self.assertRaises(ModelIsNotInRegisterError): site.unregister(self.Model) class DedalObject(TestCase): def test_actions(self): actions = [ACTION_CREATE] instance = Dedal(site, Post, actions) for action in actions: self.assertTrue(hasattr(instance, action), action) for action in set(ACTIONS) - set(actions): self.assertFalse(hasattr(instance, action), action)
988,427
d0880230db2256ee23a781df3fcf4406955fbfc2
# Generated by Django 3.1.2 on 2020-10-17 13:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='categoryattribute', name='attributes', ), migrations.AlterField( model_name='subcategory', name='attributes', field=models.ManyToManyField(blank=True, default='', to='test.Attribute'), ), ]
988,428
87027ec3e0b7cab90d6d8f2f1658315dfc24d880
#!/usr/bin/python import os import sys import urlparse import subprocess import argparse import giturlparse from mygogs import * import gogs_client import errno from inspect import getmembers from pprint import pprint from common import * from mygogs import * from fnmatch import fnmatch def main(): parser = argparse.ArgumentParser(description = "List gogs projects") parser.add_argument("-u", "--url", help = "Gogs url", default=getEnv('GOGS_URL', None), required='GOGS_URL' not in os.environ ) parser.add_argument("-t", "--token", help = "Gog token", default=getEnv('GOGS_TOKEN', None), required='GOGS_TOKEN' not in os.environ ) parser.add_argument("-o", "--organization", help = "Organisation filter", required = False) parser.add_argument("-n", "--name", help = "Organisation filter", required = False) parser.add_argument("-f", "--format", help = "Print format. Default is '{o} {p} {s}' ( %o organisation name, %p project name, %h http url, %s ssh Url)", default="{o} {p} {s}", required = False) options = parser.parse_args() gogs = MyGogsApi(options.url) token = gogs_client.Token(options.token) repos=gogs.repos( token, options.organization ) for repo in repos : if options.name is not None : if not fnmatch( repo.name, options.name ) : continue params = {'p': repo.name, 'o': repo.json['owner']['username'], 's': repo.urls.ssh_url, 'h': repo.urls.html_url} print options.format.format(**params) if __name__ == "__main__": main()
988,429
a3088f95abfc3aa387e3914226b4febcc4af1f15
l = input().split(' ') for i in range(0, len(l), 2): print(l[i])
988,430
f1547499fc27492e5d1b8bd218a21fe7405a1335
from django.apps import AppConfig class LevelgamingConfig(AppConfig): name = 'levelgaming'
988,431
91362c68f0822f0f8647e900144da8b7c1bd2fd0
#### #Vacation Cost Calculator #### #Calculates total cost of vacation #Completed by Anthony Lee #from Unit4: "Functions" on Codecademy #Hotel cost function def hotel_cost(nights): return 140*nights #Plane ride cost function def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 #Rental car cost function def rental_car_cost(days): if days >= 7: #discount of 50$ if over 7 days return 40*days - 50 elif days >= 3: #discount of 20$ if over 3 days return 40*days - 20 else: #if no discount return 40*days #Total cost of trip def trip_cost(city, days, spending_money): return rental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money print trip_cost("Los Angeles", 5, 600)
988,432
95bf2e01a9a148f0176e7051f4ef11282dc32bd3
#! python3 # excelToCsv.py # Author: Kene Udeh # Source: Automate the Boring stuff with python Ch. 14 Project import os import csv import openpyxl def excelToCsv(folder): """converts sheets in every excel file in a folder to csv Args: folder (str): folder containing excel files Returns: None """ for excelFile in os.listdir(folder): # Skip non-xlsx files, load the workbook object. if not excelFile.endswith('xlsx'): continue wb = openpyxl.load_workbook(excelFile) for sheetName in wb.get_sheet_names(): # Loop through every sheet in the workbook. sheet = wb.get_sheet_by_name(sheetName) # Create the CSV filename from the Excel filename and sheet title. csvFilename = excelFile.split('.')[0]+'_'+sheet.title+'.csv' csvFileObj = open(csvFilename, 'w', newline='') # Create the csv.writer object for this CSV file. csvWriter = csv.writer(csvFileObj) # Loop through every row in the sheet. for rowObj in sheet.rows: rowData = [] # append each cell to this list # Loop through each cell in the row. for cellObj in rowObj: # Append each cell's data to rowData. rowData.append(cellObj.value) # Write the rowData list to the CSV file. csvWriter.writerow(rowData) csvFileObj.close() if __name__ == "__main__": excelToCsv('.')
988,433
0c0d95078a25bffb60ce54183cb4e80dac540cfe
''' Tugas Kecil 3 IF2211 Strategi Algoritma : Shortest Path with A* Algorithm Cr : Mohammad Sheva Almeyda Sofjan (13519018/K01) | Alif Bhadrika Parikesit (13519186/K04) ''' import graph import math import sys def start(): print("#### A* Shortest Path Finder ####") filename = input("ENTER MAP NAME (map.txt): ") G = graph.parseFile(filename) G.visualize() nodes = [node for node in G.vertices] print("\nPLACES AT",filename.split('.')[0].upper()) for i in range (len(nodes)): print("[",i+1,"]", nodes[i].name) src = int(input("SOURCE: ")) dest = int(input("DESTINATION: ")) try: out = G.computeAStar(nodes[src-1].name,nodes[dest-1].name) except: print("Node not Found. Exiting program . . .") sys.exit() if len(out) == 0: print("THERE'S NO WAY YOU CAN GO FROM ", nodes[src-1].name," TO ",nodes[dest-1].name) print() else: print("\nTHE SHORTEST PATH FROM ", nodes[src-1].name," TO ",nodes[dest-1].name) for i in range (len(out[1])): if i == (len(out[1]) - 1): print(out[1][i]) else: print(out[1][i], end=" --> ") print("\nWITH DISTANCE {:.3f} KMs\n".format(out[0]/1000)) G.visualize(out[1]) if __name__ == '__main__': start()
988,434
8e05a16fb92419a5a8fbbdff37f8a5c8f776cfe9
''' Created on Mar 7, 2011 @author: mkiyer ''' def insert_sam(self, filename, genome=False, fragment_length=-1, rmdup=False, multimap=False): bamfh = pysam.Samfile(filename, "rb") # count reads and get other info from BAM file logging.debug("%s: Computing track statistics" % (filename)) hits = 0 reads = 0.0 duplicate_reads = 0.0 unmapped_reads = 0.0 mate_unmapped_reads = 0.0 qcfail_reads = 0.0 read_lengths = collections.defaultdict(lambda: 0.0) multihit_counts = collections.defaultdict(lambda: 0.0) cycle_mismatch_counts = collections.defaultdict(lambda: 0.0) read_mismatch_counts = collections.defaultdict(lambda: 0.0) mismatch_re = re.compile(r"(\d+)([agtcAGTC]*)") for read in bamfh: hits += 1 if read.mate_is_unmapped: mate_unmapped_reads += 1 if read.is_unmapped or read.is_qcfail: unmapped_reads += 1 num_read_hits = 0 if read.is_qcfail: qcfail_reads += 1 else: if multimap: num_read_hits = read.opt('NH') else: num_read_hits = 1 weighted_cov = 1.0 / num_read_hits # count reads reads += weighted_cov if read.is_duplicate: duplicate_reads += weighted_cov read_lengths[read.rlen] += weighted_cov # mismatch counts along read mm_iter = mismatch_re.finditer(read.opt('MD')) offset = 0 for mismatch in mm_iter: skip, mmbase = mismatch.groups() offset += int(skip) if mmbase: pos = (read.rlen - offset - 1) if read.is_reverse else 0 cycle_mismatch_counts[pos] += weighted_cov # total mismatches per read read_mismatch_counts[read.opt('NM')] += weighted_cov multihit_counts[num_read_hits] += 1 # number of reads parent_group = self.hdf_group parent_group._v_attrs.hits = hits logging.info("%s: Number of alignment hits=%d" % (filename,hits)) parent_group._v_attrs.reads = reads logging.info("%s: Number of reads=%d" % (filename,int(reads))) parent_group._v_attrs.duplicate_reads = duplicate_reads logging.info("%s: Number of qc fail reads=%d" % (filename,int(qcfail_reads))) parent_group._v_attrs.qcfail_reads = qcfail_reads logging.info("%s: Number of read flagged as duplicates=%d" % (filename,int(duplicate_reads))) parent_group._v_attrs.unmapped_reads = unmapped_reads logging.info("%s: Number of mapped reads=%d" % (filename,int(reads-unmapped_reads))) logging.info("%s: Number of unmapped reads=%d" % (filename,unmapped_reads)) parent_group._v_attrs.mate_unmapped_reads = mate_unmapped_reads logging.info("%s: Number of reads with unmapped mate=%d" % (filename,mate_unmapped_reads)) parent_group._v_attrs.read_length_variable = True if len(read_lengths) > 1 else False # set to the most abundant read length in the case of variable read length runs parent_group._v_attrs.read_length = int(sorted(read_lengths.items(), key=operator.itemgetter(1), reverse=True)[0][0]) logging.info("%s: Most common read length=%d" % (filename, parent_group._v_attrs.read_length)) parent_group._v_attrs.read_length_distribution = dict(read_lengths) logging.info("%s: Number of different read lengths=%d" % (filename, len(read_lengths))) parent_group._v_attrs.fragment_length = fragment_length logging.info("%s: Fragment length (specified as input)=%d" % (filename, parent_group._v_attrs.fragment_length)) max_multihits = max(multihit_counts.keys()) arr = np.zeros(max_multihits, dtype=np.int) for i in xrange(max_multihits): if i in multihit_counts: arr[i] = int(multihit_counts[i]) parent_group._v_attrs.multihits = list(arr) logging.info("%s: Multimapping read counts=%s" % (filename, parent_group._v_attrs.multihits)) max_rlen = max(read_lengths.keys()) arr = np.zeros(max_rlen, dtype=np.int) for i in xrange(max_rlen): if i in cycle_mismatch_counts: arr[i] = int(cycle_mismatch_counts[i]) parent_group._v_attrs.cycle_mismatches = list(arr) logging.info("%s: Mismatches per cycle=%s" % (filename, parent_group._v_attrs.cycle_mismatches)) max_mismatches = max(read_mismatch_counts.keys()) arr = np.zeros(max_mismatches, dtype=np.int) for i in xrange(max_mismatches): if i in read_mismatch_counts: arr[i] = int(read_mismatch_counts[i]) parent_group._v_attrs.read_mismatches = list(arr) logging.info("%s: Mismatches per read=%s" % (filename, parent_group._v_attrs.read_mismatches)) # insert data for ref,length in zip(self._get_references(), self._get_lengths()): if ref not in bamfh.references: logging.debug("Skipping reference %s in BAM file that is not part of the track" % (ref)) continue logging.debug("Adding file %s ref %s to database" % (filename, ref)) ca = self.hdf_group._f_getChild(ref) # insert the reads from the BAM file into the array if genome: bam_to_array_chunked(bamfh.fetch(ref), ca, fragment_length=fragment_length, rmdup=rmdup) elif multimap: bam_pileup_to_array_multihit(bamfh.pileup(ref), ca, dtype=ca.atom.dtype) else: bam_pileup_to_array(bamfh.pileup(ref), ca, dtype=ca.atom.dtype) bamfh.close()
988,435
2b6bf599f20f5cc18c5fe8d38ef8576be116fbb1
''' !/usr/bin/env python _*_coding:utf-8 _*_ @Time    :2019/9/4 10:22 @Author  :Zhangyunjia @FileName: 4.5_featureSelection.py @Software: PyCharm ''' from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler
988,436
f4612fb4ca946e020e31d6ea956a56390a3a59c8
def mul(li): out=[] p=1 #왼쪽부터 곱해서 result 추가 [1,1,2,6] for i in range(0,len(li)): out.append(p) p=p*li[i] p=1 #오른쪾부터 시작 [24,12,4,1] for i in range(len(li)-1,-1,-1): out[i]=out[i]*p p=p*li[i] return out li=[1,2,3,4] print(mul(li))
988,437
0ecff6284f491bcf0697643870726bed9c6321d9
import ldap import os from loguru import logger from .db import db, User def init(app): ldapuri = os.environ.get("LDAPURI") ldapbase = os.environ.get("LDAPBASE") ldapbind = os.environ.get("LDAPBIND") ldappswd = os.environ.get("LDAPPSWD") ldap_conn = ldap.initialize(ldapuri) ldap_conn.simple_bind_s(ldapbind, ldappswd) searchFilter = "(objectClass=*)" searchAttribute = ["givenname","sn"] searchScope = ldap.SCOPE_SUBTREE try: ldaprslt = ldap_conn.search(ldapbase, searchScope, searchFilter, searchAttribute) result_set = [] while 1: result_type, result_data = ldap_conn.result(ldaprslt, 0) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print(result_set) for entry in result_set[1:]: logger.success(entry) user = User(first_name=entry[0][1]["givenName"][0].decode("utf-8"), mid_name="", last_name=entry[0][1]["sn"][0].decode("utf-8")) with app.app_context(): db.session.add(user) db.session.commit() except ldap.LDAPError as e: import traceback traceback.print_tb(e)
988,438
638e3a43889dccc64840c664934f967d34d6b94e
# Copyright (c) 2021-22 elParaguayo # # 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 pytest import libqtile.bar import libqtile.config from libqtile.command.base import expose_command from libqtile.widget import Spacer, TextBox from libqtile.widget.base import ThreadPoolText, _Widget from test.helpers import BareConfig, Retry class TimerWidget(_Widget): @expose_command() def set_timer1(self): self.timer1 = self.timeout_add(10, self.set_timer1) @expose_command() def cancel_timer1(self): self.timer1.cancel() @expose_command() def set_timer2(self): self.timer2 = self.timeout_add(10, self.set_timer2) @expose_command() def cancel_timer2(self): self.timer2.cancel() @expose_command() def get_active_timers(self): active = [x for x in self._futures if getattr(x, "_scheduled", False)] return len(active) class PollingWidget(ThreadPoolText): poll_count = 0 def poll(self): self.poll_count += 1 return f"Poll count: {self.poll_count}" def test_multiple_timers(minimal_conf_noscreen, manager_nospawn): config = minimal_conf_noscreen config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([TimerWidget(10)], 10))] # Start manager and check no active timers manager_nospawn.start(config) assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 0 # Start both timers and confirm both are active manager_nospawn.c.widget["timerwidget"].set_timer1() manager_nospawn.c.widget["timerwidget"].set_timer2() assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 2 # Cancel timer1 manager_nospawn.c.widget["timerwidget"].cancel_timer1() assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 1 # Cancel timer2 manager_nospawn.c.widget["timerwidget"].cancel_timer2() assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 0 # Restart both timers manager_nospawn.c.widget["timerwidget"].set_timer1() manager_nospawn.c.widget["timerwidget"].set_timer2() assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 2 # Verify that `finalize()` cancels all timers. manager_nospawn.c.widget["timerwidget"].eval("self.finalize()") assert manager_nospawn.c.widget["timerwidget"].get_active_timers() == 0 def test_mirrors_same_bar(minimal_conf_noscreen, manager_nospawn): """Verify that mirror created when widget reused in same bar.""" config = minimal_conf_noscreen tbox = TextBox("Testing Mirrors") config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([tbox, tbox], 10))] manager_nospawn.start(config) info = manager_nospawn.c.bar["top"].info()["widgets"] # First instance is retained, second is replaced by mirror assert len(info) == 2 assert [w["name"] for w in info] == ["textbox", "mirror"] def test_mirrors_different_bar(minimal_conf_noscreen, manager_nospawn): """Verify that mirror created when widget reused in different bar.""" config = minimal_conf_noscreen tbox = TextBox("Testing Mirrors") config.fake_screens = [ libqtile.config.Screen(top=libqtile.bar.Bar([tbox], 10), x=0, y=0, width=400, height=600), libqtile.config.Screen( top=libqtile.bar.Bar([tbox], 10), x=400, y=0, width=400, height=600 ), ] manager_nospawn.start(config) screen0 = manager_nospawn.c.screen[0].bar["top"].info()["widgets"] screen1 = manager_nospawn.c.screen[1].bar["top"].info()["widgets"] # Original widget should be in the first screen assert len(screen0) == 1 assert [w["name"] for w in screen0] == ["textbox"] # Widget is replaced with a mirror on the second screen assert len(screen1) == 1 assert [w["name"] for w in screen1] == ["mirror"] def test_mirrors_stretch(minimal_conf_noscreen, manager_nospawn): """Verify that mirror widgets stretch according to their own bar""" config = minimal_conf_noscreen tbox = TextBox("Testing Mirrors") stretch = Spacer() config.fake_screens = [ libqtile.config.Screen( top=libqtile.bar.Bar([stretch, tbox], 10), x=0, y=0, width=600, height=600 ), libqtile.config.Screen( top=libqtile.bar.Bar([stretch, tbox], 10), x=600, y=0, width=200, height=600 ), ] manager_nospawn.start(config) screen0 = manager_nospawn.c.screen[0].bar["top"].info()["widgets"] screen1 = manager_nospawn.c.screen[1].bar["top"].info()["widgets"] # Spacer is the first widget in each bar. This should be stretched according to its own bar # so check its length is equal to the bar length minus the length of the text box. assert screen0[0]["length"] == 600 - screen0[1]["length"] assert screen1[0]["length"] == 200 - screen1[1]["length"] def test_threadpolltext_force_update(minimal_conf_noscreen, manager_nospawn): """Check that widget can be polled instantly via command interface.""" config = minimal_conf_noscreen tpoll = PollingWidget("Not polled") config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([tpoll], 10))] manager_nospawn.start(config) widget = manager_nospawn.c.widget["pollingwidget"] # Widget is polled immediately when configured assert widget.info()["text"] == "Poll count: 1" # Default update_interval is 600 seconds so the widget won't poll during test unless forced widget.force_update() assert widget.info()["text"] == "Poll count: 2" def test_threadpolltext_update_interval_none(minimal_conf_noscreen, manager_nospawn): """Check that widget will be polled only once if update_interval == None""" config = minimal_conf_noscreen tpoll = PollingWidget("Not polled", update_interval=None) config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([tpoll], 10))] manager_nospawn.start(config) widget = manager_nospawn.c.widget["pollingwidget"] # Widget is polled immediately when configured assert widget.info()["text"] == "Poll count: 1" class ScrollingTextConfig(BareConfig): screens = [ libqtile.config.Screen( top=libqtile.bar.Bar( [ TextBox("NoWidth", name="no_width", scroll=True), TextBox("ShortText", name="short_text", width=100, scroll=True), TextBox("Longer text " * 5, name="longer_text", width=100, scroll=True), TextBox( "ShortFixedWidth", name="fixed_width", width=200, scroll=True, scroll_fixed_width=True, ), ], 32, ) ) ] scrolling_text_config = pytest.mark.parametrize("manager", [ScrollingTextConfig], indirect=True) @scrolling_text_config def test_text_scroll_no_width(logger, manager): """ Scrolling text needs a fixed width. If this is not set a warning is provided and scrolling is disabled. """ records = [r for r in logger.get_records("setup") if r.msg.startswith("no_width")] assert records assert records[0].levelname == "WARNING" assert records[0].msg == "no_width: You must specify a width when enabling scrolling." _, output = manager.c.widget["no_width"].eval("self.scroll") assert output == "False" @scrolling_text_config def test_text_scroll_short_text(manager): """ When scrolling is enabled, width is a "max_width" setting. Shorter text will reslult in widget shrinking. """ widget = manager.c.widget["short_text"] # Width is shorter than max width assert widget.info()["width"] < 100 # Scrolling is still enabled (but won't do anything) _, output = widget.eval("self.scroll") assert output == "True" _, output = widget.eval("self._should_scroll") assert output == "False" @scrolling_text_config def test_text_scroll_long_text(manager): """ Longer text scrolls by incrementing an offset counter. """ @Retry(ignore_exceptions=(AssertionError,)) def wait_for_scroll(widget): _, scroll_count = widget.eval("self._scroll_offset") assert int(scroll_count) > 5 widget = manager.c.widget["longer_text"] # Width is fixed at set width assert widget.info()["width"] == 100 # Scrolling is still enabled _, output = widget.eval("self.scroll") assert output == "True" _, output = widget.eval("self._should_scroll") assert output == "True" # Check actually scrolling wait_for_scroll(widget) @scrolling_text_config def test_scroll_fixed_width(manager): widget = manager.c.widget["fixed_width"] _, layout = widget.eval("self.layout.width") assert int(layout) < 200 # Widget width is fixed at set width assert widget.info()["width"] == 200
988,439
cf4f98a99530c512f1ea5fe03928d700d2d6e42a
import random import math import matplotlib.pyplot as plt def init_weights(layers): weights = list() #probar con layers[i] + layers[i+1] en el denomidor #probar con diferente numerador, 2.0 es XAVIER method for i in range(len(layers)-1): var = math.sqrt(2.0/layers[i]) weights.append([[random.random() * var for _ in range(layers[i])] for _ in range(layers[i+1])]) return weights def sigmoid(z): return 1.0/(1.0 + math.exp(-z)) def dot_product(inputs, weights): acum = 0 for i in range(len(inputs)): acum += inputs[i] * weights[i] return acum def feed_forward_propagation(inputs, weights): nodes[0] = inputs for i in range(len(nodes) - 1): for j in range(len(nodes[i+1])): nodes[i+1][j] = sigmoid(dot_product(nodes[i], weights[i][j])) if __name__ == '__main__': layers = (784, 64, 10) weights = init_weights(layers) input = [8.5, 0.65, 1.2] nodes = [[0.0 for _ in range(layers[i])] for i in range(len(layers))] prediction = feed_forward_propagation(input, weights)
988,440
2233f1daeafc13cc24bbf822cad731ee16bc5b64
# encoding = utf-8 def fetch_every_nth_record(db, table, n, limit, where=None): query = create_query_every_nth_record(table, n, where, limit) records = db_perform_query(db, query) return records def create_query_every_nth_record(table: str, n: int, where: str, limit: int = 50): query = create_query_every_nth_record_mysql(table, n, where, limit) return query def db_perform_query(db, query: str): result = db_perform_query_sqlalchemy(db, query) return result def create_query_every_nth_record_mysql(table: str, n: int, where: str, limit: int) -> str: if where: where = " " + where else: where = "" query = f""" SELECT {table}.* FROM {table} INNER JOIN ( SELECT id FROM ( SELECT @row:=@row+1 AS rownum, id FROM ( SELECT id FROM {table}{where} ORDER BY id desc LIMIT {limit * n} ) AS sorted ) as ranked WHERE rownum mod {n} = 0 ) AS subset ON subset.id = {table}.id """ return query def db_perform_query_sqlalchemy(db, query): query = " ".join(query.split()) db.engine.execute("set @row:=-1;") result = db.engine.execute(query) return result
988,441
e30bc421edb93ea8857219585c62e2dcdb5fd824
# bfs, dfs 에서 # Queue 또는 Stack을 활용하여 그래프를 traverse해야하는 예 # 1000 1 1000 # 999 1000 # 에러가 계속 났던 이유 # 답을 구하고 print 할 때, # list 자체를 print해서 []를 포합하고 있었기 때문 class My_Vertex: def __init__(self, nodeA, nodeB=None): self.node_main = nodeA self.node_neighbors = [] if nodeB != None: self.node_neighbors.append(nodeB) def put_neighbor(self, nodeB): self.node_neighbors.append(nodeB) def get_neighbors(self): self.node_neighbors.sort() return self.node_neighbors class My_Graph: def __init__(self, num_ver, num_edge): self.num_ver = num_ver self.num_edge = num_edge self.vertex_set = {} def add_vertex(self, vertex1, vertex2): if vertex1 not in self.vertex_set: # print(str(vertex1) ,"is added") self.vertex_set[vertex1] = My_Vertex(vertex1, vertex2) else: # print(str(vertex1), "added anyway") self.get_vertex(vertex1).put_neighbor(vertex2) def get_vertex(self, vertex): return self.vertex_set[vertex] def get_neighbors(self, vertex): return self.get_vertex(vertex).get_neighbors() # def show_set(self): # return (self.vertex_set) def bfs(self, start_v): visited_node = [] temp_queue = [start_v] while temp_queue: from_vertex = temp_queue[0] temp_queue = temp_queue[1:] if from_vertex in visited_node: continue else: visited_node.append(from_vertex) temp_set = self.get_neighbors(from_vertex) temp_queue = temp_queue + temp_set return visited_node # while self.num_ver != len(visited_node): # from_vertex = temp_queue[0] # temp_queue = temp_queue[1:] # # if from_vertex in visited_node: # continue # else: # visited_node.append(from_vertex) # # temp_set = self.get_neighbors(from_vertex) # temp_queue = temp_queue + temp_set # # return visited_node def dfs(self, start_v): visited_node = [] temp_stack = [start_v] while temp_stack: from_vertex = temp_stack[0] temp_stack = temp_stack[1:] if from_vertex in visited_node: continue else: visited_node.append(from_vertex) temp_set = self.get_neighbors(from_vertex) temp_stack = temp_set + temp_stack return visited_node # while self.num_ver != len(visited_node): # from_vertex = temp_stack[0] # temp_stack = temp_stack[1:] # # if from_vertex in visited_node: # continue # else: # visited_node.append(from_vertex) # # temp_set = self.get_neighbors(from_vertex) # temp_stack = temp_set + temp_stack # # return visited_node def main(): num_ver, num_edge, start_v = map(int, input().split()) my_graph = My_Graph(num_ver, num_edge) for i in range(num_edge): nodeA, nodeB = map(int, input().split()) my_graph.add_vertex(nodeA, nodeB) my_graph.add_vertex(nodeB, nodeA) print(' '.join(map(str,my_graph.dfs(start_v)))) print(' '.join(map(str,my_graph.bfs(start_v)))) if __name__ == "__main__": main()
988,442
6b7c05fd482cdcc043cd6fe7cc53df8850a0f35c
num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) def compute_lcm(num1, num2): largest = max(num1, num2) while True: if largest % num1 == 0 and largest % num2 == 0: lcm = largest break largest += 1 return lcm result = compute_lcm(num1, num2) print(result)
988,443
98cb5e1c225be283a4b98e5f48a05b3d004dd9f3
#!/usr/bin/env python import re from re_08_choiceredata import choice_data # data = choice_data() # print(data) # # patt_time = ' (\d+:\d+:\d+) ' # print("Time: " + re.search(patt_time, data).group(1)) # # patt_email = '\w+@\w+\.(?:net|org|edu|com|gov)' # print("Email: " + re.search(patt_email, data).group()) # # patt_month = '\w+ (\w+)(?: | )\d+ ' # print("Month: " + re.search(patt_month, data).group(1)) # # patt_year = '\d+:\d+:\d+ (\d+):' # print("Year: " + re.search(patt_year, data).group(1)) # # patt_domain = '(\w+)@(\w+\.(?:net|org|edu|com|gov))' # m = re.search(patt_domain, data) # print("Name: " + m.group(1) + '\n' + "Domain: " + m.group(2)) # # patt_my_email = '\w+@\w+\.(?:net|org|edu|com|gov)' # print("My email: " + re.sub(patt_my_email, "justsweetpotato@gmail.com", data)) # # patt_date = "\w+ (\w+)(?: | )(\d+) \d+:\d+:\d+ (\d+)::" # m = re.search(patt_date, data) # print("Date: {},{},{}".format(m.group(1), m.group(2), m.group(3))) # patt = '^(\w{3})' # m = re.match(patt, data) # if m is not None: print(m.group()) # # patt = '.+(\d+-\d+-\d)' # print(re.search(patt, data).group(1)) # data = "so, i hope you can bit me." # # patt = '[b|h][a|i|u|]t' # print(re.search(patt, data).group()) # data = "My name is Jake Wong. He name is Sam Lee." # # patt = '[A-Z]\w+ [A-Z]\w+' # print(re.findall(patt, data)) # data = "My name is Jake Wong, I like movies, and music." # # patt = ' (\w+), (\w+) ' # print(re.findall(patt, data)) # data = 'Python' # # patt = '^[A-Z|a-z|_][A-Z|a-z|\d|_]*' # try: # m = re.match(patt, data).group() # except Exception as e: # print("命名不合法!") # else: # print(m) # data = "https://www.google.eduwww.baidu.comwww.mahuateng.orgWWW.YAMAXUN.COM" # patt = r'(?:http|https://)?www\.\w+\.(?:com|org|net|edu)' # print(len(re.findall(patt, data, re.I))) # data = "0." # patt = "\d+\.(?:\d*)?" # print(re.findall(patt, data)) # data = "ewar@gmail.come242@qq.comrkehjrw_ehwhka@ieowqjioqrq.com" # patt = "[A-Za-z0-9_]+@[A-Za-z0-9]+\.com" # print(re.findall(patt, data)) # data = "我们的电话号码是:589-333-3334,或者:(589)333-2451,333-2325." # patt = "(?:(?:\d{3}-)|(?:\(\d{3}\)))?\d{3}-\d{4}" # print(re.findall(patt, data))
988,444
767274f2c9c0ea68419398651f575509363fa2fd
import torch.nn as nn import params as P import utils import basemodel.model4 import hebbmodel.top4 class Net(nn.Module): # Layer names FC5 = 'fc5' BN5 = 'bn5' FC6 = 'fc6' CLASS_SCORES = FC6 # Symbolic name of the layer providing the class scores as output NET_G1_4_PATH = P.PROJECT_ROOT + '/results/gdes/config_4l/save/model0.pt' NET_H5_6_PATH = P.PROJECT_ROOT + '/results/hebb/top4/save/model0.pt' def __init__(self, input_shape=P.INPUT_SHAPE): super(Net, self).__init__() # Shape of the tensors that we expect to receive as input self.input_shape = input_shape # Here we define the layers of our network self.net_g1_4 = basemodel.model4.Net(input_shape) loaded_model = utils.load_dict(self.NET_G1_4_PATH) if loaded_model is not None: self.net_g1_4.load_state_dict(loaded_model) self.net_g1_4.to(P.DEVICE) self.net_h5_6 = hebbmodel.top4.Net(utils.get_output_fmap_shape(self.net_g1_4, basemodel.model4.Net.BN4)) loaded_model = utils.load_dict(self.NET_H5_6_PATH) if loaded_model is not None: self.net_h5_6.load_state_dict(loaded_model) self.net_h5_6.to(P.DEVICE) # Here we define the flow of information through the network def forward(self, x): return self.net_h5_6(self.net_g1_4(x)[basemodel.model4.Net.BN4])
988,445
99f56e27bc022e0206fe096db958b342940635d6
import requests import json from conf import * from hidden_conf import * __version__ = '1.0' __author__ = 'Yair Stemmer and Yoav Wigelman' class PostText(object): def __init__(self, text: tuple, content_type: str = CONTENT_TYPE, accept_encoding: str = ACCEPT_ENCODING, x_rapidapi_key: str = X_RAPID_API_KEY, x_rapidapi_host: str = X_RAPID_API_HOST, url_language: str = URL_LANGUAGE, url_translation: str = URL_TRANSLATION, sentiment_key: str = SENTIMENT_SUBSCRIPTION_KEY, url_sentiment: str = URL_SENTIMENT): """ PostText is an object that for parsing, translating and analysing post sentiment :param text: str object that represents instagram post record :param content_type: str object that represents content type for translate api :param accept_encoding: str object that represents encoding for translate api :param x_rapidapi_key: str object that represents key for rapid-api :param x_rapidapi_host: str object that represents the rapid-api host address :param url_language: str object that represents the url for language detection :param url_translation: str object that represents the url for translation :param sentiment_key: str object that represents the key for sentiment analysis :param url_sentiment: str object that represents the url for sentiment analysis """ self.text = text self.translate_headers = {'content-type': content_type, 'accept-encoding': accept_encoding, 'x-rapidapi-key': x_rapidapi_key, 'x-rapidapi-host': x_rapidapi_host} self.sentiment_headers = {'Ocp-Apim-Subscription-Key': sentiment_key} self.url_language = url_language self.url_translation = url_translation self.url_sentiment = url_sentiment self.clean = False self.language = None self.payload = None self.translation = None self.sentiment = None def _text_clean(self): """ a function for parsing post text item to contain only the content :return: None """ try: self.text = eval(self.text[0])[0]['node']['text'] self.clean = True except IndexError: return def detect_language(self): """ a function that connects with an api to detect the language of a post :return: None """ if not self.clean: self._text_clean() if not self.clean: return self.payload = "q={}".format(self.text) resp = requests.request('POST', self.url_language, data=self.payload.encode('utf-8'), headers=self.translate_headers) try: self.language = json.loads(resp.text)['data']['detections'][0][0]['language'] except KeyError: return def translate(self, to_lang: str = TARGET_LANG): """ a function for translating a post to a given language :param to_lang: str object that represents a target language for translation :return: None """ if not self.language: self.detect_language() if not all([self.clean, self.language != to_lang]): return self.payload += '&source={}&target={}'.format(self.language, to_lang) resp = requests.request('POST', self.url_translation, data=self.payload.encode('utf-8'), headers=self.translate_headers) try: self.translation = json.loads(resp.text)['data']['translations'][0]['translatedText'] except KeyError: return def analyze_sentiment(self, lang: str = TARGET_LANG): """ a function for analyzing a sentiments from a text (either positive, negative or neutral) :param lang: the language to analyze from :return: None """ if not self.translation and self.language != lang: self.translate() if not self.clean: return query = {"documents": [ {"id": "1", "language": "{}".format(lang), "text": "{}".format(self.translation)} ]} response = requests.post(self.url_sentiment, headers=self.sentiment_headers, json=query) self.sentiment = response.json()['documents'][0]['sentiment']
988,446
0acf61e2b8da8740403b14694cb95e344605878d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 3 22:04:52 2017 @author: akashmantry """ import os from models import ParserModel from bs4 import BeautifulSoup from readability.readability import Document from text_utils import TextFilter class Parser: def __init__(self, path): self.path = path @staticmethod def parse_document(url, htmltext): print ("Parsing " + url) try: readable_article = Document(htmltext).summary() readable_title = Document(htmltext).short_title() soup = BeautifulSoup(readable_article, "html.parser") final_article = soup.text except Exception as e: print (str(e)) final_article = '' cleaned_final_article = TextFilter.filter_text(final_article) Parser.store_data_in_db(url, cleaned_final_article) @staticmethod def store_data_in_db(url, text): parser_object = ParserModel(url=url, text=text) parser_object.save() def read_html_files(self): for file_name in os.listdir(self.path): file_path = self.path + '/' + file_name with open(file_path, 'rt', encoding='utf-8') as f: temp_list = f.readlines() url = temp_list[0].strip() document = ''.join(temp_list[1:]) print('Parsing ', url) Parser.parse_document(url, document) parser = Parser('/Users/akashmantry/Documents/folfox_search/FolfoxSearch/100_files') parser.read_html_files()
988,447
ce3876916bccd79e422fb1e5125e11a6a4c03842
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 11 13:47:53 2018 @author: emrecemaksu """ import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler from sklearn.svm import SVC from sklearn.cross_validation import train_test_split from sklearn.metrics import confusion_matrix from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn import metrics veriler = pd.read_csv('veriler.csv') ulke = veriler[['ulke']].values cinsiyet = veriler[['cinsiyet']] LE = LabelEncoder() ulke[:,0] = LE.fit_transform(ulke[:,0]) OHE = OneHotEncoder(categorical_features="all") ulke = OHE.fit_transform(ulke).toarray() bky = veriler[['boy','kilo','yas']] SS = StandardScaler() bky = SS.fit_transform(bky) ulke = pd.DataFrame(data =ulke, index = range(22), columns = ['us', 'fr', 'tr']) bky = pd.DataFrame(data =bky, index = range(22), columns = ['boy', 'kilo', 'yas']) ubky = pd.concat([ulke, bky], axis=1) ubky = SS.fit_transform(ubky) X_train, X_test, y_train, y_test = train_test_split(ubky, cinsiyet, test_size=0.33, random_state=1) GNB = GaussianNB() GNB.fit(X_train, y_train) y_test_predict = GNB.predict(X_test) print(y_test_predict) cm = confusion_matrix(y_test, y_test_predict) print(cm) DTC = DecisionTreeClassifier(criterion = 'entropy') DTC.fit(X_train, y_train) y_test_predict2 = DTC.predict(X_test) cm2 = confusion_matrix(y_test, y_test_predict2) print('DTC') print(cm2) RFC = RandomForestClassifier(n_estimators=10, criterion='entropy') RFC.fit(X_train, y_train) y_test_predict3 = RFC.predict(X_test) cm3 = confusion_matrix(y_test, y_test_predict2) print('RFC') print(cm3) y_proba = GNB.predict_proba(X_test) print(y_proba) y_proba2 = DTC.predict_proba(X_test) print('DTC') print(y_proba2) y_proba3 = RFC.predict_proba(X_test) print('RFC') print(y_test) print(y_proba3[:,0]) print(y_proba3) fpr, tpr, thold = metrics.roc_curve(y_test, y_proba3[:,0], pos_label='e') print(fpr) print(tpr)
988,448
058379d22d4c8b9f1e6134b023e0ab3e8d975f8c
from scrawler import * import pymysql import uuid import sys from database import * from logger import Logger import time l = Logger() db = Database("pitt_course") subject_list = [] subject_dict = db.query_db_dict("SELECT major_id, subject_index FROM subject", l) for i in subject_dict: subject_list.append({'subject_index':i['subject_index'], 'major_id':i['major_id']}) #subject_list = ["BUSACC","ADMJ","AFROTC","AFRCNA","ANTH","ARTSC","ASTRON","BIOETH","BIOSC","BUS","BUSECN","BUSENV","BUSERV","CDACCT","HYBRID","SELF","WWW","CHEM","CHIN","CLASS","COMMRC","CS","CLST","EAS","ECON","ENGCMP","ENGFLM","ENGLIT","ENGWRT","FILMST","BUSFIN","FP","FR","FTDA","FTDB","FTDC","GEOL","GER","GREEK","HIST","HPS","HAA","HONORS","BUSHRM","INFSCI","ISSP","ITAL","JPNSE","JS","KOREAN","LATIN","LEGLST","LING","BUSMIS","BUSMKT","MATH","MRST","MILS","MUSIC","NROSCI","BUSORG","PHIL","PEDC","PHYS","POLISH","PS","PORT","PSY","PUBSRV","BUSQOM","REL","RELGST","RUSS","SERCRO","SLAV","SLOVAK","SOC","SPAN","STAT","BUSSPP","SA","THEA","UKRAIN","HONORS","URBNST","GSWS"] course_crawler = CourseCrawler() for subject in subject_list: l.log("Start crawling course for subject: "+subject['subject_index']) course_process = CourseProcess(course_crawler.session) course_process.set_term("spring1920") course_process.set_campus("pittsburgh") course_process.set_subject(subject['subject_index']) search_string = course_process.search() major_id = subject['major_id'] cih = CourseInformationHandler(search_string) for i in cih.course_block_list: templist = [] first_index = re.search(r'\d+',i.find("a",{"id":re.compile(r'^MTG_CLASSNAME\$\d+')})['id']).group() c_detail = course_process.get_class_detail(first_index) course_name = str(cih.get_course_name(i)).strip() cdh = ClassDetailHandler(c_detail) requirement = cdh.get_requirement().strip() unit = cdh.get_unit().strip() component = cdh.get_class_component().strip() grading_method = cdh.get_grading().strip() career = cdh.get_career().strip() description = cdh.get_description().strip() session = cdh.get_session().strip() attribute = cdh.get_attribute().strip() attribute_list = attribute.split('\r') #which is because one course can have multiple attributes if len(db.query_db_dict('SELECT course_id FROM course WHERE name = "' + course_name + '"', l)) == 0: course_id = str(uuid.uuid1()) #insert into course db.insert('course',{'id': str(uuid.uuid1()), 'course_id': course_id, 'major_id': major_id, 'name': course_name, 'requirement': requirement, 'unit': unit, 'component': component, 'grading_method': grading_method, 'career': career, 'description': description, 'session': session, 'add_time': str(int(time.time()))}, l) #insert into course attribute (which is because one course can have multiple attributes, so it need to be seperated) for attribute in attribute_list: db.insert('course_attribute',{'id': str(uuid.uuid1()), 'course_id': course_id, 'attribute': attribute.strip(), 'add_time': str(int(time.time()))}, l) db.commit() l.log(str(subject['subject_index'])+":"+ str(course_name)) else: l.log("Course " + course_name + " already exist.") del l
988,449
4bec8a5796cf9bd0486306c214b5056c4075ed6e
#!/bin/env python3 # https://pymolwiki.org/index.php/Launching_From_a_Script # how to use pymol as cli # https://pymolwiki.org/index.php/Iterate # how to get information from selected atoms # https://github.com/schrodinger/pymol-open-source/blob/master/modules/pymol/wizard/mutagenesis.py # pymol mutagenesis internals, including bump_scores (strain value for rotamers), and an example on pymol.storage for pymol interal->external communication # http://www.mayachemtools.org/docs/scripts/html/code/PyMOLMutateAminoAcids.html # the inspiration for this script, though not much (none?) of that code is actually included in this file # http://www.mayachemtools.org/docs/modules/html/PyMOLUtil.py.html#GetChains # reference for pymol chain retrieval, though not much (none?) of that code is actually included in this file # http://www.endmemo.com/bio/codon.php # codon table because i cannot remember them myself import sys try: import pymol # wait for pymol to finish launching cli (-c), in quiet mode (-q), and disable loading of pymolrc and plugins (-k) pymol.finish_launching(['pymol', '-ckq']) except ImportError as ErrMsg: sys.stderr.write(f"Failed to import PyMOL package, most likely because pymol is not installed: {ErrMsg}\n") sys.exit(1) aa_table_one_to_three={ "A":"ALA", "C":"CYS", "D":"ASP", "E":"GLU", "F":"PHE", "G":"GLY", "H":"HIS", "I":"ILE", "K":"LYS", "L":"LEU", "M":"MET", "N":"ASN", "P":"PRO", "Q":"GLN", "R":"ARG", "S":"SER", "T":"THR", "V":"VAL", "W":"TRP", "Y":"TYR", } from contextlib import redirect_stdout, redirect_stderr def prepare(in_file,out_file,molecule_name,chain_id,mutation): with open("redirect_output.out","a+") as file: with redirect_stdout(file): """Mutate specified residues across chains and generate an output file.""" #reinitialize to restore program to default state after possible previous calls of this function pymol.cmd.reinitialize() pymol.cmd.load(in_file, molecule_name) if "from_long" not in mutation: mutation["from_long"]=aa_table_one_to_three[mutation["from"]] if "to_long" not in mutation: mutation["to_long"]=aa_table_one_to_three[mutation["to"]] mutation["position"]=int(mutation["position"]) assert mutation["from_long"]==aa_table_one_to_three[mutation["from"]] assert mutation["to_long"]==aa_table_one_to_three[mutation["to"]] """Retrieve chain IDs. """ try: ChainIDs = pymol.cmd.get_chains(f"model {molecule_name}") except pymol.CmdException as ErrMsg: print(f"PyMOLUtil.GetChains: Invalid molecule name: {molecule_name}") sys.exit(1) if len(ChainIDs)==0: print(f"no chains found for molecule {molecule_name}") sys.exit(1) if not chain_id in ChainIDs: print(f"chain {chain_id} not found in chain ids of molecule {molecule_name}") sys.exit(1) # Apply mutations # Setup mutagenesis wizard pymol.cmd.wizard("mutagenesis") pymol.cmd.refresh_wizard() # select residue to be mutated select_residue = "/%s//%s/%s" % (molecule_name, chain_id, mutation["position"]) pymol.cmd.iterate(select_residue, "(stored.resi,stored.resn)=(resi,oneletter)") if int(pymol.stored.resi)!=mutation["position"] or pymol.stored.resn!=mutation["from"]: print(f"WT residue or position wrong: expected {mutation}, but structure actually contains {pymol.stored.resn} at {pymol.stored.resi}") sys.exit(1) pymol.cmd.get_wizard().do_select(select_residue) # setup mutation (create mutation and open list of rotamers) pymol.cmd.get_wizard().set_mode(mutation["to_long"]) # get rotamer with lowest strain strain=pymol.cmd.get_wizard().bump_scores[0] least_strain_rotamer_index=0 for i in range(0,len(pymol.cmd.get_wizard().bump_scores)): if pymol.cmd.get_wizard().bump_scores[i]<strain: strain=pymol.cmd.get_wizard().bump_scores[i] least_strain_rotamer_index=i # apply mutation pymol.cmd.get_wizard().do_state(least_strain_rotamer_index+1) pymol.cmd.get_wizard().apply() # quit wizard pymol.cmd.set_wizard("done") select_residue = "/%s//%s/%s" % (molecule_name, chain_id, mutation["position"]) pymol.cmd.iterate(select_residue, "(stored.resi,stored.resn)=(resi,oneletter)") if int(pymol.stored.resi)!=mutation["position"] or pymol.stored.resn!=mutation["to"]: print(f"WT residue or position wrong: expected mutation {mutation}, but got {pymol.stored.resn} in position {pymol.stored.resi}") sys.exit(1) # save to output file pymol.cmd.save(out_file, molecule_name) # pymol.cmd.delete(MolName) if __name__=="__main__": mutation={ "from":"Q", "from_long":"GLN", "to":"R", "to_long":"ARG", "position":54, } molecule_name="fgf2" chain_id="A" # from testing. automate how? in_file=sys.argv[1] print("mutating structure: ", in_file) if len(sys.argv)>2: out_file=sys.argv[2] else: out_file=sys.argv[1][:-4]+f"_mutated_{mutation['from']}{mutation['position']}{mutation['to']}.pdb" prepare(in_file,out_file,molecule_name,chain_id,mutation)
988,450
c102cad4e037cf8685b1848f8b7db0dcbcfb7b11
import requests import webbrowser import time import turtle screen = turtle.Screen() screen.setup(8192,4096) screen.bgpic('map.gif') turtle.mainloop() '''astronaut_data= 'http://api.open-notify.org/astros.json' #result=requests.get(astronaut_data).json() #print(result) #print(f"People in space {result['number']}") #for person in result['people']: #print(person['name'] + 'in ' + person['craft']) iss_location= 'http://api.open-notify.org/iss-now.json' while True: result=requests.get(iss_location).json() #print(result) timestamp= result['timestamp'] lat=result['iss_position']['latitude'] lon=result['iss_position']['longitude'] print( str(timestamp)+ ' '+ lat +' '+ lon) time.sleep(.1) maps=f"http://maps.google.com/?q={lat},{lon}" webbrowser.open_new_tab(maps)'''
988,451
649a1d39a6c295e15cc761e97ab6e39b0e26b0bd
import random import turtle class TurtleFPO: def __init__(self, energy=100): self.t = turtle.Turtle() self.energy = energy def forward(self, value): if value < 0: raise ValueError('Error: Value must be positive') if self.energy - value >= 0: self.t.forward(value) else: self.t.forward(self.energy) self.energy = max(self.energy - value, 0) def backward(self, value): if value < 0: raise ValueError('Error: Value must be positive') if self.energy - value >= 0: self.t.backward(value) else: self.t.backward(self.energy) self.energy = max(self.energy - value, 0) def leap_forward(self, value): self.t.penup() self.forward(value) self.t.pendown() def leap_backward(self, value): self.t.penup() self.backward(value) self.t.pendown() def race(): # init turtle red = turtle.Turtle() blue = turtle.Turtle() green = TurtleFPO(random.randint(500, 800)) purple = TurtleFPO(random.randint(450, 700)) start = -400 red.color('red') red.shape('turtle') red.up() red.goto(start, 50) red.down() blue.color('blue') blue.shape('turtle') blue.up() blue.goto(start, 25) blue.down() green.t.color('green') green.t.shape('turtle') green.t.up() green.t.goto(start, 0) green.t.down() purple.t.color('purple') purple.t.shape('turtle') purple.t.up() purple.t.goto(start, -25) purple.t.down() # finish line _win_x = 200 finish = turtle.Turtle() finish.up() finish.goto(_win_x, -75) finish.down() finish.left(90) finish.forward(170) finish.hideturtle() # farthest = win while True: red.forward(random.randint(5, 20)) blue.forward(random.randint(5, 20)) green.forward(random.randint(5, 20)) purple.forward(random.randint(5, 20)) if red.pos()[0] >= _win_x or blue.pos()[0] >= _win_x or \ green.t.pos()[0] >= _win_x or purple.t.pos()[0] >= _win_x: break turtle.done() def main(): race() if __name__ == '__main__': main()
988,452
3430e2493be60aa8df485c8d23e9a97ac426933a
''' @Author: CSY @Date: 2020-01-27 15:31:29 @LastEditors : CSY @LastEditTime : 2020-01-27 15:35:25 ''' """ 23、用lambda函数实现两个数相乘 """ sum=lambda x,y:x*y print(sum(1,2))
988,453
c321873e2067e22078930b140b690de024fae742
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import time class Query(object): endpoint = 'https://api.us2.sumologic.com/api/v1/logs/search' def __init__(self, template, conn, timestamp='_timeslice', value='value', span=900000): template_path = os.path.join(os.path.expanduser('~'), '.kambi/templates', template) with open(template_path, 'r') as f: self.query = f.read() self.conn = conn self.timestamp = timestamp self.value = value self.span = span def fetch(self, from_timestamp=None, to_timestamp=None): from_timestamp = from_timestamp or int(time.time() * 1000)-self.span to_timestamp = to_timestamp or int(time.time() * 1000) params = { 'q': self.query, 'from': from_timestamp, 'to': to_timestamp, 'tz': 'Etc/UTC', 'format': 'json' } r = self.conn.get(self.endpoint, params=params) r.raise_for_status() data = r.json() data = {x[self.timestamp]: x[self.value] for x in data} return data
988,454
f142f9192a2415a0fadf31f47e5264d13f011adb
#returns approved, incresed/decreased, number def main(last2, last1, new): if new >= 100 or last1 >= 100 or last2 >= 100: #if too far return ["FAR", new] if abs(last1 - new) >= 30: #if big difference return ["BIG", new] if abs(last1 - new) <= 0.5: #if very small difference return ["SMALL", new] if last2 < last1 < new: #if stable increase print("increase1") if (last1-last2)/last2 >= 0.02 and (new-last1)/last1 >= 0.02: #if stable changes above 5% of distance amount = int(((last1-last2)/last2 + (new-last1)/last1) * 20) return [True, "increase", amount] #increase if last2 > last1 > new: #if stable decrease #if (last2-last1)/last1 >= 0.01 and (last1-new)/new >= 0.01: #if stable changes above 5% of distance if (last1-new)/new >= 0.01: amount = int(((last1-new)/new) * 10) return [True, "decrease", amount] #decrase else: return ["ELSE", last2, last1, new] if __name__ == "__main__": main(args)
988,455
4a28f74b35a7faaaa3b4a9733a074928174ddef7
from collections import deque def is_scheduling_possible(tasks, prerequisites): nodes = [[] for task_index in range(tasks)] in_degree = [0 for task_index in range(tasks)] for from_node, to_node in prerequisites: nodes[from_node].append(to_node) in_degree[to_node] += 1 q = deque() for node_index in range(tasks): if in_degree[node_index] == 0: q.append(node_index) while q: curr_node = q.popleft() for connected_node in nodes[curr_node]: in_degree[connected_node] -= 1 if in_degree[connected_node] == 0: q.append(connected_node) return sum(in_degree) == 0 def main(): print("Is scheduling possible: " + str(is_scheduling_possible(3, [[0, 1], [1, 2]]))) print("Is scheduling possible: " + str(is_scheduling_possible(3, [[0, 1], [1, 2], [2, 0]]))) print("Is scheduling possible: " + str(is_scheduling_possible(6, [[0, 4], [1, 4], [3, 2], [1, 3]]))) main()
988,456
c7a5a9263dc1666ce0b9590bd79997d0a93124f3
# General Utility import time import sys # PYQT5, GUI Library from PyQt5 import QtCore, QtGui, QtWidgets # Serial and MIDI from serial.tools import list_ports import rtmidi # SKORE modules import globals #------------------------------------------------------------------------------- # Functions class DeviceDetector(QtCore.QThread): """ This class is a thread that detects any USB/MIDI device insertion/removal events and informs the user about the event. Additionally, if the USB/MIDI is inserted, the DeviceDetector attempts to re-establish the communication line with the inserted device. """ arduino_change_signal = QtCore.pyqtSignal('QString') piano_change_signal = QtCore.pyqtSignal('QString') def __init__(self, gui = None): """ This function simply connects the DeviceDetector to the SKORE gui. """ QtCore.QThread.__init__(self) self.gui = gui return None def enumerate_serial_devices(self): """ This helper function simply obtains the serial ports. """ ports = list(list_ports.comports()) return ports def enumerate_midi_devices(self): """ This helper function simply obtains the MIDI ports. """ ports = self.midiout.get_ports() return ports def check_device_changes(self): """ This function does the comparison of current and past USB/MIDI ports. If the thread detects a change, it determines if it is a removal/insertion. If removal, inform the user. Else if insertion, restablish communication. """ #--------------------------------------------------------------------------- # USB ports current_serial_devices = self.enumerate_serial_devices() for device in self.old_serial_devices: if device not in current_serial_devices: print("Removed USB port: ", device) self.removed_serial_devices.append(device) self.arduino_change_signal.emit('OFF') for device in current_serial_devices: if device not in self.old_serial_devices: print("Added USB port: ", device) self.added_serial_devices.append(device) self.arduino_change_signal.emit('ON') self.old_serial_devices = current_serial_devices #--------------------------------------------------------------------------- # MIDI port detection current_midi_devices = self.enumerate_midi_devices() for device in self.old_midi_devices: if device not in current_midi_devices: print("Removed MIDI port: ", device) self.removed_midi_devices.append(device) self.piano_change_signal.emit('OFF') for device in current_midi_devices: if device not in self.old_midi_devices: print("Added MIDI port: ", device) self.added_midi_devices.append(device) self.piano_change_signal.emit('ON') self.old_midi_devices = current_midi_devices def run(self): print("DEVICE EVENT DETECTOR ENABLED") self.old_serial_devices = self.enumerate_serial_devices() self.added_serial_devices = [] self.removed_serial_devices = [] self.midiout = rtmidi.MidiOut() self.old_midi_devices = self.enumerate_midi_devices() self.added_midi_devices = [] self.removed_midi_devices = [] while True: self.check_device_changes() time.sleep(0.5) #------------------------------------------------------------------------------- # Main Code if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) detector = DeviceDetector() detector.start() sys.exit(app.exec_())
988,457
90f4bad1fd73fb63118fe388d1e680057e06e85b
#NAME: # Board.py # #PURPOSE: # To organize and manage the data of a Sudoku game board. The Board class # represents the Sudoku game board as a 9x9 array of Cell objects. # #INPUTS: # In order to properly function, the Cell class must be imported, along with # copy and random packages. # #CALLING SEQUENCE: # The Board class only needs to be imported to be used. from Cell import Cell import copy, random class Board(): def __init__(self): self.cells = [[Cell() for row in range(9)] for col in range(9)] self.cell_list = [] self.master = [None] * 81 # Create the associations between each cell and it's peers for row in range(9): for col in range(9): self.cell_list.extend([self.cells[row][col]]) for index in range(9): if index != row: self.cells[row][col].peers.extend([self.cells[index][col]]) if index != col: self.cells[row][col].peers.extend([self.cells[row][index]]) for box_row in range(row - (row % 3), row - (row % 3) + 3): for box_col in range(col - (col % 3), col - (col % 3) + 3): if box_row != row and box_col != col: self.cells[row][col].peers.extend([self.cells[box_row][box_col]]) # Fix designates cells containing nonzero values as fixed def fix(self): for row in range(9): for col in range(9): if self.cells[row][col].value > 0: self.cells[row][col].fixed = True # Use a depth-first recursive search algorithm to exhaustively try # every possible combination of possible solutions given the current arrangement # of fixed values on the game board. def solve(self, depth): if depth == 81: self.master = self.solution() return True cell = self.cell_list[depth] if cell.fixed: return self.solve(depth + 1) cell.revise() while cell.possible: possible_value = random.choice(cell.possible) cell.value = possible_value cell.possible.remove(possible_value) if self.solve(depth + 1): return True cell.value = 0 return False # Erase a variable number of randomly selected cells, # depending on the provided difficulty. Checke for uniqueness # prior to erasing the cell value def conceal(self, difficulty): self.fix() for cell in random.sample(self.cell_list, difficulty): if self.is_unique(cell): cell.value = 0 cell.fixed = False # Test whether or not erasing the provided cell will preserve the uniqueness # of the solution to the remaining puzzle. def is_unique(self, cell): cell.revise() for possible_value in cell.possible: if possible_value != cell.value: save = cell.value cell.value = possible_value result = copy.deepcopy(self).solve(depth = 0) cell.value = save if result: return False return True # Make a master solution key from the completed board. def solution(self): master = list() for cell in self.cell_list: master.append(cell.value) return master # Check the current board against the master solution key. def is_complete(self): for index in range(81): if self.cell_list[index].value != self.master[index]: return False return True
988,458
2b63a6d9c70755a081c9125ad5fe815eb540e41e
# from urllib.parse import quote # from django.core.urlresolvers import reverse # from django.core.exceptions import ObjectDoesNotExist # from django.test import TestCase, Client # # from ..models import User # # # class UserViewsTests(TestCase): # def setUp(self): # self.password = 'mypassword' # # self.admin_user = User.objects.create_superuser( # 'admin', 'admin@test.com', 'Administrator', self.password) # self.user = User.objects.create_user('normal-user', 'user@test.com', # 'Normal User', self.password) # # def test_login_logout(self): # # testing login # client = Client() # result = client.login(username='normal-user', password=self.password) # self.assertEqual(result, True) # # # testing logout # client.logout() # self.assertEqual(client.session, {}) # # def test_user_redirect_view_not_logged(self): # client = Client() # response = client.get(reverse('users:redirect'), follow=True) # self.assertRedirects( # response, # '%s?next=%s' % (reverse('users:login'), # quote(reverse('users:redirect'))), # status_code=302, # target_status_code=200) # # def test_user_redirect_view_logged_in(self): # client = Client() # client.login(username='normal-user', password=self.password) # # response = client.get(reverse('users:redirect'), follow=True) # self.assertRedirects( # response, # reverse('users:detail', kwargs={'username': 'normal-user'}), # status_code=302, # target_status_code=200) # # def test_user_update_view_change_fields(self): # """ # Checks if all fields are saved when changed. # """ # client = Client() # client.login(username=self.user.username, password=self.password) # # response = client.post( # reverse('users:update'), # { # 'username': 'normal-user-renamed', # 'email': 'newmail@test.com', # 'password1': 'mynewpassword', # 'password2': 'mynewpassword', # }, # follow=True, # ) # # # Check if view got redirected to user profile # self.assertRedirects( # response, # reverse('users:detail', kwargs={'username': 'normal-user-renamed'}), # status_code=302, # target_status_code=200) # # # user got renamed, so there it should not return user with old username # with self.assertRaises(ObjectDoesNotExist): # User.objects.get(username='normal-user') # # # load renamed user # updated_user = User.objects.get(username='normal-user-renamed') # # # Check if new password got saved # self.assertEqual(updated_user.check_password('mynewpassword'), True) # # # Check if new email got saved # self.assertEqual(updated_user.email, 'newmail@test.com') # # def test_user_update_view_no_changes(self): # """ # Checks if fields stay same when we don't change values. # """ # client = Client() # client.login(username=self.user.username, password=self.password) # # response = client.post( # reverse('users:update'), # { # 'username': 'normal-user', # 'email': 'user@test.com', # }, # follow=True, # ) # # # Check if view got redirected to user profile # self.assertRedirects( # response, # reverse('users:detail', kwargs={'username': 'normal-user'}), # status_code=302, # target_status_code=200) # # # load user # updated_user = User.objects.get(username='normal-user') # # # Check if email is still same # self.assertEqual(updated_user.email, 'user@test.com') # # # Check if password is still same # self.assertEqual(updated_user.check_password('mypassword'), True) # # def test_user_update_view_not_matching_password(self): # """ # Checks if two different password will raise error. # """ # client = Client() # client.login(username=self.user.username, password=self.password) # from django.template.response import SimpleTemplateResponse # response_class = SimpleTemplateResponse # # response = client.post( # reverse('users:update'), # { # 'username': 'normal-user', # 'email': 'user@test.com', # 'password1': 'mynewpassword', # 'password2': 'mynewpassword-not-same', # }, # follow=True, # ) # # # For following to work properly TEMPLATE_DEBUG has to be True if using # # jingo. # self.assertFormError(response, 'form', 'password2', # 'Passwords do not match.') # # def test_user_update_view_already_registered_email(self): # """ # Checks if already registered email by different user will raise error. # """ # client = Client() # client.login(username=self.user.username, password=self.password) # # response = client.post( # reverse('users:update'), # { # 'username': 'normal-user', # 'email': 'admin@test.com', # }, # follow=True, # ) # # self.assertFormError(response, 'form', 'email', # 'This email is already registered.')
988,459
deda5609f81313e92d98d632cf5ec9ef7c2c23db
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: root # @Date: 2015-08-25 15:44:32 # @Last Modified by: lancezhange # @Last Modified time: 2015-08-26 14:59:21 import cv2 import numpy as np import logging import logging.config from array import array logging.config.fileConfig("logger.conf") logger = logging.getLogger("smoke_logger") orb = cv2.ORB_create(1000) image_path = 'image_train/smoke/building_smoke_0015.jpg' def getFeature(image_path): global feature img0 = cv2.imread(image_path) if img0 is None: logger.info("not valid image path %s" % image_path) return np.empty(0) else: img = cv2.cvtColor(img0, cv2.COLOR_RGB2GRAY) kp = orb.detect(img, None) kp, des = orb.compute(img, kp) if des is None: return np.empty(0) else: feature.append(i for i in des.tolist()) getFeature(image_path) # 计算每个关键点的描述 kp, des = orb.compute(img, kp) if(os.path.isfile(image_path)): feature = process_image_file(image_path, feature.getFeature) proba = classifier.predict_proba(feature) logger.info("feature: %s", feature) logger.info(os.path.basename(image_path) + " is 1 with proba %f" % proba[0][1]) elif os.path.isdir(image_path): file_count = 0 positive_count = 0 for root, _, files in os.walk(image_path): for file_name in files: file_count = file_count + 1 file_path = os.path.join(root, file_name) proba = classifier.predict_proba( process_image_file(file_path, feature.getFeature)) logger.info(os.path.basename(file_path) + " is 1 with proba %f" % proba[0][1]) if(proba[0][1] > threshold): positive_count = positive_count + 1 logger.info("%d be positive in total %d images" % ( positive_count, file_count))
988,460
a4f21d29dd199869a89abf032a50f9433a353f4c
import re from glob import glob def parseTexts(fileglob='G:/TEC/tablas1/*txt'): texts, words = {}, set() documento_t = {} for txtFile in glob(fileglob): with open(txtFile, 'r') as f: txt = re.findall(r'([-À-ÿa-zA-Z0-9]+)',f.read().lower()) words |= set(txt) docId = txtFile.split('\\')[-1] documento_t[docId] = txtFile texts[docId] = txt return documento_t, texts, sorted(words)
988,461
d30bf02a37c4149de62912963f36d9827574af1c
from rest_framework import viewsets, serializers from profiles.models import GigPoster, GigSeeker # serializers class GigPosterSerializer(serializers.ModelSerializer): class Meta: model = GigPoster class GigSeekerSerializer(serializers.ModelSerializer): class Meta: model = GigSeeker # viewsets class GigPosterViewSet(viewsets.ModelViewSet): queryset = GigPoster.objects.all() serializer_class = GigPosterSerializer class GigSeekerViewSet(viewsets.ModelViewSet): queryset = GigSeeker.objects.all() serializer_class = GigSeekerSerializer
988,462
de21b931e141e8b52418bee944203c129cda66c8
# -*- coding: utf-8 -*- aliceblue=(240,248,255) antiquewhite=(250,235,215) aqua=(0,255,255) aquamarine=(127,255,212) azure=(240,255,255) beige=(245,245,220) bisque=(255,228,196) black=(0,0,0) blanchedalmond=(255,235,205) blue=( 0,0,255) blueviolet=( 138,43,226) brown=( 165,42,42) burlywood=( 222,184,135) cadetblue=( 95,158,160) chartreuse=( 127,255,0) chocolate=( 210,105,30) coral=( 255,127,80) cornflowerblue=( 100,149,237) cornsilk=( 255,248,220) crimson=( 220,20,60) cyan=( 0,255,255) darkblue=( 0,0,139) darkcyan=( 0,139,139) darkgoldenrod=( 184,134,11) darkgray=( 169,169,169) darkgreen=( 0,100,0) darkgrey=( 169,169,169) darkkhaki=( 189,183,107) darkmagenta=( 139,0,139) darkolivegreen=( 85,107,47) darkorange=( 255,140,0) darkorchid=( 153,50,204) darkred=( 139,0,0) darksalmon=( 233,150,122) darkseagreen=( 143,188,143) darkslateblue=( 72,61,139) darkslategrey=( 47,79,79) darkturquoise=( 0,206,209) darkviolet=( 148,0,211) deeppink=( 255,20,147) deepskyblue=( 0,191,255) dimgrey=( 105,105,105) dodgerblue=( 30,144,255) firebrick=( 178,34,34) floralwhite=( 255,250,240) forestgreen=( 34,139,34) fuchsia=( 255,0,255) gainsboro=( 220,220,220) ghostwhite=(248,248,255) gold=( 255,215,0) goldenrod=( 218,165,32) gray=( 128,128,128) green=( 0,128,0) greenyellow=( 173,255,47) grey=( 128,128,128) honeydew=( 240,255,240) hotpink=( 255,105,180) indianred=( 205,92,92) indigo=( 75,0,130) ivory=( 255,255,240) khaki=( 240,230,140) lavender=( 230,230,250) lavenderblush=( 255,240,245) lawngreen=( 124,252,0) lemonchiffon=( 255,250,205) lightblue=( 173,216,230) lightcoral=( 240,128,128) lightcyan=( 224,255,255) lightgoldenrodyellow=( 250,250,210) lightgray=( 211,211,211) lightgreen=( 144,238,144) lightgrey=( 211,211,211) lightpink=( 255,182,193) lightsalmon=( 255,160,122) lightseagreen=( 32,178,170) lightskyblue=( 135,206,250) lightslategrey=( 119,136,153) lightsteelblue=( 176,196,222) lightyellow=( 255,255,224) lime=( 0,255,0) limegreen=( 50,205,50) linen=( 250,240,230) magenta=( 255,0,255) maroon=( 128,0,0) mediumaquamarine=( 102,205,170) mediumblue=( 0,0,205) mediumorchid=( 186,85,211) mediumpurple=( 147,112,219) mediumseagreen=( 60,179,113) mediumslateblue=( 123,104,238) mediumspringgreen=( 0,250,154) mediumturquoise=( 72,209,204) mediumvioletred=( 199,21,133) midnightblue=( 25,25,112) mintcream=( 245,255,250) mistyrose=( 255,228,225) moccasin=( 255,228,181) navajowhite=( 255,222,173) navy=( 0,0,128) oldlace=( 253,245,230) olive=( 128,128,0) olivedrab=( 107,142,35) orange=( 255,165,0) orangered=( 255,69,0) orchid=( 218,112,214) palegoldenrod=( 238,232,170) palegreen=( 152,251,152) paleturquoise=( 175,238,238) palevioletred=( 219,112,147) papayawhip=( 255,239,213) peachpuff=( 255,218,185) peru=( 205,133,63) pink=( 255,192,203) plum=( 221,160,221) powderblue=( 176,224,230) purple=( 128,0,128) red=( 255,0,0) rosybrown=( 188,143,143) royalblue=( 65,105,225) saddlebrown=( 139,69,19) salmon=( 250,128,114) sandybrown=( 244,164,96) seagreen=( 46,139,87) seashell=( 255,245,238) sienna=( 160,82,45) silver=( 192,192,192) skyblue=( 135,206,235) slateblue=( 106,90,205) slategrey=( 112,128,144) snow=( 255,250,250) springgreen=( 0,255,127) steelblue=( 70,130,180) tan=( 210,180,140) teal=( 0,128,128) thistle=( 216,191,216) tomato=( 255,99,71) turquoise=( 64,224,208) violet=( 238,130,238) wheat=( 245,222,179) white=( 255,255,255) whitesmoke=( 245,245,245) yellow=( 255,255,0) yellowgreen=( 154,205,50)
988,463
20a9393fd51e68efff51dc2e5ed3aa3179324ec9
# Generated by Django 3.0.8 on 2020-07-31 04:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gestor_general', '0003_auto_20200731_0106'), ] operations = [ migrations.RenameField( model_name='ansewer_post', old_name='id_dad', new_name='id_create', ), ]
988,464
3d738de7c59a05e8083186aafefdceaf40493506
#!/usr/bin/env python # -*- coding: utf-8 -*- from os.path import expanduser from workWithModule import workWithModule from basicCommands import basicCommands from Googletts import tts import xml.etree.ElementTree as ET import os, gettext, time, sys, subprocess # Permet d'exécuter la commande associée à un mot prononcé class stringParser(): """ @description: This class parses the text retrieve by Google in order to distinguish external commands, internal commands and modules """ def __init__(self,text,File,PID): # read configuration files self.pid=PID try: max = 0 text=text.lower() tree = ET.parse(File) root = tree.getroot() tp = '' # si le mode dictée est activé if os.path.exists('/tmp/g2u_dictation'): for entry in root.findall('entry'): if entry.get('name') == _('internal') and entry.find('command').text == unicode(_('exit dictation mode'),"utf8"): score = 0 Type=entry.get('name') Key=entry.find('key').text Command=entry.find('command').text key=Key.split(' ') for j in range(len(key)): score += text.count(key[j]) if score == len(key): do = Command tp = Type else: do = text else: for entry in root.findall('entry'): score = 0 Type=entry.get('name') Key=entry.find('key').text Command=entry.find('command').text key=Key.split(' ') for j in range(len(key)): score += text.count(key[j]) if max < score: max = score do = Command tp = Type # on regarde si la commande fait appel à un module # si oui, alors on lui passe en paramètre les dernier mots prononcé # ex: si on prononce "quelle est la météo à Paris" # la ligne de configuration dans le fichier est: [q/Q]uelle*météo=/modules/weather/weather.sh # on coupe donc l'action suivant '/' do = do.encode('utf8') tp = tp.encode('utf8') print tp, do os.system('echo "'+do+'" > /tmp/g2u_cmd_'+self.pid) if _('modules') in tp: check = do.split('/') # si on trouve le mot "modules", on instancie une classe workWithModule et on lui passe # le dossier ie weather, search,...; le nom du module ie weather.sh, search.sh et le texte prononcé wm = workWithModule(check[0],check[1],text,self.pid) elif _('internal') in tp: # on execute une commande intene, la commande est configurée # ainsi interne/batterie, on envoie batterie à la fonction b = basicCommands(do,self.pid) elif _('external') in tp: os.system(do) else: os.system('xdotool type "'+do+'"') os.system('> /tmp/g2u_stop_'+self.pid) except Exception as e: message = _('Setup file missing') os.system('echo "'+message+'" > /tmp/g2u_error_'+self.pid) sys.exit(1)
988,465
855f7302dbb2bd76ce17f299df090a3fb9f31008
# Generated by Django 3.0.8 on 2020-08-12 22:46 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('data', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='customer', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='appstorereview', name='app', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='data.App'), ), migrations.AddField( model_name='app', name='similar', field=models.ManyToManyField(blank=True, related_name='_app_similar_+', to='data.App'), ), migrations.AlterUniqueTogether( name='app', unique_together={('appid', 'primaryCountry')}, ), ]
988,466
960f40ac05845aafde22b636311a3c2186fbd44f
from typing import Generator from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.config import settings from typing import Generator # # For PostgreSQL # SQLALCHEMY_DATABASE_URL = settings.POSTGRES_URL # engine = create_engine(SQLALCHEMY_DATABASE_URL) # For SQLite SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) SessionLocal = sessionmaker(autocommit=False, autoflush=False,bind=engine) def get_db() -> Generator: try: db = SessionLocal() yield db finally: db.close()
988,467
713730a20f151adf26f22c698a1e76bb4ea4537b
#! /usr/bin/python #k-means clustering is a method of vector quantization, #originally from signal processing, that is popular for cluster #analysis in data mining. k-means clustering aims to partition n #observations into k clusters in which each observation belongs #to the cluster with the nearest mean, serving as a #prototype of the cluster. #INSTRUCTION # #RUN: #"python kmeans.py" #open *.png and slide down to view the changes # #VIEW RESULT WITH GNUPLOT #gnuplot %one_name_of_the_file_with_cmd_extension% #e.g "gnuplot clustering_003_009.cmd" # #ERROR PLOT #run: python kmeans.py > error #open gnuplot #run: plot "error" w l import random import math import subprocess dimensions = 2 clouds = 5 #centers = [[random.uniform(-1.0, 1.0) for j in range(dimensions)] for c in range(clouds)] centers = [ [1.0, -1.0], [-1.0, 1.0], [1.0, 1.0], [-1.0, -1.0] ] #sigma parameter control the spread of each cluster sigma = .4 #numer of points n = 1000 #costant for the push of the prototype eta = .5 #we use matrix ETA to describe correlation between the prototypes #ETA[i,j] == 1 if i == j #ETA[i,j] == 0.5 if i is correlated to j #ETA[i,j] == 0 if i doesn't have relationship with j ETA = [ [1.0, 0.5, 0.5, 0.0], [0.5, 1.0, 0.0, 0.5], [0.5, 0.0, 1.0, 0.0], [0.0, 0.5, 0.5, 1.0] ] #number of prototype (exactly the number of ETA column / rows) K = 4 #function that given a point and a list of prototype give as output the index of the closest #prototype for this point and also the corresponding square of its distance def closest_prototype_index(point, mu): #intial min distance = huge number min_distance = 1.0e30 min_c = 1.0e30 for c in range(len(mu)): dist = 0.0 for i in range(len(point)): d = point[i] - mu[c][i] dist += d * d if dist < min_distance: min_distance = dist min_c = c return min_c, min_distance #create random points m = len(centers[0]) points = [] for i in range(n): c = random.randint(0, len(centers) - 1) points.append ([random.gauss (centers[c][j], sigma) for j in range(m)]) #print '\n'.join('\t'.join(str(v) for v in point) for point in points) #reperat the clustering procedure K_max times (inclusive) mu = [] for j in range(K): i = random.randint(0, n-1) mu.append(list(points[i])) for iteration in range(1000): #select random point in dataset i = random.randint(0, n-1) #find index of th closest prototype with the function point = points[i] c = closest_prototype_index(point, mu)[0] # for c1 in range(K): #foreach coordinates in my point move them towards the selected point #based on constant and ETA that is the correlation matrix for j in range(m): mu[c][j] += eta * ETA[c][c1] * (point[j] - mu[c][j]) if iteration % 10 == 0: #output result in a file to plot (concat iteration) f = open("clustering", "w") #foreach point write cluster and coordinates for i in range(n): f.write ("c%d %s\n" % (closest_prototype_index(points[i], mu)[0], ' '.join(str(v) for v in points[i]))); #scac cluster index for c in range(K): f.write("p%d %s\n" % (c, ' '.join(str(v) for v in mu[c]))) f.close() #write a file with the pair of every point correlated (based on ETA) f = open('lines', 'w') for i in range(K): for j in range(i): if ETA[i][j] > 0.0: f.write ('%f %f\n%f %f\n\n' % (mu[i][0], mu[i][1], mu[j][0], mu[j][1])) f.close() #create command file for gnuplot f = open("clustering.cmd", "w") f.write("set term png\nset output \"%03d.png\"\nplot " % iteration + ','.join('"<grep c%d clustering" using 2:3 title "Cluster %d"' % (c, c) for c in range(K)) + ',' + ','.join('"<grep p%d clustering" using 2:3 title "Prototype %d" ps 10' % (c, c) for c in range(K)) + ', "lines" with lines linetype 1' ) f.close() #call gnuplot with parameter our file subprocess.call(['gnuplot', 'clustering.cmd']) #cluster = [closest_prototype_index(point, mu)[0] for point in points] #at the end of clustering procedure compute the quantization error E = 0.0 for point in points: E += closest_prototype_index(point, mu)[1] print "%d %f" % (K, math.sqrt(E/n))
988,468
d4842bf5d1f69425080dc5b39f090a4c64f0bfd7
import pdb import uuid import json import base64 import logging from django.conf import settings from django.core.files.base import ContentFile from django.db.models import F from django.shortcuts import render from models import Card, ShareText, CardList from users.models import UserProfile from django.http import JsonResponse from django.utils.decorators import decorator_from_middleware_with_args, decorator_from_middleware from users.middleware import TokenCheck from django.views.decorators.cache import cache_page from django.core.cache import cache import urllib2 check_token = decorator_from_middleware(TokenCheck) logger = logging.getLogger(__name__) """ Token authentication must be in the form Authorization:9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Status codes 400 = Bad request 404 = Not Found 403 = Forbidden 405 = Not Allowed """ class HttpTable(object): get = 'GET' post = 'POST' put = 'PUT' delete = 'DELETE' def my_response(data={},success=False,reason='Failed request',status_code=200): if status_code == 404: reason = 'Object not found - %s' % reason if status_code == 200 or status_code == 201: reason = '' message = {} message['success'] = success message['reason'] = reason if data: message['data'] = data response = JsonResponse(message) response.status_code = status_code return response def get_cached_cards(request): query = request.GET.get('q',None) query = query.replace(' ','-') if query: cards = cache.get(query) if cards < 1: cache.delete(query) return else: return cards def cache_cards_page(request,data,expires=60*60): query = request.GET.get('q',None) query = query.replace(' ','-') if query: cache.set(query,data,expires) #cache for 1 hour @check_token def show_cards(request): message = {'success':False} status_code = 200 http_method = HttpTable.get query = request.GET.get('q',None) uuid = request.GET.get('uuid',None) # first check cache cached_cards = get_cached_cards(request) if cached_cards: if str(cached_cards['uuid']) == uuid: reason = "No new data for this category" return my_response(reason=reason,status_code=222) return my_response(cached_cards,success=True) # Only get requests if request.method == http_method: #get limit and offset from client if there limit = request.GET.get('limit',None) offset = request.GET.get('offset',None) # Off for now limit = None offset = None newOffset = None if limit and offset: #if we have limi and offset convert them to ints offset = int(offset) limit = int(limit) temp_limit = offset + limit # try getting cards try: logger.debug('trying list for query %s' % query) category = CardList.objects.select_related().get(name=query) logger.debug('got list for query %s' % query) # check for uuid to see if we need to return new data or nothing if uuid: if uuid == str(category.uuid): reason = "No new data for this category" return my_response(reason=reason,status_code=222) all_cards = category.cards.all()[offset:temp_limit] if all_cards: # only return this if we have data so client knows to stop fetching newOffset = int(limit) + int(offset) except CardList.DoesNotExist: logger.debug('list doesnt exist for query %s' % query) reason = "CardList object does not exist" return my_response(reason=reason,status_code=400) else: # if no limit or offset just return the last 100 objects max try: logger.debug('trying list for query %s' % query) category = CardList.objects.select_related().get(name=query) logger.debug('got list for query %s' % query) # check for uuid to see if we need to return new data or nothing if uuid: if uuid == str(category.uuid): reason = "No new data for this category" return my_response(reason=reason,status_code=222) all_cards = category.cards.all()[:100] except CardList.DoesNotExist: logger.debug('list doesnt exist for query %s' % query) reason = "CardList object does not exist" return my_response(reason=reason,status_code=400) logger.debug('returning %s cards' % all_cards.count()) cards = CardList.queryset_to_dict(all_cards) message['cards'] = cards message['uuid'] = str(category.uuid) cache_cards_page(request,message,60*10) if newOffset: message['next_offset'] = str(newOffset) message['next_limit'] = str(limit) del message['success'] return my_response(message,success=True) reason = "Only '%s' to this endpoint" % http_method return my_response(reason=reason,status_code=405) @check_token def update_card(request,id): message = {'success':False} http_method = HttpTable.put if request.method == http_method: data = json.loads(request.body,strict=False) card = Card.objects.filter(id=id)[0] if not card: return my_response(status_code=404) for key, value in data.iteritems(): setattr(card,key,value) card.save() return my_response(success=True) reason = "Only '%s' to this endpoint" % http_method return my_response(reason=reason,status_code=405) @cache_page(60*10) @check_token def view_card(request,id): message = {} if request.method == HttpTable.get: try: card = Card.objects.get(id=id) except Card.DoesNotExist: return my_response(status_code=404) message['card'] = card.to_dict() return my_response(message,success=True) reason = "Only '%s' to this endpoint" % HttpTable.get return my_response(reason=reason,status_code=405) @check_token def card_vote(request,id,vote): message = {'success':False} http_method = HttpTable.post if request.method == http_method: try: card = Card.objects.get(id=id) except Card.DoesNotExist: return my_response(status_code=404) if int(vote) == 1: # update left count card.left_votes_count = F('left_votes_count') + 1 card.save() elif int(vote) == 2: #update right count card.right_votes_count = F('right_votes_count') + 1 card.save() else: reason = "'%s' vote either isnt 1 or 2 or isnt in the right format" % vote return my_response(reason=reason,status_code=400) message['success'] = True return my_response(success=True) reason = "Only '%s' to this endpoint" % http_method return my_response(reason=reason,status_code=405) @check_token def delete_card(request,id): message = {'success':False} http_method = HttpTable.delete if request.method == http_method: try: card = Card.objects.get(id=id) except Card.DoesNotExist: return my_response(status_code=404) card.delete() return my_response(success=True) reason = "Only '%s' to this endpoint" % http_method return my_response(reason=reason,status_code=405) @check_token def create_card(request): message = {'success':False} http_method = HttpTable.post if request.method == http_method: params = ['facebook_id','image','question','question_type'] data = json.loads(request.body,strict=False) for name in params: if name not in data.keys(): message['reason'] = 'Missing %s param' % name logger.debug(message['reason']) response = JsonResponse(message) response.status_code = 400 return response facebook_id = data['facebook_id'] imageData = data['image'] question = data['question'] question_type = data['question_type'] creator_name = data.get('creator_name',None) if question_type != settings.QUESTION_TYPE_A_B and question_type != settings.QUESTION_TYPE_YES_NO: logger.debug('Not a valid questin type when creating card') return my_response(reason='Not valid question type. 100 or 101',status_code=400) user = None #see if we need to get or create fake user first if creator_name: logger.debug('creating fake user') user, created = UserProfile.objects.get_or_create(username=creator_name) if created: # get last user's facebook id and increment it to add to fake user last_user = UserProfile.objects.last() last_id = last_user.id * 100 user.facebook_id = last_id user.fake_user = True user.email = "%s@aol.com" % last_id user.save() logger.debug('new fake user created %s' % creator_name) if not user: try: user = UserProfile.objects.get(facebook_id=facebook_id) except UserProfile.MultipleObjectsReturned: user = UserProfile.objects.filter(facebook_id=facebook_id)[0] except UserProfile.DoesNotExist: reason = 'fb id:%s user doesnt exist' % facebook_id return my_response(reason=reason,status_code=404) image = base64.b64decode(imageData) randomNumbers = str(uuid.uuid4())[:10] imagename = '%s-%s.jpg' % (user.username,randomNumbers) card = Card() card.user = user card.question = question card.question_type = question_type card.image.save(imagename,ContentFile(image)) card.fake_votes(save=False,notify=False) if not creator_name and not user.is_staff: card.created_by = Card.COMMUNITY_CREATED card.save() message['card'] = card.to_dict(); return my_response(message,success=True,status_code=201) reason = "Only '%s' to this endpoint" % http_method return my_response(reason=reason,status_code=405) def cards(request): message = {'success':False} if request.method == HttpTable.get: # get all cards return show_cards(request) elif request.method == HttpTable.post: # create card return create_card(request) else: reason = "Invalid http method (GET or POST)" return my_response(reason=reason,status_code=405) def cards_object(request,id): if request.method == HttpTable.delete: # delete card with id return delete_card(request,id) elif request.method == HttpTable.put: # update card with id return update_card(request,id) elif request.method == HttpTable.get: # view card with id return view_card(request,id) else: reason = "Invalid http method (DELETE or PUT, GET)" return my_response(reason=reason,status_code=405) @check_token def share_text(request): message = {} if request.method == HttpTable.get: message['share_text'] = ShareText.get_lastest_share_text() return my_response(message,success=True) reason = "Only '%s' to this endpoint" % HttpTable.get return my_response(reason=reason,status_code=405) @check_token def lists(request): message = {} if request.method == HttpTable.get: lists = CardList.objects.filter(approved=True).order_by('id') message['lists'] = CardList.queryset_to_dict(lists) return my_response(message,success=True) reason = "Only '%s' to this endpoint" % HttpTable.get return my_response(reason=reason,status_code=405)
988,469
e6bff741c074db80c0d1539bd48583284e392e6d
from django.db import models # Create your models here. class Home(models.Model): title=models.CharField(max_length=50) description=models.CharField(max_length=100) Tech=models.CharField(max_length=50) image=models.ImageField(upload_to='home') project_link = models.URLField(max_length=100) github_link = models.URLField(max_length=100) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='home' verbose_name_plural='houses' def __srt__(self): return self.title()
988,470
a37fcc090e40b7341fb75f620d92e8ef98f2e7be
class SegmentTreeNode: def __init__(self, start, end) -> None: self.start = start self.end = end self.left :'SegmentTreeNode' = None self.right :'SegmentTreeNode' = None self.val = None class SegmentTree: def __init__(self, seq) -> None: self._seq = seq self._root = self._build_tree(0, len(self._seq) - 1) def _build_tree(self, start, end): if start > end: return None if start == end: root = SegmentTreeNode(start, end) root.val = self._seq[start] return root mid = (start + end) // 2 left_node = self._build_tree(start, mid) right_node = self._build_tree(mid + 1, end) root = SegmentTreeNode(start, end) root.left = left_node root.right = right_node root.val = min(root.left.val, root.right.val) return root def _query(self, root: SegmentTreeNode, start, end): if start == root.start and end == root.end: return root.val left = root.left right = root.right if start > left.end: return self._query(right, start, end) if end < right.start: return self._query(left, start, end) lv = self._query(left, start, left.end) rv = self._query(right, right.start, end) return min(lv, rv) def query(self, start, end): return self._query(self._root, start, end) def _update(self, root: SegmentTreeNode, i, val): if root.start == root.end == i: root.val = val return l, r = root.left, root.right if i <= l.end: self._update(l, i, val) else: self._update(r, i, val) root.val = min(root.left.val, root.right.val) def update(self, i, val): self._update(self._root, i, val) class ArrayVirtualNode: def __init__(self, index, start, end) -> None: self.index :int = index self.start :int = start self.end :int = end self.mid = (start + end) // 2 self.left_index = 2 * index + 1 self.right_index = 2 * index + 2 @property def left(self) -> 'ArrayVirtualNode': return ArrayVirtualNode(2 * self.index + 1, self.start, (self.start + self.end) // 2) @property def right(self) -> 'ArrayVirtualNode': return ArrayVirtualNode(2 * self.index + 2, (self.start + self.end) // 2 + 1, self.end) class SegmentTreeWithArray: def __init__(self, arr) -> None: self.size = len(arr) self.tree = [0] * (4 * self.size) self.arr = arr self.root = ArrayVirtualNode(0, 0, self.size - 1) self._build_tree(self.root) del self.arr def _build_tree(self, root: ArrayVirtualNode): if root.start == root.end: self.tree[root.index] = self.arr[root.start] return l, r = root.left, root.right self._build_tree(l) self._build_tree(r) self.tree[root.index] = min(self.tree[l.index], self.tree[r.index]) def _query(self, root: ArrayVirtualNode, start, end): if root.start == start and root.end == end: return self.tree[root.index] l, r = root.left, root.right if start > l.end: return self._query(r, start, end) if end <= l.end: return self._query(l, start, end) lv = self._query(l, start, l.end) rv = self._query(r, r.start, end) return min(lv, rv) def query(self, start, end): return self._query(self.root, start, end) def _update(self, root: ArrayVirtualNode, i, val): if root.start == root.end == i: self.tree[root.index] = val return l, r = root.left, root.right if i <= l.end: self._update(l, i, val) else: self._update(r, i, val) self.tree[root.index] = min(self.tree[l.index], self.tree[r.index]) def update(self, i, val): self._update(self.root, i, val) def main(): seq = list(range(20)) print('seq', seq) seg_tree = SegmentTreeWithArray(seq) m = seg_tree.query(0, 6) print(m) seg_tree.update(5, -1) print(seg_tree.query(0, 6)) main()
988,471
9a6670eb9c401fac00f7bfb56167499c6f04540b
# Copyright 2011 the original author or authors. # # 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 org.vertx.java.core.streams.Pump from core.handlers import BufferHandler, NullDoneHandler, ExceptionHandler __author__ = "Scott Horn" __email__ = "scott@hornmicro.com" __credits__ = "Based entirely on work by Tim Fox http://tfox.org" class ExceptionSupport(object): def exception_handler(self, handler): """Set an execption handler on the stream. Keyword arguments: @param handler: The exception handler """ self.java_obj.exceptionHandler(ExceptionHandler(handler)) return self class DrainSupport(object): def set_write_queue_max_size(self, size): """Set the maximum size of the write queue. You will still be able to write to the stream even if there is more data than this in the write queue. This is used as an indicator by classes such as to provide flow control. Keyword arguments: @param size: The maximum size, in bytes. """ self.java_obj.setWriteQueueMaxSize(size) return self def get_write_queue_max_size(self): return self.java_obj.getWriteQueueMaxSize() write_queue_max_size = property(get_write_queue_max_size, set_write_queue_max_size) @property def write_queue_full(self): """Is the write queue full? return True if there are more bytes in the write queue than the max write queue size. """ return self.java_obj.writeQueueFull() def drain_handler(self, handler): """Set a drain handler on the stream. If the write queue is full, then the handler will be called when the write queue has been reduced to maxSize / 2. See for an example of this being used. Keyword arguments: @param handler: The drain handler """ self.java_obj.drainHandler(NullDoneHandler(handler)) return self class WriteStream(DrainSupport, ExceptionSupport, object): """ A mixin class which represents a stream of data that can be written to. Any class that mixes in this class can be used by a to pump data from a to it. """ def write(self, buff): """Write some data to the stream. The data is put on an internal write queue, and the write actually happens asynchronously. To avoid running out of memory by putting too much on the write queue, check the method before writing. This is done automatically if using a . param [Buffer]. The buffer to write. """ self.java_obj.write(buff._to_java_buffer()) return self def _to_write_stream(self): return self.java_obj class ReadSupport(ExceptionHandler, object): def data_handler(self, handler): """Set a data handler. As data is read, the handler will be called with the data. Keyword arguments: @param handler: The data handler """ self.java_obj.dataHandler(handler) return self def pause(self): """Pause the ReadStream. After calling this, the ReadStream will aim to send no more data to the """ self.java_obj.pause() return self def resume(self): """Resume reading. If the ReadStream has been paused, reading will recommence on it.""" self.java_obj.resume() return self class ReadStream(ExceptionSupport, ReadSupport, object): """A mixin class which represents a stream of data that can be read from. Any class that mixes in this class can be used by a to pump data from a to it. """ def data_handler(self, handler): """Set a data handler. As data is read, the handler will be called with the data. Keyword arguments: @param handler: The data handler """ self.java_obj.dataHandler(BufferHandler(handler)) return self def end_handler(self, handler): """Set an end handler on the stream. Once the stream has ended, and there is no more data to be read, this handler will be called. Keyword arguments: @param handler: The exception handler""" self.java_obj.endHandler(NullDoneHandler(handler)) return self def _to_read_stream(self): return self.java_obj class Pump(object): """Pumps data from a ReadStream to a WriteStream and performs flow control where necessary to prevent the write stream from getting overloaded. Instances of this class read bytes from a ReadStream and write them to a WriteStream. If data can be read faster than it can be written this could result in the write queue of the WriteStream growing without bound, eventually causing it to exhaust all available RAM. To prevent this, after each write, instances of this class check whether the write queue of the WriteStream is full, and if so, the ReadStream is paused, and a WriteStreamdrain_handler is set on the WriteStream. When the WriteStream has processed half of its backlog, the drain_handler will be called, which results in the pump resuming the ReadStream. This class can be used to pump from any ReadStream to any WriteStream, e.g. from an HttpServerRequest to an AsyncFile, or from NetSocket to a WebSocket. """ def __init__(self, read_stream, write_stream): #raise "read_stream is not a ReadStream" if !read_stream.is_a? ReadStream #raise "write_stream is not a WriteStream" if !write_stream.is_a? WriteStream self.j_rs = read_stream._to_read_stream() self.j_ws = write_stream._to_write_stream() self.j_pump = org.vertx.java.core.streams.Pump.createPump(self.j_rs, self.j_ws) def set_write_queue_max_size(self, val): """Set the write queue max size Keyword arguments: @param val: The write queue max size """ self.j_pump.setWriteQueueMaxSize(val) return self write_queue_max_size = property(fset=set_write_queue_max_size) def start(self): """Start the Pump. The Pump can be started and stopped multiple times.""" self.j_pump.start() return self def stop(self): """Stop the Pump. The Pump can be started and stopped multiple times.""" self.j_pump.stop() return self @property def bytes_pumped(self): """return the total number of bytes pumped by this pump.""" return self.j_pump.bytesPumped()
988,472
4ee8e9c6b876fe8cb6d07251dd175419a5c2effb
from flask import Flask from flask_cors import CORS from pymongo import MongoClient from cashcog.config import DEBUG, MONGODB_CASHCOG_URI app = Flask(__name__, static_url_path="/static/") CORS(app) app.debug = DEBUG client = MongoClient(MONGODB_CASHCOG_URI) db = client.expenses_db from cashcog.routes import routes
988,473
89f042eca67cdbc4a683dfc67cfd42cddfd5af3e
tF = int(input("t = ")) tC = (tF-32)*5/9 print ("Температура в цельсиях = ",tC)
988,474
31446f6b0b53d409db359e54b00c1cfadd79784f
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 6 05:32:49 2018 @author: yahkun """ from random import randint, sample # 每个字母代表一个球员 data = sample('abcdefg', randint(3, 6)) s1 = {x: randint(1, 4) for x in data} s2 = {x: randint(1, 4) for x in data} s3 = {x: randint(1, 4) for x in data} #方法1 res = [] for k in s1: if k in s2 and k in s3: res.append(k) print(res) #方法2: 使用集合(set)的交集操作 # Step1: 使用字典的 viewkeys() 方法, 得到一个字典keys 的集合 # Step2: 使用 map 函数,得到所有字典的keys的集合 # Step3: 使用 reduce 函数,取所有字典的 keys 的集合的交集 # s1.keys() & s2.keys() & s3.keys() #原理 from functools import reduce res = reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])) print(res)
988,475
20e5a5c1abbc340132daaba27e8772bbdce297d3
# -*- coding: utf-8 -*- from __future__ import unicode_literals import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a) b = a.ravel() print('b', b) c = a.flatten() print('c', c) a *= 10 print('a', a, 'b', b, 'c', c, sep='\n') d = a.reshape(6) print(d) a += 1 print(a, d, sep='\n')
988,476
f25ce7934b600306dabc2549817fffd392d73172
#!/usr/bin/env python import sys from litter import LtrCli if __name__ == "__main__": LtrCli(sys.argv[1:])
988,477
2b758a484f159bf94f03d519925b09f3cf6002ee
import numpy as np import scipy.spatial.distance import scipy.stats as st import matplotlib.pyplot as plt from ..search import get_distributed_recipes from ..search import get_random_recipes def compare_cluster_vs_random(cursor,ingred,metric, num_recipes_list=[10,20,30],num_trials=10, data_dir="/Users/amorten/Projects/" "RecipeSearch/Database/HClusters/"): # Load and convert the saved pdist to squareform. pdist = scipy.spatial.distance.squareform( np.load(data_dir+metric+'/pdist_'+ingred+'.npy',allow_pickle=False) ) # Load the rec_ids that index pdist pdist_rec_ids = np.load(data_dir+metric+'/rec_ids_'+ingred+'.npy',allow_pickle=False).tolist() num_clusters_list = num_recipes_list data_shape = (len(num_recipes_list),num_trials) # collective_distances[][] is a 2d numpy array collective_distances = {'random': {'nearest':np.empty(data_shape), 'average':np.empty(data_shape)}, 'cluster': {'nearest':np.empty(data_shape), 'average':np.empty(data_shape)}} # e.g. collective_distances['random']['nearest'][num_rec_idx,trial_num] # equals the nearest distance between randomly selected recipes # when the number of recipes is num_recipes_list[num_rec_idx] # for trial number trial_num. means = {'random': {'nearest':np.empty(data_shape[0]), 'average':np.empty(data_shape[0])}, 'cluster': {'nearest':np.empty(data_shape[0]), 'average':np.empty(data_shape[0])}} for trial_num in range(num_trials): random_recipes_list = get_random_recipes(cursor,ingred,num_recipes_list) cluster_recipes_list = get_distributed_recipes(ingred,metric,num_clusters_list,data_dir) # might want to find a more Python-fu way to do the following random_collective_distance_list = [ collective_distance(rec_list,pdist,pdist_rec_ids) for rec_list in random_recipes_list ] cluster_collective_distance_list = [ collective_distance(rec_list,pdist,pdist_rec_ids) for rec_list in cluster_recipes_list ] collective_distances['random']['nearest'][:,trial_num] = np.array( [ distance_dict['nearest'] for distance_dict in random_collective_distance_list ] ) collective_distances['cluster']['nearest'][:,trial_num] = np.array( [ distance_dict['nearest'] for distance_dict in cluster_collective_distance_list ] ) collective_distances['random']['average'][:,trial_num] = np.array( [ distance_dict['average'] for distance_dict in random_collective_distance_list ] ) collective_distances['cluster']['average'][:,trial_num] = np.array( [ distance_dict['average'] for distance_dict in cluster_collective_distance_list ] ) #print collective_distances['random']['nearest'] #print collective_distances['cluster']['nearest'] #print collective_distances['random']['average'] #print collective_distances['cluster']['average'] for select_method,distance_method in [(x,y) for x in ['random','cluster'] for y in ['nearest','average']]: means[select_method][distance_method] = ( collective_distances[select_method][distance_method].mean(axis=1)) # I should calculate confidence intervals #conf_intervals[select_method][distance_method] = ( # st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))) #print means label_fontsize = 14 title_fontsize = 18 plt.figure(1,figsize=(15,6)) plt.subplot(1,2,1) plt.title('Recipe distances (smallest of nearest)',fontsize=title_fontsize) plt.plot(num_recipes_list,means['cluster']['nearest'],'bs', label='cluster',linewidth=2) plt.plot(num_recipes_list,means['random']['nearest'],'r^', label='random',linewidth=2) #plt.xscale('log') plt.axis([0,num_recipes_list[-1],0,1.0]) plt.ylabel('smallest of nearest distance',fontsize=label_fontsize) plt.xlabel('number of recipes',fontsize=label_fontsize) plt.legend() plt.subplot(1,2,2) plt.title('Recipe distances (average of nearest)',fontsize=title_fontsize) plt.plot(num_recipes_list,means['cluster']['average'],'bs', label='cluster',linewidth=2) plt.plot(num_recipes_list,means['random']['average'],'r^', label='random',linewidth=2) #plt.xscale('log') plt.axis([0,num_recipes_list[-1],0,1.0]) plt.ylabel('average of nearest distance',fontsize=label_fontsize) plt.xlabel('number of recipes',fontsize=label_fontsize) plt.legend() plt.show() def collective_distance(rec_list,pdist,pdist_rec_ids): rec_list_idxs = [pdist_rec_ids.index(rec_id) for rec_id in rec_list] pdist_slice = pdist[rec_list_idxs,:][:,rec_list_idxs] #print pdist_slice n = pdist_slice.shape[0] pdist_slice[range(n),range(n)] = 1.0 distance_to_nearest_recipe = np.amin(pdist_slice,axis=0) #print {'nearest': np.amin(distance_to_nearest_recipe), # 'average': np.mean(distance_to_nearest_recipe)} return {'nearest': np.amin(distance_to_nearest_recipe), 'average': np.mean(distance_to_nearest_recipe)}
988,478
4cc67c778d8ffb4a5033071cc3f19f34cf5b5629
from abc import ABCMeta, abstractmethod from typing import List from core.customer.domain.customer import Customer from core.customer.domain.customer_id import CustomerId class CustomerRepository(metaclass=ABCMeta): @abstractmethod def find_by_id(self, customer_id: CustomerId) -> Customer: raise NotImplemented() @abstractmethod def store(self, customer: Customer) -> None: raise NotImplemented() @abstractmethod def find_all(self) -> List[Customer]: raise NotImplemented()
988,479
243fa72218e73d8833a69a878ccd4be88fa1af0e
import socket import time import os UDP_MASTER_IP = "192.168.111.101" UDP_MASTER_PORT = 5010 UDP_IP = "192.168.111.100" UDP_PORT = 5006 UDP_IP_RPI = "192.168.111.99" UDP_PORT_RPI = 5009 print "UDP target IP:", UDP_MASTER_IP print "UDP target port:", UDP_MASTER_PORT print "UDP receive IP:", UDP_IP print "UDP receive port:", UDP_PORT sock_master = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock_master.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((UDP_IP, UDP_PORT)) sock_slave = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock_slave.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) for i in range (0,120): sock_slave.sendto("R", (UDP_IP_RPI, UDP_PORT_RPI)) print "Sending receiving ack" filesize= int(sock.recv(1024)) print ("File Size\n",filesize) filename = 'new.jpg' with open(filename,'wb') as f: while (filesize>0): data = sock.recv(1024) filesize -= 1024 f.write(data) filesize = 0 f.close() print ("Successfully got the file") sock_master.sendto("M", (UDP_MASTER_IP, UDP_MASTER_PORT)) st = os.stat(filename) sock_master.sendto(str(st.st_size), (UDP_MASTER_IP, UDP_MASTER_PORT)) file_master = open(filename,'rb') l = file_master.read(1024) while (l): sock_master.sendto(l, (UDP_MASTER_IP, UDP_MASTER_PORT)) l = file_master.read(1024) file_master.close() print("Sent image\n",i) print('Done sending') sock_master.close() sock.close()
988,480
1c7bcd4286dde9628f7ccd81053479d25ecb46f5
pessoa =[] lista = [] maior = menor = 0 continuar = 's' while continuar not in 'Nn': pessoa.append(str(input('Informe o nome : '))) pessoa.append(float(input('Informe o peso : '))) if maior == 0: maior = pessoa[1] menor = pessoa[1] if pessoa[1]>maior: maior = pessoa[1] if pessoa[1] < menor: menor = pessoa[1] lista.append(pessoa [:]) pessoa.clear() continuar = str(input('Continuar [S/N] ? ')) print(f'No total de pessoas cadastradas foi de {len(lista)}') print(f'O maior peso é {maior}, essas pessoas são ',end='') for contador in lista: if contador[1] == maior: print(f'{contador[0]} ',end=' ') print(f'O menor peso é {menor}, essas pessoas são ',end='') for contador in lista: if contador[1] == menor: print(f'{contador[0]} ',end=' ')
988,481
4ff10f8499caea4d5b5b13c16eb0d1891621c0e7
import requests # 需要请求的目标地址 # 人人字幕 # url = 'http://www.zmz2019.com/user/user' url = 'https://www.lmonkey.com/' # 登录请求的地址 # 人人字幕 # login_url = 'http://www.zmz2019.com/user/login/ajaxlogin' login_url = 'https://www.lmonkey.com/login' # 请求头 headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36' } # 如果需要爬虫主动记录cookies # 那么在使用requests之前先调用session # 并且使用session返回的对象发送请求即可 req = requests.session() # 登录请求时的数据 # data需要chrome F12 network勾选preservelog # 人人字幕data # data = { # 'account': '563797067@qq.com', # 'password': 'lycLYC85302250', # 'remember': '1', # 'url_back': 'http://www.zmz2019.com/' # } # data = { # '_token': 'mHC4eTd5PTr4fNhWP9rtGhYxwBqlRPxiXaCM2SzK', # 'username': '李彦辰', # 'password': '123456789' # } # 发起登录请求 res = req.post(url=login_url, headers=headers, data=data) # 判断状态 code = res.status_code print(code) if code == 200: # 发起新的请求,去获取目标数据 res = req.get(url=url, headers=headers) with open('学习猿地.html', 'w') as fp: fp.write(res.text)
988,482
a25a2de708cb14227ad570dbf27fa39eae76c7f6
class Bank: # #static declaration # @staticmethod # def utility_method():#nothing related to object # print("utility method") #class method @classmethod def change_bank_name(cls): cls.bank_name("SBI") bank_name="sbk" def create_account(self,acno,person_name,balance): self.acno=acno self.person_name=person_name self.balance=balance def deposit(self,amount): self.balance+=amount print(Bank.bank_name,"your account",self.acno,"has been credited with amount",amount,"your availale balance:",self.balance) def withdraw(self,amount): if amount>self.balance: print("your account",self.acno,"balance",self.balance) else: self.balance-=amount print("your account", self.acno, "hasbeen debited with amount",amount,"available balance",self.balance) def balance_enq(self): print("your available balance", self.balance) obj=Bank() obj.create_account(101,"test",5000) obj.deposit(1000) obj.withdraw(200) obj.balance_enq() #Bank.utility_method() Bank.change_bank_name() print(Bank.bank_name)
988,483
ca26ba9db40190b18b2a002ee0c6798187139297
""" Demonstrates using an LJTick-DAC with the LabJackPython modules. """ import struct import u3 # import u6 # import ue9 class LJTickDAC: """Updates DACA and DACB on a LJTick-DAC connected to a U3, U6 or UE9.""" EEPROM_ADDRESS = 0x50 DAC_ADDRESS = 0x12 def __init__(self, device, dioPin): """device: The object to an opened U3, U6 or UE9. dioPin: The digital I/O line that the LJTick-DAC's DIOA is connected to. """ self.device = device # The pin numbers for the I2C command-response self.sclPin = dioPin self.sdaPin = self.sclPin + 1 self.getCalConstants() def toDouble(self, buff): """Converts the 8 byte array into a floating point number. buff: An array with 8 bytes. """ right, left = struct.unpack("<Ii", struct.pack("B" * 8, *buff[0:8])) return float(left) + float(right)/(2**32) def getCalConstants(self): """Loads or reloads the calibration constants for the LJTick-DAC. See datasheet for more info. """ data = self.device.i2c(LJTickDAC.EEPROM_ADDRESS, [64], NumI2CBytesToReceive=36, SDAPinNum=self.sdaPin, SCLPinNum=self.sclPin) response = data['I2CBytes'] self.slopeA = self.toDouble(response[0:8]) self.offsetA = self.toDouble(response[8:16]) self.slopeB = self.toDouble(response[16:24]) self.offsetB = self.toDouble(response[24:32]) if 255 in response: msg = "LJTick-DAC calibration constants seem off. Check that the " \ "LJTick-DAC is connected properly." raise Exception(msg) def update(self, dacA, dacB): """Updates the voltages on the LJTick-DAC. dacA: The DACA voltage to set. dacB: The DACB voltage to set. """ binaryA = int(dacA*self.slopeA + self.offsetA) self.device.i2c(LJTickDAC.DAC_ADDRESS, [48, binaryA // 256, binaryA % 256], SDAPinNum=self.sdaPin, SCLPinNum=self.sclPin) binaryB = int(dacB*self.slopeB + self.offsetB) self.device.i2c(LJTickDAC.DAC_ADDRESS, [49, binaryB // 256, binaryB % 256], SDAPinNum=self.sdaPin, SCLPinNum=self.sclPin)
988,484
e86ed3b75b3245c6dd2842862bc42e0896fcd766
""" Configures pytest and fixtures for tests in this package """ import pytest from src.app import create_app from src.settings import TestConfig def pytest_addoption(parser): """ Allows us to add --runslow as an argument to py.test so we can run tests marked slow """ parser.addoption("--runslow", action="store_true", help="run slow tests") def pytest_runtest_setup(item): """ Skip tests marked 'slow' unless we explicility asked to run them """ if 'slow' in item.keywords and not item.config.getoption("--runslow"): pytest.skip("need --runslow option to run") @pytest.fixture(scope='function') def app(request): """ Flask app instance fixture with an active request context. See: http://flask.pocoo.org/docs/0.10/reqcontext/ """ _app = create_app(TestConfig) request.instance.app = _app ctx = _app.test_request_context() ctx.push() request.addfinalizer(ctx.pop) return _app @pytest.fixture(scope='function') def client(app, request): request.instance.client = app.test_client()
988,485
95750b3e5c0bba9d131a176ded01c007f8b27f68
a=100 b=200 product=a*1000 if product <=1000: print(product) else: sum=a+b print(sum)
988,486
77f21b4877bdf776dc631c5d7209f8f8556a74d5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 27 11:18:12 2020 @author: lheusing Work through the tutorial found at http://earthpy.org/pandas-basics.html Time series analysis with pands written by nikolay koldunov majority of commands done via shell line. Essential commands saved to script """ import pandas as pd import numpy as np from pandas import Series, DataFrame, Panel pd.set_option('display.max_rows',15) ao = np.loadtxt('monthly.ao.index.b50.current.ascii') #import data into time array dates = pd.date_range('1950-01', periods=ao.shape[0], freq='M') #take dates off AO = Series(ao[:,2], index = dates) #pair the date and value nao = np.loadtxt('norm.nao.monthly.b5001.current.ascii') dates_nao = pd.date_range('1950-01', periods =nao.shape[0], freq ='M') NAO = Series(nao[:,2], index = dates_nao) aonao = DataFrame({'AO' : AO, 'NAO':NAO}) #if the size is different then fill to longer one and fill shorter with NA AO_mm = AO.resample("A").mean() #resample to mean value AO_md = AO.resample("A").mean() #resample for median plot via command line aonao.rolling(window=12, center = False).mean().plot(style='-g') #plot rolling mean for ao and nao
988,487
3ffa12528440aecf584901e582e094fe8573f70e
import json f= open('./test_intensity.json','w') import numpy as np import os root='./ActionUnit_Labels/' subs=os.listdir(root) data=[] i=0 for sub in subs: i=i+1 if i%5!=0: continue print(sub) aus=os.listdir(root+sub) arr=[] for au in aus: print(au[6:-4]) f2=open(root+sub+'/'+au) lines=f2.readlines() #print(lines) seq=[] for line in lines: ch=line.split(',') seq.append(int(ch[1])) sequ=np.array(seq) arr.append(seq) arrr=np.array(arr) print(np.shape(arrr)) anno={ 'sub':sub, 'intensity':arr } #print(anno) data.append(anno) json.dump(data,f)
988,488
2b5befdb780c92cf6558b0e4d8d33286c1c7c041
import keras from keras.models import model_from_json print('Started') model = keras.applications.inception_v3.InceptionV3(include_top=True, weights= None, input_shape=(150, 150, 3), input_tensor=None, pooling=None, classes=1000) print('Downloaded') model_json = model.to_json() with open("arch.json", "w") as json_file: json_file.write(model_json) print('Saved')
988,489
abedc93baade4c473a0e904ee616c7233808888d
# -*- coding: utf-8 -*- """ Created on Sat Jul 18 16:13:57 2020 @author: Shikhar Nathani """ print "Hello, world!"
988,490
d23faab3739d96d02ab5ab03daf882da58fe994c
## simple python script to take a list of customers and generate a MySQL enum for bugs.customer column definition. # as of: June 4th 6pm # -- ENUM('-','ALL CUSTOMERS','American Eagle','American Standard','APL','BMS','Cargill','CAT Logistics','CEVA','CEVA-Microsoft','Charming Shoppes','China Shipping','CNH','Cost Plus','CP Ships','Crowley','CSAV','CSO','DHL','DuPont','Engineering','Furniture Brands','GAP','GBE','Grainger','GTN','Hanjin','Hapag-Llyod','Home Depot','HP','Hyundai','Imperial Tobacco','KB Toys','K-Line','Kmart','Kraft Foods','Liz Claiborne','Maersk Logistics','MOL','Nestle','OSA','PBD','P&G','Polo Ralph Lauren','PVH','Product Manager','Rhodia','Seagha','Sears Canada','SCA','Schenker','SPARK','UPS','Vis2005','Wal-Mart','Warnaco','Westwood','Weyerhaeuser','WSI','Xerox','Yang Ming','Yazaki','ZF','Zim') import os, sys # enum = ['-','ALL CUSTOMERS','American Eagle','American Standard','APL','BMS','Cargill','CAT Logistics','CEVA','CEVA-Microsoft','Charming Shoppes','China Shipping','CNH','Cost Plus','CP Ships','Crowley','CSAV','CSO','DHL','DuPont','Engineering','Furniture Brands','GAP','GBE','Grainger','GTN','Hanjin','Hapag-Llyod','Home Depot','HP','Hyundai','Imperial Tobacco','KB Toys','K-Line','Kmart','Kraft Foods','Liz Claiborne','Maersk Logistics','MOL','Nestle','OSA','PBD','P&G','Polo Ralph Lauren','PVH','Product Manager','Rhodia','Seagha','Sears Canada','SCA','Schenker','SPARK','UPS','Vis2005','Wal-Mart','Warnaco','Westwood','Weyerhaeuser','WSI','Xerox','Yang Ming','Yazaki','ZF','Zim'] #for c in enum: # print c customers = """- ALL CUSTOMERS Adisseo American Eagle American Standard APL BMS BritishAmericanTobacco Cardinal Health Cargill CAT Logistics Celanese CEVA CEVA-Microsoft Charming Shoppes China Shipping CNH Connell Bros. Corning Inc. Cost Plus CP Ships Crowley CSAV CSO Daimler Dachser Del Monte Foods Company DHL Dicks Sporting Goods DuPont Eagle Global Logistics LP Engineering Furniture Brands GAP GBE Grainger GTN Hanjin Hapag-Llyod Hellmann Hewlett Packard Company Home Depot HP Hyundai Imperial Tobacco Inditex INVISTA International Paper JFHillebrand Johnson & Johnson KB Toys K-Line Kmart Kraft Foods KuehneNagel Liz Claiborne Maersk Logistics MalloryAlexander Mattel MOL Nestle Nike, Inc. NYK OSA Otto International Panalpina PBD P&G Philips Philips Van Heusen Corp. Polo Ralph Lauren Procter & Gamble Company PVH Product Manager Restoration Hardware Rhodia SA Recycling Seagha Sears Canada Sears Holdings SCA Schenker SM21 SPARK Suzano Papel e Celulose Transalpe Votorantim Unipac UPS Vis2005 Wal-Mart Warnaco Westwood Weyerhaeuser WSI Wyeth Xerox Yang Ming Yazaki ZF Zim""" custlist = customers.split("\n") custlist.sort() for c in custlist: print c enum = "ENUM(" for c in custlist: c2 = "'%s', "%(c) enum = enum + c2 enum = enum + ")" print enum
988,491
16e18a740828ff563e5bda8d16eea401ed0cbf2f
from os import makedirs from os.path import join import click APP_NAME = "McScript" ASSET_DIRECTORY = join(click.get_app_dir(APP_NAME, roaming=False), "assets") makedirs(ASSET_DIRECTORY, exist_ok=True) LOG_DIRECTORY = join(click.get_app_dir(APP_NAME, roaming=True), "logs") makedirs(LOG_DIRECTORY, exist_ok=True) VERSION_DIR = join(ASSET_DIRECTORY, "versions") def getVersionDir(version: str) -> str: """ A dir for assets for the different minecraft versions """ path = join(VERSION_DIR, version) makedirs(path, exist_ok=True) return path
988,492
6650fea9025381979c56b8c2b85dca81a907547c
#loops in Python # use for loops over a list numbers = [1,2,3,4,5] for number in numbers: print (number) stocks = ["fb", "aapl", "nflx", "goog"] for stock in stocks: print (stock.upper())
988,493
250f9c71187da43868f4b8fb09daa34e24bb1b18
# File generated from our OpenAPI spec from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.abstract import APIResource from stripe.api_resources.customer import Customer from stripe.six.moves.urllib.parse import quote_plus class CashBalance(APIResource): OBJECT_NAME = "cash_balance" def instance_url(self): customer = util.utf8(self.customer) base = Customer.class_url() cust_extn = quote_plus(customer) return "%s/%s/cash_balance" % (base, cust_extn) @classmethod def retrieve(cls, id, api_key=None, **params): raise NotImplementedError( "Can't retrieve a Customer Cash Balance without a Customer ID. " "Use Customer.retrieve_cash_balance('cus_123')" )
988,494
85bbb88e9d4767f02efbad0e8e187d308d62c122
from django.shortcuts import render, get_object_or_404 from .models import Skill from random import shuffle # Create your views here. def skill(request, skill_id): skill = get_object_or_404(Skill, pk=skill_id) skill_questions = skill.skillquestion_set.all() for q in skill_questions: answers = [q.answer, q.answer1, q.answer2, q.answer3] shuffle(answers) q.answer, q.answer1, q.answer2, q.answer3 = answers return render(request, 'skill/skill.html', {'skill':skill, 'skill_questions':skill_questions})
988,495
692aff7dba51c62bf238c2c67fdecf55c20331e9
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import json import re import base64 import urllib.request import urllib.error import urllib.parse import time import html.parser # Parameters URL="" USERNAME="" PASSWORD="" # Calculated parameters TENANT=URL.split("//")[1].split(".")[0] CLIENT_ID=URL.split("/")[-1] # Constants AUTH0_CLIENT_INFO="""{"name":"lock.js","version":"11.11.0","lib_version":{"raw":"9.8.1"}}""" AUTH0_CLIENT_HEADER=base64.b64encode(AUTH0_CLIENT_INFO.encode()) class FormParser(html.parser.HTMLParser): def __init__(self): html.parser.HTMLParser.__init__(self) self.flags_inside_form = False self.action = None self.method = None self.fields = [] def handle_starttag(self, tag, attributes): attributes_map = dict(attributes) if tag == "form": self.flags_inside_form = True self.action = attributes_map["action"] self.method = attributes_map["method"] elif tag == "input" and self.flags_inside_form and "name" in attributes_map: self.fields.append((attributes_map["name"], attributes_map["value"])) def handle_endtag(self, tag): if tag == "form": self.flags_inside_form = False def get_login_info(opener): """ access url => redirect => get parameters from json in html """ request = urllib.request.Request(URL) response = opener.open(request) html = response.read().decode() # print(html) params_base64 = re.search("window.atob\('(.+?)'\)", html).group(1) params = json.loads(base64.b64decode(params_base64).decode()) # print(params) return params def get_connection_name(): """ get connection list from json in javascript => choose connection """ request = urllib.request.Request("https://cdn.auth0.com/client/%s.js"%CLIENT_ID) response = urllib.request.urlopen(request) javascript = response.read().decode() # print(javascript) client_info = json.loads(re.search("Auth0.setClient\((.*)\)", javascript).group(1)) # print(client_info) connection_names = [] for strategy in client_info["strategies"]: for connection in strategy["connections"]: connection_names.append(connection["name"]) # print(connection_names) if len(connection_names) == 0: raise RuntimeError("No connection available") elif len(connection_names) == 1: connection_name = connection_names[0] else: print("Please enter the index of connection that contains your account:") for index, name in enumerate(connection_names): print("%d: %s"%(index+1, name)) index = int(input("index: "))-1 connection_name = connection_names[index] print("Use connection: %s"%(connection_name)) return connection_name def do_login(opener, login_info, connection_name, username, password): """ post json to /usernamepassword/login => get a form => post the form => get mfa parameters from html """ login_payload = { "client_id": CLIENT_ID, "connection": connection_name, "password": password, "popup_options": "{}", "protocol": "samlp", "redirect_uri": "https://signin.aws.amazon.com/saml", "response_type": "code", "scope": "openid profile email", "sso": True, "state": login_info["state"], "tenant": TENANT, "username": username, "_csrf": login_info["_csrf"], "_intstate": "deprecated" } login_payload_json = json.dumps(login_payload).encode() # print(login_payload) headers = { "Content-Type": "application/json", "Origin": "https://%s.auth0.com"%TENANT, "Auth0-Client": AUTH0_CLIENT_HEADER } request = urllib.request.Request( "https://%s.auth0.com/usernamepassword/login"%TENANT, data=login_payload_json, method="POST", headers=headers) try: response = opener.open(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("Login error: %s"%error) from None # print(result) # if success we will get a form in html, post it parser = FormParser() parser.feed(result) callback_params = urllib.parse.urlencode(parser.fields).encode() headers = { "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://%s.auth0.com"%TENANT } request = urllib.request.Request( parser.action, data=callback_params, method=parser.method.upper(), # post => POST headers=headers) try: response = opener.open(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("Login callback error: %s"%error) from None # print(result) mfa_info = { "mfaServerUrl": re.search("mfaServerUrl:\s*?\"(.+?)\"", result).group(1), "requestToken": re.search("requestToken:\s*?\"(.+?)\"", result).group(1), "postActionURL": re.search("postActionURL:\s*?\"(.+?)\"", result).group(1), "globalTrackingId": re.search("globalTrackingId:\s*?\"(.+?)\"", result).group(1), } # print(mfa_info) return mfa_info def do_mfa_verify(mfa_info): """ call /api/start-flow => get transaction token from json result => ask verification code => call /api/verify-otp => 204 means success => call /api/transaction-state => get mfa result from json result also see: https://github.com/auth0/auth0-guardian.js/blob/master/lib/utils/polling_client.js """ headers = { "Content-Type": "application/json", "Origin": "https://%s.auth0.com"%TENANT, "Authorization": "Bearer %s"%mfa_info["requestToken"], "x-global-tracking-id": mfa_info["globalTrackingId"] } request = urllib.request.Request( "%s/api/start-flow"%mfa_info["mfaServerUrl"], data=json.dumps({ "state_transport": "polling" }).encode(), method="POST", headers=headers) try: response = urllib.request.urlopen(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("MFA start flow error: %s"%error) from None mfa_flow_info = json.loads(result) mfa_transaction_token = mfa_flow_info["transaction_token"] # print(mfa_flow_info) # print(mfa_transaction_token) mfa_code = input("Please enter your MFA verification code: ") mfa_payload = { "code": mfa_code, "type": "manual_input" } mfa_payload_json = json.dumps(mfa_payload).encode() headers = { "Content-Type": "application/json", "Origin": "https://%s.auth0.com"%TENANT, "Authorization": "Bearer %s"%mfa_transaction_token, "x-global-tracking-id": mfa_info["globalTrackingId"] } request = urllib.request.Request( "%s/api/verify-otp"%mfa_info["mfaServerUrl"], data=mfa_payload_json, method="POST", headers=headers) try: response = urllib.request.urlopen(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("MFA verify error: %s"%error) from None # print(result) headers = { "Origin": "https://%s.auth0.com"%TENANT, "Authorization": "Bearer %s"%mfa_transaction_token, "x-global-tracking-id": mfa_info["globalTrackingId"] } request = urllib.request.Request( "%s/api/transaction-state"%mfa_info["mfaServerUrl"], method="POST", headers=headers) try: response = urllib.request.urlopen(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("Get MFA result error: %s"%error) from None mfa_result = json.loads(result) if mfa_result["state"] != "accepted": raise RuntimeError("MFA verification is not accepted: %s"%result) # print(mfa_result) return mfa_result def get_saml_response(opener, mfa_info, mfa_result): """ get url from mfa_info and post with signature => get saml response from html """ post_fields = { "rememberBrowser": "false", "signature": mfa_result["token"] } post_params = urllib.parse.urlencode(post_fields).encode() headers = { "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://%s.auth0.com"%TENANT } request = urllib.request.Request( mfa_info["postActionURL"], data=post_params, method="POST", headers=headers) try: response = opener.open(request) result = response.read().decode() except urllib.error.HTTPError as e: error = e.read().decode() raise RuntimeError("Get SAMLResponse error: %s"%error) from None # print(result) saml_response = re.search("<input.+?name=\"SAMLResponse\".+?value=\"(.+?)\"", result).group(1) return saml_response def main(): # cookie recoding is required otherwise you will see this error: # {"statusCode":403,"description":"Invalid state","name":"AnomalyDetected","code":"access_denied"} cookie_processor = urllib.request.HTTPCookieProcessor() opener = urllib.request.build_opener(cookie_processor) login_info = get_login_info(opener) connection_name = get_connection_name() mfa_info = do_login(opener, login_info, connection_name, USERNAME, PASSWORD) mfa_result = do_mfa_verify(mfa_info) saml_response = get_saml_response(opener, mfa_info, mfa_result) print("Login successful, SAMLResponse:") print(saml_response) if __name__ == "__main__": main()
988,496
0d72336563340d6390d2319d3d81deede2c6f4dd
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import tarfile import textwrap import zipfile from io import BytesIO from textwrap import dedent import pytest from pants.backend.python import target_types_rules as python_target_type_rules from pants.backend.python.goals import package_pex_binary, run_pex_binary from pants.backend.python.target_types import PexBinary, PythonSourceTarget from pants.backend.python.util_rules import pex_from_targets from pants.core.goals import run from pants.core.goals.package import BuiltPackage from pants.core.target_types import ( ArchiveFieldSet, ArchiveTarget, FilesGeneratorTarget, FileSourceField, FileTarget, LockfilesGeneratorSourcesField, LockfileSourceField, RelocatedFiles, RelocateFilesViaCodegenRequest, ResourceTarget, http_source, per_platform, ) from pants.core.target_types import rules as target_type_rules from pants.core.util_rules import archive, source_files, system_binaries from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest from pants.engine.addresses import Address from pants.engine.fs import EMPTY_SNAPSHOT, DigestContents, FileContent, GlobMatchErrorBehavior from pants.engine.platform import Platform from pants.engine.target import ( GeneratedSources, SourcesField, TransitiveTargets, TransitiveTargetsRequest, ) from pants.option.global_options import UnmatchedBuildFileGlobs from pants.testutil.python_rule_runner import PythonRuleRunner from pants.testutil.rule_runner import QueryRule, mock_console def test_relocated_files() -> None: rule_runner = PythonRuleRunner( rules=[ *target_type_rules(), *archive.rules(), *source_files.rules(), *system_binaries.rules(), QueryRule(GeneratedSources, [RelocateFilesViaCodegenRequest]), QueryRule(TransitiveTargets, [TransitiveTargetsRequest]), QueryRule(SourceFiles, [SourceFilesRequest]), ], target_types=[FilesGeneratorTarget, RelocatedFiles], ) def assert_prefix_mapping( *, original: str, src: str, dest: str, expected: str, ) -> None: rule_runner.write_files( { original: "", "BUILD": dedent( f"""\ files(name="original", sources=[{repr(original)}]) relocated_files( name="relocated", files_targets=[":original"], src={repr(src)}, dest={repr(dest)}, ) """ ), } ) tgt = rule_runner.get_target(Address("", target_name="relocated")) result = rule_runner.request( GeneratedSources, [RelocateFilesViaCodegenRequest(EMPTY_SNAPSHOT, tgt)] ) assert result.snapshot.files == (expected,) # We also ensure that when looking at the transitive dependencies of the `relocated_files` # target and then getting all the code of that closure, we only end up with the relocated # files. If we naively marked the original files targets as a typical `Dependencies` field, # we would hit this issue. transitive_targets = rule_runner.request( TransitiveTargets, [TransitiveTargetsRequest([tgt.address])] ) all_sources = rule_runner.request( SourceFiles, [ SourceFilesRequest( (tgt.get(SourcesField) for tgt in transitive_targets.closure), enable_codegen=True, for_sources_types=(FileSourceField,), ) ], ) assert all_sources.snapshot.files == (expected,) # No-op. assert_prefix_mapping(original="old_prefix/f.ext", src="", dest="", expected="old_prefix/f.ext") assert_prefix_mapping( original="old_prefix/f.ext", src="old_prefix", dest="old_prefix", expected="old_prefix/f.ext", ) # Remove prefix. assert_prefix_mapping(original="old_prefix/f.ext", src="old_prefix", dest="", expected="f.ext") assert_prefix_mapping( original="old_prefix/subdir/f.ext", src="old_prefix", dest="", expected="subdir/f.ext" ) # Add prefix. assert_prefix_mapping(original="f.ext", src="", dest="new_prefix", expected="new_prefix/f.ext") assert_prefix_mapping( original="old_prefix/f.ext", src="", dest="new_prefix", expected="new_prefix/old_prefix/f.ext", ) # Replace prefix. assert_prefix_mapping( original="old_prefix/f.ext", src="old_prefix", dest="new_prefix", expected="new_prefix/f.ext", ) assert_prefix_mapping( original="old_prefix/f.ext", src="old_prefix", dest="new_prefix/subdir", expected="new_prefix/subdir/f.ext", ) # Replace prefix, but preserve a common start. assert_prefix_mapping( original="common_prefix/foo/f.ext", src="common_prefix/foo", dest="common_prefix/bar", expected="common_prefix/bar/f.ext", ) assert_prefix_mapping( original="common_prefix/subdir/f.ext", src="common_prefix/subdir", dest="common_prefix", expected="common_prefix/f.ext", ) def test_relocated_relocated_files() -> None: rule_runner = PythonRuleRunner( rules=[ *target_type_rules(), *archive.rules(), *source_files.rules(), *system_binaries.rules(), QueryRule(GeneratedSources, [RelocateFilesViaCodegenRequest]), QueryRule(TransitiveTargets, [TransitiveTargetsRequest]), QueryRule(SourceFiles, [SourceFilesRequest]), ], target_types=[FilesGeneratorTarget, RelocatedFiles], ) rule_runner.write_files( { "original_prefix/file.txt": "", "BUILD": dedent( """\ files(name="original", sources=["original_prefix/file.txt"]) relocated_files( name="relocated", files_targets=[":original"], src="original_prefix", dest="intermediate_prefix", ) relocated_files( name="double_relocated", files_targets=[":relocated"], src="intermediate_prefix", dest="final_prefix", ) """ ), } ) tgt = rule_runner.get_target(Address("", target_name="double_relocated")) result = rule_runner.request( GeneratedSources, [RelocateFilesViaCodegenRequest(EMPTY_SNAPSHOT, tgt)] ) assert result.snapshot.files == ("final_prefix/file.txt",) def test_archive() -> None: """Integration test for the `archive` target type. This tests some edges: * Using both `files` and `relocated_files`. * An `archive` containing another `archive`. """ rule_runner = PythonRuleRunner( rules=[ *target_type_rules(), *pex_from_targets.rules(), *package_pex_binary.rules(), *python_target_type_rules.rules(), QueryRule(BuiltPackage, [ArchiveFieldSet]), ], target_types=[ArchiveTarget, FilesGeneratorTarget, RelocatedFiles, PexBinary], ) rule_runner.set_options([], env_inherit={"PATH", "PYENV_ROOT", "HOME"}) rule_runner.write_files( { "resources/d1.json": "{'k': 1}", "resources/d2.json": "{'k': 2}", "resources/BUILD": dedent( """\ files(name='original_files', sources=['*.json']) relocated_files( name='relocated_files', files_targets=[':original_files'], src="resources", dest="data", ) """ ), "project/app.py": "print('hello world!')", "project/BUILD": "pex_binary(entry_point='app.py')", "BUILD": dedent( """\ archive( name="archive1", packages=["project"], files=["resources:original_files"], format="zip", ) archive( name="archive2", packages=[":archive1"], files=["resources:relocated_files"], format="tar", output_path="output/archive2.tar", ) """ ), } ) def get_archive(target_name: str) -> FileContent: tgt = rule_runner.get_target(Address("", target_name=target_name)) built_package = rule_runner.request(BuiltPackage, [ArchiveFieldSet.create(tgt)]) digest_contents = rule_runner.request(DigestContents, [built_package.digest]) assert len(digest_contents) == 1 return digest_contents[0] def assert_archive1_is_valid(zip_bytes: bytes) -> None: io = BytesIO() io.write(zip_bytes) with zipfile.ZipFile(io) as zf: assert set(zf.namelist()) == { "resources/d1.json", "resources/d2.json", "project/project.pex", } with zf.open("resources/d1.json", "r") as f: assert f.read() == b"{'k': 1}" with zf.open("resources/d2.json", "r") as f: assert f.read() == b"{'k': 2}" archive1 = get_archive("archive1") assert_archive1_is_valid(archive1.content) archive2 = get_archive("archive2") assert archive2.path == "output/archive2.tar" io = BytesIO() io.write(archive2.content) io.seek(0) with tarfile.open(fileobj=io, mode="r:") as tf: assert set(tf.getnames()) == {"data/d1.json", "data/d2.json", "archive1.zip"} def get_file(fp: str) -> bytes: reader = tf.extractfile(fp) assert reader is not None return reader.read() assert get_file("data/d1.json") == b"{'k': 1}" assert get_file("data/d2.json") == b"{'k': 2}" assert_archive1_is_valid(get_file("archive1.zip")) @pytest.mark.parametrize("use_per_platform", [True, False]) def test_url_assets(use_per_platform: bool) -> None: rule_runner = PythonRuleRunner( rules=[ *target_type_rules(), *pex_from_targets.rules(), *package_pex_binary.rules(), *run_pex_binary.rules(), *python_target_type_rules.rules(), *run.rules(), ], target_types=[FileTarget, ResourceTarget, PythonSourceTarget, PexBinary], objects={"http_source": http_source, "per_platform": per_platform}, ) http_source_info = ( 'url="https://raw.githubusercontent.com/python/cpython/7e46ae33bd522cf8331052c3c8835f9366599d8d/Lib/antigravity.py",' + "len=500," + 'sha256="8a5ee63e1b79ba2733e7ff4290b6eefea60e7f3a1ccb6bb519535aaf92b44967"' ) def source_field_value(http_source_value: str) -> str: if use_per_platform: return f"per_platform({Platform.create_for_localhost().value}={http_source_value})" return http_source_value rule_runner.write_files( { "assets/BUILD": dedent( f"""\ resource( name='antigravity', source={source_field_value(f'http_source({http_source_info})')} ) resource( name='antigravity_renamed', source={source_field_value(f'http_source({http_source_info}, filename="antigravity_renamed.py")')} ) """ ), "app/app.py": textwrap.dedent( """\ import pathlib assets_path = pathlib.Path(__file__).parent.parent / "assets" for path in assets_path.iterdir(): print(path.name) assert "https://xkcd.com/353/" in path.read_text() """ ), "app/BUILD": textwrap.dedent( """\ python_source( source="app.py", dependencies=[ "assets:antigravity", "assets:antigravity_renamed", ] ) pex_binary(name="app.py", entry_point='app.py') """ ), } ) with mock_console(rule_runner.options_bootstrapper) as (console, stdout_reader): rule_runner.run_goal_rule( run.Run, args=[ "app:app.py", ], env_inherit={"PATH", "PYENV_ROOT", "HOME"}, ) stdout = stdout_reader.get_stdout() assert "antigravity.py" in stdout assert "antigravity_renamed.py" in stdout @pytest.mark.parametrize( "url, expected", [ ("http://foo/bar", "bar"), ("http://foo/bar.baz", "bar.baz"), ("http://foo/bar.baz?query=yes/no", "bar.baz"), ("http://foo/bar/baz/file.ext", "file.ext"), ("www.foo.bar", "www.foo.bar"), ("www.foo.bar?query=yes/no", "www.foo.bar"), ], ) def test_http_source_filename(url, expected): assert http_source(url, len=0, sha256="").filename == expected @pytest.mark.parametrize( "kwargs, exc_match", [ ( dict(url=None, len=0, sha256=""), pytest.raises(TypeError, match=r"`url` must be a `str`"), ), ( dict(url="http://foo/bar", len="", sha256=""), pytest.raises(TypeError, match=r"`len` must be a `int`"), ), ( dict(url="http://foo/bar", len=0, sha256=123), pytest.raises(TypeError, match=r"`sha256` must be a `str`"), ), ( dict(url="http://foo/bar", len=0, sha256="", filename=10), pytest.raises(TypeError, match=r"`filename` must be a `str`"), ), ( dict(url="http://foo/bar/", len=0, sha256=""), pytest.raises(ValueError, match=r"Couldn't deduce filename"), ), ( dict(url="http://foo/bar/", len=0, sha256="", filename="../foobar.txt"), pytest.raises(ValueError, match=r"`filename` cannot contain a path separator."), ), ], ) def test_invalid_http_source(kwargs, exc_match): with exc_match: http_source(**kwargs) @pytest.mark.parametrize( "error_behavior", [GlobMatchErrorBehavior.warn, GlobMatchErrorBehavior.error] ) def test_lockfile_glob_match_error_behavior( error_behavior: GlobMatchErrorBehavior, ) -> None: lockfile_source = LockfileSourceField("test.lock", Address("", target_name="lockfile-test")) assert ( GlobMatchErrorBehavior.ignore == lockfile_source.path_globs( UnmatchedBuildFileGlobs(error_behavior) ).glob_match_error_behavior ) @pytest.mark.parametrize( "error_behavior", [GlobMatchErrorBehavior.warn, GlobMatchErrorBehavior.error] ) def test_lockfiles_glob_match_error_behavior( error_behavior: GlobMatchErrorBehavior, ) -> None: lockfile_sources = LockfilesGeneratorSourcesField( ["test.lock"], Address("", target_name="lockfiles-test") ) assert ( GlobMatchErrorBehavior.ignore == lockfile_sources.path_globs( UnmatchedBuildFileGlobs(error_behavior) ).glob_match_error_behavior )
988,497
aefdd394cdd888d30c20f4ac8921be52958bc150
# # PySNMP MIB module VALERE-DC-POWER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VALERE-DC-POWER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:33:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") sysUpTime, = mibBuilder.importSymbols("SNMPv2-MIB", "sysUpTime") NotificationType, Bits, TimeTicks, Counter64, enterprises, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, IpAddress, Gauge32, MibIdentifier, Integer32, iso, ObjectIdentity, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "TimeTicks", "Counter64", "enterprises", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "IpAddress", "Gauge32", "MibIdentifier", "Integer32", "iso", "ObjectIdentity", "Counter32") DisplayString, TestAndIncr, TimeStamp, TextualConvention, AutonomousType, TimeInterval = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TestAndIncr", "TimeStamp", "TextualConvention", "AutonomousType", "TimeInterval") vpwrDcPowerMgt = ModuleIdentity((1, 3, 6, 1, 4, 1, 13858)) if mibBuilder.loadTexts: vpwrDcPowerMgt.setLastUpdated('0512020000Z') if mibBuilder.loadTexts: vpwrDcPowerMgt.setOrganization('Valere Power Inc.') if mibBuilder.loadTexts: vpwrDcPowerMgt.setContactInfo('Contact: Valere Customer Support Postal: 661 N. Plano Road, Suite 300 Richardson, TX-75081 Web: http://www.valerepower.com email: support@valerepower.com Phone 866-240-6614 ') if mibBuilder.loadTexts: vpwrDcPowerMgt.setDescription(' MIB Version 0.8 Need description here. History Add table to retrieve module inventory info MIB Version 0.7 Dec 1, 05 Fixed HP Openview error Fixed warnings generated by MG-SOFT Add table to retrieve rectifier inventory info MIB Version 0.6 Feb 10, 2004 Added additional traps. Defined Ringers and other modules. Feb 08, 2003 Changed vpwrTrapDestinationTable to vpwrTrapTable Corrected entry for vpwrTrapTable to be VpwrTrapTableEntry This fixes errors generated by MG-SOFT mib compiler. Oct 30, 2002 initial release - version 0.4 ') class PositiveInteger(TextualConvention, Integer32): description = 'This data type is a non-zero and non-negative value.' status = 'current' displayHint = 'd' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 2147483647) class NonNegativeInteger(TextualConvention, Integer32): description = 'This data type is a non-negative value.' status = 'current' displayHint = 'd' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) vpwrDcPowerProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 1)) vpwrDcPowerSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2)) vpwrDcPowerRectifier = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 3)) vpwrDcPowerLvd = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 4)) vpwrDcPowerTest = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 5)) vpwrDcPowerModuleIdent = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 6)) vpwrDcPowerBatteryGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 7)) vpwrDcPowerAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 8)) vpwrDcPowerSnmpConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 9)) vpwrDcPowerTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 10)) vpwrDcPowerTrapsMsgString = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 11)) vpwrDcPowerRinger = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 12)) vpwrDcPowerDcDcConverter = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 13)) vpwrDcPowerDcAcInverter = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 14)) vpwrDcPowerBayController = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 15)) vpwrDcPowerIoModule = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 16)) vpwrDcPowerDist = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 17)) vpwrDcPowerTrio = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 18)) vpwrSystemIdentGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2, 1)) vpwrSystemConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2, 2)) vpwrSystemParameterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2, 3)) vpwrSystemPanelIdentGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2, 4)) vpwrSystemBayctrlIdentGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 2, 5)) vpwrLvdConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 4, 1)) vpwrLvdAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 4, 2)) vpwrLvdTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 4, 3)) vpwrRectifierConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 3, 1)) vpwrRectifierAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 3, 2)) vpwrRectifierTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 3, 3)) vpwrBatteryTempGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 7, 1)) vpwrBatteryCurrentGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 7, 2)) vpwrBatteryBoostGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 7, 3)) vpwrBatteryDischargeTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 7, 4)) vpwrRingerConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 12, 1)) vpwrRingerAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 12, 2)) vpwrRingerTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 12, 3)) vpwrDcDcConverterConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 13, 1)) vpwrDcDcConverterAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 13, 2)) vpwrDcDcConverterTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 13, 3)) vpwrDcAcInverterConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 14, 1)) vpwrDcAcInverterAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 14, 2)) vpwrDcAcInverterTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 14, 3)) vpwrIoModuleConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 16, 1)) vpwrIoModuleAlarmGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 16, 2)) vpwrIoModuleTestGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 13858, 16, 3)) vpwrIdentManufacturer = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrIdentManufacturer.setStatus('current') if mibBuilder.loadTexts: vpwrIdentManufacturer.setDescription('The name of the DC Power manufacturer.') vpwrIdentModel = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrIdentModel.setStatus('current') if mibBuilder.loadTexts: vpwrIdentModel.setDescription('The DC Power Model designation.') vpwrIdentControllerVersion = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrIdentControllerVersion.setStatus('current') if mibBuilder.loadTexts: vpwrIdentControllerVersion.setDescription('The hardware/firmware version(s). This variable may or may not have the same value as vpwrIdentAgentSoftwareVersion.') vpwrIdentAgentSoftwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrIdentAgentSoftwareVersion.setStatus('current') if mibBuilder.loadTexts: vpwrIdentAgentSoftwareVersion.setDescription('The SNMP agent software version. This variable may or may not have the same value as vpwrIdentControllerFirmwareVersion.') vpwrIdentName = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrIdentName.setStatus('current') if mibBuilder.loadTexts: vpwrIdentName.setDescription('A string identifying the system. This object should be set by the administrator.') vpwrSystemIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6), ) if mibBuilder.loadTexts: vpwrSystemIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrSystemIdentTable.setDescription(' This table describes shelves and modules that make up the sysetm. ') vpwrSystemIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrBayIndex"), (0, "VALERE-DC-POWER-MIB", "vpwrModuleIndex")) if mibBuilder.loadTexts: vpwrSystemIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrSystemIdentEntry.setDescription('An entry containing information applicable to a particular alarm.') vpwrBayIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayIndex.setStatus('current') if mibBuilder.loadTexts: vpwrBayIndex.setDescription('Identifies Bay number that this module belongs to. The possible values are 1 through 16 limited by vpwrSystemShelfCapacity.') vpwrModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 2), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleIndex.setStatus('current') if mibBuilder.loadTexts: vpwrModuleIndex.setDescription('This object identifies the module by its position in the shelf. Module numbering is left to right starting with module 1. So, the module in the first slot has an index of 1, the next module is 2 and so on.') vpwrModuleOID = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleOID.setStatus('current') if mibBuilder.loadTexts: vpwrModuleOID.setDescription('It indicates the type of the module by specifiying its OID') vpwrModuleCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrModuleCurrent.setDescription('The meaning of this object depends upon the module type which is indicated by vpwrModuleOID as follows - Current for Rectifier module. - Not Applicable for LVD module ') vpwrModuleOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("moduleStatusOK", 0), ("moduleStatusAlarm", 1), ("moduleStatusDisabled", 2), ("moduleStatusRingerAOn", 3), ("moduleStatusRingerBOn", 4), ("moduleStatusUnknown", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleOperStatus.setStatus('current') if mibBuilder.loadTexts: vpwrModuleOperStatus.setDescription('This object indicates current over all status of the module.') vpwrModuleCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 1, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleCapacity.setStatus('current') if mibBuilder.loadTexts: vpwrModuleCapacity.setDescription('The meaning of this object depends upon the module type which is indicated by vpwrModuleOID as follows - Capacity for Rectifier module. - Not Applicable for LVD module ') vpwrPanelIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1), ) if mibBuilder.loadTexts: vpwrPanelIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrPanelIdentTable.setDescription(' This table describes shelves and modules that make up the panels. ') vpwrPanelIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrPanelBayIndex"), (0, "VALERE-DC-POWER-MIB", "vpwrPanelModuleIndex")) if mibBuilder.loadTexts: vpwrPanelIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrPanelIdentEntry.setDescription('An entry containing information applicable to a particular panel making up the system.') vpwrPanelBayIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelBayIndex.setStatus('current') if mibBuilder.loadTexts: vpwrPanelBayIndex.setDescription('Identifies bay number that this module belongs to. The possible values are 1 through 16, starting from the top.') vpwrPanelModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 2), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleIndex.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleIndex.setDescription('This object identifies the module within the panel. The orentation of modules within the panel is mappable.') vpwrPanelModuleOID = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleOID.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleOID.setDescription('It indicates the type of the module by specifiying its OID') vpwrPanelModuleCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleCurrent.setDescription('This is the Current of the first shunt of the module.') vpwrPanelModuleOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("moduleStatusOK", 0), ("moduleStatusAlarm", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleOperStatus.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleOperStatus.setDescription('This object indicates over all status of the module.') vpwrPanelModuleCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 4, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleCapacity.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleCapacity.setDescription('This is the overall Capacity of the module and is for reference only.') vpwrBayctrlIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1), ) if mibBuilder.loadTexts: vpwrBayctrlIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlIdentTable.setDescription(' This table describes bay controllers that make up the system. ') vpwrBayctrlIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrBayctrlIndex")) if mibBuilder.loadTexts: vpwrBayctrlIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlIdentEntry.setDescription('An entry containing information applicable to a particular bay controller making up the system.') vpwrBayctrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlIndex.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlIndex.setDescription('Identifies bay number that this module belongs to. The possible values are 0 through 15, starting from the top.') vpwrBayctrlOID = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlOID.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlOID.setDescription('It indicates the type of the module by specifiying its OID') vpwrBayctrlCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlCurrent.setDescription('This is the total output Current of the bay') vpwrBayctrlOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("moduleStatusOK", 0), ("moduleStatusAlarm", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlOperStatus.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlOperStatus.setDescription('This object indicates over all status of the bay') vpwrBayctrlCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 2, 5, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlCapacity.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlCapacity.setDescription('This is the overall Capacity of the bay and is for reference only.') vpwrSystemTempCompensation = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("tempCompDisabled", 0), ("tempCompEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemTempCompensation.setReference(' ') if mibBuilder.loadTexts: vpwrSystemTempCompensation.setStatus('current') if mibBuilder.loadTexts: vpwrSystemTempCompensation.setDescription(' This parameter enables/disables temperature compensation. ') vpwrSystemTempCompStartTemperature = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(25, 60))).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemTempCompStartTemperature.setReference(' ') if mibBuilder.loadTexts: vpwrSystemTempCompStartTemperature.setStatus('current') if mibBuilder.loadTexts: vpwrSystemTempCompStartTemperature.setDescription(' The temperature at which temperature compensation becomes active. ') vpwrSystemTempCompStopVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 3), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemTempCompStopVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrSystemTempCompStopVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrSystemTempCompStopVoltage.setDescription(' When temperature compensation is active, vpwrSystemTempCompStopVoltage is the limit to which float voltage will be reduced. For example, to set this voltage to 51.75 volts enter a value of 5175. ') vpwrSystemTempCompensationSlope = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setUnits(' milli-Volts per degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemTempCompensationSlope.setReference(' ') if mibBuilder.loadTexts: vpwrSystemTempCompensationSlope.setStatus('current') if mibBuilder.loadTexts: vpwrSystemTempCompensationSlope.setDescription(' The rate at which float voltage is changed, within the specified limits, when temperature compensation is active. ') vpwrSystemThermalSenseType = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("external", 0), ("internal", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemThermalSenseType.setReference(' ') if mibBuilder.loadTexts: vpwrSystemThermalSenseType.setStatus('current') if mibBuilder.loadTexts: vpwrSystemThermalSenseType.setDescription(' This parameter selects the temperature sensing point for temperature compensation (in)activation. ') vpwrSystemHVAlarmSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 6), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemHVAlarmSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrSystemHVAlarmSetpoint.setDescription('System High voltage alarm voltage setting. ') vpwrSystemBDAlarmSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 7), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemBDAlarmSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrSystemBDAlarmSetpoint.setDescription('System Battery Discharge voltage setting.') vpwrSystemInternalTempLThreshold = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 8), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemInternalTempLThreshold.setStatus('current') if mibBuilder.loadTexts: vpwrSystemInternalTempLThreshold.setDescription('Temperature value at which temperature compensation inactive (clear) trap would be sent if temperature compensation was active when this value is reached. ') vpwrSystemInternalTempUThreshold = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 2, 9), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrSystemInternalTempUThreshold.setStatus('current') if mibBuilder.loadTexts: vpwrSystemInternalTempUThreshold.setDescription('Temperature value at which temperature compensation active (set) trap would be sent. ') vpwrSystemShelfCapacity = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemShelfCapacity.setReference(' ') if mibBuilder.loadTexts: vpwrSystemShelfCapacity.setStatus('current') if mibBuilder.loadTexts: vpwrSystemShelfCapacity.setDescription(' It describes the maximum number of shelves that can/are controlled by the controller. Each shelf is uniquely numbered in the range from 1 to vpwrShelfCapacity. ') vpwrSystemVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 2), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrSystemVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrSystemVoltage.setDescription(' The current system voltage. ') vpwrSystemCurrent = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 3), Integer32()).setUnits(' Amperes').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemCurrent.setReference(' ') if mibBuilder.loadTexts: vpwrSystemCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrSystemCurrent.setDescription(' The current system current. ') vpwrSystemControllerState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("systemControllerStateUnknown", 0), ("systemControllerStateNormal", 1), ("systemControllerStateChange", 2), ("systemControllerStateAlarm", 3), ("systemControllerStateMenu", 4), ("systemControllerStateIrActive", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemControllerState.setReference(' ') if mibBuilder.loadTexts: vpwrSystemControllerState.setStatus('current') if mibBuilder.loadTexts: vpwrSystemControllerState.setDescription(' Current System state as shown on the enhanced display. ') vpwrSystemInternalTemperature = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 5), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemInternalTemperature.setReference(' ') if mibBuilder.loadTexts: vpwrSystemInternalTemperature.setStatus('current') if mibBuilder.loadTexts: vpwrSystemInternalTemperature.setDescription(' The current controller internal temperature. ') vpwrSystemTempCompensationState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("systemTempCompInactive", 0), ("systemTempCompActive", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemTempCompensationState.setReference(' ') if mibBuilder.loadTexts: vpwrSystemTempCompensationState.setStatus('current') if mibBuilder.loadTexts: vpwrSystemTempCompensationState.setDescription(' Active or Inactive. Applicable only if temperature compensation is enabled. This means that the controller is temperature compensating the float voltage. ') vpwrSystemType = MibScalar((1, 3, 6, 1, 4, 1, 13858, 2, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("sysTypeUnknow", 0), ("sysType48V", 1), ("sysType24V", 2), ("sysType12V", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrSystemType.setStatus('current') if mibBuilder.loadTexts: vpwrSystemType.setDescription('This parameter describes the type of the system being managed. This object is set by Valere Power Inc. ') vpwrLvdWarningSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 4, 1, 1), Integer32()).setUnits(' * .01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdWarningSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdWarningSetpoint.setDescription('LVD Warning voltage setpoint.') vpwrLvdDisconnectSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 4, 1, 2), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdDisconnectSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdDisconnectSetpoint.setDescription('LVD disconnect voltage setpoint.') vpwrLvdReconnectSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 4, 1, 3), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdReconnectSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdReconnectSetpoint.setDescription('LVD Reconnect voltage setpoint.') vpwrLvdReconnectDelayTimer = MibScalar((1, 3, 6, 1, 4, 1, 13858, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(20, 240))).setUnits(' Seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdReconnectDelayTimer.setStatus('current') if mibBuilder.loadTexts: vpwrLvdReconnectDelayTimer.setDescription('The delay time, in seconds, before LVD is reconnected') vpwrLvdContactorConfigTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5), ) if mibBuilder.loadTexts: vpwrLvdContactorConfigTable.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorConfigTable.setDescription(' This table describes shelves and modules that make up the sysetm. ') vpwrLvdContactorConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrBayIndex"), (0, "VALERE-DC-POWER-MIB", "vpwrModuleIndex"), (0, "VALERE-DC-POWER-MIB", "vpwrLvdContactorIndex")) if mibBuilder.loadTexts: vpwrLvdContactorConfigEntry.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorConfigEntry.setDescription('An entry containing information applicable to a particular module making up the system.') vpwrLvdContactorIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 1), PositiveInteger()).setUnits(' None').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrLvdContactorIndex.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorIndex.setDescription('contactor index') vpwrLvdContactorWarningSetpoint = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 2), PositiveInteger()).setUnits(' * .01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdContactorWarningSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorWarningSetpoint.setDescription('LVD Warning voltage setpoint.') vpwrLvdContactorDisconnectSetpoint = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 3), PositiveInteger()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdContactorDisconnectSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorDisconnectSetpoint.setDescription('LVD disconnect voltage setpoint.') vpwrLvdContactorReconnectSetpoint = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 4), PositiveInteger()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdContactorReconnectSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorReconnectSetpoint.setDescription('LVD Reconnect voltage setpoint.') vpwrLvdContactorReconnectDelayTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 5), PositiveInteger().subtype(subtypeSpec=ValueRangeConstraint(0, 240))).setUnits(' Seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdContactorReconnectDelayTimer.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorReconnectDelayTimer.setDescription('The delay time, in seconds, before LVD is reconnected') vpwrLvdContactorState = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 4, 1, 5, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("contactorOpen", 0), ("contactorClose", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrLvdContactorState.setStatus('current') if mibBuilder.loadTexts: vpwrLvdContactorState.setDescription('The delay time, in seconds, before LVD is reconnected') vpwrRectifierFVSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 3, 1, 1), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRectifierFVSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrRectifierFVSetpoint.setDescription('System Float Voltage setting') vpwrRectifierHVSDSetpoint = MibScalar((1, 3, 6, 1, 4, 1, 13858, 3, 1, 2), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRectifierHVSDSetpoint.setStatus('current') if mibBuilder.loadTexts: vpwrRectifierHVSDSetpoint.setDescription('System High Voltage Shutdown voltage setting') vpwrRectifierCurrentLimitAdminState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("rectCurrentLimitDisabled", 0), ("rectCurrentLimitEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRectifierCurrentLimitAdminState.setReference(' ') if mibBuilder.loadTexts: vpwrRectifierCurrentLimitAdminState.setStatus('current') if mibBuilder.loadTexts: vpwrRectifierCurrentLimitAdminState.setDescription(' This parameter allows enabling or disabling boost. ') vpwrRectifierCurrentLimit = MibScalar((1, 3, 6, 1, 4, 1, 13858, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 200))).setUnits('Amperes').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRectifierCurrentLimit.setStatus('current') if mibBuilder.loadTexts: vpwrRectifierCurrentLimit.setDescription('Rectifier current limit setpoint') vpwrAlarmsPresent = MibScalar((1, 3, 6, 1, 4, 1, 13858, 8, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrAlarmsPresent.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmsPresent.setDescription('The present number of active alarm conditions.') vpwrAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 8, 2), ) if mibBuilder.loadTexts: vpwrAlarmTable.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmTable.setDescription('A list of alarm table entries. The table contains zero, one, or many rows at any moment, depending upon the number of alarm conditions in effect. The table is initially empty at agent startup. The agent creates a row in the table each time a condition is detected and deletes that row when that condition no longer pertains. The vpwrAlarmIndex, for each type of module starts at 1 and is limited by the total number of alarams that can be generated by the module. Alarms are named by an AutonomousType (OBJECT IDENTIFIER), vpwrAlarmDescr, to allow a single table to reflect alarms for different type of modules. The number of rows in the table at any given time is reflected by the value of vpwrAlarmsPresent.') vpwrAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 8, 2, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrAlarmIndex")) if mibBuilder.loadTexts: vpwrAlarmEntry.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmEntry.setDescription('An entry containing information applicable to a particular alarm.') vpwrAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 2, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrAlarmIndex.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmIndex.setDescription('Identifies the alarm associated with the module. It is unique on per module type basis. For example, multiple rectifiers can have the same alarm and therefore same vpwrAlarmIndex active at any one time. ') vpwrAlarmDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 2, 1, 2), AutonomousType()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrAlarmDescr.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmDescr.setDescription('A reference to an alarm description object. The object referenced should not be accessible, but rather be used to provide a unique description of the alarm condition.') vpwrAlarmTime = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 2, 1, 3), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrAlarmTime.setStatus('current') if mibBuilder.loadTexts: vpwrAlarmTime.setDescription('The value of sysUpTime when the alarm condition was detected.') vpwrBatteryTempTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 7, 1, 1), ) if mibBuilder.loadTexts: vpwrBatteryTempTable.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempTable.setDescription('This table describes battery temperature probes. ') vpwrBatteryTempEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 7, 1, 1, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrBatteryTempIndex")) if mibBuilder.loadTexts: vpwrBatteryTempEntry.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempEntry.setDescription('An entry containing information applicable to a particular temperature probe.') vpwrBatteryTempIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 7, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBatteryTempIndex.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempIndex.setDescription('Index into temperature table') vpwrBatteryTempName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 7, 1, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBatteryTempName.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempName.setDescription('A string identifying probe location.') vpwrBatteryTemp = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 7, 1, 1, 1, 3), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBatteryTemp.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTemp.setDescription('Current temperature as recorded by the probe.') vpwrBatteryTempLThreshold = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 2), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBatteryTempLThreshold.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempLThreshold.setDescription('Temperature value at which a clear trap would be sent. All three battery temperature must be at or below this value to trigger this trap. ') vpwrBatteryTempUThreshold = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 3), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBatteryTempUThreshold.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryTempUThreshold.setDescription('Temperature value at which a set trap would be sent. Any one of the three battery temperatures at or exceeding this limit would trigger the trap. ') batteryTempCompensation = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("tempCompDisabled", 0), ("tempCompEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompensation.setReference(' ') if mibBuilder.loadTexts: batteryTempCompensation.setStatus('current') if mibBuilder.loadTexts: batteryTempCompensation.setDescription(' This parameter enables/disables temperature compensation. ') batteryTempCompHighStartTemperature = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(25, 60))).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompHighStartTemperature.setReference(' ') if mibBuilder.loadTexts: batteryTempCompHighStartTemperature.setStatus('current') if mibBuilder.loadTexts: batteryTempCompHighStartTemperature.setDescription(' The temperature at which temperature compensation becomes active. ') batteryTempCompHighStopVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 6), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompHighStopVoltage.setReference(' ') if mibBuilder.loadTexts: batteryTempCompHighStopVoltage.setStatus('current') if mibBuilder.loadTexts: batteryTempCompHighStopVoltage.setDescription(' When temperature compensation is active, batteryTempCompHighStopVoltage is the limit to which float voltage will be reduced. For example, to set this voltage to 51.75 volts enter a value of 5175. ') batteryTempCompHighSlope = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setUnits(' milli-Volts per degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompHighSlope.setReference(' ') if mibBuilder.loadTexts: batteryTempCompHighSlope.setStatus('current') if mibBuilder.loadTexts: batteryTempCompHighSlope.setDescription(' The rate at which float voltage is changed, within the specified limits, when temperature compensation is active. ') batteryTempCompLowStartTemperature = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 8), Integer32()).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompLowStartTemperature.setReference(' ') if mibBuilder.loadTexts: batteryTempCompLowStartTemperature.setStatus('current') if mibBuilder.loadTexts: batteryTempCompLowStartTemperature.setDescription(' The temperature at which temperature compensation becomes active. ') batteryTempCompLowStopVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 9), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompLowStopVoltage.setReference(' ') if mibBuilder.loadTexts: batteryTempCompLowStopVoltage.setStatus('current') if mibBuilder.loadTexts: batteryTempCompLowStopVoltage.setDescription(' When temperature compensation is active, batteryTempCompLowStopVoltage is the limit to which float voltage will be reduced. For example, to set this voltage to 51.75 volts enter a value of 5175. ') batteryTempCompLowSlope = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 250))).setUnits(' milli-Volts per degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompLowSlope.setReference(' ') if mibBuilder.loadTexts: batteryTempCompLowSlope.setStatus('current') if mibBuilder.loadTexts: batteryTempCompLowSlope.setDescription(' The rate at which float voltage is changed, within the specified limits, when temperature compensation is active. ') batteryTempCompRunawayTemperature = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(25, 60))).setUnits('degrees Centigrade').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompRunawayTemperature.setReference(' ') if mibBuilder.loadTexts: batteryTempCompRunawayTemperature.setStatus('current') if mibBuilder.loadTexts: batteryTempCompRunawayTemperature.setDescription(' The temperature at which system voltage will be set to batteryTempCompRunawayStopVoltage. ') batteryTempCompRunawayStopVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 12), Integer32()).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompRunawayStopVoltage.setReference(' ') if mibBuilder.loadTexts: batteryTempCompRunawayStopVoltage.setStatus('current') if mibBuilder.loadTexts: batteryTempCompRunawayStopVoltage.setDescription(' When temperature compensation is enabled, float voltage will be reduced to batteryTempCompRunawayStopVoltage if temperature reaches batteryTempCompRunawayTemperature. ') batteryTempCompSenseSource = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("external", 0), ("internal", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: batteryTempCompSenseSource.setReference(' ') if mibBuilder.loadTexts: batteryTempCompSenseSource.setStatus('current') if mibBuilder.loadTexts: batteryTempCompSenseSource.setDescription(' This parameter selects the temperature sensing point for temperature compensation (in)activation. ') batteryTempCompRunawayState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("inactive", 0), ("active", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: batteryTempCompRunawayState.setReference(' ') if mibBuilder.loadTexts: batteryTempCompRunawayState.setStatus('current') if mibBuilder.loadTexts: batteryTempCompRunawayState.setDescription(' This parameter selects the temperature sensing point for temperature compensation (in)activation. ') thermalProbeTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 7, 1, 15), ) if mibBuilder.loadTexts: thermalProbeTable.setStatus('current') if mibBuilder.loadTexts: thermalProbeTable.setDescription('This table describes battery temperature probes. ') thermalProbeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 7, 1, 15, 1), ) vpwrBatteryTempEntry.registerAugmentions(("VALERE-DC-POWER-MIB", "thermalProbeEntry")) thermalProbeEntry.setIndexNames(*vpwrBatteryTempEntry.getIndexNames()) if mibBuilder.loadTexts: thermalProbeEntry.setStatus('current') if mibBuilder.loadTexts: thermalProbeEntry.setDescription('An entry containing information applicable to a particular temperature probe.') thermalProbeState = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 7, 1, 15, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("notPresent", 0), ("present", 1), ("removed", 2), ("shorted", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: thermalProbeState.setStatus('current') if mibBuilder.loadTexts: thermalProbeState.setDescription('State of thermal probe.') vpwrTrapTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 9, 1), ) if mibBuilder.loadTexts: vpwrTrapTable.setStatus('current') if mibBuilder.loadTexts: vpwrTrapTable.setDescription('A list of possible trap destinations depending upon the criticality of the trap. ') vpwrTrapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 9, 1, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrTrapIpIndex")) if mibBuilder.loadTexts: vpwrTrapEntry.setStatus('current') if mibBuilder.loadTexts: vpwrTrapEntry.setDescription('An entry containing information applicable to a particular trap destination.') vpwrTrapIpIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 9, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrTrapIpIndex.setStatus('current') if mibBuilder.loadTexts: vpwrTrapIpIndex.setDescription('Trap Entry Index ') vpwrTrapIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 9, 1, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrTrapIpAddress.setStatus('current') if mibBuilder.loadTexts: vpwrTrapIpAddress.setDescription('Trap destination IP Address') vpwrTrapCriticality = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 9, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrTrapCriticality.setStatus('current') if mibBuilder.loadTexts: vpwrTrapCriticality.setDescription('Criticality of traps sent to this IP Address') vpwrReadCommunityString = MibScalar((1, 3, 6, 1, 4, 1, 13858, 9, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(3, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrReadCommunityString.setStatus('current') if mibBuilder.loadTexts: vpwrReadCommunityString.setDescription(' This allows setting password to be able to do Get operations') vpwrWriteCommunityString = MibScalar((1, 3, 6, 1, 4, 1, 13858, 9, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(3, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrWriteCommunityString.setStatus('current') if mibBuilder.loadTexts: vpwrWriteCommunityString.setDescription(' This allows setting password to be able to do Get and Set operations. The read-access is not allowed in the actual implementation. ') vpwrTrapCommunityString = MibScalar((1, 3, 6, 1, 4, 1, 13858, 9, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(3, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrTrapCommunityString.setStatus('current') if mibBuilder.loadTexts: vpwrTrapCommunityString.setDescription(' This allows setting community string required for the trap to be accepted at the destination. ') vpwrTrapPowerMajorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,1)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapPowerMajorAlarm.setDescription('Major Alarm') vpwrTrapPowerMinorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,2)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapPowerMinorAlarm.setDescription('Minor Alarm') vpwrTrapACFAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,3)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapACFAlarm.setDescription('AC Fail Alarm') vpwrTrapHVAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,4)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapHVAlarm.setDescription('High Voltage Warning Alarm') vpwrTrapHVSDAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,5)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapHVSDAlarm.setDescription('High Voltage Shutdown Alarm') vpwrTrapBDAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,6)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapBDAlarm.setDescription('Battery on Discharge Alarm') vpwrTrapLVDWarningAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,7)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapLVDWarningAlarm.setDescription('LVD Warning Alarm') vpwrTrapLVDOpenAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,8)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapLVDOpenAlarm.setDescription('LVD Open Alarm') vpwrTrapDistAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,9)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapDistAlarm.setDescription('Distribution Open Alarm') vpwrTrapAuxAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,10)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapAuxAlarm.setDescription('Auxiliary System Alarm') vpwrTrapSystemRedundancyAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,11)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSystemRedundancyAlarm.setDescription('System Redundant Capacity Alarm') vpwrTrapIShareAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,12)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapIShareAlarm.setDescription('Rectifier Current Share Alarm') vpwrTrapModuleFailAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,13)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapModuleFailAlarm.setDescription('Single Rectifier Fail Alarm') vpwrTrapMultipleModuleFailAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,14)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapMultipleModuleFailAlarm.setDescription('Multiple Rectifier Fail Alarm') vpwrTrapModuleCommAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,15)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapModuleCommAlarm.setDescription('Module Communication Alarm') vpwrTrapSystemOverTemperatureAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,16)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSystemOverTemperatureAlarm.setDescription('System Over Temperature Alarm') vpwrTrapSystemOK = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,17)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSystemOK.setDescription('SYSTEM OK - No Active Alarms') vpwrTrapModuleInserted = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,18)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString"), ("VALERE-DC-POWER-MIB", "vpwrBayIndex"), ("VALERE-DC-POWER-MIB", "vpwrModuleIndex")) if mibBuilder.loadTexts: vpwrTrapModuleInserted.setDescription('A new module has been inserted into the system.') vpwrTrapModuleRemoved = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,19)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString"), ("VALERE-DC-POWER-MIB", "vpwrBayIndex"), ("VALERE-DC-POWER-MIB", "vpwrModuleIndex")) if mibBuilder.loadTexts: vpwrTrapModuleRemoved.setDescription('A module has been removed from the system.') vpwrTrapThermalCompActive = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,20)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapThermalCompActive.setDescription('Thermal compensation has become active.') vpwrTrapThermalCompInactive = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,21)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapThermalCompInactive.setDescription('Thermal compensation has been de-activated.') vpwrTrapInternalTempAlarmSet = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,22)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapInternalTempAlarmSet.setDescription('Internal Temperature upper threshold exceeded.') vpwrTrapInternalTempAlarmCleared = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,23)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapInternalTempAlarmCleared.setDescription('Internal Temperature within limits') vpwrTrapBatteryTempAlarmSet = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,24)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapBatteryTempAlarmSet.setDescription('At least one Battery Temperature exceeded upper threshold.') vpwrTrapBatteryTempAlarmCleared = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,25)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapBatteryTempAlarmCleared.setDescription('All Battery Temperatures within limits.') vpwrTrapLoginFail = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,26)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapLoginFail.setDescription('Admin login failed due to wrong username/password.') vpwrTrapLoginSuccess = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,27)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapLoginSuccess.setDescription('Admin login successful.') vpwrTrapLogout = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,28)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapLogout.setDescription('Admin logout.') vpwrTrapAdminPwdChange = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,29)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapAdminPwdChange.setDescription('Config change submitted with invalid access.') vpwrTrapIllegalConfigSubmit = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,30)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapIllegalConfigSubmit.setDescription('Config change submitted with invalid access.') vpwrTrapCfgChange = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,31)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapCfgChange.setDescription('Config change submitted.') vpwrTrapClearEventHistory = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,32)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapClearEventHistory.setDescription('Clear Event history buffer clear request.') vpwrTrapSwDownloadNoReboot = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,33)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSwDownloadNoReboot.setDescription('System software upgrade without reboot.') vpwrTrapSwDownloadAndReboot = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,34)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSwDownloadAndReboot.setDescription('System reboot due to software upgrade.') vpwrTrapSystemClockChange = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,35)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSystemClockChange.setDescription('System clock updated.') vpwrTrapModuleAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,36)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapModuleAlarm.setDescription('Module Alarm.') vpwrTrapOIDChange = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,37)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapOIDChange.setDescription('Change in OID.') vpwrTrapThermalRunaway = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,38)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapThermalRunaway.setDescription('Thermal Runaway Alarm.') vpwrTrapBatteryDischargeTestAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,39)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapBatteryDischargeTestAlarm.setDescription('System Voltage dropped to BDT Alarm Setpoint.') vpwrTrapRingerAAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,40)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapRingerAAlarm.setDescription('Ringer A Fail Alarm.') vpwrTrapRingerBAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,41)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapRingerBAlarm.setDescription('Ringer B Fail Alarm.') vpwrTrapSingleRingerAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,42)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSingleRingerAlarm.setDescription('Single Ringer Fail Alarm.') vpwrTrapMultipleRingerAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,43)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapMultipleRingerAlarm.setDescription('Multiple Ringer Fail Alarm.') vpwrTrapThermalProbeAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,44)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapThermalProbeAlarm.setDescription('Thermal Probe Missing Alarm.') vpwrTrapRingerCommAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,45)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapRingerCommAlarm.setDescription('Ringer Communication Alarm.') vpwrTrapDistributionCommAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,46)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapDistributionCommAlarm.setDescription('Distribution Communication Alarm.') vpwrTrapConverterAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,47)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapConverterAlarm.setDescription('Single Converter Fail Alarm.') vpwrTrapMultipleConvFailAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,48)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapMultipleConvFailAlarm.setDescription('Multiple Converter Fail Alarm.') vpwrTrapUnmappedAddressAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,49)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapUnmappedAddressAlarm.setDescription('Unmapped I2C Address.') vpwrTrapConfigErrorAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,50)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapConfigErrorAlarm.setDescription('Configuration Error.') vpwrTrapDisplayFirmwareMismatchAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,51)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapDisplayFirmwareMismatchAlarm.setDescription('Display Firmware Mismatch.') vpwrTrapConverterInputFailAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,52)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapConverterInputFailAlarm.setDescription('Converter Input Fail Alarm.') vpwrTrapBatteryRechgIlimitFailAlarm = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,53)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapBatteryRechgIlimitFailAlarm.setDescription('Battery Recharge Current Limit Fail.') vpwrTrapSystemAlive = NotificationType((1, 3, 6, 1, 4, 1, 13858, 10) + (0,54)).setObjects(("VALERE-DC-POWER-MIB", "vpwrTrapsMsgString")) if mibBuilder.loadTexts: vpwrTrapSystemAlive.setDescription('Periodic Keepalive trap.') vpwrLvdAlarmContactorOpen = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 4, 2, 1)) if mibBuilder.loadTexts: vpwrLvdAlarmContactorOpen.setStatus('current') if mibBuilder.loadTexts: vpwrLvdAlarmContactorOpen.setDescription('Contactor open') vpwrLvdAlarmCBOpen = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 4, 2, 2)) if mibBuilder.loadTexts: vpwrLvdAlarmCBOpen.setStatus('current') if mibBuilder.loadTexts: vpwrLvdAlarmCBOpen.setDescription('Circuit Breaker open') vpwrTrapLvdFuseOpen = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 4, 2, 3)) if mibBuilder.loadTexts: vpwrTrapLvdFuseOpen.setStatus('current') if mibBuilder.loadTexts: vpwrTrapLvdFuseOpen.setDescription('Fuse open') vpwrLvdAlarmWarning = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 4, 2, 4)) if mibBuilder.loadTexts: vpwrLvdAlarmWarning.setStatus('current') if mibBuilder.loadTexts: vpwrLvdAlarmWarning.setDescription('Plant Voltage below warning threshold') vpwrRectAlarmDCFail = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 1)) if mibBuilder.loadTexts: vpwrRectAlarmDCFail.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmDCFail.setDescription(' ') vpwrRectAlarmBoostFail = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 2)) if mibBuilder.loadTexts: vpwrRectAlarmBoostFail.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmBoostFail.setDescription(' ') vpwrRectAlarmACFail = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 3)) if mibBuilder.loadTexts: vpwrRectAlarmACFail.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmACFail.setDescription(' ') vpwrRectAlarmHVSD = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 4)) if mibBuilder.loadTexts: vpwrRectAlarmHVSD.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmHVSD.setDescription(' ') vpwrRectAlarmFanFail = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 5)) if mibBuilder.loadTexts: vpwrRectAlarmFanFail.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmFanFail.setDescription(' ') vpwrRectAlarmAmbTemp = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 6)) if mibBuilder.loadTexts: vpwrRectAlarmAmbTemp.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmAmbTemp.setDescription(' ') vpwrRectAlarmIntTemp = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 7)) if mibBuilder.loadTexts: vpwrRectAlarmIntTemp.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmIntTemp.setDescription(' ') vpwrRectAlarmIShare = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 8)) if mibBuilder.loadTexts: vpwrRectAlarmIShare.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmIShare.setDescription(' ') vpwrRectAlarmUV = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 9)) if mibBuilder.loadTexts: vpwrRectAlarmUV.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmUV.setDescription(' ') vpwrRectAlarmLowVoltage = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 10)) if mibBuilder.loadTexts: vpwrRectAlarmLowVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmLowVoltage.setDescription(' ') vpwrRectAlarmReserved = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 11)) if mibBuilder.loadTexts: vpwrRectAlarmReserved.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmReserved.setDescription(' ') vpwrRectAlarmDCEnable = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 12)) if mibBuilder.loadTexts: vpwrRectAlarmDCEnable.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmDCEnable.setDescription(' ') vpwrRectAlarmRemoteShutdown = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 13)) if mibBuilder.loadTexts: vpwrRectAlarmRemoteShutdown.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmRemoteShutdown.setDescription(' ') vpwrRectAlarmModDisableShutdown = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 14)) if mibBuilder.loadTexts: vpwrRectAlarmModDisableShutdown.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmModDisableShutdown.setDescription(' ') vpwrRectAlarmShortPinShutdown = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 15)) if mibBuilder.loadTexts: vpwrRectAlarmShortPinShutdown.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmShortPinShutdown.setDescription(' ') vpwrRectAlarmBoostComm = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 3, 2, 16)) if mibBuilder.loadTexts: vpwrRectAlarmBoostComm.setStatus('current') if mibBuilder.loadTexts: vpwrRectAlarmBoostComm.setDescription(' ') vpwrTrapsMsgString = MibScalar((1, 3, 6, 1, 4, 1, 13858, 11, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 127))) if mibBuilder.loadTexts: vpwrTrapsMsgString.setStatus('current') if mibBuilder.loadTexts: vpwrTrapsMsgString.setDescription(' Place holder for trap notification message string') vpwrTrapUserIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 13858, 11, 2), IpAddress()) if mibBuilder.loadTexts: vpwrTrapUserIpAddress.setStatus('current') if mibBuilder.loadTexts: vpwrTrapUserIpAddress.setDescription('Place holder for IP address of the user accessing the system') vpwrTrapEventTimeStamp = MibScalar((1, 3, 6, 1, 4, 1, 13858, 11, 3), IpAddress()) if mibBuilder.loadTexts: vpwrTrapEventTimeStamp.setStatus('current') if mibBuilder.loadTexts: vpwrTrapEventTimeStamp.setDescription('Place holder for time-stamp.') sysRelayConfigTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 8, 3), ) if mibBuilder.loadTexts: sysRelayConfigTable.setStatus('current') if mibBuilder.loadTexts: sysRelayConfigTable.setDescription('This table describes battery temperature probes. ') sysRelayConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 8, 3, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "sysRelayIndex")) if mibBuilder.loadTexts: sysRelayConfigEntry.setStatus('current') if mibBuilder.loadTexts: sysRelayConfigEntry.setDescription('An entry containing information applicable to a particular temperature probe.') sysRelayIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysRelayIndex.setStatus('current') if mibBuilder.loadTexts: sysRelayIndex.setDescription('Index into temperature table') sysRelayDefaultName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysRelayDefaultName.setStatus('current') if mibBuilder.loadTexts: sysRelayDefaultName.setDescription('A string identifying probe location.') sysRelayCustomName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 3, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysRelayCustomName.setStatus('current') if mibBuilder.loadTexts: sysRelayCustomName.setDescription('A string identifying probe location.') sysRelayAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("alarmNone", 0), ("alarmMajor", 1), ("alarmMinor", 2), ("alarmMajorAndMinor", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysRelayAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: sysRelayAlarmSeverity.setDescription('Current temperature as recorded by the probe.') sysAlarmConfigTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 8, 4), ) if mibBuilder.loadTexts: sysAlarmConfigTable.setStatus('current') if mibBuilder.loadTexts: sysAlarmConfigTable.setDescription('This table describes battery temperature probes. ') sysAlarmConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "sysAlarmIndex")) if mibBuilder.loadTexts: sysAlarmConfigEntry.setStatus('current') if mibBuilder.loadTexts: sysAlarmConfigEntry.setDescription('An entry containing information applicable to a particular temperature probe.') sysAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAlarmIndex.setStatus('current') if mibBuilder.loadTexts: sysAlarmIndex.setDescription('Index into temperature table') sysAlarmDefaultName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAlarmDefaultName.setStatus('current') if mibBuilder.loadTexts: sysAlarmDefaultName.setDescription('A string identifying probe location.') sysAlarmCustomName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmCustomName.setStatus('current') if mibBuilder.loadTexts: sysAlarmCustomName.setDescription('A string identifying probe location.') sysAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("major", 1), ("minor", 2), ("majorAndMinor", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: sysAlarmSeverity.setDescription('Alarm Severity as denoted by Major and Minor Alarm Mask') sysAlarmToRelayMapping = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmToRelayMapping.setStatus('current') if mibBuilder.loadTexts: sysAlarmToRelayMapping.setDescription('No additional mapping = 0 Map to Relay A = 1 Map to Relay B = 2 Map to Relay C = 4 Map to Relay D = 8 Map to Relay E = 16 Map to Relay F = 32 Map to Relay A and B = (1 + 2) and so on The major/minor classification of alarms automatically associates it with Major/Minor relay. Assigning a null mapping here does not override sysRelayAlarmSeverity for the alarm. It should be used to define mapping to additional relays. ') sysAlarmOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 4, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("inactive", 0), ("active", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAlarmOperStatus.setStatus('current') if mibBuilder.loadTexts: sysAlarmOperStatus.setDescription('Indicates current alarm status') sysAuxAlarmConfigTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 8, 5), ) if mibBuilder.loadTexts: sysAuxAlarmConfigTable.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmConfigTable.setDescription('This table describes battery temperature probes. ') sysAuxAlarmConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "sysAuxAlarmIndex")) if mibBuilder.loadTexts: sysAuxAlarmConfigEntry.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmConfigEntry.setDescription('An entry containing information applicable to a particular temperature probe.') sysAuxAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAuxAlarmIndex.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmIndex.setDescription('Index into temperature table') sysAuxAlarmDefaultName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAuxAlarmDefaultName.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmDefaultName.setDescription('A string identifying probe location.') sysAuxAlarmCustomName = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAuxAlarmCustomName.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmCustomName.setDescription('A string identifying probe location.') sysAuxAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("major", 1), ("minor", 2), ("majorAndMinor", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAuxAlarmSeverity.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmSeverity.setDescription('Aux Alarm Severity') sysAuxAlarmToRelayMapping = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAuxAlarmToRelayMapping.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmToRelayMapping.setDescription('No additional mapping = 0 Map to Relay A = 1 Map to Relay B = 2 Map to Relay C = 4 Map to Relay D = 8 Map to Relay E = 16 Map to Relay F = 32 Map to Relay A and B = (1 + 2) and so on The major/minor classification of alarms automatically associates it with Major/Minor relay. Assigning a null mapping here does not override sysRelayAlarmSeverity for the alarm. It should be used to define mapping to additional relays. ') sysAuxAlarmPolarity = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("alarmOnOpen", 0), ("alarmOnClose", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAuxAlarmPolarity.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmPolarity.setDescription('Current temperature as recorded by the probe.') sysAuxAlarmOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 8, 5, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("inactive", 0), ("active", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysAuxAlarmOperStatus.setStatus('current') if mibBuilder.loadTexts: sysAuxAlarmOperStatus.setDescription('Indicates current alarm status') sysAlarmComFailState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1), ("other", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmComFailState.setStatus('current') if mibBuilder.loadTexts: sysAlarmComFailState.setDescription('Enable/Disable generation of comm fail alarm.') sysAlarmIShareState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 8, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1), ("other", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmIShareState.setStatus('current') if mibBuilder.loadTexts: sysAlarmIShareState.setDescription('Enable/Disable generation of current share alarm.') sysAlarmRedundancyState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 8, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("disabled", 0), ("nPlus1", 1), ("nPlus2", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysAlarmRedundancyState.setStatus('current') if mibBuilder.loadTexts: sysAlarmRedundancyState.setDescription('Enable/Disable generation of redundancy alarm.') vpwrRingerParameterTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1), ) if mibBuilder.loadTexts: vpwrRingerParameterTable.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterTable.setDescription('A list of alarm table entries. The table contains zero, one, or many rows at any moment, depending upon the number of alarm conditions in effect. The table is initially empty at agent startup. The agent creates a row in the table each time a condition is detected and deletes that row when that condition no longer pertains. The vpwrAlarmIndex, for each type of module starts at 1 and is limited by the total number of alarams that can be generated by the module. Alarms are named by an AutonomousType (OBJECT IDENTIFIER), vpwrAlarmDescr, to allow a single table to reflect alarms for different type of modules. The number of rows in the table at any given time is reflected by the value of vpwrAlarmsPresent.') vpwrRingerParameterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1), ).setIndexNames((0, "VALERE-DC-POWER-MIB", "vpwrModuleIndex"), (0, "VALERE-DC-POWER-MIB", "vpwrRingerIndex")) if mibBuilder.loadTexts: vpwrRingerParameterEntry.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterEntry.setDescription('An entry containing information applicable to a particular alarm.') vpwrRingerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrRingerIndex.setReference(' ') if mibBuilder.loadTexts: vpwrRingerIndex.setStatus('current') if mibBuilder.loadTexts: vpwrRingerIndex.setDescription(' This parameter allows selecting ringer A or Ringer B as the active ringer. ') vpwrRingerParameterAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ringerDisabled", 0), ("ringerAOn", 1), ("ringerBOn", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRingerParameterAdminState.setReference(' ') if mibBuilder.loadTexts: vpwrRingerParameterAdminState.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterAdminState.setDescription(' This parameter allows selecting ringer A or Ringer B as the active ringer. ') vpwrRingerParameterAcVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(7000, 11000))).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRingerParameterAcVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrRingerParameterAcVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterAcVoltage.setDescription(' ') vpwrRingerParameterDcVoltage = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 5600))).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRingerParameterDcVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrRingerParameterDcVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterDcVoltage.setDescription(' ') vpwrRingerParameterFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 12, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(17, 50))).setUnits(' Hz').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrRingerParameterFrequency.setReference(' ') if mibBuilder.loadTexts: vpwrRingerParameterFrequency.setStatus('current') if mibBuilder.loadTexts: vpwrRingerParameterFrequency.setDescription(' ') vpwrRingerNumberPresent = MibScalar((1, 3, 6, 1, 4, 1, 13858, 12, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrRingerNumberPresent.setStatus('current') if mibBuilder.loadTexts: vpwrRingerNumberPresent.setDescription('The present number of active alarm conditions.') vpwrRingerAlarmaAFailed = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 1)) if mibBuilder.loadTexts: vpwrRingerAlarmaAFailed.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmaAFailed.setDescription('Ringer A Failed') vpwrRingerAlarmAOTemp = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 2)) if mibBuilder.loadTexts: vpwrRingerAlarmAOTemp.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmAOTemp.setDescription('Ringer A Heatsink Over-Temperature') vpwrRingerAlarmAOCurrent = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 3)) if mibBuilder.loadTexts: vpwrRingerAlarmAOCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmAOCurrent.setDescription('Ringer A Over-Current protection') vpwrRingerAlarmaBFailed = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 4)) if mibBuilder.loadTexts: vpwrRingerAlarmaBFailed.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmaBFailed.setDescription('Ringer A Failed') vpwrRingerAlarmBOverTemp = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 5)) if mibBuilder.loadTexts: vpwrRingerAlarmBOverTemp.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmBOverTemp.setDescription('Ringer A Heatsink Over-Temperature') vpwrRingerAlarmBOverCurrent = ObjectIdentity((1, 3, 6, 1, 4, 1, 13858, 12, 2, 6)) if mibBuilder.loadTexts: vpwrRingerAlarmBOverCurrent.setStatus('current') if mibBuilder.loadTexts: vpwrRingerAlarmBOverCurrent.setDescription('Ringer A Over-Current protection') vpwrBoostAdminState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("boostDisabled", 0), ("boostEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBoostAdminState.setReference(' ') if mibBuilder.loadTexts: vpwrBoostAdminState.setStatus('current') if mibBuilder.loadTexts: vpwrBoostAdminState.setDescription(' This parameter allows enabling or disabling boost. ') vpwrBoostVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 3, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(7000, 11000))).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBoostVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrBoostVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrBoostVoltage.setDescription(' ') vpwrBoostDuration = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 3, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('Hours').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBoostDuration.setReference(' ') if mibBuilder.loadTexts: vpwrBoostDuration.setStatus('current') if mibBuilder.loadTexts: vpwrBoostDuration.setDescription(' ') vpwrBoostOperState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 3, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("boostInactive", 0), ("boostActive", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBoostOperState.setReference(' ') if mibBuilder.loadTexts: vpwrBoostOperState.setStatus('current') if mibBuilder.loadTexts: vpwrBoostOperState.setDescription(' This parameter allows starting or stoping boost if it is enabled. ') vpwrBatteryCurrentLimitAdminState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("battetyCurrentLimitDisabled", 0), ("battetyCurrentLimitEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBatteryCurrentLimitAdminState.setReference(' ') if mibBuilder.loadTexts: vpwrBatteryCurrentLimitAdminState.setStatus('current') if mibBuilder.loadTexts: vpwrBatteryCurrentLimitAdminState.setDescription(' This parameter allows enabling or disabling battery current limit. ') vpwrBattetyCurrentLimitValue = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 40))).setUnits('Ampere').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBattetyCurrentLimitValue.setReference(' ') if mibBuilder.loadTexts: vpwrBattetyCurrentLimitValue.setStatus('current') if mibBuilder.loadTexts: vpwrBattetyCurrentLimitValue.setDescription(' ') vpwrBattetyCurrentValue = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 2, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 40))).setUnits('Ampere').setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBattetyCurrentValue.setReference(' ') if mibBuilder.loadTexts: vpwrBattetyCurrentValue.setStatus('current') if mibBuilder.loadTexts: vpwrBattetyCurrentValue.setDescription(' ') vpwrBDTAdminState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("bdtDisabled", 0), ("bdtEnabled", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTAdminState.setReference(' ') if mibBuilder.loadTexts: vpwrBDTAdminState.setStatus('current') if mibBuilder.loadTexts: vpwrBDTAdminState.setDescription(' Enable /Disable Battery Discharge Test execution. ') vpwrBDTDuration = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(17, 50))).setUnits('Minutes').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTDuration.setReference(' ') if mibBuilder.loadTexts: vpwrBDTDuration.setStatus('current') if mibBuilder.loadTexts: vpwrBDTDuration.setDescription(' ') vpwrBDTAlarmVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(7000, 11000))).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTAlarmVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrBDTAlarmVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrBDTAlarmVoltage.setDescription(' ') vpwrBDTAbortVoltage = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 5600))).setUnits(' *.01 Volts').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTAbortVoltage.setReference(' ') if mibBuilder.loadTexts: vpwrBDTAbortVoltage.setStatus('current') if mibBuilder.loadTexts: vpwrBDTAbortVoltage.setDescription(' ') vpwrBDTAlarmCoefficient = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1))).setUnits('None').setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTAlarmCoefficient.setReference(' ') if mibBuilder.loadTexts: vpwrBDTAlarmCoefficient.setStatus('current') if mibBuilder.loadTexts: vpwrBDTAlarmCoefficient.setDescription(' ') vpwrBDTOperState = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("bdtInactive", 0), ("bdtActive", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTOperState.setReference(' ') if mibBuilder.loadTexts: vpwrBDTOperState.setStatus('current') if mibBuilder.loadTexts: vpwrBDTOperState.setDescription(' Start/Stop Battery Discharge Test execution. ') vpwrBDTClearAlarm = MibScalar((1, 3, 6, 1, 4, 1, 13858, 7, 4, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("bdtNoAlarm", 0), ("bdtAlarmPresent", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: vpwrBDTClearAlarm.setReference(' ') if mibBuilder.loadTexts: vpwrBDTClearAlarm.setStatus('current') if mibBuilder.loadTexts: vpwrBDTClearAlarm.setDescription(' Clears any active bdt alarm. ') vpwrModuleIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 6, 1), ) if mibBuilder.loadTexts: vpwrModuleIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrModuleIdentTable.setDescription(' This table describes shelves and modules that make up the sysetm. ') vpwrModuleIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1), ) vpwrSystemIdentEntry.registerAugmentions(("VALERE-DC-POWER-MIB", "vpwrModuleIdentEntry")) vpwrModuleIdentEntry.setIndexNames(*vpwrSystemIdentEntry.getIndexNames()) if mibBuilder.loadTexts: vpwrModuleIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrModuleIdentEntry.setDescription('An entry containing information applicable to a particular Module.') vpwrModuleSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleSerialNumber.setStatus('current') if mibBuilder.loadTexts: vpwrModuleSerialNumber.setDescription('Serial Number of the module') vpwrModuleModelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleModelNumber.setStatus('current') if mibBuilder.loadTexts: vpwrModuleModelNumber.setDescription('Model Number of the module.') vpwrModuleFwVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleFwVersion.setStatus('current') if mibBuilder.loadTexts: vpwrModuleFwVersion.setDescription('Firmware version of the module.') vpwrModuleTestDate = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleTestDate.setStatus('current') if mibBuilder.loadTexts: vpwrModuleTestDate.setDescription('Date when the module was last tested.') vpwrModuleOperHours = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrModuleOperHours.setStatus('current') if mibBuilder.loadTexts: vpwrModuleOperHours.setDescription('Cumulative Operating Hours.') vpwrPanelModuleIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 6, 2), ) if mibBuilder.loadTexts: vpwrPanelModuleIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleIdentTable.setDescription(' This table describes shelves and modules that make up the sysetm. ') vpwrPanelModuleIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1), ) VpwrPanelIdentEntry.registerAugmentions(("VALERE-DC-POWER-MIB", "vpwrPanelModuleIdentEntry")) vpwrPanelModuleIdentEntry.setIndexNames(*VpwrPanelIdentEntry.getIndexNames()) if mibBuilder.loadTexts: vpwrPanelModuleIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleIdentEntry.setDescription('An entry containing information applicable to a particular alarm.') vpwrPanelModuleSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleSerialNumber.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleSerialNumber.setDescription('Serial Number of the module') vpwrPanelModuleModelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleModelNumber.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleModelNumber.setDescription('Model Number of the module.') vpwrPanelModuleFwVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleFwVersion.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleFwVersion.setDescription('Firmware version of the module.') vpwrPanelModuleTestDate = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleTestDate.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleTestDate.setDescription('Date when the module was last tested.') vpwrPanelModuleOperHours = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrPanelModuleOperHours.setStatus('current') if mibBuilder.loadTexts: vpwrPanelModuleOperHours.setDescription('Cumulative Operating Hours.') vpwrBayctrlModuleIdentTable = MibTable((1, 3, 6, 1, 4, 1, 13858, 6, 3), ) if mibBuilder.loadTexts: vpwrBayctrlModuleIdentTable.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlModuleIdentTable.setDescription(' This table describes bay controllers that make up the sysetm. ') vpwrBayctrlModuleIdentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1), ) VpwrBayctrlIdentEntry.registerAugmentions(("VALERE-DC-POWER-MIB", "vpwrBayctrlModuleIdentEntry")) vpwrBayctrlModuleIdentEntry.setIndexNames(*VpwrBayctrlIdentEntry.getIndexNames()) if mibBuilder.loadTexts: vpwrBayctrlModuleIdentEntry.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlModuleIdentEntry.setDescription('An entry containing information applicable to a particular bay controller.') vpwrBayctrlSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlSerialNumber.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlSerialNumber.setDescription('Serial Number of the bay controller') vpwrBayctrlModelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlModelNumber.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlModelNumber.setDescription('Model Number of the bay controller.') vpwrBayctrlFwVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlFwVersion.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlFwVersion.setDescription('Firmware version of the bay controller.') vpwrBayctrlTestDate = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlTestDate.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlTestDate.setDescription('Date when the bayctrl was last tested.') vpwrBayctrlOperHours = MibTableColumn((1, 3, 6, 1, 4, 1, 13858, 6, 3, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vpwrBayctrlOperHours.setStatus('current') if mibBuilder.loadTexts: vpwrBayctrlOperHours.setDescription('Cumulative Operating Hours.') mibBuilder.exportSymbols("VALERE-DC-POWER-MIB", vpwrTrapModuleInserted=vpwrTrapModuleInserted, vpwrTrapRingerBAlarm=vpwrTrapRingerBAlarm, PYSNMP_MODULE_ID=vpwrDcPowerMgt, vpwrIdentControllerVersion=vpwrIdentControllerVersion, vpwrBatteryTempEntry=vpwrBatteryTempEntry, vpwrTrapIpIndex=vpwrTrapIpIndex, sysRelayConfigTable=sysRelayConfigTable, vpwrLvdReconnectDelayTimer=vpwrLvdReconnectDelayTimer, vpwrTrapRingerAAlarm=vpwrTrapRingerAAlarm, vpwrDcPowerProducts=vpwrDcPowerProducts, vpwrDcPowerTrio=vpwrDcPowerTrio, vpwrTrapEventTimeStamp=vpwrTrapEventTimeStamp, vpwrBattetyCurrentValue=vpwrBattetyCurrentValue, vpwrTrapIShareAlarm=vpwrTrapIShareAlarm, vpwrPanelModuleModelNumber=vpwrPanelModuleModelNumber, vpwrLvdContactorConfigEntry=vpwrLvdContactorConfigEntry, vpwrTrapMultipleModuleFailAlarm=vpwrTrapMultipleModuleFailAlarm, vpwrLvdContactorReconnectDelayTimer=vpwrLvdContactorReconnectDelayTimer, vpwrRingerNumberPresent=vpwrRingerNumberPresent, sysRelayAlarmSeverity=sysRelayAlarmSeverity, vpwrBattetyCurrentLimitValue=vpwrBattetyCurrentLimitValue, sysAlarmSeverity=sysAlarmSeverity, vpwrIdentName=vpwrIdentName, vpwrLvdTestGroup=vpwrLvdTestGroup, vpwrDcPowerRinger=vpwrDcPowerRinger, vpwrLvdAlarmGroup=vpwrLvdAlarmGroup, vpwrTrapIllegalConfigSubmit=vpwrTrapIllegalConfigSubmit, vpwrSystemTempCompStartTemperature=vpwrSystemTempCompStartTemperature, vpwrBayctrlModelNumber=vpwrBayctrlModelNumber, vpwrRectAlarmReserved=vpwrRectAlarmReserved, sysAlarmOperStatus=sysAlarmOperStatus, vpwrPanelModuleCurrent=vpwrPanelModuleCurrent, thermalProbeState=thermalProbeState, vpwrDcDcConverterTestGroup=vpwrDcDcConverterTestGroup, vpwrRingerTestGroup=vpwrRingerTestGroup, vpwrRectAlarmLowVoltage=vpwrRectAlarmLowVoltage, sysAuxAlarmPolarity=sysAuxAlarmPolarity, vpwrTrapSwDownloadNoReboot=vpwrTrapSwDownloadNoReboot, vpwrSystemPanelIdentGroup=vpwrSystemPanelIdentGroup, vpwrModuleIdentEntry=vpwrModuleIdentEntry, vpwrSystemTempCompensationState=vpwrSystemTempCompensationState, vpwrSystemCurrent=vpwrSystemCurrent, vpwrModuleIdentTable=vpwrModuleIdentTable, vpwrSystemInternalTempUThreshold=vpwrSystemInternalTempUThreshold, vpwrSystemInternalTempLThreshold=vpwrSystemInternalTempLThreshold, vpwrTrapPowerMinorAlarm=vpwrTrapPowerMinorAlarm, vpwrBayctrlIdentTable=vpwrBayctrlIdentTable, vpwrTrapHVAlarm=vpwrTrapHVAlarm, vpwrTrapConverterInputFailAlarm=vpwrTrapConverterInputFailAlarm, vpwrTrapSystemAlive=vpwrTrapSystemAlive, vpwrRectAlarmDCEnable=vpwrRectAlarmDCEnable, vpwrDcPowerDcAcInverter=vpwrDcPowerDcAcInverter, vpwrSystemHVAlarmSetpoint=vpwrSystemHVAlarmSetpoint, vpwrSystemControllerState=vpwrSystemControllerState, vpwrTrapBDAlarm=vpwrTrapBDAlarm, thermalProbeEntry=thermalProbeEntry, vpwrRectAlarmRemoteShutdown=vpwrRectAlarmRemoteShutdown, vpwrBoostDuration=vpwrBoostDuration, vpwrBayctrlModuleIdentEntry=vpwrBayctrlModuleIdentEntry, vpwrBayctrlTestDate=vpwrBayctrlTestDate, vpwrModuleFwVersion=vpwrModuleFwVersion, vpwrRectifierCurrentLimit=vpwrRectifierCurrentLimit, vpwrSystemParameterGroup=vpwrSystemParameterGroup, vpwrPanelModuleFwVersion=vpwrPanelModuleFwVersion, vpwrRingerParameterFrequency=vpwrRingerParameterFrequency, vpwrTrapThermalCompInactive=vpwrTrapThermalCompInactive, vpwrTrapSingleRingerAlarm=vpwrTrapSingleRingerAlarm, vpwrBDTAlarmCoefficient=vpwrBDTAlarmCoefficient, vpwrRectAlarmAmbTemp=vpwrRectAlarmAmbTemp, vpwrSystemInternalTemperature=vpwrSystemInternalTemperature, batteryTempCompLowSlope=batteryTempCompLowSlope, vpwrDcPowerTest=vpwrDcPowerTest, vpwrDcDcConverterConfigGroup=vpwrDcDcConverterConfigGroup, vpwrPanelIdentEntry=vpwrPanelIdentEntry, vpwrTrapClearEventHistory=vpwrTrapClearEventHistory, vpwrWriteCommunityString=vpwrWriteCommunityString, vpwrTrapModuleCommAlarm=vpwrTrapModuleCommAlarm, vpwrLvdDisconnectSetpoint=vpwrLvdDisconnectSetpoint, sysAlarmIShareState=sysAlarmIShareState, vpwrBatteryTemp=vpwrBatteryTemp, sysAlarmIndex=sysAlarmIndex, sysAlarmRedundancyState=sysAlarmRedundancyState, vpwrRectifierAlarmGroup=vpwrRectifierAlarmGroup, vpwrRectAlarmModDisableShutdown=vpwrRectAlarmModDisableShutdown, vpwrRingerParameterAdminState=vpwrRingerParameterAdminState, vpwrSystemBayctrlIdentGroup=vpwrSystemBayctrlIdentGroup, vpwrSystemIdentGroup=vpwrSystemIdentGroup, batteryTempCompRunawayTemperature=batteryTempCompRunawayTemperature, vpwrLvdContactorReconnectSetpoint=vpwrLvdContactorReconnectSetpoint, vpwrAlarmDescr=vpwrAlarmDescr, vpwrBatteryBoostGroup=vpwrBatteryBoostGroup, vpwrTrapAdminPwdChange=vpwrTrapAdminPwdChange, vpwrRectAlarmFanFail=vpwrRectAlarmFanFail, vpwrLvdAlarmWarning=vpwrLvdAlarmWarning, vpwrRectAlarmIShare=vpwrRectAlarmIShare, sysAlarmCustomName=sysAlarmCustomName, vpwrRingerAlarmAOTemp=vpwrRingerAlarmAOTemp, vpwrTrapLogout=vpwrTrapLogout, vpwrAlarmsPresent=vpwrAlarmsPresent, vpwrRingerParameterAcVoltage=vpwrRingerParameterAcVoltage, vpwrBatteryTempTable=vpwrBatteryTempTable, vpwrModuleOID=vpwrModuleOID, vpwrDcPowerTraps=vpwrDcPowerTraps, vpwrPanelBayIndex=vpwrPanelBayIndex, vpwrTrapLoginFail=vpwrTrapLoginFail, vpwrLvdAlarmContactorOpen=vpwrLvdAlarmContactorOpen, vpwrBayctrlIndex=vpwrBayctrlIndex, sysAuxAlarmConfigTable=sysAuxAlarmConfigTable, vpwrModuleModelNumber=vpwrModuleModelNumber, vpwrTrapIpAddress=vpwrTrapIpAddress, vpwrTrapOIDChange=vpwrTrapOIDChange, vpwrRectAlarmDCFail=vpwrRectAlarmDCFail, sysAuxAlarmCustomName=sysAuxAlarmCustomName, vpwrTrapInternalTempAlarmSet=vpwrTrapInternalTempAlarmSet, vpwrTrapThermalProbeAlarm=vpwrTrapThermalProbeAlarm, sysAuxAlarmConfigEntry=sysAuxAlarmConfigEntry, vpwrRectAlarmShortPinShutdown=vpwrRectAlarmShortPinShutdown, vpwrDcPowerMgt=vpwrDcPowerMgt, vpwrRectAlarmUV=vpwrRectAlarmUV, sysRelayCustomName=sysRelayCustomName, vpwrDcPowerIoModule=vpwrDcPowerIoModule, vpwrDcPowerModuleIdent=vpwrDcPowerModuleIdent, sysAuxAlarmIndex=sysAuxAlarmIndex, vpwrTrapUnmappedAddressAlarm=vpwrTrapUnmappedAddressAlarm, vpwrModuleOperHours=vpwrModuleOperHours, vpwrTrapDistAlarm=vpwrTrapDistAlarm, NonNegativeInteger=NonNegativeInteger, vpwrBatteryTempName=vpwrBatteryTempName, vpwrTrapCriticality=vpwrTrapCriticality, vpwrRingerAlarmAOCurrent=vpwrRingerAlarmAOCurrent, vpwrSystemTempCompensation=vpwrSystemTempCompensation, vpwrBoostOperState=vpwrBoostOperState, vpwrSystemConfigGroup=vpwrSystemConfigGroup, vpwrModuleCapacity=vpwrModuleCapacity, vpwrRingerAlarmGroup=vpwrRingerAlarmGroup, vpwrLvdAlarmCBOpen=vpwrLvdAlarmCBOpen, vpwrPanelModuleOID=vpwrPanelModuleOID, vpwrBDTAbortVoltage=vpwrBDTAbortVoltage, vpwrIoModuleConfigGroup=vpwrIoModuleConfigGroup, vpwrTrapHVSDAlarm=vpwrTrapHVSDAlarm, vpwrModuleOperStatus=vpwrModuleOperStatus, vpwrBayctrlOperHours=vpwrBayctrlOperHours, vpwrBDTAdminState=vpwrBDTAdminState, vpwrPanelModuleSerialNumber=vpwrPanelModuleSerialNumber, vpwrPanelModuleTestDate=vpwrPanelModuleTestDate, vpwrBayctrlCapacity=vpwrBayctrlCapacity, vpwrSystemIdentTable=vpwrSystemIdentTable, sysRelayIndex=sysRelayIndex, vpwrBDTClearAlarm=vpwrBDTClearAlarm, vpwrPanelModuleIdentEntry=vpwrPanelModuleIdentEntry, vpwrTrapCommunityString=vpwrTrapCommunityString, vpwrRingerAlarmBOverTemp=vpwrRingerAlarmBOverTemp, batteryTempCompSenseSource=batteryTempCompSenseSource, vpwrBoostVoltage=vpwrBoostVoltage, vpwrLvdConfigGroup=vpwrLvdConfigGroup, vpwrLvdContactorWarningSetpoint=vpwrLvdContactorWarningSetpoint, vpwrRectAlarmIntTemp=vpwrRectAlarmIntTemp, vpwrTrapCfgChange=vpwrTrapCfgChange, sysAlarmDefaultName=sysAlarmDefaultName, vpwrSystemType=vpwrSystemType, sysAlarmConfigEntry=sysAlarmConfigEntry, vpwrTrapThermalCompActive=vpwrTrapThermalCompActive, vpwrTrapTable=vpwrTrapTable, vpwrIdentModel=vpwrIdentModel, vpwrDcPowerLvd=vpwrDcPowerLvd, vpwrBayIndex=vpwrBayIndex, vpwrAlarmTable=vpwrAlarmTable, batteryTempCompensation=batteryTempCompensation, vpwrTrapModuleRemoved=vpwrTrapModuleRemoved, vpwrBayctrlSerialNumber=vpwrBayctrlSerialNumber, vpwrTrapBatteryTempAlarmCleared=vpwrTrapBatteryTempAlarmCleared, vpwrBatteryDischargeTestGroup=vpwrBatteryDischargeTestGroup, sysRelayConfigEntry=sysRelayConfigEntry, sysAlarmComFailState=sysAlarmComFailState, vpwrIoModuleTestGroup=vpwrIoModuleTestGroup, batteryTempCompHighStartTemperature=batteryTempCompHighStartTemperature, vpwrDcPowerSystem=vpwrDcPowerSystem, vpwrBatteryCurrentLimitAdminState=vpwrBatteryCurrentLimitAdminState, vpwrTrapSystemOK=vpwrTrapSystemOK, vpwrLvdContactorIndex=vpwrLvdContactorIndex, vpwrDcDcConverterAlarmGroup=vpwrDcDcConverterAlarmGroup, vpwrBDTDuration=vpwrBDTDuration, vpwrTrapPowerMajorAlarm=vpwrTrapPowerMajorAlarm, vpwrAlarmTime=vpwrAlarmTime, vpwrDcPowerSnmpConfig=vpwrDcPowerSnmpConfig, vpwrBayctrlOID=vpwrBayctrlOID, vpwrBayctrlOperStatus=vpwrBayctrlOperStatus, vpwrSystemTempCompensationSlope=vpwrSystemTempCompensationSlope, vpwrLvdContactorState=vpwrLvdContactorState, thermalProbeTable=thermalProbeTable, vpwrRingerAlarmaAFailed=vpwrRingerAlarmaAFailed, vpwrTrapSystemOverTemperatureAlarm=vpwrTrapSystemOverTemperatureAlarm, vpwrSystemBDAlarmSetpoint=vpwrSystemBDAlarmSetpoint, vpwrTrapConverterAlarm=vpwrTrapConverterAlarm, vpwrTrapUserIpAddress=vpwrTrapUserIpAddress, vpwrBDTAlarmVoltage=vpwrBDTAlarmVoltage, vpwrDcPowerRectifier=vpwrDcPowerRectifier, vpwrRingerIndex=vpwrRingerIndex, vpwrDcPowerDcDcConverter=vpwrDcPowerDcDcConverter, vpwrTrapConfigErrorAlarm=vpwrTrapConfigErrorAlarm, vpwrDcPowerTrapsMsgString=vpwrDcPowerTrapsMsgString, vpwrTrapDisplayFirmwareMismatchAlarm=vpwrTrapDisplayFirmwareMismatchAlarm, vpwrRectifierFVSetpoint=vpwrRectifierFVSetpoint, vpwrSystemShelfCapacity=vpwrSystemShelfCapacity, vpwrTrapBatteryDischargeTestAlarm=vpwrTrapBatteryDischargeTestAlarm, vpwrTrapModuleFailAlarm=vpwrTrapModuleFailAlarm, vpwrPanelModuleOperHours=vpwrPanelModuleOperHours, batteryTempCompRunawayStopVoltage=batteryTempCompRunawayStopVoltage, PositiveInteger=PositiveInteger, vpwrBayctrlIdentEntry=vpwrBayctrlIdentEntry, vpwrTrapMultipleConvFailAlarm=vpwrTrapMultipleConvFailAlarm, vpwrRectifierTestGroup=vpwrRectifierTestGroup, batteryTempCompHighStopVoltage=batteryTempCompHighStopVoltage, vpwrDcAcInverterAlarmGroup=vpwrDcAcInverterAlarmGroup, vpwrRectifierHVSDSetpoint=vpwrRectifierHVSDSetpoint, vpwrTrapThermalRunaway=vpwrTrapThermalRunaway, vpwrDcPowerBayController=vpwrDcPowerBayController, vpwrPanelModuleIndex=vpwrPanelModuleIndex, vpwrSystemTempCompStopVoltage=vpwrSystemTempCompStopVoltage, vpwrTrapLVDWarningAlarm=vpwrTrapLVDWarningAlarm, vpwrDcAcInverterTestGroup=vpwrDcAcInverterTestGroup, vpwrLvdContactorConfigTable=vpwrLvdContactorConfigTable, sysAuxAlarmOperStatus=sysAuxAlarmOperStatus, vpwrTrapLoginSuccess=vpwrTrapLoginSuccess, vpwrModuleIndex=vpwrModuleIndex, vpwrTrapAuxAlarm=vpwrTrapAuxAlarm, sysAuxAlarmSeverity=sysAuxAlarmSeverity, batteryTempCompRunawayState=batteryTempCompRunawayState, vpwrDcPowerBatteryGroup=vpwrDcPowerBatteryGroup, vpwrIoModuleAlarmGroup=vpwrIoModuleAlarmGroup, vpwrReadCommunityString=vpwrReadCommunityString, vpwrIdentAgentSoftwareVersion=vpwrIdentAgentSoftwareVersion, vpwrLvdContactorDisconnectSetpoint=vpwrLvdContactorDisconnectSetpoint, vpwrRingerParameterTable=vpwrRingerParameterTable, vpwrBoostAdminState=vpwrBoostAdminState, vpwrPanelModuleIdentTable=vpwrPanelModuleIdentTable, vpwrBDTOperState=vpwrBDTOperState, vpwrBatteryCurrentGroup=vpwrBatteryCurrentGroup, vpwrRectifierConfigGroup=vpwrRectifierConfigGroup, vpwrSystemThermalSenseType=vpwrSystemThermalSenseType, batteryTempCompHighSlope=batteryTempCompHighSlope, vpwrTrapEntry=vpwrTrapEntry, sysAuxAlarmToRelayMapping=sysAuxAlarmToRelayMapping, vpwrRingerConfigGroup=vpwrRingerConfigGroup, vpwrBayctrlModuleIdentTable=vpwrBayctrlModuleIdentTable, vpwrTrapLVDOpenAlarm=vpwrTrapLVDOpenAlarm, vpwrBayctrlCurrent=vpwrBayctrlCurrent, vpwrModuleCurrent=vpwrModuleCurrent, vpwrPanelIdentTable=vpwrPanelIdentTable, vpwrDcAcInverterConfigGroup=vpwrDcAcInverterConfigGroup, vpwrAlarmIndex=vpwrAlarmIndex, vpwrBatteryTempUThreshold=vpwrBatteryTempUThreshold, vpwrRectAlarmACFail=vpwrRectAlarmACFail, sysAlarmConfigTable=sysAlarmConfigTable) mibBuilder.exportSymbols("VALERE-DC-POWER-MIB", vpwrTrapBatteryRechgIlimitFailAlarm=vpwrTrapBatteryRechgIlimitFailAlarm, vpwrTrapLvdFuseOpen=vpwrTrapLvdFuseOpen, vpwrRectAlarmBoostComm=vpwrRectAlarmBoostComm, vpwrTrapSystemRedundancyAlarm=vpwrTrapSystemRedundancyAlarm, vpwrTrapsMsgString=vpwrTrapsMsgString, vpwrTrapMultipleRingerAlarm=vpwrTrapMultipleRingerAlarm, vpwrTrapRingerCommAlarm=vpwrTrapRingerCommAlarm, vpwrTrapDistributionCommAlarm=vpwrTrapDistributionCommAlarm, sysAuxAlarmDefaultName=sysAuxAlarmDefaultName, vpwrBayctrlFwVersion=vpwrBayctrlFwVersion, vpwrDcPowerAlarmGroup=vpwrDcPowerAlarmGroup, vpwrRectAlarmHVSD=vpwrRectAlarmHVSD, vpwrTrapSwDownloadAndReboot=vpwrTrapSwDownloadAndReboot, vpwrBatteryTempGroup=vpwrBatteryTempGroup, vpwrSystemVoltage=vpwrSystemVoltage, vpwrModuleTestDate=vpwrModuleTestDate, vpwrLvdWarningSetpoint=vpwrLvdWarningSetpoint, vpwrTrapSystemClockChange=vpwrTrapSystemClockChange, vpwrAlarmEntry=vpwrAlarmEntry, batteryTempCompLowStopVoltage=batteryTempCompLowStopVoltage, batteryTempCompLowStartTemperature=batteryTempCompLowStartTemperature, vpwrBatteryTempLThreshold=vpwrBatteryTempLThreshold, vpwrRingerParameterDcVoltage=vpwrRingerParameterDcVoltage, vpwrRingerAlarmBOverCurrent=vpwrRingerAlarmBOverCurrent, vpwrSystemIdentEntry=vpwrSystemIdentEntry, vpwrRingerAlarmaBFailed=vpwrRingerAlarmaBFailed, vpwrRingerParameterEntry=vpwrRingerParameterEntry, vpwrLvdReconnectSetpoint=vpwrLvdReconnectSetpoint, vpwrDcPowerDist=vpwrDcPowerDist, vpwrTrapModuleAlarm=vpwrTrapModuleAlarm, vpwrPanelModuleCapacity=vpwrPanelModuleCapacity, vpwrIdentManufacturer=vpwrIdentManufacturer, vpwrRectifierCurrentLimitAdminState=vpwrRectifierCurrentLimitAdminState, vpwrPanelModuleOperStatus=vpwrPanelModuleOperStatus, sysAlarmToRelayMapping=sysAlarmToRelayMapping, vpwrModuleSerialNumber=vpwrModuleSerialNumber, vpwrBatteryTempIndex=vpwrBatteryTempIndex, vpwrTrapACFAlarm=vpwrTrapACFAlarm, vpwrTrapInternalTempAlarmCleared=vpwrTrapInternalTempAlarmCleared, vpwrTrapBatteryTempAlarmSet=vpwrTrapBatteryTempAlarmSet, sysRelayDefaultName=sysRelayDefaultName, vpwrRectAlarmBoostFail=vpwrRectAlarmBoostFail)
988,498
573298bcc65ad076bc71d5ccf1a10aa396cd82fd
# -*- coding: utf-8 -*- import Aan from Aan.lib.curve.ttypes import * from datetime import datetime from bs4 import BeautifulSoup import time, random, sys, re, os, json, subprocess, threading, glob, string, codecs, requests, tweepy, ctypes, urllib, urllib2, wikipedia import requests from gtts import gTTS import goslate from urllib import urlopen import urllib2 import urllib3 import tempfile import html5lib cl = Aan.LINE() #cl.login(qr=True) cl.login(token="EoQWRbeN7FPR5gzhOyvb.VHH0q0Dhr8pSns5/+RsmgW.CPUNaL2uPZmGbAAiahXHnSxhdOxPEABgVlFFTtNKPvw=") cl.loginResult() print "login success" reload(sys) sys.setdefaultencoding('utf-8') helpMessage =""" ╔═══════ M.E.N.U ════════ ╠➩Apakah <teks> (seperti kerang ajaib) ╠➩kedapkedip <Teks>= coba aja ╠➩Dosa @(by tag) = Buat lucu2an ╠➩Pahala @(by tag) = Buat lucu2an ╠➩Cinta <teks> = buat lucu2an ╠➩Mid @(by tag) = melihat mid ╠➩Info @(by tag) = info yg di tag ╠➩Invite = mengundang by kontak ╠➩Pap set <link gambar> ╠➩Pap = mengirim gambar yg telah di set ╠➩Google <yg dicari> ╠➩/set > /tes Untuk Cek Sider ╠➩/tagall = Tag semua member ╠➩/tid = translate ing > ind ╠➩/ten = translate ind > ing ╠➩/gcreator = Menunjukkan pembuat grup ╠➩/ginfo = Info grup ╠➩/cancel = Membatalkan semua undanganan ╠➩/ourl = Invite by link on ╠➩/curl = Invite by link off ╠➩/restart = merestart bot ╠➩/cek <tanggal> |contoh: /cek 21-02-2222 ╠➩/musik <penyanyi> <judul> ╠➩/wiki <yg dicari> ╠➩/image <yg dicari> ╠➩/video <judul> ╠➩/ig <nama> ╠➩/yt <judul> ╠➩/ps <app playstore> ╚═══════ M.E.N.U ════════ ➩ Nb: gausah pake <> ╚═══════ M.E.N.U ════════ ✟ Steal = Menu steal ✟ Say = menu teks ke suara ✟ Gift = menu gift ✟ Admin = menu admin """ qwerty =""" ╔═════════════════ ║ ✟Khusus Admin✟ ╠═════════════════ ╠➩ List grup ╠➩ Gbc ╠➩ Gbcs ╠➩ Gbcp ╠➩ Cbc ╠➩ Cb ╠➩ Cn ╠➩ K on/off ╠➩ W on/off ╠➩ Like on/off ╠➩ Join on/offf ╠➩ Bye on/off ╠➩ Tag on/off ╠➩ Invitemeto <gid> ╠➩ Keluar dari <gid> ╠➩ Spam on/off <jumlah> <kata> ╚═══════════════ """ hadiah =""" ╔═══════ M.E.N.U ════════ ╠➩/gift1 ╠➩/gift2 ╠➩/gift3 ╠➩/gift4 ╠➩/all gift ╠➩/unicode1 ╚═══════M.E.N.U 1════════ Nb: untuk line versi uptodate unicode tidak menyababkan lag """ say =""" ╔═══════ M.E.N.U ════════ ╠➩/say <teks> = teks ke suara Indo ╠➩.say Jepang ╠➩-say inggris ╠➩*say Arab ╠➩#say Korea ╠➩!say Jawa ╠➩^say Sunda ╠➩'say prancis ╚═══════M.E.N.U 1════════""" steal =""" ╔═══════ M.E.N.U ════════ ╠➩Steal dp @(by tag) ╠➩Steal home @(by tag) ╠➩Steal bio @(by tag) ╠➩Steal contact @(by tag) ╠➩Steal grup = melihat dp grup ╠➩Steal gid = melihat id grup ╠➩Myname = nama kalian ╠➩Mybio = bio kalian ╠➩Mymid = mid kalian ╠➩Mydp = dp kalian ╠➩Mycover = cover kalian ╠➩Mycontact = kontak kalian ╚═══════ M.E.N.U ════════ ╔═══════ Mimic ════════ ╠➩Mimic on/off ╠➩Target @ ╠➩Target del @ ╠➩Target list ╠➩Mycopy @ ╠➩Mybackup ╚═══════ Mimic ════════ """ KAC= [cl] mid= cl.getProfile().mid Bots=[mid,"ube187443474747c3ec352e7efeb48c1b"] admin=["ube187443474747c3ec352e7efeb48c1b","ua3db06f09cca59c24623cb4b6518d1cd"] staff=["ube187443474747c3ec352e7efeb48c1b","ua3db06f09cca59c24623cb4b6518d1cd"] wait = { 'contact':False, 'autoJoin':True, 'autoCancel':{"on":False,"members":1}, 'leaveRoom':True, 'timeline':False, 'autoAdd':False, 'message':"cie yang add wkwk", "lang":"JP", "comment":"AutoLike by aked\n\n=> instagram.com/dekaprabowoo", "commentOn":False, "commentBlack":{}, "wblack":False, "dblack":False, "clock":False, "cName":" ", "blacklist":{}, "wblacklist":False, "dblacklist":False, "atjointicket":True, "Protectcancl":False, "Protectjoin":False, "Protectgr":False, "Welcomemessage":True, "Byemessage":True, "likeOn":True, "tag":True, "winvite":False, "Pap":True, "displayName":{}, } wait2 = { 'readPoint':{}, 'readMember':{}, 'setTime':{}, 'ROM':{} } wait3 = { "copy":True, "copy2":"target", "target":{} } setTime = {} setTime = wait2['setTime'] def restart_program(): python = sys.executable os.execl(python, python, * sys.argv) contact = cl.getProfile() mybackup = cl.getProfile() mybackup.displayName = contact.displayName mybackup.statusMessage = contact.statusMessage mybackup.pictureStatus = contact.pictureStatus setTime = {} setTime = wait2['setTime'] def restart_program(): python = sys.executable os.execl(python, python, * sys.argv) 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 NOTIFIED_READ_MESSAGE(op): 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 else: pass except: pass def waktu(secs): mins, secs = divmod(secs,60) hours, mins = divmod(mins,60) return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs) #------------------- 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"])) #------Protect Group Kick start------# if op.type == 11: if wait["Protectgr"] == True: if op.param2 not in Bots: G = cl.getGroup(op.param1) G.preventJoinByTicket = True random.choice(DEF).kickoutFromGroup(op.param1,[op.param2]) random.choice(DEF).updateGroup(G) #------Protect Group Kick finish-----# #------Cancel Invite User start------# if op.type == 13: if wait["Protectcancl"] == True: if op.param2 not in Bots: group = cl.getGroup(op.param1) gMembMids = [contact.mid for contact in group.invitee] random.choice(DEF).cancelGroupInvitation(op.param1, gMembMids) #------Cancel Invite User Finish------# if op.type == 13: if op.param3 in Bots: if wait["autojoin"] == True: cl.acceptGroupInvitation(op.param1) cl.sendText(op.param1, "Terimakasih \(^o^)/\nSilahkan ketik /help.") cl.sendText(op.param1, "Creator:\n=> Giananda") print "Bot join grup" #------Cancel Invite User Finish------## if op.type == 13: if op.param3 in Bots: if op.param2 in admin: cl.acceptGroupInvitation(op.param1) cl.sendText(op.param1, "Terimakasih \(^o^)/\nSilahkan ketik /help.") cl.sendText(op.param1, "Creator:\n=> Giananda") print "Bot join grup" #------------------------------------------------------------------------------- if op.type == 17: if wait["Welcomemessage"] == True: group = cl.getGroup(op.param1) cb = Message() cb.to = op.param1 cb.text = cl.getContact(op.param2).displayName + "\n\nWelcome di Grup : " + group.name + "\n\nGrup Creator => " + group.creator.displayName cl.sendMessage(cb) if op.type == 15: if wait["Byemessage"] == True: if op.param2 in Bots: return cl.sendText(op.param1, "Bah Dia Pengen Ke Surga.. Wkwk") print "MemberLeft" #------------------------------------------------------ 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 == 26: msg = op.message try: if msg.contentType == 0: try: if msg.to in wait2['readPoint']: if msg.from_ in wait2["ROM"][msg.to]: del wait2["ROM"][msg.to][msg.from_] else: pass except: pass else: pass except KeyboardInterrupt: sys.exit(0) except Exception as error: print error print ("\n\nRECEIVE_MESSAGE\n\n") return if op.type == 26: msg = op.message 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 == 25: msg = op.message if msg.contentType == 13: if wait["wblack"] == True: if msg.contentMetadata["mid"] in wait["commentBlack"]: cl.sendText(msg.to,"already") 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") ki.sendText(msg.to,"deleted") kk.sendText(msg.to,"deleted") kc.sendText(msg.to,"deleted") wait["dblack"] = False else: wait["dblack"] = False cl.sendText(msg.to,"It is not in the black list") ki.sendText(msg.to,"It is not in the black list") kk.sendText(msg.to,"It is not in the black list") kc.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,"already") ki.sendText(msg.to,"already") kk.sendText(msg.to,"already") kc.sendText(msg.to,"already") wait["wblacklist"] = False else: wait["blacklist"][msg.contentMetadata["mid"]] = True wait["wblacklist"] = False cl.sendText(msg.to,"aded") ki.sendText(msg.to,"aded") kk.sendText(msg.to,"aded") kc.sendText(msg.to,"aded") elif wait["dblacklist"] == True: if msg.contentMetadata["mid"] in wait["blacklist"]: del wait["blacklist"][msg.contentMetadata["mid"]] cl.sendText(msg.to,"deleted") ki.sendText(msg.to,"deleted") kk.sendText(msg.to,"deleted") kc.sendText(msg.to,"deleted") wait["dblacklist"] = False else: wait["dblacklist"] = False cl.sendText(msg.to,"It is not in the black list") ki.sendText(msg.to,"It is not in the black list") kk.sendText(msg.to,"It is not in the black list") kc.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,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\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,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\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 ["Say"]: if wait["lang"] == "JP": cl.sendText(msg.to,say) elif msg.text in ["Steal"]: if wait["lang"] == "JP": cl.sendText(msg.to,steal) elif msg.text in ["/help"]: if wait["lang"] == "JP": cl.sendText(msg.to,helpMessage) else: cl.sendText(msg.to,helpt) elif msg.text in ["Admin"]: if msg.from_ in admin: if wait["lang"] == "JP": cl.sendText(msg.to,qwerty) else: cl.sendText(msg.to,Sett) elif ("/gn " in msg.text): X = cl.getGroup(msg.to) X.name = msg.text.replace("Gn ","") cl.updateGroup(X) elif "Kick " in msg.text: if msg.from_ in admin: midd = msg.text.replace("Kick ","") cl.kickoutFromGroup(msg.to,[midd]) elif "Invite " in msg.text: if msg.from_ in admin: midd = msg.text.replace("Invite ","") cl.findAndAddContactsByMid(midd) cl.inviteIntoGroup(msg.to,[midd]) elif msg.text in ["/bot"]: msg.contentType = 13 msg.contentMetadata = {'mid': mid} cl.sendMessage(msg) elif msg.text in ["Gift"]: cl.sendText(msg.to,hadiah) elif msg.text in ["æ„›ã�®ãƒ—レゼント","/gift1"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '5'} 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': '8'} msg.text = None cl.sendMessage(msg) elif msg.text in ["æ„›ã�®ãƒ—レゼント","/gift4"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '10'} msg.text = None cl.sendMessage(msg) elif msg.text in ["æ„›ã�®ãƒ—レゼント","/all gift"]: msg.contentType = 9 msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '12'} msg.text = None cl.sendMessage(msg) cl.sendMessage(msg) cl.sendMessage(msg) elif msg.text in ["/cancel"]: 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") elif msg.text in ["/ourl"]: X = cl.getGroup(msg.to) X.preventJoinByTicket = False cl.updateGroup(X) if wait["lang"] == "JP": cl.sendText(msg.to,"Invite by link open") else: cl.sendText(msg.to,"Already open") elif msg.text in ["/curl"]: X = cl.getGroup(msg.to) X.preventJoinByTicket = True cl.updateGroup(X) if wait["lang"] == "JP": cl.sendText(msg.to,"Invite by link Close") else: cl.sendText(msg.to,"Already close") 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 msg.text == "/ginfo": if msg.toType == 2: 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)) if ginfo.preventJoinByTicket == True: u = "close" else: u = "open" cl.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\nmembers:" + str(len(ginfo.members)) + "members\npending:" + sinvitee + "people\nURL:" + u + "it is inside") else: cl.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus) 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 "Steal gid" == msg.text: cl.sendText(msg.to,msg.to) elif "Mymid" == msg.text: cl.sendText(msg.to, msg.from_) elif "Mid RA" == msg.text: cl.sendText(msg.to,mid) elif msg.text in ["Wkwkwk","Wkwk","Wk","wkwkwk","wkwk","wk"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "100", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Hehehe","Hehe","He","hehehe","hehe","he"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "10", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Galau"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "9", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["You"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "7", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Hadeuh"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "6", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) elif msg.text in ["Please"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "4", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Haaa"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "3", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Lol"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "110", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Hmmm","Hmm","Hm","hmmm","hmm","hm"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "101", "STKPKGID": "1", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["Welcome"]: msg.contentType = 7 msg.text = None msg.contentMetadata = { "STKID": "247", "STKPKGID": "3", "STKVER": "100" } cl.sendMessage(msg) ki.sendMessage(msg) elif msg.text in ["TL: "]: 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: string = msg.text.replace("Cn ","") if len(string.decode('utf-8')) <= 9999999999999: profile = cl.getProfile() profile.displayName = string cl.updateProfile(profile) cl.sendText(msg.to,"Update Names >" + string + "<") elif "Cb " in msg.text: if msg.from_ in admin: string = msg.text.replace("Cb ","") if len(string.decode('utf-8')) <= 500: profile = cl.getProfile() profile.statusMessage = string cl.updateProfile(profile) cl.sendText(msg.to,"Update Bio >" + string + "<") elif msg.text in ["Mc "]: mmid = msg.text.replace("Mc ","") msg.contentType = 13 msg.contentMetadata = {"mid":mmid} cl.sendMessage(msg) elif msg.text in ["Joinn on","joinn on"]: if msg.from_ in admin: if wait["Protectjoin"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"kick Joined Group On") else: cl.sendText(msg.to,"done") else: wait["Protectjoin"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"kick Joined Group On") else: cl.sendText(msg.to,"done") elif msg.text in ["Joinn off","joinn off"]: if msg.from_ in admin: if wait["Protectjoin"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"kick Joined Group Off") else: cl.sendText(msg.to,"done") else: wait["Protectjoin"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"kick Joined Group Off") else: cl.sendText(msg.to,"done") elif msg.text in ["Cancl on","cancl on"]: if msg.from_ in admin: if wait["Protectcancl"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Cancel All Invited On") else: cl.sendText(msg.to,"done") else: wait["Protectcancl"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Cancel All Invited On") else: cl.sendText(msg.to,"done") elif msg.text in ["Cancl off","cancl off"]: if msg.from_ in admin: if wait["Protectcancl"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Cancel All Invited Off") else: cl.sendText(msg.to,"done") else: wait["Protectcancl"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Cancel All Invited Off") else: cl.sendText(msg.to,"done") elif msg.text in ["Gr on","gr on"]: if msg.from_ in admin: if wait["Protectgr"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Protect Group On") else: cl.sendText(msg.to,"done") else: wait["Protectgr"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Protect Group On") else: cl.sendText(msg.to,"done") elif msg.text in ["Gr off","gr off"]: if msg.from_ in admin: if wait["Protectgr"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Protect Group Off") else: cl.sendText(msg.to,"done") else: wait["Protectgr"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Protect Group Off") else: cl.sendText(msg.to,"done") elif msg.text in ["K On","K on","k on"]: if msg.from_ in admin: if wait["contact"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Cek Mid Send Contact On") else: cl.sendText(msg.to,"done") else: wait["contact"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Cek Mid Send Contact On") else: cl.sendText(msg.to,"done") elif msg.text in ["K Off","K off","k off"]: if msg.from_ in admin: if wait["contact"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Cek Mid Send Contact Off") else: cl.sendText(msg.to,"done") else: wait["contact"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Cek Mid Send Contact Off") else: cl.sendText(msg.to,"done") elif msg.text in ["Join on"]: 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,"done") elif msg.text in ["Join off"]: 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 msg.text in ["Gcancel:"]: try: strnum = msg.text.replace("Gcancel:","") 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: cl.sendText(msg.to,"关了邀请拒ç»�。è¦�时开请指定人数å�‘é€�") 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") else: cl.sendText(msg.to,strnum + "使人以下的å°�组用自动邀请拒ç»�") 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 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 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 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 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 ["Set View"]: md = "" if wait["Protectjoin"] == True: md+="􀔃􀆑lock􏿿 Block Join\n" else: md+=" Block Join Off\n" if wait["Protectgr"] == True: md+="􀔃􀆑lock􏿿 Block Group\n" else: md+=" Block Group Off\n" if wait["Protectcancl"] == True: md+="􀔃􀆑lock􏿿 Cancel All Invited\n" else: md+=" Cancel All Invited Off\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+=" Group cancel :" + str(wait["autoCancel"]["members"]) + "\n" else: md+= " Group cancel : off\n" if wait["leaveRoom"] == True: md+=" Auto leave : on\n" else: md+=" Auto leave : 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" cl.sendText(msg.to,md) elif "album merit " in msg.text: gid = msg.text.replace("album merit ","") album = cl.getAlbum(gid) if album["result"]["items"] == []: if wait["lang"] == "JP": cl.sendText(msg.to,"There is no album") else: cl.sendText(msg.to,"相册没在。") else: if wait["lang"] == "JP": mg = "The following is the target album" else: mg = "以下是对象的相册" for y in album["result"]["items"]: if "photoCount" in y: mg += str(y["title"]) + ":" + str(y["photoCount"]) + "sheet\n" else: mg += str(y["title"]) + ":0sheet\n" cl.sendText(msg.to,mg) elif "album " in msg.text: gid = msg.text.replace("album ","") album = cl.getAlbum(gid) if album["result"]["items"] == []: if wait["lang"] == "JP": cl.sendText(msg.to,"There is no album") else: cl.sendText(msg.to,"相册没在。") else: if wait["lang"] == "JP": mg = "The following is the target album" else: mg = "以下是对象的相册" for y in album["result"]["items"]: if "photoCount" in y: mg += str(y["title"]) + ":" + str(y["photoCount"]) + "sheet\n" else: mg += str(y["title"]) + ":0sheet\n" elif "album remove " in msg.text: gid = msg.text.replace("album remove ","") albums = cl.getAlbum(gid)["result"]["items"] i = 0 if albums != []: for album in albums: cl.deleteAlbum(gid,album["id"]) i += 1 if wait["lang"] == "JP": cl.sendText(msg.to,str(i) + "Deleted albums") else: cl.sendText(msg.to,str(i) + "åˆ é™¤äº†äº‹çš„ç›¸å†Œã€‚") elif msg.text in ["Grup id"]: gid = cl.getGroupIdsJoined() h = "" for i in gid: h += "[%s]:\n%s\n" % (cl.getGroup(i).name,i) cl.sendText(msg.to,h) elif msg.text in ["Cancelall"]: 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 "album removeat’" in msg.text: gid = msg.text.replace("album removeat’","") albums = cl.getAlbum(gid)["result"]["items"] i = 0 if albums != []: for album in albums: cl.deleteAlbum(gid,album["id"]) i += 1 if wait["lang"] == "JP": cl.sendText(msg.to,str(i) + "Albums deleted") else: cl.sendText(msg.to,str(i) + "åˆ é™¤äº†äº‹çš„ç›¸å†Œã€‚") elif msg.text in ["è‡ªå‹•è¿½åŠ :オン","Add on","Auto add:on","è‡ªå‹•è¿½åŠ ï¼šé–‹"]: 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 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 "Message change: " in msg.text: wait["message"] = msg.text.replace("Message change: ","") cl.sendText(msg.to,"message changed") elif "Message add: " in msg.text: wait["message"] = msg.text.replace("Message add: ","") if wait["lang"] == "JP": cl.sendText(msg.to,"message changed") else: cl.sendText(msg.to,"done。") elif msg.text in ["Message","è‡ªå‹•è¿½åŠ å•�候語確èª�"]: if wait["lang"] == "JP": cl.sendText(msg.to,"message change to\n\n" + wait["message"]) else: cl.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"]) elif msg.text in ["コメント:オフ","Comment on","Comment off","自動首é �留言:關"]: 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 ["Comment","留言確èª�"]: cl.sendText(msg.to,"message changed to\n\n" + str(wait["comment"])) elif msg.text in ["/gurl"]: 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 ["Comment bl "]: 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) #-------------Fungsi Jam on/off Start-------------------# elif msg.text in ["Jam on"]: if wait["clock"] == True: kc.sendText(msg.to,"Bot 4 jam on") else: wait["clock"] = True now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = kc.getProfile() profile.displayName = wait["cName4"] + nowT kc.updateProfile(profile) kc.sendText(msg.to,"Jam Selalu On") elif msg.text in ["Jam off"]: if wait["clock"] == False: kc.sendText(msg.to,"Bot 4 jam off") else: wait["clock"] = False kc.sendText(msg.to,"Jam Sedang Off") #-------------Fungsi Jam on/off Finish-------------------# #-------------Fungsi Change Clock Start------------------# elif msg.text in ["Change clock"]: 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) #-------------Fungsi Change Clock Finish-----------------# #--------------------# elif "/lirik " in msg.text.lower(): songname = msg.text.replace("/lirik ","") params = {"songname":songname} r = requests.get('https://ide.fdlrcn.com/workspace/yumi-apis/' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: cl.sendText(msg.to, 'Tunggu....') cl.sendText(msg.to,song[5]) print "[Command] Lirik" elif msg.text in ["/gcreator"]: if msg.toType == 2: msg.contentType = 13 ginfo = cl.getGroup(msg.to) gCreator = ginfo.creator.mid try: msg.contentMetadata = {'mid': gCreator} gCreator1 = ginfo.creator.displayName except: gCreator = "Error" cl.sendText(msg.to, "Group Creator : " + gCreator1) cl.sendMessage(msg) elif "kedapkedip " in msg.text.lower(): txt = msg.text.replace("kedapkedip ", "") cl.kedapkedip(msg.to,txt) #--------------ListGroup------------------# elif msg.text in ["List grup"]: 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,"▒▒▓█[List Grup]█▓▒▒\n"+ h +"Total Group ="+"["+str(len(gid))+"]") elif "Steal bio " in msg.text: nk0 = msg.text.replace("Steal bio ","") 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: contact = cl.getContact(target) y = contact.statusMessage cl.sendText(msg.to,y) except Exception as e: cl.sendText(msg.to,"Lupa") print e #-------------------# elif "Steal dp @" in msg.text: print "[Command]dp executing" _name = msg.text.replace("Steal dp @","") _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 "Steal home @" in msg.text: print "[Command]dp executing" _name = msg.text.replace("Steal home @","") _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) cu = cl.channel.getCover(target) path = str(cu) cl.sendImageWithURL(msg.to, path) except: pass print "[Command]dp executed" #----------------------------------------------- elif "^say " in msg.text.lower(): query = msg.text.replace("^say ","") with requests.session() as s: s.headers['user-agent'] = 'Mozilla/5.0' url = 'https://google-translate-proxy.herokuapp.com/api/tts' params = {'language': 'su', 'speed': '1', 'query': query} r = s.get(url, params=params) mp3 = r.url cl.sendAudioWithURL(msg.to, mp3) elif "!say " in msg.text.lower(): query = msg.text.replace("!say ","") with requests.session() as s: s.headers['user-agent'] = 'Mozilla/5.0' url = 'https://google-translate-proxy.herokuapp.com/api/tts' params = {'language': 'jw', 'speed': '1', 'query': query} r = s.get(url, params=params) mp3 = r.url cl.sendAudioWithURL(msg.to, mp3) elif "/say " in msg.text: psn = msg.text.replace("/say ","") tts = gTTS(psn, lang='id', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif ".say " in msg.text: psn = msg.text.replace(".say ","") tts = gTTS(psn, lang='ja', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif "-say " in msg.text: psn = msg.text.replace("-say ","") tts = gTTS(psn, lang='en', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif "#say " in msg.text: psn = msg.text.replace("#say ","") tts = gTTS(psn, lang='ko', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif "*say " in msg.text: psn = msg.text.replace("*say ","") tts = gTTS(psn, lang='ar', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif "'say " in msg.text: psn = msg.text.replace("'say ","") tts = gTTS(psn, lang='fr', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif "Cinta " in msg.text: tanya = msg.text.replace("Cinta ","") jawab = ("10%","20%","30%","40%","50%","60%","70%","80%","90%","100%") jawaban = random.choice(jawab) tanyu = ("Cinta " + tanya + " Adalah ") tts = gTTS(tanyu + jawaban, lang='id', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif msg.text in ["Pagi","pagi","selamat pagi","Selamat Pagi","Ohayou","Ohayo","ohayou","ohayo","Met pagi","met pagi"]: sapa = ("オハイオニイちゃんおにちゃんガンバッテクダサイイネ") tts = gTTS(sapa, lang='ja', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif msg.text in ["malam","Malam"]: sapa = ("Malam Semua Para Jomblo") tts = gTTS(sapa, lang='ja', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') elif msg.text in ["Alista","alista","Sayang alista"]: sapa = ("sayang kamu dimana kevin merindukamu alista ku sayang salam dari kevin") tts = gTTS(sapa, lang='id', slow=False) tts.save('tts.mp3') cl.sendAudio(msg.to, 'tts.mp3') #----------------------------------------------------- elif "/cek " in msg.text: tanggal = msg.text.replace("/cek ","") r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal) data=r.text data=json.loads(data) lahir = data["data"]["lahir"] usia = data["data"]["usia"] ultah = data["data"]["ultah"] zodiak = data["data"]["zodiak"] cl.sendText(msg.to,"Tanggal Lahir: "+lahir+"\n\nUsia: "+usia+"\n\nUltah: "+ultah+"\n\nZodiak: "+zodiak) #----------------------------------------------------- elif "/musik " in msg.text: songname = msg.text.replace("/musik ","") params = {"songname": songname} r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: abc = song[3].replace('https://','http://') cl.sendText(msg.to, "Title : " + song[0] + "\nLength : " + song[1] + "\nLink download : " + song[4]) cl.sendText(msg.to, "Lagu " + song[0] + "\nSedang Di Prosses... Tunggu Sebentar ^_^ ") cl.sendAudioWithURL(msg.to,abc) cl.sendText(msg.to, "That's the song for " + song[0]) elif '.musik ' in msg.text.lower(): try: songname = msg.text.lower().replace('.musik ','') params = {'songname': songname} r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: hasil = 'This is Your Music\n' hasil += 'Judul : ' + song[0] hasil += '\nDurasi : ' + song[1] hasil += '\nLink Download : ' + song[4] cl.sendText(msg.to, hasil) cl.sendText(msg.to, "Please Wait for audio...") cl.sendAudioWithURL(msg.to, song[4]) except Exception as njer: cl.sendText(msg.to, str(njer)) #----------------------------------------------- elif '/lirik ' in msg.text.lower(): try: songname = msg.text.lower().replace('/lirik ','') params = {'songname': songname} r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params)) data = r.text data = json.loads(data) for song in data: hasil = 'Lirik Lagu (' hasil += song[0] hasil += ')\n\n' hasil += song[5] cl.sendText(msg.to, hasil) except Exception as wak: cl.sendText(msg.to, str(wak)) elif "/ytl " in msg.text: query = msg.text.replace("/ytl ","") with requests.session() as s: s.headers['user-agent'] = 'Mozilla/5.0' url = 'http://www.youtube.com/results' params = {'search_query': query} r = s.get(url, params=params) soup = BeautifulSoup(r.content, 'html5lib') hasil = "" for a in soup.select('.yt-lockup-title > a[title]'): if '&list=' not in a['href']: hasil += ''.join((a['title'],'\nhttp://www.youtube.com' + a['href'],'\n\n')) cl.sendText(msg.to,hasil) print '[Command] Youtube Search' #========================================== elif "/yt " in msg.text.lower(): query = msg.text.split(" ") try: if len(query) == 3: isi = yt(query[2]) hasil = isi[int(query[1])-1] cl.sendText(msg.to, hasil) else: isi = yt(query[1]) cl.sendText(msg.to, isi[0]) except Exception as e: cl.sendText(msg.to, str(e)) #======================================== elif '/wiki ' in msg.text.lower(): try: wiki = msg.text.lower().replace("/wiki ","") wikipedia.set_lang("id") pesan=wikipedia.page(wiki).title pesan+="\n\n" pesan+=wikipedia.summary(wiki, sentences=1) pesan+="\n" pesan+=wikipedia.page(wiki).url cl.sendText(msg.to, pesan) except: try: pesan="Over Text Limit! Please Click link\n" pesan+=wikipedia.page(wiki).url cl.sendText(msg.to, pesan) except Exception as e: cl.sendText(msg.to, str(e)) elif '/ig ' in msg.text.lower(): try: instagram = msg.text.lower().replace("/ig ","") html = requests.get('https://www.instagram.com/' + instagram + '/?') soup = BeautifulSoup(html.text, 'html5lib') data = soup.find_all('meta', attrs={'property':'og:description'}) text = data[0].get('content').split() data1 = soup.find_all('meta', attrs={'property':'og:image'}) text1 = data1[0].get('content').split() user = "Name: " + text[-2] + "\n" user1 = "Username: " + text[-1] + "\n" followers = "Followers: " + text[0] + "\n" following = "Following: " + text[2] + "\n" post = "Post: " + text[4] + "\n" link = "Link: " + "https://www.instagram.com/" + instagram detail = "===INSTAGRAM INFO USER====\n" details = "\n===INSTAGRAM INFO USER===" cl.sendText(msg.to, detail + user + user1 + followers + following + post + link + details) cl.sendImageWithURL(msg.to, text1[0]) except Exception as njer: cl.sendText(msg.to, str(njer)) #Restart_Program-------- elif msg.text in ["/restart"]: cl.sendText(msg.to, "Bot has been restarted") restart_program() print "@Restart" elif ("Add staff " in msg.text): if msg.from_ in admin: if msg.toType == 2: key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] targets = [] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: admin.append(target) cl.sendText(msg.to,"Staff Ditambahkan") print "[Command]Staff add executed" except: pass elif ("Del staff " in msg.text): if msg.from_ in admin: if msg.toType == 2: key = eval(msg.contentMetadata["MENTION"]) key["MENTIONEES"][0]["M"] targets = [] for x in key["MENTIONEES"]: targets.append(x["M"]) for target in targets: try: admin.remove(target) cl.sendText(msg.to,"Deleting staff") print "[Command]Staff remove executed" except: pass else: cl.sendText(msg.to,"Command denied.") cl.sendText(msg.to,"Owner permission required.") elif msg.text.lower() == 'stafflist': if admin == []: cl.sendText(msg.to,"The stafflist is empty") else: cl.sendText(msg.to,"Waiting...") num=1 mc = "===[Staff List]===" for mi_d in admin: mc += "\n%i. %s" % (num, cl.getContact(mi_d).displayName) num=1 mc = "===[Staff List]===" for mi_d in admin: mc += "\n%i. %s" % (num, cl.getContact(mi_d).displayName) num=(num+1) cl.sendText(msg.to,mc) print "[Command]Stafflist executed" elif msg.text in ["W on"]: if msg.from_ in admin: if wait["Welcomemessage"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message On") else: cl.sendText(msg.to,"done") else: wait["Welcomemessage"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"welcome message On") else: cl.sendText(msg.to,"done") elif msg.text in ["W off"]: if msg.from_ in admin: if wait["Welcomemessage"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Welcome message Off") else: cl.sendText(msg.to,"done") else: wait["Welcomemessage"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Welcome message Off") else: cl.sendText(msg.to,"done") elif msg.text in ["Bye on"]: if msg.from_ in admin: if wait["Byemessage"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Bye message On") else: cl.sendText(msg.to,"done") else: wait["Byemessage"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Bye message On") else: cl.sendText(msg.to,"done") elif msg.text in ["Bye off"]: if msg.from_ in admin: if wait["Byemessage"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Bye message Off") else: cl.sendText(msg.to,"done") else: wait["Byemessage"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Bye message Off") else: cl.sendText(msg.to,"done") #-----------------------------[Command]----------------------------# elif msg.text in ["Like on"]: 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。") elif msg.text in ["いいね:オフ","Like off"]: 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。") elif "/image " in msg.text: search = msg.text.replace("/image ","") url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search raw_html = (download_page(url)) items = [] items = items + (_images_get_all_items(raw_html)) path = random.choice(items) print path try: cl.sendImageWithURL(msg.to,path) print "Image" except: pass #------ elif msg.text in ["Tag on"]: if msg.from_ in admin: if wait["tag"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on") else: cl.sendText(msg.to,"Tag On") else: wait["tag"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Tag On") else: cl.sendText(msg.to,"already on") elif msg.text in ["Tag off"]: if msg.from_ in admin: if wait["tag"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Already off") else: cl.sendText(msg.to,"Tag Off") else: wait["tag"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Tag Off") else: cl.sendText(msg.to,"Already off") #-----------------------------[Command]-----------------------------# elif "@Kevin " in msg.text: if wait["tag"] == True: resp = ("《《AUTO RESPON》》\n") jawab = ("Jgn Tag Si Giananda!!","Berisik jgn tag si Giananda") jawaban = random.choice(jawab) cl.sendText(msg.to,resp + jawaban) elif "@"+cl.getProfile().displayName in msg.text: if wait["tag"] == True: resp = ("《《AUTO RESPON》》\n") jawab = ("kenapa si ","iya gue ganteng") jawabam = random.choice(jawab) cl.sendText(msg.to,resp + jawabam) elif msg.text in ["Invite"]: wait["winvite"] = True cl.sendText(msg.to,"send contact 😉\njika ingin membatalkan ketik /restart") if wait["winvite"] == True: _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: cl.sendText(msg.to,"-> " + _name + " was here") break elif invite in wait["blacklist"]: cl.sendText(msg.to,"Sorry, " + _name + " On Blacklist") cl.sendText(msg.to,"Call my daddy to use command !, \n➡Unban: " + invite) wait["winvite"] = False 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,"Done, Invited this human: \n➡" + _name) wait["winvite"] = False break except: cl.sendText(msg.to,"Negative, Error detected\nmaybe limit inv") wait["winvite"] = False break #----------------------------------------- elif "Info @" in msg.text: nama = msg.text.replace("Info @","") target = nama.rstrip(' ') van = cl.getGroup(msg.to) for linedev in van.members: if target == linedev.displayName: mid = cl.getContact(linedev.mid) try: cover = cl.channel.getCover(linedev.mid) except: cover = "" cl.sendText(msg.to,"[Display Name]:\n" + mid.displayName + "\n[Mid]:\n" + linedev.mid + "\n[BIO]:\n" + mid.statusMessage + "\n[Ava]:\nhttp://dl.profile.line-cdn.net/" + mid.pictureStatus + "\n[Cover]:\n" + str(cover)) else: pass #----------------------------------------------- elif "Stalk @" in msg.text: print "[Command]Stalk executing" stalkID = msg.text.replace("Stalk @","") subprocess.call(["instaLooter",stalkID,"tmp/","-n","1"]) files = glob.glob("tmp/*.jpg") for file in files: os.rename(file,"tmp/tmp.jpg") fileTmp = glob.glob("tmp/tmp.jpg") if not fileTmp: cl.sendText(msg.to, "Image not found, maybe the account haven't post a single picture or the account is private") print "[Command]Stalk,executed - no image found" else: image = upload_tempimage(client) cl.sendText(msg.to, format(image['link'])) subprocess.call(["sudo","rm","-rf","tmp/tmp.jpg"]) print "[Command]Stalk executed - succes" elif "/ps " in msg.text.lower(): tob = msg.text.lower().replace("/ps ","") cl.sendText(msg.to,"Sedang Mencari...") cl.sendText(msg.to,"Title : "+tob+"\nSource : Google Play\nLink : https://play.google.com/store/search?q=" + tob) cl.sendText(msg.to,"Tuh link nya boss") elif "Google " in msg.text: go = msg.text.replace("Google ","") cl.sendText(msg.to,"Search: " + go + "\n Link: google.com/search?q=" + go) #================================= elif "Invitemeto " in msg.text.lower(): ng = msg.text.lower().replace("Invitemeto ","") gid = cl.getGroupIdsJoined() try: if msg.from_ in admin: for i in gid: h = cl.getGroup(i).name if h == ng: cl.inviteIntoGroup(i,[Creator]) cl.sendText(msg.to,"Success join to ["+ h +"] group") else: pass else: cl.sendText(msg.to,"Hanya admin dan creator yg bisa menggunakan") except Exception as e: cl.sendMessage(msg.to, str(e)) #================================================================== elif "Keluar dari " in msg.text.lower(): ng = msg.text.lower().replace("Keluar dari ","") gid = cl.getGroupIdsJoined() try: if msg.from_ in admin: for i in gid: h = cl.getGroup(i).name if h == ng: cl.leaveGroup(i) cl.sendText(msg.to,"Success leave to "+ h) else: pass else: cl.sendText(msg.to,"Hanya admin dan creator yg bisa menggunakan") except Exception as e: cl.sendMessage(msg.to, str(e)) #=================================-------------================================= elif '/video ' in msg.text.lower(): try: textToSearch = msg.text.lower().replace('/video ', "").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'}) ght=('https://www.youtube.com' + results['href']) cl.sendVideoWithURL(msg.to,ght) except: cl.sendText(msg.to,"Could not find it") #================================= ======================================== elif msg.text in ["Myname"]: h = cl.getContact(msg.from_) cl.sendText(msg.to,h.displayName) #======================================== elif msg.text in ["Mybio"]: h = cl.getContact(msg.from_) cl.sendText(msg.to,h.statusMessage) #======================================== ===============Image====================# elif msg.text in ["Mydp"]: h = cl.getContact(msg.from_) cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus) #==============Image finish================# ===============Image====================# elif msg.text in ["Mycover"]: h = cl.getContact(msg.from_) cu = cl.channel.getCover(msg.from_) path = str(cu) cl.sendImageWithURL(msg.to, path) #==============Image finish================# #//commandnya elif msg.text.lower() == 'runtime': eltime = time.time() - mulai van = "「Sudah berjalan selama 」"+waktu(eltime) cl.sendText(msg.to,van) #---------------- elif "Steal contact" in msg.text: key = eval(msg.contentMetadata["MENTION"]) key1 = key["MENTIONEES"][0]["M"] mmid = cl.getContact(key1) msg.contentType = 13 msg.contentMetadata = {"mid": key1} cl.sendMessage(msg) #---------------- elif "Mycontact" in msg.text: mmid = cl.getContact(msg.from_) msg.contentType = 13 msg.contentMetadata = {"mid": msg.from_} cl.sendMessage(msg) #================================================= elif "Spam " in msg.text: if msg.from_ in admin: 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, "Out of range! ") elif txt[1] == "off": if jmlh <= 10000: cl.sendText(msg.to, tulisan) else: cl.sendText(msg.to, "Out of range! ") #------------------------------------------------- elif msg.text in ["Mimic on","mimic on"]: if wait3["copy"] == True: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on") else: cl.sendText(msg.to,"Mimic On") else: wait3["copy"] = True if wait["lang"] == "JP": cl.sendText(msg.to,"Mimic On") else: cl.sendText(msg.to,"Already on") #-------------------------------------------------- elif msg.text in ["Mimic off","mimic:off"]: if wait3["copy"] == False: if wait["lang"] == "JP": cl.sendText(msg.to,"Already on") else: cl.sendText(msg.to,"Mimic Off") else: wait3["copy"] = False if wait["lang"] == "JP": cl.sendText(msg.to,"Mimic Off") else: cl.sendText(msg.to,"Already on") elif msg.text in ["Target list"]: if wait3["target"] == {}: cl.sendText(msg.to,"nothing") else: mc = "Target mimic user\n" for mi_d in wait3["target"]: mc += "✔️ "+cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) elif "Mimic target " in msg.text: if wait3["copy"] == True: siapa = msg.text.replace("Mimic target ","") if siapa.rstrip(' ') == "me": wait3["copy2"] = "me" cl.sendText(msg.to,"Mimic change to me") elif siapa.rstrip(' ') == "target": wait3["copy2"] = "target" cl.sendText(msg.to,"Mimic change to target") else: cl.sendText(msg.to,"I dont know") elif "Target @" in msg.text: target = msg.text.replace("Target @","") gc = cl.getGroup(msg.to) targets = [] for member in gc.members: if member.displayName == target.rstrip(' '): targets.append(member.mid) if targets == []: cl.sendText(msg.to, "User not found") else: for t in targets: wait3["target"][t] = True cl.sendText(msg.to,"Target added") elif "Del target @" in msg.text: target = msg.text.replace("Del target @","") gc = cl.getGroup(msg.to) targets = [] for member in gc.members: if member.displayName == target.rstrip(' '): targets.append(member.mid) if targets == []: cl.sendText(msg.to, "User not found") else: for t in targets: del wait3["target"][t] cl.sendText(msg.to,"Target deleted") #------------------------------------------------- elif "Mycopy @" in msg.text: if msg.toType == 2: if msg.from_ in admin: print "[COPY] Ok" _name = msg.text.replace("Mycopy @","") _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, "Tidak Ada Target Copy") else: for target in targets: try: cl.cloneContactProfile(target) cl.sendText(msg.to, "Sukses Copy Profile") except Exception as e: print e elif msg.text in ["Mybackup"]: try: cl.updateDisplayPicture(mybackup.pictureStatus) cl.updateProfile(mybackup) cl.sendText(msg.to, "Backup Sukses Bosqu") except Exception as e: cl.sendText(msg.to, str (e)) #----------------------------------------- elif "Pap set " in msg.text: wait["Pap"] = msg.text.replace("Pap set ","") cl.sendText(msg.to,"Pap Has Ben Set To") elif msg.text in [".Pap","Pap"]: cl.sendImageWithURL(msg.to,wait["Pap"]) elif "Vid set " in msg.text: wait["vid"] = msg.text.replace("Vid set ","") cl.sendText(msg.to,"Vid Has Ben Set To") elif msg.text in [".vid","Vid"]: cl.sendVideoWithURL(msg.to,wait["vid"]) #------------------------------------------------- elif "Mid @" in msg.text: _name = msg.text.replace("Mid @","") _nametarget = _name.rstrip(' ') gs = cl.getGroup(msg.to) for g in gs.members: if _nametarget == g.displayName: cl.sendText(msg.to, g.mid) else: pass elif msg.text in ["Remove all chat"]: if msg.from_ in admin: cl.removeAllMessages(op.param2) cl.sendText(msg.to,"Removed all chat") elif "Gbcs " in msg.text: if msg.from_ in admin: bctxt = msg.text.replace("Gbcs ", "") bc = (".Btw.. Ini adalah Broadcast") cb = (bctxt + bc) tts = gTTS(cb, lang='id', slow=False) tts.save('tts.mp3') n = cl.getGroupIdsJoined() for manusia in n: cl.sendAudio(manusia, 'tts.mp3') elif "Gbcp " in msg.text: if msg.from_ in admin: bctxt = msg.text.replace("Gbcp ", "") n = cl.getGroupIdsJoined() for manusia in n: cl.sendText(manusia,bctxt) elif "Gbc " in msg.text: if msg.from_ in admin: bctxt = msg.text.replace("Gbc ", "") bc = ("《《BROAD CAST》》\n_________________________________\n") cb = ("\n\n_________________________________\nBot creator:\n=> Kevin") n = cl.getGroupIdsJoined() for manusia in n: cl.sendText(manusia,bc + bctxt + cb) elif "Cbc " in msg.text: if msg.from_ in admin: bctxt = msg.text.replace("Cbc ", "") t = cl.getAllContactIds() for manusia in t: cl.sendText(manusia, (bctxt)) #--------------------------------- TRANSLATE -------------------------------- elif "/ten " in msg.text: txt = msg.text.replace("/ten ","") 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 "/tid " in msg.text: txt = msg.text.replace("/tid ","") try: gs = goslate.Goslate() trs = gs.translate(txt,'id') cl.sendText(msg.to,trs) print '[Command] Translate ID' except: cl.sendText(msg.to,'Error.') #-----------KERANG---------# elif "Apakah " in msg.text: tanya = msg.text.replace("Apakah ","") jawab = ("Iya","Tidak","Mana saya tau sayakan autis","mungkin iya","mungkin tidak") jawaban = random.choice(jawab) tts = gTTS(text=jawaban, lang='id') tts.save('tts.mp3') cl.sendAudio(msg.to,'tts.mp3') #---------------------- elif "Dosa @" in msg.text: tanya = msg.text.replace("Dosa @","") jawab = ("60%","70%","80%","90%","100%","Tak terhingga") jawaban = random.choice(jawab) cl.sendText(msg.to,"Dosanya " + tanya + "adalah " + jawaban + " Banyak banyak tobat Nak ") #---------------------- elif "Pahala @" in msg.text: tanya = msg.text.replace("Pahala @","") jawab = ("0%","20%","40%","50%","60%","Tak ada") jawaban = random.choice(jawab) cl.sendText(msg.to,"Pahalanya " + tanya + "adalah " + jawaban + "\nTobatlah nak") #-------------------------------# elif "Steal grup" in msg.text: group = cl.getGroup(msg.to) path =("http://dl.profile.line-cdn.net/" + group.pictureStatus) cl.sendImageWithURL(msg.to, path) #-------------Fungsi Jam Update Start---------------------# elif msg.text in ["Jam Update"]: if wait["clock"] == True: now2 = datetime.now() nowT = datetime.strftime(now2,"(%H:%M)") profile = kc.getProfile() profile.displayName = wait["cName"] + nowT kc.updateProfile(profile) kc.sendText(msg.to,"Sukses update") else: kc.sendText(msg.to,"Aktifkan jam terlebih dulu") #-------------Fungsi Jam Update Finish-------------------# elif msg.text in ["/set"]: if msg.toType == 2: cl.sendText(msg.to, "Set reading point\nSilahkan ketik 「/tes」") try: del wait2['readPoint'][msg.to] del wait2['readMember'][msg.to] except: pass wait2['readPoint'][msg.to] = msg.id wait2['readMember'][msg.to] = "" wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S') wait2['ROM'][msg.to] = {} print "Lurkset" elif msg.text in ["/tes"]: if msg.toType == 2: print "\nSider check aktif..." 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, "Pembaca:\n_________________________________%s\n\nSidernya:\n_________________________________\n%s\n\n_________________________________\nIn the last seen point:\n[%s]\n_________________________________" % (wait2['readMember'][msg.to],chiya,setTime[msg.to])) print "\nReading Point Set..." try: del wait2['readPoint'][msg.to] del wait2['readMember'][msg.to] except: pass wait2['readPoint'][msg.to] = msg.id wait2['readMember'][msg.to] = "" wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S') wait2['ROM'][msg.to] = {} print "lukers" cl.sendText(msg.to, "Auto set reading point\nSilahkan ketik 「/tes」") else: cl.sendText(msg.to, "Ketik 「/set」 dulu kaka...\nHehe") #-------------Fungsi Leave Group Start---------------# elif msg.text in ["/keluar"]: if msg.from_ in admin: if msg.toType == 2: ginfo = cl.getGroup(msg.to) try: cl.sendText(msg.to, "kakak jahatヽ(`Д´)ノ") cl.leaveGroup(msg.to) except: pass else: cl.sendText(msg.to, "Maaf anda kurang beruntung") #-------------Fungsim Leave Group Finish---------------# #-------------Fungsi Tag All Start---------------# elif msg.text in ["/tagall"]: group = cl.getGroup(msg.to) nama = [contact.mid for contact in group.members] nm1, nm2, nm3, nm4, jml = [], [], [], [], len(nama) if jml <= 100: mention(msg.to, nama) if jml > 100 and jml < 200: for i in range (0, 99): nm1 += [nama[i]] mention(msg.to, nm1) for j in range (100, len(nama)-1): nm2 += [nama[j]] mention(msg.to, nm2) if jml > 200 and jml < 300: for i in range (0, 99): nm1 += [nama[i]] mention(msg.to, nm1) for j in range (100, 199): nm2 += [nama[j]] mention(msg.to, nm2) for k in range (200, len(nama)-1): nm3 += [nama[k]] mention(msg.to, nm3) if jml > 300 and jml < 400: for i in range (0, 99): nm1 += [nama[i]] mention(msg.to, nm1) for j in range (100, 199): nm2 += [nama[j]] mention(msg.to, nm2) for k in range (200, 299): nm3 += [nama[k]] mention(msg.to, nm3) for l in range (300, len(nama)-1): nm4 += [nama[l]] mention(msg.to, nm4) cnt = Message() cnt.text = "Done:"+str(jml) cnt.to = msg.to cl.sendMessage(cnt) elif (msg.text == 'Memlist'): a = cl.getGroup(msg.to) b = [] for i in a.members: b.append('•'+i.displayName) c = '\n'.join(b) cl.sendText(msg.to,'MEMBER LIST\n' + c) #-------------Fungsi Tag All Finish---------------# #----------------Fungsi Banned Kick Target Start-----------------------# elif msg.text in ["Killban"]: if msg.from_ in admin: if msg.toType == 2: group = ki.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 == []: kk.sendText(msg.to,"Selamat tinggal") ki.sendText(msg.to,"Jangan masuk lagi􀨁􀆷devil smile􏿿") return for jj in matched_list: try: klist=[ki,kk,cl] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[jj]) print (msg.to,[jj]) except: pass #----------------Fungsi Banned Kick Target Finish----------------------# elif "Cleanse" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "ok" _name = msg.text.replace("Cleanse","") gs = cl.getGroup(msg.to) cl.sendText(msg.to,"maaf kalo gak sopan") cl.sendText(msg.to,"makasih semuanya..") cl.sendText(msg.to,"he") msg.contentType = 13 msg.contentMetadata = {'mid': mid} cl.sendMessage(msg) 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: try: klist=[cl,ki,kk,kc] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendText(msg.to,"Group cleanse") kk.sendText(msg.to,"Group cleanse") kc.sendText(msg.to,"Group cleanse") #----------------Fungsi Kick User Target Start----------------------# 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: klist=[cl] kicker=random.choice(klist) kicker.kickoutFromGroup(msg.to,[target]) print (msg.to,[g.mid]) except: cl.sendText(msg.to,"Kasian Di Kick....") #----------------Fungsi Banned User Target Start-----------------------# elif "Ban @" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "[Banned] Sukses" _name = msg.text.replace("Ban @","") _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,"Dilarang Banned Bot") else: 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) cl.sendText(msg.to,"Akun telah sukses di banned") except: cl.sendText(msg.to,"Error") #----------------Fungsi Banned User Target Finish-----------------------# #----------------Fungsi Unbanned User Target Start-----------------------# elif "Unban @" in msg.text: if msg.from_ in admin: if msg.toType == 2: print "[Unban] Sukses" _name = msg.text.replace("Unban @","") _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,"Tidak Ditemukan.....") else: for target in targets: try: del wait["blacklist"][target] 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,"Akun Bersih Kembali") except: cl.sendText(msg.to,"Error") #----------------Fungsi Unbanned User Target Finish-----------------------# elif msg.text in ["join"]: if msg.from_ in admin: cl.sendText(msg.to,"/join") elif msg.text in ["hi"]: cl.sendText(msg.to,"hahaha") #----------------------------------------------- elif msg.text in ["/unicode1"]: cl.sendText(msg.to,"44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.55.44.44.44.44.44.44.44.4444.44.44.4.44.4.44.44.4.440.440.004444.4444.44.33.") elif msg.text in ["/creator"]: cl.sendText(msg.to,"==========BotCreator==========\n\nĜ̵͚͈̠̟͎̝͑̎̎̐̀̃͐Ḭ̸̛̞̣̠͓͖͚̽̏̉̍͌͒̅̈́̋̕͠A̴̢̨͕̳͕̲̪͙̰͍̯̲̿̀̅͒̌̌̉̆̏͠ͅN̷̨̨̫̞̭͔̖̳͍͔̗̰͚̺̋̿͛͒̏͜͝Ȁ̵͖̲̥̜̣̞̝̔̀̽̀̆́̐͐́̚͘ͅN̷̨̨̫̞̭͔̖̳͍͔̗̰͚̺̋̿͛͒̏͜͝D̴̯͍̝̯͔̤̟̭̦͓͖̺̣̟͚́͗̈́͛̋̈́̓̄̄͘͜Ȁ̵͖̲̥̜̣̞̝̔̀̽̀̆́̐͐́̚͘ͅ\n==>'Instagram.com/dekaprabowoo'<==\nWajib follow􀜁􀅔Har Har􏿿") elif msg.text in ["bobo ah","Bobo dulu ah"]: cl.sendText(msg.to,"Have a nice dream 􀜁􀅔Har Har􏿿") elif msg.text in ["wc"]: cl.sendText(msg.to,"Selamat datang") cl.sendText(msg.to,"Jangan nakal ok!") elif msg.text in ["PING","Ping","ping"]: cl.sendText(msg.to,"PONG 􀨁􀄻double thumbs up􏿿􀜁􀅔Har Har􏿿") #----------------------------------------------- #-------------Fungsi Balesan Respon Start---------------------# elif msg.text in ["Ini Apa","ini apa","Apaan Ini","apaan ini"]: cl.sendText(msg.to,"Ya gitu deh") #-------------Fungsi Balesan Respon Finish---------------------# #-------------Fungsi Speedbot Start---------------------# elif msg.text in [".sp","sb","Sb"]: start = time.time() elapsed_time = time.time() - start cl.sendText(msg.to, "seconds" % (elapsed_time)) #-------------Fungsi Speedbot Finish---------------------# #-------------Fungsi Speedbot Start---------------------# elif msg.text in ["sp","Speedbot","speedbot"]: start = time.time() cl.sendText(msg.to, "Tunggu..") elapsed_time = time.time() - start cl.sendText(msg.to, "%s /Detik" % (elapsed_time)) #-------------Fungsi Speedbot Finish---------------------# #-------------Fungsi Banned Send Contact Start------------------# elif msg.text in ["Ban"]: if msg.from_ in admin: wait["wblacklist"] = True cl.sendText(msg.to,"send contact") ki.sendText(msg.to,"send contact") kk.sendText(msg.to,"send contact") kc.sendText(msg.to,"send contact") elif msg.text in ["Unban"]: if msg.from_ in admin: wait["dblacklist"] = True cl.sendText(msg.to,"send contact") ki.sendText(msg.to,"send contact") kk.sendText(msg.to,"send contact") kc.sendText(msg.to,"send contact") #-------------Fungsi Banned Send Contact Finish------------------# #-------------Fungsi Bannlist Start------------------# elif msg.text in ["Banlist"]: if wait["blacklist"] == {}: cl.sendText(msg.to,"Tidak Ada Akun Terbanned") else: cl.sendText(msg.to,"Blacklist user") mc = "" for mi_d in wait["blacklist"]: mc += "->" +cl.getContact(mi_d).displayName + "\n" cl.sendText(msg.to,mc) #-------------Fungsi Bannlist Finish------------------# elif msg.text in ["Cek ban"]: 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 ["Kill ban"]: 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 == []: cl.sendText(msg.to,"There was no blacklist user") return for jj in matched_list: cl.kickoutFromGroup(msg.to,[jj]) cl.sendText(msg.to,"Blacklist emang pantas tuk di usir") elif msg.text in ["Clear"]: 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,"I pretended to cancel and canceled.") elif "random: " in msg.text: if msg.from_ in admin: if msg.toType == 2: strnum = msg.text.replace("random: ","") source_str = 'abcdefghijklmnopqrstuvwxyz1234567890@:;./_][!&%$#)(=~^|' try: num = int(strnum) group = cl.getGroup(msg.to) for var in range(0,num): name = "".join([random.choice(source_str) for x in xrange(10)]) time.sleep(0.01) group.name = name cl.updateGroup(group) except: cl.sendText(msg.to,"Error") elif "albumat'" in msg.text: try: albumtags = msg.text.replace("albumat'","") gid = albumtags[:6] name = albumtags.replace(albumtags[:34],"") cl.createAlbum(gid,name) cl.sendText(msg.to,name + "created an album") except: cl.sendText(msg.to,"Error") elif "fakecat'" in msg.text: try: source_str = 'abcdefghijklmnopqrstuvwxyz1234567890@:;./_][!&%$#)(=~^|' name = "".join([random.choice(source_str) for x in xrange(10)]) anu = msg.text.replace("fakecat'","") cl.sendText(msg.to,str(cl.channel.createAlbum(msg.to,name,anu))) except Exception as e: try: cl.sendText(msg.to,str(e)) except: pass # if op.type == 55: 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 + datetime.today().strftime(' [%d - %H:%M:%S]') wait2['ROM'][op.param1][op.param2] = "👉 " + Name wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S') else: pass except: pass # if op.type == 59: print op except Exception as error: print error 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"] cl.updateProfile(profile) profile2 = ki.getProfile() profile2.displayName = wait["cName2"] ki.updateProfile(profile2) profile3 = kk.getProfile() profile3.displayName = wait["cName3"] kk.updateProfile(profile3) profile4 = kc.getProfile() profile4.displayName = wait["cName4"] kc.updateProfile(profile4) profile5 = ks.getProfile() profile5.displayName = wait["cName5"] ks.updateProfile(profile5a) profile6 = ka.getProfile() profile6.displayName = wait["cName6"] ka.updateProfile(profile6) profile7 = kb.getProfile() profile7.displayName = wait["cName7"] kb.updateProfile(profile7) profile8 = ko.getProfile() profile8.displayName = wait["cName8"] ko.updateProfile(profile8) profile9 = ke.getProfile() profile9.displayName = wait["cName9"] ke.updateProfile(profile9) profile10 = ku.getProfile() profile10.displayName = wait["cName10"] ku.updateProfile(profile10) time.sleep(600) except: pass thread2 = threading.Thread(target=nameUpdate) thread2.daemon = True thread2.start() def autolike(): 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"], 1002) cl.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"]) print "Like" except: count += 1 if(count == 50): sys.exit(0) thread1 = threading.Thread(target=autolike) thread1.daemon = True thread1.start() def yt(query): with requests.session() as s: isi = [] if query == "": query = "S1B tanysyz" s.headers['user-agent'] = 'Mozilla/5.0' url = 'http://www.youtube.com/results' params = {'search_query': query} r = s.get(url, params=params) soup = BeautifulSoup(r.content, 'html5lib') for a in soup.select('.yt-lockup-title > a[title]'): if '&list=' not in a['href']: if 'watch?v' in a['href']: b = a['href'].replace('watch?v=', '') isi += ['youtu.be' + b] return isi def download_page(url): version = (3,0) cur_version = sys.version_info if cur_version >= version: #If the Current Version of Python is 3.0 or above import urllib,request #urllib library for Extracting web pages try: headers = {} headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" req = urllib,request.Request(url, headers = headers) resp = urllib,request.urlopen(req) respData = str(resp.read()) return respData except Exception as e: print(str(e)) else: #If the Current Version of Python is 2.x import urllib2 try: headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17" req = urllib2.Request(url, headers = headers) response = urllib2.urlopen(req) page = response.read() return page except: return"Page Not found" def _images_get_next_item(s): start_line = s.find('rg_di') if start_line == -1: #If no links are found then give an error! end_quote = 0 link = "no_links" return link, end_quote else: start_line = s.find('"class="rg_meta"') start_content = s.find('"ou"',start_line+90) end_content = s.find(',"ow"',start_content-90) content_raw = str(s[start_content+6:end_content-1]) return content_raw, end_content def _images_get_all_items(page): items = [] while True: item, end_content = _images_get_next_item(page) if item == "no_links": break else: items.append(item) #Append all the links in the list named 'Links' time.sleep(0.1) #Timer could be used to slow down the request for image downloads page = page[end_content:] return items def mention(to,nama): aa = "" bb = "" strt = int(12) akh = int(12) nm = nama #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 += "▪ @c \n" aa = (aa[:int(len(aa)-1)]) msg = Message() msg.to = to msg.text = "「Mention」\n"+bb msg.contentMetadata = {'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'} #print msg try: cl.sendMessage(msg) except Exception as error: print error 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)
988,499
0bcc4feb3099494ea47ac91de76061cdc5160dbc
# -*- encoding: utf-8 -*- ############################################################################## # # Purchase - Computed Purchase Order Module for Odoo # Copyright (C) 2013-Today GRAP (http://www.grap.coop) # @author Julien WESTE # @author Sylvain LE GAL (https://twitter.com/legalsylvain) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, api, fields import openerp.addons.decimal_precision as dp class ProductProduct(models.Model): _inherit = 'product.product' # Private section @api.model @api.one # Later, we may want to implement other valid_psi options def _valid_psi(self, method): if method == 'first': return self._first_valid_psi() elif method == 'all': return self._all_valid_psi() else: return False @api.model @api.one def _all_valid_psi(self): today = fields.Date.today() if not self.product_tmpl_id.seller_ids: return False valid_si = self.product_tmpl_id.seller_ids.filtered( lambda si, t=today: ((not si.date_start or si.date_start <= t) and (not si.date_end or si.date_end >= t))) return valid_si @api.model @api.one def _first_valid_psi(self): if not self.product_tmpl_id.seller_ids: return False valid_si = self._all_valid_psi()[0] seq = min([si.sequence for si in valid_si]) return valid_si.filtered(lambda si, seq=seq: si.sequence == seq) class PricelistPartnerinfo(models.Model): _inherit = 'product.supplierinfo' @api.multi def _calc_qty(self): for supplier_info in self: qty = supplier_info.min_qty self.qty = qty @api.multi def _calc_diff_price(self): for pricelist_supplierinfo in self: diff_price = pricelist_supplierinfo.suppinfo_id.price - pricelist_supplierinfo.price @api.one def _compute_unit_price_cmp(self): #for supplierinfo in self: if len(self.pricelist_ids) == 0: self.unit_price = 0 self.unit_price_note = '-' else: txt = '(' size = len(self.pricelist_ids) uom_precision = self.product_tmpl_id.uom_id.rounding for i in range(size - 1): txt += '%s - %s : %s\n' % ( self.pricelist_ids[i].min_quantity, (self.pricelist_ids[i + 1].min_quantity - uom_precision), self.pricelist_ids[i].price) txt += '>=%s : %s' % ( self.pricelist_ids[size - 1].min_quantity, self.pricelist_ids[size - 1].price) txt += ')' self.unit_price = self.pricelist_ids[0].price self.unit_price_note = txt diff_price = fields.Float(string='Difference of price', compute=_calc_diff_price, store=False, multi="diff_price", help="This is a difference of price between last payed price and contracted") unit_price_note = fields.Char(compute='_compute_unit_price_cmp', multi='unit_price', string='Unit Price') unit_price = fields.Float( compute='_compute_unit_price_cmp', multi='unit_price', store=False, digits_compute=dp.get_precision('Product Price'), help="""Purchase Price of the product for this supplier. \n If many""" """ prices are defined, The price will be the price associated with""" """ the smallest quantity.""", default=False) qty = fields.Float(string='Quantity', compute=_calc_qty, store=True, multi="qty", help="This is a quantity which is converted into Default Unit of Measure.") #price = fields.Float(string='Price', required=True, digits_compute=dp.get_precision('Product Price'), default=0.0, help="The price to purchase a product") #currency_id = fields.Many2one(string='Currency', comodel_name='res.currency', required=True) date_start = fields.Date(string='Start Date', help="Start date for this vendor price") date_end = fields.Date(string='End Date', help="End date for this vendor price") package_qty = fields.Float('Package Qty', digits_compute=dp.get_precision('Product UoM'), help="""The quantity of products in the supplier package.""" """ You will always have to buy a multiple of this quantity.""", default=1)