content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding: utf-8 -*- # from __future__ import print_function from betterbib.__about__ import ( __version__, __author__, __author_email__, __website__, ) from betterbib.tools import ( create_dict, decode, pybtex_to_dict, pybtex_to_bibtex_string, write, update, JournalNameUpdater, translate_month ) from betterbib.crossref import Crossref from betterbib.dblp import Dblp try: import pipdate except ImportError: pass else: if pipdate.needs_checking(__name__): print(pipdate.check(__name__, __version__), end='')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 6738, 1365, 65, 571, 13, 834, 10755, 834, 1330, 357, 198, 220, 220, 220, 11593, 9641, 834, 11, 198, ...
2.330709
254
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import logout, login, authenticate from django.contrib.auth.forms import UserCreationForm from .decorators import * from .forms import PostForm, CustomUserCreationForm, ProfileForm, UserForm from .filters import PostFilter from .models import * # Create your views here. #CRUD VIEWS def sendEmail(request): if request.method == 'POST': template = render_to_string('base/email_template.html', { 'name':request.POST['name'], 'email':request.POST['email'], 'message':request.POST['message'], }) email = EmailMessage( request.POST['subject'], template, settings.EMAIL_HOST_USER, ['cotechlevy@gmail.com'] ) email.fail_silently=False email.send() return render(request, 'base/email_sent.html') def loginPage(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': email = request.POST.get('email') password =request.POST.get('password') #Little Hack to work around re-building the usermodel try: user = User.objects.get(email=email) user = authenticate(request, username=user.username, password=password) except: messages.error(request, 'User with this email does not exists') return redirect('login') if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Email OR password is incorrect') context = {} return render(request, 'base/login.html', context) def registerPage(request): form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request, 'Account successfuly created!') user = authenticate(request, username=user.username, password=request.POST['password1']) if user is not None: login(request, user) next_url = request.GET.get('next') if next_url == '' or next_url == None: next_url = 'home' return redirect(next_url) else: messages.error(request, 'An error has occured with registration') context = {'form':form} return render(request, 'base/register.html', context) def logoutUser(request): logout(request) return redirect('home') def myEducation(request): return render(request, 'base/education.html') def myExperience(request): return render(request, 'base/experience.html') def myAchievements(request): return render(request, 'base/achievements.html') def myAbout(request): return render(request, 'base/about.html') def myContact(request): return render(request, 'base/contact.html') def mySkills(request): return render(request, 'base/skills.html')
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, ...
2.999028
1,029
#!/usr/bin/env python ############################################################################# # Pastebin.py - Python 3.2 Pastebin API. # Copyright (C) 2012 Ian Havelock # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################# # This software is a derivative work of: # http://winappdbg.sourceforge.net/blog/pastebin.py ############################################################################# __ALL__ = ['delete_paste', 'user_details', 'trending', 'pastes_by_user', 'generate_user_key', 'legacy_paste', 'paste', 'Pastebin', 'PastebinError'] import sys import urllib ###################################################### delete_paste = PastebinAPI.delete_paste user_details = PastebinAPI.user_details trending = PastebinAPI.trending pastes_by_user = PastebinAPI.pastes_by_user generate_user_key = PastebinAPI.generate_user_key legacy_paste = PastebinAPI.legacy_paste paste = PastebinAPI.paste ###################################################### if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 29113, 29113, 7804, 4242, 2, 198, 2, 220, 220, 220, 29582, 13, 9078, 532, 11361, 513, 13, 17, 29582, 7824, 13, 198, 2, 220, 220, 220, 15069, 357, 34, 8, 2321, 220, 12930, 9398...
3.615222
473
import urllib.request,json from .models import News import requests News = News # Getting api key api_key = None # Getting the news base url base_url = None base_url2 = None def get_news(category): ''' Function that gets the json responce to our url request ''' get_news_url = base_url.format(category,api_key) print(get_news_url) get_news_response = requests.get(get_news_url).json() print(get_news_response) news_results = None if get_news_response['articles']: news_results_list = get_news_response['articles'] news_results = process_results(news_results_list) return news_results def process_results(news_list): ''' Function that processes the news result and transform them to a list of Objects Args: news_list: A list of dictionaries that contain news details Returns : news_results: A list of news objects ''' news_results = [] for news_item in news_list: title = news_item.get('title') image = news_item.get('urlToImage') description = news_item.get('description') date = news_item.get('publishedAt') article = news_item.get('url') if image: news_object = News(title,image,description,date,article) news_results.append(news_object) return news_results def get_article(source): ''' Function that gets the json responce to our url request ''' get_news_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_url) as url: get_news_data = url.read() get_news_response = json.loads(get_news_data) news_results = None if get_news_response['articles']: news_results_list = get_news_response['articles'] news_results = process_results(news_results_list) return news_results
[ 11748, 2956, 297, 571, 13, 25927, 11, 17752, 198, 6738, 764, 27530, 1330, 3000, 198, 11748, 7007, 198, 198, 9980, 796, 3000, 628, 198, 2, 18067, 40391, 1994, 198, 15042, 62, 2539, 796, 6045, 198, 2, 18067, 262, 1705, 2779, 19016, 198,...
2.49281
765
""" Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". For C programmers: Try to solve it in-place in O(1) space. Clarification: * What constitutes a word? A sequence of non-space characters constitutes a word. * Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. * How about multiple spaces between two words? Reduce them to a single space in the reversed string. https://leetcode.com/problems/reverse-words-in-a-string/ """
[ 37811, 201, 198, 201, 198, 15056, 281, 5128, 4731, 11, 9575, 262, 4731, 1573, 416, 1573, 13, 201, 198, 201, 198, 1890, 1672, 11, 201, 198, 15056, 264, 796, 366, 1169, 6766, 318, 4171, 1600, 201, 198, 7783, 366, 17585, 318, 6766, 262...
3.335106
188
import socket, datetime, os from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal from direct.distributed.DistributedObject import DistributedObject from toontown.toonbase import ToontownGlobals from toontown.uberdog import InGameNewsResponses
[ 11748, 17802, 11, 4818, 8079, 11, 28686, 198, 6738, 1277, 13, 17080, 6169, 13, 20344, 6169, 10267, 22289, 1330, 4307, 6169, 10267, 22289, 198, 6738, 1277, 13, 17080, 6169, 13, 20344, 6169, 10267, 1330, 4307, 6169, 10267, 198, 6738, 284, ...
3.898551
69
# Day 10 Loops from countries import * # While Loop # count = 0 # while count < 5: # if count == 3: # break # print(count) # count = count + 1 # numbers = [0,2,3,4,5,6,7,8,9,10] # for number in numbers: # print(number) # language = 'Python' # for letter in language: # print(letter) # tpl = ('python','updates','wow') # for number in tpl: # print(number) # person = { # 'first_name':'Asabeneh', # 'last_name':'Yetayeh', # 'age':250, # 'country':'Finland', # 'is_marred':True, # 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], # 'address':{ # 'street':'Space street', # 'zipcode':'02210' # } # } # print('------------------------------------') # for key in person: # print(key) # print('------------------------------------') # for key,value in person.items(): # print(key, value) # print('--------------------------------------') # it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} # for company in it_companies: # print(company) # print('--------------------------------------') # numbers = (0,1,2,3,4,5,6,7) # for number in numbers: # print(number) # if(number == 3): # break # print('--------------------------------------') # for number in numbers: # print(number) # if(number == 3): # continue # print('--------------------------------------') # numbers = (0,1,2,3,4,5) # for number in numbers: # print(number) # if number == 3: # continue # print('Next number should be ', number + 1) if number != 5 else print("loop's end") # for short hand conditions need both if and else statements # print('outside the loop') # print('--------------------------------------') # lst = list(range(11)) # print(lst) # st = set(range(1,11)) # print(st) # lst = list(range(0,11,2)) # print(lst) # st = set(range(0,11,2)) # print(st) # Exercises: Day 10 # Iterate 0 to 10 using for loop, do the same using while loop. # numbers = [0,1,2,3,4,5,6,7,8,9,10] # for number in numbers: # print(number) # count = 0 # while count < 10: # print(count) # count += 1 # Iterate 10 to 0 using for loop, do the same using while loop. # for number in range(10,-1,-1): # print(number) # count = 10 # while count > -1: # print(count) # count -= 1 # Write a loop that makes seven calls to print(), so we get on the output the following triangle: for index in range(0,8): print(index * '#') limit = 9 for i in range(0,limit): for j in range(0,limit): print('# ', end='') print('') for i in range(0, 11): print(f'{i} x {i} = {i * i}') frameworks = ['Python', 'Numpy','Pandas','Django', 'Flask'] for framework in frameworks: print(framework) for i in range(0,101): if i % 2 == 0: print(i) for i in range(0,101): if i % 2 != 0: print(i) sum = 0 for i in range(0,101): sum += i print('The sum of all numbers is : ', sum) even_sum = odd_sum = 0 for i in range(0,101): if i % 2 == 0: even_sum += i elif i % 2 != 0: odd_sum += i print(f'The sum of all evens is {even_sum}. And the sum of all odds is {odd_sum}.') for country in countries: if 'land' in country: print(country) fruits = ['banana', 'orange', 'mango', 'lemon'] total_elements = len(fruits) - 1 for i in range(0, int(len(fruits) / 2)): temp_element = fruits[i] fruits[i] = fruits[total_elements - i] fruits[total_elements - i] = temp_element print(fruits)
[ 2, 3596, 838, 6706, 2840, 198, 6738, 2678, 1330, 1635, 220, 198, 198, 2, 2893, 26304, 198, 2, 954, 796, 657, 198, 2, 981, 954, 1279, 642, 25, 198, 2, 220, 220, 220, 220, 611, 954, 6624, 513, 25, 198, 2, 220, 220, 220, 220, 220...
2.43299
1,455
# -*- mode:python -*- import flask import json import logging from datetime import datetime import inflection from functools import wraps from flask import request, url_for from werkzeug.exceptions import HTTPException from .client.api.model import * from . import database from . import helpers from .application import db mgr = database.DatabaseManager(db) log = logging.getLogger(__name__) api = flask.Blueprint('api', __name__) # ============================================================================= # API Helpers # ============================================================================= def _dashboard_sort_column(): """Return a SQLAlchemy column descriptor to sort results by, based on the 'sort' and 'order' request parameters. """ columns = { 'created' : database.DashboardRecord.creation_date, 'modified' : database.DashboardRecord.last_modified_date, 'category' : database.DashboardRecord.category, 'id' : database.DashboardRecord.id, 'title' : database.DashboardRecord.title } colname = helpers.get_param('sort', 'created') order = helpers.get_param('order') column = database.DashboardRecord.creation_date if colname in columns: column = columns[colname] if order == 'desc' or order == u'desc': return column.desc() else: return column.asc() def _set_dashboard_hrefs(dash): """Add the various ReSTful hrefs to an outgoing dashboard representation. dash should be the dictionary for of the dashboard, not the model object. """ id = dash['id'] dash['href'] = url_for('api.dashboard_get', id=id) dash['definition_href'] = url_for('api.dashboard_get_definition', id=id) dash['view_href'] = url_for('ui.dashboard_with_slug', id=id, slug=inflection.parameterize(dash['title'])) if 'definition' in dash: definition = dash['definition'] definition['href'] = url_for('api.dashboard_get_definition', id=id) return dash def _dashboards_response(dashboards): """Return a Flask response object for a list of dashboards in API format. dashboards must be a list of dashboard model objects, which will be converted to their JSON representation. """ if not isinstance(dashboards, list): dashboards = [dashboards] include_definition = helpers.get_param_boolean('definition', False) return [ _set_dashboard_hrefs(d.to_json(include_definition=include_definition)) for d in dashboards] def _set_tag_hrefs(tag): """Add ReSTful href attributes to a tag's dictionary representation. """ id = tag['id'] tag['href'] = url_for('api.tag_get', id=id) return tag def _tags_response(tags): """Return a Flask response object for a list of tags in API format. tags must be a list of tag model objects, which will be converted to their JSON representation. """ if not isinstance(tags, list): tags = [tags] return [_set_tag_hrefs(t.to_json()) for t in tags] # ============================================================================= # Dashboards # ============================================================================= # ============================================================================= # Tags # ============================================================================= # ============================================================================= # Miscellany # =============================================================================
[ 2, 532, 9, 12, 4235, 25, 29412, 532, 9, 12, 198, 198, 11748, 42903, 198, 11748, 33918, 198, 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 1167, 1564, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 6738, 42903...
3.244585
1,108
import sys import re import boto3 from botocore.exceptions import ClientError import uuid import time import yaml import os # def upload_file_s3_bucket(file_name, results, test_file, isArchive): # region = config['region'] # s3_client = boto3.client('s3', region_name=region) # if isArchive: # response = s3_client.upload_file(file_name, 'attack-range-attack-data', str(test_file['simulation_technique'] + '/attack_data.tar.gz')) # else: # response = s3_client.upload_file(file_name, 'attack-range-attack-data', str(test_file['simulation_technique'] + '/attack_data.json')) # # with open('tmp/test_results.yml', 'w') as f: # yaml.dump(results, f) # response2 = s3_client.upload_file('tmp/test_results.yml', 'attack-range-automated-testing', str(test_file['simulation_technique'] + '/test_results.yml')) # os.remove('tmp/test_results.yml')
[ 11748, 25064, 198, 11748, 302, 198, 11748, 275, 2069, 18, 198, 6738, 10214, 420, 382, 13, 1069, 11755, 1330, 20985, 12331, 198, 11748, 334, 27112, 198, 11748, 640, 198, 11748, 331, 43695, 198, 11748, 28686, 628, 628, 628, 198, 2, 825, ...
2.501393
359
# -*- coding: utf-8 -*- """ Created on Fri Aug 31 18:33:58 2018 @author: Marios Michailidis metrics and method to check metrics used within StackNet """ from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score , mean_squared_log_error #regression metrics from sklearn.metrics import roc_auc_score, log_loss ,accuracy_score, f1_score ,matthews_corrcoef import numpy as np valid_regression_metrics=["rmse","mae","rmsle","r2","mape","smape"] valid_classification_metrics=["auc","logloss","accuracy","f1","matthews"] ############ classification metrics ############ ############ regression metrics ############ """ metric: string or class that returns a metric given (y_true, y_pred, sample_weight=None) Curently supported metrics are "rmse","mae","rmsle","r2","mape","smape" """ """ metric: string or class that returns a metric given (y_true, y_pred, sample_weight=None) Curently supported metrics are "rmse","mae","rmsle","r2","mape","smape" """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 2447, 3261, 1248, 25, 2091, 25, 3365, 2864, 198, 198, 31, 9800, 25, 1526, 4267, 2843, 603, 29207, 198, 198, 4164, 10466, 290, 2446, 284, ...
2.50463
432
#!/usr/bin/env python # coding=utf-8 # vim:ts=4:sts=4:sw=4:et # # Author: Hari Sekhon # Date: 2017-11-24 21:10:35 +0100 (Fri, 24 Nov 2017) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on LinkedIn # and optionally send me feedback to help steer this or other code I publish # # https://www.linkedin.com/in/harisekhon # """ Nagios Plugin to check a Logstash pipeline is online via the Logstash Rest API API is only available in Logstash 5.x onwards, will get connection refused on older versions Optional thresholds apply to the number of pipeline workers Ensure Logstash options: --http.host should be set to 0.0.0.0 if querying remotely --http.port should be set to the same port that you are querying via this plugin's --port switch Tested on Logstash 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 6.0, 6.1 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import sys import traceback srcdir = os.path.abspath(os.path.dirname(__file__)) libdir = os.path.join(srcdir, 'pylib') sys.path.append(libdir) try: # pylint: disable=wrong-import-position #from harisekhon.utils import log from harisekhon.utils import ERRORS, UnknownError, support_msg_api from harisekhon.utils import validate_chars from harisekhon import RestNagiosPlugin except ImportError as _: print(traceback.format_exc(), end='') sys.exit(4) __author__ = 'Hari Sekhon' __version__ = '0.6' if __name__ == '__main__': CheckLogstashPipeline().main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 19617, 28, 40477, 12, 23, 198, 2, 220, 43907, 25, 912, 28, 19, 25, 6448, 28, 19, 25, 2032, 28, 19, 25, 316, 198, 2, 198, 2, 220, 6434, 25, 2113, 72, 37558, 24130, 198, ...
2.848485
594
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Example DAG demonstrating the usage of the BashOperator.""" from datetime import timedelta import datetime import airflow from airflow.models import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.python_operator import BranchPythonOperator args = { 'owner': 'Airflow', 'start_date': airflow.utils.dates.days_ago(14), } dag = DAG( dag_id='exercise_weekday', default_args=args, schedule_interval='0 0 * * *', dagrun_timeout=timedelta(minutes=60), ) dummy_last = DummyOperator( task_id='run_this_last', dag=dag, trigger_rule='one_success', ) weekday_task = PythonOperator( task_id='weekday_task', python_callable=print_weekday, provide_context=True, dag=dag, ) # optimize with try exept weekday_person = { "Mon": "bob", "Tue": "joe", "Thu": "joe", } branch_task = BranchPythonOperator( task_id='branch_task', python_callable=define_oncall, provide_context=True, dag=dag, ) tasks = ["bob", "joe", "ali"] for p in tasks: taski = DummyOperator( task_id=p, dag=dag, ) branch_task >> taski taski >> dummy_last weekday_task >> branch_task
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351,...
2.918956
728
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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. # """Python equivalent of jdbc_type.h. Python definition of the JDBC type constant values defined in Java class java.sql.Types. Since the values don't fall into the range allowed by a protocol buffer enum, we use Python constants instead. If you update this, update jdbc_type.py also. """ BIT = -7 TINYINT = -6 SMALLINT = 5 INTEGER = 4 BIGINT = -5 FLOAT = 6 REAL = 7 DOUBLE = 8 NUMERIC = 2 DECIMAL = 3 CHAR = 1 VARCHAR = 12 LONGVARCHAR = -1 DATE = 91 TIME = 92 TIMESTAMP = 93 BINARY = -2 VARBINARY = -3 LONGVARBINARY = -4 NULL = 0 OTHER = 1111 JAVA_OBJECT = 2000 DISTINCT = 2001 STRUCT = 2002 ARRAY = 2003 BLOB = 2004 CLOB = 2005 REF = 2006 DATALINK = 70 BOOLEAN = 16 ROWID = -8 NCHAR = -15 NVARCHAR = -9 LONGNVARCHAR = -16 NCLOB = 2011 SQLXML = 2009
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 4343, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
2.903846
468
from django.http import HttpResponse from django.core.mail import send_mail import json from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from GestiRED.models import User from GestiRED.models import QualityControl, Phase, Resource, ResourceType,PhaseType from django.core import serializers from django.db.models import Q # Create your views here.
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 7295, 13, 4529, 1330, 3758, 62, 4529, 198, 11748, 33918, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 13, ...
3.545455
110
from maix import nn from PIL import Image, ImageDraw, ImageFont from maix import display, camera import time from maix.nn import decoder camera.config(size=(224, 224)) model = { "param": "/root/models/yolo2_face_awnn.param", "bin": "/root/models/yolo2_face_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+1)*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } print("-- load model:", model) m = nn.load(model, opt=options) print("-- load ok") print("-- read image") w = options["inputs"]["input0"][1] h = options["inputs"]["input0"][0] # # img.show() print("-- read image ok") labels = ["person"] anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65] yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(w, h), net_out_size=(7, 7)) while 1: img = camera.capture() if not img: time.sleep(0.01) continue t = time.time() out = m.forward(img, quantize=True, layout="hwc") print("-- forward: ", time.time() - t ) t = time.time() boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.5, img_size=(240, 240)) print("-- decode: ", time.time() - t ) t = time.time() for i, box in enumerate(boxes): class_id = probs[i][0] prob = probs[i][1][class_id] disp_str = "{}:{:.2f}%".format(labels[class_id], prob*100) draw_rectangle_with_title(display.get_draw(), box, disp_str) print("-- draw: ", time.time() - t ) t = time.time() display.show() print("-- show: ", time.time() - t )
[ 628, 198, 198, 6738, 17266, 844, 1330, 299, 77, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 25302, 11, 7412, 23252, 198, 6738, 17266, 844, 1330, 220, 3359, 11, 4676, 198, 11748, 640, 198, 6738, 17266, 844, 13, 20471, 1330, 875, 12342,...
2.164948
776
from dataclasses import dataclass, field from datetime import date, datetime, time, timezone from pathlib import Path from typing import Any, Dict, Optional, Union import ciso8601 import pytest from mashumaro import DataClassDictMixin from mashumaro.exceptions import UnserializableField from mashumaro.types import SerializationStrategy from .entities import ( MutableString, MyList, ThirdPartyType, TypedDictRequiredKeys, )
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 11, 640, 11, 640, 11340, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 11, 4479,...
3.168919
148
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.metrics import classification_report from sklearn.linear_model import SGDClassifier from nltk import word_tokenize import nltk #nltk.download('punkt') import re import joblib #train_intent() ''' calender = 0 faculty =1 infra = 2 placement = 4 result = 5 small_talk = 6 student body = 7 syllabus = 8 '''
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 6738, 1341, 35720, 13, 30053, 62, 2302, 7861, 13, 5239, 1330, 2764, 38469, 7509, 11, 309, 69, 312, 69, 38469, 7509, ...
3.128713
202
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ops to manipulate lists of tensors.""" # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_list_ops # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.ops.gen_list_ops import * # pylint: enable=wildcard-import ops.NotDifferentiable("TensorListConcatLists") ops.NotDifferentiable("TensorListElementShape") ops.NotDifferentiable("TensorListLength") ops.NotDifferentiable("TensorListPushBackBatch") def _build_element_shape(shape): """Converts shape to a format understood by list_ops for element_shape. If `shape` is already a `Tensor` it is returned as-is. We do not perform a type check here. If shape is None or a TensorShape with unknown rank, -1 is returned. If shape is a scalar, an int32 tensor with empty list is returned. Note we do directly return an empty list since ops.convert_to_tensor would conver it to a float32 which is not a valid type for element_shape. If shape is a sequence of dims, None's in the list are replaced with -1. We do not check the dtype of the other dims. Args: shape: Could be None, Tensor, TensorShape or a list of dims (each dim could be a None, scalar or Tensor). Returns: A None-free shape that can be converted to a tensor. """ if isinstance(shape, ops.Tensor): return shape if isinstance(shape, tensor_shape.TensorShape): # `TensorShape.as_list` requires rank to be known. shape = shape.as_list() if shape else None # Shape is unknown. if shape is None: return -1 # Shape is a scalar. if not shape: return ops.convert_to_tensor(shape, dtype=dtypes.int32) # Shape is a sequence of dimensions. Convert None dims to -1. return [d if d is not None else -1 for d in shape]
[ 2, 15069, 2864, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
3.375154
813
import ast import re import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import astunparse from tests.common import AstunparseCommonTestCase
[ 11748, 6468, 198, 11748, 302, 198, 11748, 25064, 198, 361, 25064, 13, 9641, 62, 10951, 1279, 357, 17, 11, 767, 2599, 198, 220, 220, 220, 1330, 555, 715, 395, 17, 355, 555, 715, 395, 198, 17772, 25, 198, 220, 220, 220, 1330, 555, 7...
2.96875
64
from django.core.management.base import AppCommand, CommandError from django.core.management.sql import sql_reset from django.core.management.color import no_style from django.db import connections
[ 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 2034, 21575, 11, 9455, 12331, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 25410, 1330, 44161, 62, 42503, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8043, 1330, 645, ...
3.807692
52
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
# coding:utf-8 ''' @author = super_fazai @File : requires.py @Time : 2016/8/3 12:59 @connect : superonesfazai@gmail.com ''' install_requires = [ 'ipython', 'wheel', 'utils', 'db', 'greenlet==0.4.13', 'web.py==0.40.dev1', 'pytz', 'requests', 'selenium==3.8.0', # 3.8.1phantomjs 'asyncio', 'psutil', 'pyexecjs', 'setuptools', 'colorama', 'twine', 'numpy', 'pprint', 'selenium', 'chardet', 'bs4', 'scrapy', 'demjson', 'pymssql', 'sqlalchemy', 'gevent', 'aiohttp', 'celery', 'jsonpath', 'matplotlib', 'wget', 'flask', 'flask_login', 'mitmproxy', # shell 'pymongo', 'pyexcel', 'pyexcel-xlsx', 'fabric', 'shadowsocks', # 'pycurl==7.43.0.1', 'furl', 'yarl', 'prettytable', 'xlrd', 'pandas', 'jieba', 'geopandas', 'scikit-image', 'wordcloud', # 'pygame', ]
[ 2, 19617, 25, 40477, 12, 23, 198, 198, 7061, 6, 198, 31, 9800, 796, 2208, 62, 69, 1031, 1872, 198, 31, 8979, 220, 220, 220, 1058, 4433, 13, 9078, 198, 31, 7575, 220, 220, 220, 1058, 1584, 14, 23, 14, 18, 1105, 25, 3270, 198, 3...
1.765766
555
import subprocess import requests import argparse from concurrent.futures import ThreadPoolExecutor from time import sleep from datetime import datetime ICMP_ATTACK = "ICMP" HTTP_ATTACK = "HTTP" valid_attacks = {HTTP_ATTACK, ICMP_ATTACK} parser = argparse.ArgumentParser(description="DoS HTTP") parser.add_argument('-P', '--poolsize', default=10, help='Size of the threadpool') parser.add_argument('-T', '--target', default='localhost', help='Target URL for http request') parser.add_argument('-D', '--delay', default=0, help='Amount of time to wait between requests') parser.add_argument('-A', '--attack', help='Type of attack (e.g. HTTP, ICMP)') args = parser.parse_args() threadpool_size = int(args.poolsize) target = args.target delay = int(args.delay) attack = args.attack.upper() if attack not in valid_attacks: print(f"Invalid attack type, must be one of: {valid_attacks}") exit() terminate = False if __name__ == "__main__": main()
[ 11748, 850, 14681, 198, 11748, 7007, 198, 11748, 1822, 29572, 198, 6738, 24580, 13, 69, 315, 942, 1330, 14122, 27201, 23002, 38409, 198, 6738, 640, 1330, 3993, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 2149, 7378, 62, 17139, 81...
3.073248
314
from django.apps import apps from django.db import models from django.db.models.signals import post_save, pre_delete from typing import Type, Optional, List, cast, TYPE_CHECKING from maestro.backends.django.settings import maestro_settings from maestro.backends.django.contrib.factory import create_django_data_store from maestro.backends.django.utils import model_to_entity_name from maestro.core.metadata import Operation from .middleware import _add_operation_to_queue import copy if TYPE_CHECKING: from maestro.backends.django import DjangoDataStore
[ 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 11, 662, 62, 33678, 198, 6738, 19720, 1330, 5994, 11, 32233, ...
3.369048
168
from django.urls import include, path from .views import home, bike urlpatterns = [ path("", home), path("bike/<int:number>", bike) ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 2291, 11, 3108, 198, 6738, 764, 33571, 1330, 1363, 11, 7161, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 7203, 1600, 1363, 828, 198, 220, 220, 220, 3108, 7203, 32256, 14, 27...
2.730769
52
""" Remove Fragments not in Knowledgebase """ __author__ = "Michael Suarez" __email__ = "masv@connect.ust.hk" __copyright__ = "Copyright 2019, Hong Kong University of Science and Technology" __license__ = "3-clause BSD" from argparse import ArgumentParser import numpy as np import pickle parser = ArgumentParser(description="Build Files") parser.add_argument("--datadir", type=str, default="Data", help="input - XXX.YYY ") parser.add_argument("--envNewAcronym", type=str, default="PRT.SNW", help="input - XXX.YYY ") args = parser.parse_args() # Check the Bound Fragments BoundFrags = np.loadtxt("../%s/%s/%s.Homogenised.boundfrags_zeros.txt" %(args.datadir, args.envNewAcronym, args.envNewAcronym), delimiter=',') normalDF = pickle.load(open("../%s/GrandCID.dict" %(args.datadir), "rb")) binding = np.full(BoundFrags.shape,-1) mlength = 0 for r, i in enumerate(BoundFrags): for c, j in enumerate(i[i!=0]): try: # Checks whether the Fragment can be found in the 59k Fragment Base binding[r,c]=normalDF.index.get_loc(int(j)) except: continue temp = binding[r] if temp[temp!=-1].shape[0] > mlength: mlength = temp[temp!=-1].shape[0] print(mlength) #Finds the maximum number of Fragments per environment -> 705 indices = np.empty(binding.shape[0]) red_binding = np.full((binding.shape[0], mlength), -1) for j, i in enumerate(binding): indices[j] = i[i!=-1].shape[0] red_binding[j][:int(indices[j])] = i[i!=-1] red_binding = np.delete(red_binding, np.where(indices==0), axis=0) pickle.dump(red_binding, open("../%s/%s/%s.binding.mtr" %(args.datadir, args.envNewAcronym, args.envNewAcronym), "wb")) # Removes environments without binding Fragments Features_all = pickle.load(open("../%s/%s/%s.Homogenised.property.pvar" %(args.datadir, args.envNewAcronym, args.envNewAcronym), "rb")) Features_all = np.delete(Features_all, np.where(indices==0), axis=0) pickle.dump(Features_all, open("../%s/%s/%s.Homogenised.property.pvar" %(args.datadir, args.envNewAcronym, args.envNewAcronym), "wb")) # Removes environment annotiation without binding fragments with open("../%s/%s/%s.Homogenised.annotation.txt" %(args.datadir, args.envNewAcronym, args.envNewAcronym), "r+") as f: lines = f.readlines() for i in np.where(indices==0)[0][::-1]: del lines[i] f.seek(0) f.truncate() f.writelines(lines)
[ 37811, 198, 27914, 24229, 902, 407, 287, 20414, 8692, 198, 37811, 198, 198, 834, 9800, 834, 796, 366, 13256, 39992, 1, 198, 834, 12888, 834, 796, 366, 5356, 85, 31, 8443, 13, 436, 13, 71, 74, 1, 198, 834, 22163, 4766, 834, 796, 36...
2.460366
984
"""Tests for core.billing. Run this test from the project root $ nosetests core.tests.billing_tests Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import random import math from core.billing import get_call_cost from core.billing import get_prefix_from_number from core.billing import get_sms_cost from core.billing import process_prices from core.billing import round_to_billable_unit from core.billing import round_up_to_nearest_100 from core import config_database TARIFF = 100
[ 37811, 51, 3558, 329, 4755, 13, 65, 4509, 13, 198, 198, 10987, 428, 1332, 422, 262, 1628, 6808, 198, 220, 220, 220, 720, 43630, 316, 3558, 4755, 13, 41989, 13, 65, 4509, 62, 41989, 198, 198, 15269, 357, 66, 8, 1584, 12, 25579, 11,...
3.533333
255
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from data_interrogator.admin.forms import AdminInvestigationForm, AdminPivotTableForm from data_interrogator.interrogators import Allowable from data_interrogator.views import InterrogationView, InterrogationAutocompleteUrls, PivotTableView, \ InterrogationAutoComplete
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 2836, 62, 6603, 274, 62, 9288, 198, 6738, 42625, 14208, 13, 26791, 13, 12501, 273, 2024, 1330, 2446, 62, 12501, 273, 1352, 198, 198, 6738, 1366, 62, 3849, 3828,...
3.460177
113
_base_ = './pspnet_r50-d8_512x512_80k_loveda.py' model = dict( backbone=dict( depth=18, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')), decode_head=dict( in_channels=512, channels=128, ), auxiliary_head=dict(in_channels=256, channels=64))
[ 62, 8692, 62, 796, 705, 19571, 862, 79, 3262, 62, 81, 1120, 12, 67, 23, 62, 25836, 87, 25836, 62, 1795, 74, 62, 75, 2668, 64, 13, 9078, 6, 198, 19849, 796, 8633, 7, 198, 220, 220, 220, 32774, 28, 11600, 7, 198, 220, 220, 220, ...
1.96988
166
from typing import Dict, Any
[ 6738, 19720, 1330, 360, 713, 11, 4377 ]
4
7
from django import forms from django.forms import ModelForm from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from .choices import ActionChoice from .choices import StatusApproval from .models import GreencheckIp from .models import GreencheckIpApprove from .models import GreencheckASN, GreencheckASNapprove User = get_user_model()
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 23914, 1330, 9104, 8479, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 247...
3.495495
111
#!/usr/bin/env python # -*-coding:utf-8-*- from tld import get_tld __author__ = "Allen Woo" def get_domain(url): ''' url :param url: :return: ''' res = get_tld(url, as_object=True) return "{}.{}".format(res.subdomain, res.tld)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 66, 7656, 25, 40477, 12, 23, 12, 9, 12, 198, 6738, 256, 335, 1330, 651, 62, 83, 335, 198, 198, 834, 9800, 834, 796, 366, 39989, 39832, 1, 198, 198, 4299, 651, 62...
2.081301
123
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: BSD-3-Clause # Copyright 2017-2019, GoodData Corporation. All rights reserved. """ FreeIPA Manager - entity module Object representations of the entities configured in FreeIPA. """ import os import re import voluptuous import yaml from abc import ABCMeta, abstractproperty import schemas from command import Command from core import FreeIPAManagerCore from errors import ConfigError, ManagerError, IntegrityError class FreeIPAGroup(FreeIPAEntity): """Abstract representation a FreeIPA group entity (host/user group).""" managed_attributes_push = ['description']
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 15069, 220, 2177, 12, 2334...
3.417526
194
# pylint: skip-file from athena_glue_service_logs.catalog_manager import BaseCatalogManager
[ 2, 279, 2645, 600, 25, 14267, 12, 7753, 198, 6738, 379, 831, 64, 62, 4743, 518, 62, 15271, 62, 6404, 82, 13, 9246, 11794, 62, 37153, 1330, 7308, 49015, 13511, 628, 198 ]
2.9375
32
from twisted.internet import reactor reactor.listenTCP(8789, factory) reactor.run()
[ 6738, 19074, 13, 37675, 1330, 21905, 198, 260, 11218, 13, 4868, 268, 4825, 47, 7, 23, 40401, 11, 8860, 8, 198, 260, 11218, 13, 5143, 3419 ]
3.192308
26
import pandas as pd import numpy as np import matplotlib.pyplot as plt #Setting up Name and CSV location player_name = "Put player name" file_src = "Put target csv" raw = pd.read_csv(file_src) df = pd.DataFrame(raw) #For filtering cases replace_dict = {"description": {"hit_into_play_no_out": "contact", "hit_into_play": "contact", "hit_into_play_score": "contact", "swinging_strike": "miss", "swinging_strike_blocked": "miss"}} ballname_dict = {"FF": "4-Seam Fastball", "CH": "Changeup", "CU": "Curveball", "SL": "Slider", "FT": "2-Seam Fastball", "AB": "Automatic Ball", "AS": "Automatic Strike", "EP": "Eephus", "FC": "Cutter", "FO": "Forkball", "FS": "Splitter", "GY": "Gyroball", "IN": "Intentional Ball", "KC": "Knuckle Curve", "NP": "No Pitch", "PO": "Pitchout", "SC": "Screwball", "SI": "Sinker", "UN": "Unknown"} df = df.replace(replace_dict) df = df[df["description"].isin(["contact", "miss"])] for i in df["pitch_type"].unique(): visualize(df, i)
[ 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 201, 198, 201, 198, 2, 34149, 510, 6530, 290, 44189, 4067, 201, 198, 7829, 62, 36...
2.436754
419
# -*- coding: utf-8 -*- """ Created on Sat May 25 13:17:49 2019 @author: Toonw """ import numpy as np # Similarity measure of article ## https://pdfs.semanticscholar.org/60b5/aca20ba34d424f4236359bd5e6aa30487682.pdf
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 1737, 1679, 1511, 25, 1558, 25, 2920, 13130, 198, 198, 31, 9800, 25, 1675, 261, 86, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 628, ...
2.292929
99
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
2.857143
35
import os import time from utils.eye import Eye from utils.finger import Finger
[ 11748, 28686, 198, 11748, 640, 198, 198, 6738, 3384, 4487, 13, 25379, 1330, 14144, 198, 6738, 3384, 4487, 13, 35461, 1330, 39454, 628 ]
3.565217
23
#!/usr/bin/env python # -*- coding: UTF-8 -*- import random from ete2 import Tree, TreeStyle, NodeStyle, faces, AttrFace, CircleFace, TextFace def test_data(): D = {'taxonomy': [{"score": "0.718868", "label": "/art and entertainment/movies and tv/movies"},\ {"confident": "no", "score": "0.304296", "label": "/pets/cats"},\ {"score": "0.718868", "label": "/art and entertainment/movies and tv/series"}]} t7s = Tree7s("ThingAdamsFamily") for el in D["taxonomy"]: #n = t7s n = t7s.find_root() taxonomy_tree = el["label"] taxonomy_tree = taxonomy_tree.split("/") taxonomy_tree.pop(0) levels = len(taxonomy_tree) score = float(el["score"]) print levels, taxonomy_tree, score for i in range(levels): label = taxonomy_tree[i] #if n.find_child(label) == None: n.add_child(label, score, i+1) n = n.find_child(label) t7s.find_root().print_me() t = t7s.find_root() S = t.create_newick() + ";" print S #S = "(((A,B,(C.,D)E)F,(S,N)K)R);" #T = Tree(S, format=8) T = Tree(S, format=1) for node in T.traverse("postorder"): # Do some analysis on node print node.name for node in T.traverse("levelorder"): # Do some analysis on node print node.name #for branch in T return T if __name__ == "__main__": #t.render("bubble_map.png", w=600, dpi=300, tree_style=ts) #t.show(tree_style=ts) t = test_data() ts = give_tree_layout(t) t.show(tree_style=ts) t.render("bubble_map.png", w=600, dpi=300, tree_style=ts)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 11748, 4738, 198, 6738, 304, 660, 17, 1330, 12200, 11, 12200, 21466, 11, 19081, 21466, 11, 6698, 11, 3460, 81, 32388,...
2.275809
649
from __future__ import annotations import re import time from typing import get_args, Literal, TYPE_CHECKING, Union from lxml import html from compass.core.interface_base import InterfaceBase from compass.core.logger import logger from compass.core.schemas import member as schema from compass.core.settings import Settings from compass.core.utility import cast from compass.core.utility import maybe_int from compass.core.utility import parse if TYPE_CHECKING: import requests MEMBER_PROFILE_TAB_TYPES = Literal[ "Personal", "Roles", "Permits", "Training", "Awards", "Emergency", "Comms", "Visibility", "Disclosures" ]
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 302, 198, 11748, 640, 198, 6738, 19720, 1330, 651, 62, 22046, 11, 25659, 1691, 11, 41876, 62, 50084, 2751, 11, 4479, 198, 198, 6738, 300, 19875, 1330, 27711, 198, 198, 6738, 31855, ...
3.390374
187
from django.urls import path from . import views urlpatterns = [ path('', view=views.SuraListView.as_view(), name='sura-list'), path('<int:sura_num>/<int:number>/', view=views.AyahTextView.as_view(), name='ayah-detail'), path('<int:sura_num>/<int:number>', view=views.AyahTextView.as_view()), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 1570, 28, 33571, 13, 50, 5330, ...
2.167742
155
from konnection.settings.base import * from pathlib import Path import os import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True SECRET_KEY = 'temporaryKey' # For tests # https://stackoverflow.com/a/35224204 TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-spec', '--spec-color'] # Adding secrets to env file # From StackOverflow https://stackoverflow.com/a/61437799 # From Zack Plauch https://stackoverflow.com/users/10415970/zack-plauch%c3%a9 dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Connecting PostgreSQL to Django # From https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04 # From Digital Ocean # From Justin Ellingwood https://www.digitalocean.com/community/users/jellingwood if os.getenv('GITHUB_WORKFLOW'): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'github-actions', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432' } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'localhost', 'PORT': '', } }
[ 6738, 479, 261, 1606, 295, 13, 33692, 13, 8692, 1330, 1635, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 28686, 198, 11748, 16605, 24330, 198, 198, 2, 10934, 13532, 2641, 262, 1628, 588, 428, 25, 49688, 62, 34720, 1220, 705, 7...
2.265363
716
import random from evaluation import Evaluator from generator import generator from mutate import mutateset from deap import base from deap import creator from deap import tools from parameter_group import ParameterGroup import gaussian_output from analysis import Analysis from gaussian_input import GaussianInput from gaussian import gaussian_single from header import Header from reparm_data import ReparmData from genesis import Genesis import numpy as np from scipy.optimize import minimize from copy import deepcopy from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import svm from sklearn.linear_model import RidgeCV from sklearn.ensemble import RandomForestRegressor ############################################# # BEGIN USER INPUT ############################################# fin = open("reparm.in", 'r') file = fin.read() reparm_data = ReparmData(file) if reparm_data.reparm_input.should_continue: reparm_data.load() else: Genesis(reparm_data=reparm_data) reparm_data.save() ############################################ # END USER INPUT ############################################ ############################################# # BEGIN USER INPUT ############################################# # Number of Generation NGEN = reparm_data.reparm_input.number_generations # PopulationSize PSIZE = reparm_data.reparm_input.population_size # Crossover Probability CXPB = reparm_data.reparm_input.crossover_probability # Mutation Probability # How likely and individual will be mutated MUTPB = reparm_data.reparm_input.mutation_probability # Mutation Rate # How likely a member of an individual will be mutated MUTR = reparm_data.reparm_input.mutation_rate # Crowding Factor CWD = reparm_data.reparm_input.crowding_factor # Mutation Perturbation MUTPT = reparm_data.reparm_input.mutation_perturbation # Initial Perturbation IMUTPT = 0.05 # Initial List of parameters IL = [] for i in range(0, len(reparm_data.best_am1_individual.inputs[0].parameters[0].p_floats), 4): IL.append(reparm_data.best_am1_individual.inputs[0].parameters[0].p_floats[i]) # The evaluator (fitness, cost) function eval = Evaluator(reparm_data=reparm_data) if reparm_data.best_fitness is None: reparm_data.best_fitness = list(eval.eval(IL)) reparm_data.original_fitness = deepcopy(reparm_data.best_fitness) else: reparm_data.best_fitness = list(eval.eval(IL)) print("original_fitness", reparm_data.original_fitness) print("starting at", reparm_data.best_fitness) ############################################# # END USER INPUT ############################################# ############################################# # BEGIN DEAP SETUP ############################################# creator.create("FitnessMax", base.Fitness, weights=(-1.0, 0, 0)) creator.create("ParamSet", list, fitness=creator.FitnessMax, best=None) toolbox = base.Toolbox() toolbox.register("individual", generator, IL, IMUTPT) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("mate", tools.cxSimulatedBinary) toolbox.register("mutate", mutateset, pert=MUTPT, chance=MUTR) toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("evaluate", eval.eval) pop = toolbox.population(n=PSIZE) ############################################# # END DEAP SETUP ############################################# ############################################# # BEGIN GENETIC ALGORITHM ############################################# for g in range(NGEN): print("Starting gen:", g) offspring = toolbox.select(pop, len(pop)) offspring = list(map(toolbox.clone, offspring)) for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: toolbox.mate(child1, child2, CWD) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = [] for i in invalid_ind: try: fitness = toolbox.evaluate(i) fitnesses.append(fitness) reparm_data.observations.append(list(i)) i.fitness.values = fitness if not reparm_data.best_fitness or fitness[0] < reparm_data.best_fitness[0]: print("Previous Best", reparm_data.best_fitness) reparm_data.best_fitness = list(fitness) reparm_data.best_am1_individual.set_pfloats(i) print("NewBest Found:", reparm_data.best_fitness) except TypeError: fitnesses.append(None) reparm_data.save() pop[:] = offspring ############################################# # End Genetic Algorithm ############################################# ############################################# # Begin Particle Simulation ############################################# # for g in range(NGEN): # for part in pop: # part.fitness.values = toolbox.evaluate(part) # if not part.best or part.best.fitness < part.fitness: # part.best = creator.ParamSet(part) # part.best.fitness.values = part.fitness.values # if not best or best.fitness < part.fitness: # best = creator.ParamSet(part) # best.fitness.values = part.fitness.values # for part in pop: # toolbox.mutate(part) # print(best, "with fitness", best.fitness) ############################################# # End Particle Simulation ############################################# ############################################# # Begin Print Out ############################################# gin_best = reparm_data.best_am1_individual.inputs[0] s_opt_header = "#P AM1(Input,Print) opt\n\nAM1\n" opt_header = Header(s_opt_header) gin_opt = GaussianInput(header=opt_header, coordinates=gin_best.coordinates[0], parameters=gin_best.parameters[0]) fout = open("reparm_best_opt.com", 'w') fout.write(gin_opt.str()) fout.close() try: gout = gaussian_single(gin_opt.str()) fout = open("reparm_best_opt.log", 'w') fout.write(gout) fout.close() except TypeError: print("Could not get output file from input," "most likely, optimization failed to converge") ############################################# # End Print Out ############################################# ############################################# # Begin ScikitLearn ############################################# # # Preprocessor # targets = np.array(reparm_data.targets) # X = np.array(reparm_data.observations) # y = targets[:, 0] # 0, 1, 2 for total, energy, and dipole # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) # stdsc = StandardScaler() # X_train_std = stdsc.fit_transform(X_train) # X_test_std = stdsc.transform(X_test) # # # Training # clf = svm.SVR(C=1.3, kernel='rbf') # # clf = RandomForestRegressor(n_estimators=20) # clf.fit(X_train, y_train) # print("Using {} samples with fitness score {}".format(len(y), clf.score(X_test, y_test))) # # initial_guess = np.array(IL) # fun = lambda x: clf.predict(stdsc.transform(x.reshape(1, -1))) # print("Predicting best parameters") # min_params = (minimize(fun, initial_guess)).x # stdsc.inverse_transform(min_params) # params = min_params.tolist() # skl_best = deepcopy(reparm_data.best_am1_individual) # skl_best.set_pfloats(params) # open("skl_best.com", 'w').write(skl_best.inputs[0].str()) # skl_fitness = eval.eval(params) # if skl_fitness: # print("skl_fitness:", skl_fitness) ############################################# # End ScikitLearn ############################################# ############################################# # Begin Analysis ############################################# anal = Analysis(reparm_data) anal.trithiophene() ############################################# # End Analysis #############################################
[ 11748, 4738, 198, 6738, 12660, 1330, 26439, 84, 1352, 198, 6738, 17301, 1330, 17301, 198, 6738, 4517, 378, 1330, 4517, 689, 316, 198, 6738, 390, 499, 1330, 2779, 198, 6738, 390, 499, 1330, 13172, 198, 6738, 390, 499, 1330, 4899, 198, ...
2.837137
2,892
import unittest #import tempfile try: from StringIO import StringIO except: from io import StringIO import pyx12.error_handler from pyx12.errors import EngineError # , X12PathError import pyx12.x12context import pyx12.params from pyx12.test.x12testdata import datafiles
[ 11748, 555, 715, 395, 198, 2, 11748, 20218, 7753, 198, 28311, 25, 198, 220, 220, 220, 422, 10903, 9399, 1330, 10903, 9399, 198, 16341, 25, 198, 220, 220, 220, 422, 33245, 1330, 10903, 9399, 198, 198, 11748, 12972, 87, 1065, 13, 18224,...
2.921569
102
# -*- coding: utf-8 -*- import re,urlparse,cookielib,os,urllib from liveresolver.modules import client,recaptcha_v2,control,constants, decryptionUtils from liveresolver.modules.log_utils import log cookieFile = os.path.join(control.dataPath, 'finecastcookie.lwp') #except: # return
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 11748, 302, 11, 6371, 29572, 11, 27916, 8207, 571, 11, 418, 11, 333, 297, 571, 198, 6738, 2107, 411, 14375, 13, 18170, 1330, 5456, 11, 8344, 2373, 11693, 62, 85, ...
2.584746
118
# Copyright 2008-2015 Nokia Solutions and Networks # # 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. """Message publishing and subscribing. .. contents:: :depth: 2 :local: Introduction ------------ RIDE uses messages for communication when something of interest happens, for example a suite is loaded or item is selected in the tree. This module provides means both for subscribing to listen to those messages and for sending them. Messages are used for communication between the different components of the core application, but their main usage is notifying plugins about various events. Plugins can also send messages themselves, and also create custom messages, if they have a need. Subscribing ----------- The core application uses the global `PUBLISHER` object (an instance of the `Publisher` class) for subscribing to and unsubscribing from the messages. Plugins should use the helper methods of the `Plugin` class instead of using the `PUBLISHER` directly. Message topics ~~~~~~~~~~~~~~ Regardless the method, subscribing to messages requires a message topic. Topics can be specified using the actual message classes in `robotide.publish.messages` module or with their dot separated topic strings. It is, for example, equivalent to use the `RideTreeSelection` class and a string ``ride.tree.selection``. Topic strings can normally, but not always, be mapped directly to the class names. The topic strings represents a hierarchy where the dots separate the hierarchy levels. All messages with a topic at or below the given level will match the subscribed topic. For example, subscribing to the ``ride.notebook`` topic means that `RideNotebookTabChanged` or any other message with a topic starting with ``ride.notebook`` will match. Listeners ~~~~~~~~~ Another thing needed when subscribing is a listener, which must be a callable accepting one argument. When the corresponding message is published, the listener will be called with an instance of the message class as an argument. That instance contains the topic and possibly some additional information in its attributes. The following example demonstrates how a plugin can subscribe to an event. In this example the ``OnTreeSelection`` method is the listener and the ``message`` it receives is an instance of the `RideTreeSelection` class. :: from robotide.pluginapi import Plugin, RideTreeSelection class MyFancyPlugin(Plugin): def activate(self): self.subscribe(self.OnTreeSelection, RideTreeSelection) def OnTreeSelection(self, message): print message.topic, message.node Unsubscribing ~~~~~~~~~~~~~ Unsubscribing from a single message requires passing the same topic and listener to the unsubscribe method that were used for subscribing. Additionally both the `PUBLISHER` object and the `Plugin` class provide a method for unsubscribing all listeners registered by someone. Publishing messages ------------------- Both the core application and plugins can publish messages using message classes in the `publish.messages` module directly. Sending a message is as easy as creating an instance of the class and calling its ``publish`` method. What parameters are need when the instance is created depends on the message. Custom messages ~~~~~~~~~~~~~~~ Most of the messages in the `publish.messages` module are to be sent only by the core application. If plugins need their own messages, for example for communication between different plugins, they can easily create custom messages by extending the `RideMessage` base class:: from robotide.pluginapi import Plugin, RideMessage class FancyImportantMessage(RideMessage): data = ['importance'] class MyFancyPlugin(Plugin): def important_action(self): # some code ... MyImportantMessage(importance='HIGH').publish() Plugins interested about this message can subscribe to it using either the class ``FancyImportantMessage`` or its automatically generated title ``fancy.important``. Notice also that all the messages are exposed also through the `robotide.pluginapi` module and plugins should import them there. """ import os from robotide.context import WX_VERSION if WX_VERSION > '3.0': from wx.lib.pubsub import setuparg1 elif WX_VERSION > '2.9': from wx.lib.pubsub import setupv1 from .messages import * from .publisher import PUBLISHER
[ 2, 220, 15069, 3648, 12, 4626, 26182, 23555, 290, 27862, 201, 198, 2, 201, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 201, 198, 2, 220, 345, 743, 407, 779, 428, 2393, 2845, 28...
3.605887
1,393
#!/usr/bin/env python import os import json import tornado.ioloop import tornado.log import tornado.web from google.oauth2 import id_token from google.auth.transport import requests as google_requests import jwt import requests API_KEY = os.environ.get('OPEN_WEATHER_MAP_KEY', None) PROJECT_ID = os.environ.get('PROJECT_ID', None) if __name__ == "__main__": tornado.log.enable_pretty_logging() app = make_app() app.listen(int(os.environ.get('PORT', '8000'))) tornado.ioloop.IOLoop.current().start()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 198, 11748, 33718, 13, 1669, 11224, 198, 11748, 33718, 13, 6404, 198, 11748, 33718, 13, 12384, 198, 198, 6738, 23645, 13, 12162, 1071, 17, 1330...
2.814208
183
# AUTOGENERATED BY: ProsperCookiecutters/ProsperFlask # TEMPLATE VERSION: {{cookiecutter.template_version}} # AUTHOR: {{cookiecutter.author_name}} """PyTest fixtures and modifiers""" import pytest from {{cookiecutter.library_name}}.endpoints import APP
[ 2, 47044, 7730, 1677, 1137, 11617, 11050, 25, 41342, 34, 18055, 8968, 1010, 14, 35726, 525, 7414, 2093, 198, 2, 309, 3620, 6489, 6158, 44156, 2849, 25, 22935, 44453, 8968, 353, 13, 28243, 62, 9641, 11709, 198, 2, 44746, 25, 22935, 444...
3.160494
81
from typing import Iterator, NamedTuple, Tuple from cached_property import cached_property from cv2 import Rodrigues from pyquaternion import Quaternion ThreeTuple = Tuple[float, float, float] RotationMatrix = Tuple[ThreeTuple, ThreeTuple, ThreeTuple] def __repr__(self) -> str: return "Orientation(rot_x={},rot_y={},rot_z={})".format( self.rot_x, self.rot_y, self.rot_z )
[ 6738, 19720, 1330, 40806, 1352, 11, 34441, 51, 29291, 11, 309, 29291, 198, 198, 6738, 39986, 62, 26745, 1330, 39986, 62, 26745, 198, 6738, 269, 85, 17, 1330, 16114, 947, 198, 6738, 12972, 421, 9205, 295, 1330, 2264, 9205, 295, 628, 62...
2.518293
164
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
5.354167
96
# -*- encoding: utf-8 -*- # Module iagradm
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 19937, 1312, 363, 6335, 76, 628 ]
2.095238
21
import pytest from api.models.utils import rankings def test_rankings(test_data): """Tests if ranking works e.g. 1 returns 1st 11 returns 11th 101 return 101st """ assert rankings(test_data[0]) == "1st" assert rankings(test_data[1]) == "11th" assert rankings(test_data[2]) == "101st"
[ 11748, 12972, 9288, 198, 198, 6738, 40391, 13, 27530, 13, 26791, 1330, 16905, 628, 198, 198, 4299, 1332, 62, 43027, 654, 7, 9288, 62, 7890, 2599, 198, 220, 220, 220, 37227, 51, 3558, 611, 12759, 2499, 198, 220, 220, 220, 304, 13, 70...
2.462687
134
from flask import Flask, request, redirect, url_for import os import random import string import time # lemonthink clean = time.time() app = Flask(__name__) chars = list(string.ascii_letters + string.digits)
[ 6738, 42903, 1330, 46947, 11, 2581, 11, 18941, 11, 19016, 62, 1640, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 640, 1303, 443, 8424, 676, 198, 198, 27773, 796, 640, 13, 2435, 3419, 198, 1324, 796, 46947, 7, 834...
3.25
64
# Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. # Funo que recebe um nmero inteiro (no negativo) como argumento e o retorna com os dgitos em ordem descendente. Essencialmente, organize os dgitos para criar o maior nmero possvel. # Primeiro cdigo # Refatorao do primeiro cdigo (utilizando list comprehension) # #
[ 2, 3406, 4876, 318, 284, 787, 257, 2163, 326, 460, 1011, 597, 1729, 12, 31591, 18253, 355, 281, 4578, 290, 1441, 340, 351, 663, 19561, 287, 31491, 1502, 13, 34039, 11, 37825, 858, 262, 19561, 284, 2251, 262, 4511, 1744, 1271, 13, 19...
3.453237
139
import sqlite3 import os import datetime __all__ = ['DMARCStorage', 'totimestamp']
[ 11748, 44161, 578, 18, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 198, 834, 439, 834, 796, 37250, 23127, 25793, 31425, 3256, 705, 83, 313, 320, 27823, 20520, 628, 198 ]
2.866667
30
from setuptools import setup, find_packages setup( name="sumologic-sdk", version="0.1.9", packages=find_packages(), install_requires=['requests>=2.2.1'], # PyPI metadata author="Yoway Buorn, Melchi Salins", author_email="it@sumologic.com, melchisalins@icloud.com", description="Sumo Logic Python SDK", license="PSF", keywords="sumologic python sdk rest api log management analytics logreduce splunk security siem collector forwarder", url="https://github.com/SumoLogic/sumologic-python-sdk", zip_safe=True )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 16345, 20781, 12, 21282, 74, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 16, 13, 24, 1600, 198, 220, 220, 220, 10392, ...
2.730392
204
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import json import datetime # `Django setup` below, will add the path to `translations` module # automatically because it's been included in `project.settings`, so no need # to import it here # -- Django setup ------------------------------------------------------------ # generated project settings import django sys.path.insert( 0, os.path.join(os.path.dirname(os.path.abspath('.')), 'project') ) os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' django.setup() # -- Project information ----------------------------------------------------- with open( os.path.join( os.path.dirname(os.path.abspath('.')), 'config.json' ), 'r') as fh: info = json.load(fh) # project project = info['project']['name'] # description description = info['project']['desc'] # author author = info['author']['name'] # The short X.Y version version = info['release']['version'] # The full version, including alpha/beta/rc tags release = info['release']['name'] # github github_user = info['github']['user'] github_repo = info['github']['repo'] # donation donate_url = info['urls']['funding'] # logo logo = info['project']['logo'] # documentation documentation = '{} {}'.format(project, 'Documentation') # year year = datetime.datetime.now().year # copyright copyright = '{year}, {author}'.format(year=year, author=author) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'monokai' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { 'note_bg': '#fec', 'note_border': '#ffe2a8', 'show_relbars': True, 'logo': logo, 'touch_icon': logo, 'logo_name': True, 'description': description, 'github_user': github_user, 'github_repo': github_repo, 'github_banner': True, } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'DjangoTranslationsdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'DjangoTranslations.tex', documentation, author, 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'djangotranslations', documentation, [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'DjangoTranslations', documentation, author, 'DjangoTranslations', description, 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('https://docs.python.org/', None), 'django': ('http://django.readthedocs.org/en/latest/', None), } # -- Options for doctest extension ------------------------------------------- doctest_global_setup = """ import builtins from django.db import connection from django.test import TestCase from sample.utils import create_samples import beautifier # Turn on the test database for the doctests connection.creation.create_test_db(verbosity=0) TestCase.setUpClass() # Beautify `testoutput` def print(value='', end='\\n'): builtins.print(beautifier.beautify(value, False), end=end) # Sample creation def create_doc_samples(translations=True): if translations: create_samples( continent_names=['europe', 'asia'], country_names=['germany', 'south korea'], city_names=['cologne', 'seoul'], continent_fields=['name', 'denonym'], country_fields=['name', 'denonym'], city_fields=['name', 'denonym'], langs=['de'] ) else: create_samples( continent_names=['europe', 'asia'], country_names=['germany', 'south korea'], city_names=['cologne', 'seoul'], ) """ doctest_global_cleanup = """ import builtins from django.db import connection from django.test import TestCase # Normalize `testoutput` def print(value='', end='\\n'): builtins.print(value, end=end) # Turn off the test database for the doctests TestCase.tearDownClass() connection.creation.destroy_test_db(verbosity=0) """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 28373, 2393, 329, 262, 45368, 28413, 10314, 27098, 13, 198, 2, 198, 2, 770, 2393, 857, 691, 3994, 257, 6356, 286, 262, 749, 2219, 3689, 13, 1114, 257, 198...
3.118927
2,573
"""Import required Metric.""" from .metrics import IV_scorer __all__ = ["IV_scorer"]
[ 37811, 20939, 2672, 3395, 1173, 526, 15931, 198, 6738, 764, 4164, 10466, 1330, 8363, 62, 1416, 11934, 198, 198, 834, 439, 834, 796, 14631, 3824, 62, 1416, 11934, 8973, 198 ]
2.866667
30
import copy from django.conf import settings from django.test.utils import override_settings from rest_framework import status, test def override_waldur_core_settings(**kwargs): waldur_settings = copy.deepcopy(settings.WALDUR_CORE) waldur_settings.update(kwargs) return override_settings(WALDUR_CORE=waldur_settings)
[ 11748, 4866, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9288, 13, 26791, 1330, 20957, 62, 33692, 198, 6738, 1334, 62, 30604, 1330, 3722, 11, 1332, 628, 628, 198, 4299, 20957, 62, 21667, 333, 62, ...
3.036364
110
""" CutBlur Copyright 2020-present NAVER corp. MIT license """ import os import glob import data
[ 37811, 198, 26254, 3629, 333, 198, 15269, 12131, 12, 25579, 11746, 5959, 24614, 13, 198, 36393, 5964, 198, 37811, 198, 11748, 28686, 198, 11748, 15095, 198, 11748, 1366, 628, 198 ]
3.3
30
from ..utils import Object
[ 198, 198, 6738, 11485, 26791, 1330, 9515, 628 ]
3.75
8
import io import time import todoist
[ 11748, 33245, 198, 11748, 640, 198, 198, 11748, 284, 4598, 396, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 198 ]
2.388889
36
from setuptools import setup import iotio with open("README.md", "r") as fh: long_description = fh.read() setup( name="iot.io", version=iotio.__version__, packages=["iotio"], author="Dylan Crockett", author_email="dylanrcrockett@gmail.com", license="MIT", description="A management API for connecting and managing Clients via websocket connections.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/dylancrockett/iot.io", project_urls={ "Documentation": "https://iotio.readthedocs.io/", "Source Code": "https://github.com/dylancrockett/iot.io" }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent" ], install_requires=[ 'gevent', 'gevent-websocket', 'flask', 'flask-sockets', ], python_requires='>=3.7' )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 1312, 313, 952, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, ...
2.450495
404
import os import requests from trellominer.config import yaml
[ 11748, 28686, 198, 198, 11748, 7007, 198, 198, 6738, 2054, 297, 6351, 263, 13, 11250, 1330, 331, 43695, 628 ]
3.421053
19
import numpy as np import tensorflow as tf import os from scipy.io import savemat from scipy.io import loadmat from scipy.misc import imread from scipy.misc import imsave from alexnet_face_classifier import * import matplotlib.pyplot as plt plt.switch_backend('agg') ### def guided_backprop(graph, image, one_hot, sess): image = np.expand_dims(image, 0) one_hot = np.expand_dims(one_hot, 0) saliency_map = sess.run(graph.grad_image, feed_dict={graph.inputs:image, graph.labels_1hot:one_hot})[0] scaling_adjustment = 1E-20 saliency_map_scaled = saliency_map/(np.max(saliency_map)+scaling_adjustment) return saliency_map_scaled
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 28686, 198, 198, 6738, 629, 541, 88, 13, 952, 1330, 3613, 6759, 198, 6738, 629, 541, 88, 13, 952, 1330, 3440, 6759, 198, 6738, 629, 541, 88, 13, 4...
2.268987
316
"""Registry and RegistryMixin tests.""" from types import SimpleNamespace import pytest from coaster.db import db from coaster.sqlalchemy import BaseMixin from coaster.sqlalchemy.registry import Registry # --- Fixtures ------------------------------------------------------------------------- # --- Tests ---------------------------------------------------------------------------- # --- Creating a registry def test_registry_set_name(): """Registry's __set_name__ gets called.""" # Registry has no name unless added to a class assert Registry()._name is None assert RegistryUser.reg1._name == 'reg1' assert RegistryUser.reg2._name == 'reg2' def test_registry_reuse_error(): """Registries cannot be reused under different names.""" # Registry raises TypeError from __set_name__, but Python recasts as RuntimeError with pytest.raises(RuntimeError): def test_registry_reuse_okay(): """Registries be reused with the same name under different hosts.""" reusable = Registry() assert reusable._name is None assert HostA.registry._name == 'registry' assert HostB.registry._name == 'registry' assert HostA.registry is HostB.registry assert HostA.registry is reusable def test_registry_param_type(): """Registry's param must be string or None.""" r = Registry() assert r._param is None r = Registry('') assert r._param is None r = Registry(1) assert r._param == '1' r = Registry('obj') assert r._param == 'obj' r = Registry(param='foo') assert r._param == 'foo' def test_registry_property_cached_property(): """A registry can have property or cached_property set, but not both.""" r = Registry() assert r._default_property is False assert r._default_cached_property is False r = Registry(property=True) assert r._default_property is True assert r._default_cached_property is False r = Registry(cached_property=True) assert r._default_property is False assert r._default_cached_property is True with pytest.raises(TypeError): Registry(property=True, cached_property=True) # --- Populating a registry def test_add_to_registry( CallableRegistry, # noqa: N803 PropertyRegistry, CachedPropertyRegistry, CallableParamRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """A member can be added to registries and accessed as per registry settings.""" callable_host = CallableRegistry() property_host = PropertyRegistry() cached_property_host = CachedPropertyRegistry() callable_param_host = CallableParamRegistry() property_param_host = PropertyParamRegistry() cached_property_param_host = CachedPropertyParamRegistry() assert callable_host.registry.member(1) == (callable_host, 1) assert property_host.registry.member == (property_host, None) assert cached_property_host.registry.member == (cached_property_host, None) assert callable_param_host.registry.member(1) == (1, callable_param_host) assert property_param_host.registry.member == (None, property_param_host) assert cached_property_param_host.registry.member == ( None, cached_property_param_host, ) def test_property_cache_mismatch( PropertyRegistry, CachedPropertyRegistry # noqa: N803 ): """A registry's default setting must be explicitly turned off if conflicting.""" with pytest.raises(TypeError): with pytest.raises(TypeError): def test_add_to_registry_host( CallableRegistry, # noqa: N803 PropertyRegistry, CachedPropertyRegistry, CallableParamRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """A member can be added as a function, overriding default settings.""" callable_host = CallableRegistry() property_host = PropertyRegistry() cached_property_host = CachedPropertyRegistry() callable_param_host = CallableParamRegistry() property_param_host = PropertyParamRegistry() cached_property_param_host = CachedPropertyParamRegistry() assert callable_host.registry.member(1) == (callable_host, 1) assert property_host.registry.member(2) == (property_host, 2) assert cached_property_host.registry.member(3) == (cached_property_host, 3) assert callable_param_host.registry.member(4) == (4, callable_param_host) assert property_param_host.registry.member(5) == (5, property_param_host) assert cached_property_param_host.registry.member(6) == ( 6, cached_property_param_host, ) def test_add_to_registry_property( CallableRegistry, # noqa: N803 PropertyRegistry, CachedPropertyRegistry, CallableParamRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """A member can be added as a property, overriding default settings.""" callable_host = CallableRegistry() property_host = PropertyRegistry() cached_property_host = CachedPropertyRegistry() callable_param_host = CallableParamRegistry() property_param_host = PropertyParamRegistry() cached_property_param_host = CachedPropertyParamRegistry() assert callable_host.registry.member == (callable_host, None) assert property_host.registry.member == (property_host, None) assert cached_property_host.registry.member == (cached_property_host, None) assert callable_param_host.registry.member == (None, callable_param_host) assert property_param_host.registry.member == (None, property_param_host) assert cached_property_param_host.registry.member == ( None, cached_property_param_host, ) def test_add_to_registry_cached_property( CallableRegistry, # noqa: N803 PropertyRegistry, CachedPropertyRegistry, CallableParamRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """A member can be added as a property, overriding default settings.""" callable_host = CallableRegistry() property_host = PropertyRegistry() cached_property_host = CachedPropertyRegistry() callable_param_host = CallableParamRegistry() property_param_host = PropertyParamRegistry() cached_property_param_host = CachedPropertyParamRegistry() assert callable_host.registry.member == (callable_host, None) assert property_host.registry.member == (property_host, None) assert cached_property_host.registry.member == (cached_property_host, None) assert callable_param_host.registry.member == (None, callable_param_host) assert property_param_host.registry.member == (None, property_param_host) assert cached_property_param_host.registry.member == ( None, cached_property_param_host, ) def test_add_to_registry_custom_name(all_registry_hosts, registry_member): """Members can be added to a registry with a custom name.""" assert registry_member.__name__ == 'member' for host in all_registry_hosts: # Mock decorator call host.registry('custom')(registry_member) # This adds the member under the custom name assert host.registry.custom is registry_member # The default name of the function is not present... with pytest.raises(AttributeError): assert host.registry.member is registry_member # ... but can be added host.registry()(registry_member) assert host.registry.member is registry_member def test_add_to_registry_underscore(all_registry_hosts, registry_member): """Registry member names cannot start with an underscore.""" for host in all_registry_hosts: with pytest.raises(ValueError): host.registry('_new_member')(registry_member) def test_add_to_registry_dupe(all_registry_hosts, registry_member): """Registry member names cannot be duplicates of an existing name.""" for host in all_registry_hosts: host.registry()(registry_member) with pytest.raises(ValueError): host.registry()(registry_member) host.registry('custom')(registry_member) with pytest.raises(ValueError): host.registry('custom')(registry_member) def test_cached_properties_are_cached( PropertyRegistry, # noqa: N803 CachedPropertyRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """Cached properties are truly cached.""" # Register registry member property_host = PropertyRegistry() cached_property_host = CachedPropertyRegistry() property_param_host = PropertyParamRegistry() cached_property_param_host = CachedPropertyParamRegistry() # The properties and cached properties work assert property_host.registry.member == [property_host, None] assert cached_property_host.registry.member == [cached_property_host, None] assert property_param_host.registry.member == [None, property_param_host] assert cached_property_param_host.registry.member == [ None, cached_property_param_host, ] # The properties and cached properties return equal values on each access assert property_host.registry.member == property_host.registry.member assert cached_property_host.registry.member == cached_property_host.registry.member assert property_param_host.registry.member == property_param_host.registry.member assert ( cached_property_param_host.registry.member == cached_property_param_host.registry.member ) # Only the cached properties return the same value every time assert property_host.registry.member is not property_host.registry.member assert cached_property_host.registry.member is cached_property_host.registry.member assert ( property_param_host.registry.member is not property_param_host.registry.member ) assert ( cached_property_param_host.registry.member is cached_property_param_host.registry.member ) # TODO: # test_registry_member_cannot_be_called_clear_cache # test_multiple_positional_and_keyword_arguments # test_registry_iter # test_registry_members_must_be_callable # test_add_by_directly_sticking_in # test_instance_registry_is_cached # test_clear_cache_for # test_clear_cache # test_registry_mixin_config # test_registry_mixin_subclasses # --- RegistryMixin tests -------------------------------------------------------------- def test_access_item_from_class(registrymixin_models): """Registered items are available from the model class.""" assert ( registrymixin_models.RegistryTest1.views.test is registrymixin_models.RegisteredItem1 ) assert ( registrymixin_models.RegistryTest2.views.test is registrymixin_models.RegisteredItem2 ) assert ( registrymixin_models.RegistryTest1.views.test is not registrymixin_models.RegisteredItem2 ) assert ( registrymixin_models.RegistryTest2.views.test is not registrymixin_models.RegisteredItem1 ) assert registrymixin_models.RegistryTest1.features.is1 is registrymixin_models.is1 assert registrymixin_models.RegistryTest2.features.is1 is registrymixin_models.is1 def test_access_item_class_from_instance(registrymixin_models): """Registered items are available from the model instance.""" r1 = registrymixin_models.RegistryTest1() r2 = registrymixin_models.RegistryTest2() # When accessed from the instance, we get a partial that resembles # the wrapped item, but is not the item itself. assert r1.views.test is not registrymixin_models.RegisteredItem1 assert r1.views.test.func is registrymixin_models.RegisteredItem1 assert r2.views.test is not registrymixin_models.RegisteredItem2 assert r2.views.test.func is registrymixin_models.RegisteredItem2 assert r1.features.is1 is not registrymixin_models.is1 assert r1.features.is1.func is registrymixin_models.is1 assert r2.features.is1 is not registrymixin_models.is1 assert r2.features.is1.func is registrymixin_models.is1 def test_access_item_instance_from_instance(registrymixin_models): """Registered items can be instantiated from the model instance.""" r1 = registrymixin_models.RegistryTest1() r2 = registrymixin_models.RegistryTest2() i1 = r1.views.test() i2 = r2.views.test() assert isinstance(i1, registrymixin_models.RegisteredItem1) assert isinstance(i2, registrymixin_models.RegisteredItem2) assert not isinstance(i1, registrymixin_models.RegisteredItem2) assert not isinstance(i2, registrymixin_models.RegisteredItem1) assert i1.obj is r1 assert i2.obj is r2 assert i1.obj is not r2 assert i2.obj is not r1 def test_features(registrymixin_models): """The features registry can be used for feature tests.""" r1 = registrymixin_models.RegistryTest1() r2 = registrymixin_models.RegistryTest2() assert r1.features.is1() is True assert r2.features.is1() is False
[ 37811, 8081, 4592, 290, 33432, 35608, 259, 5254, 526, 15931, 198, 198, 6738, 3858, 1330, 17427, 36690, 10223, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 42450, 13, 9945, 1330, 20613, 198, 6738, 42450, 13, 25410, 282, 26599, 1330, 7308,...
2.913485
4,427
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-02-06 16:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 1485, 319, 2864, 12, 2999, 12, 3312, 1467, 25, 1495, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
import pytest from nesta.packages.misc_utils.guess_sql_type import guess_sql_type def test_guess_sql_type_int(int_data): assert guess_sql_type(int_data) == 'INTEGER' def test_guess_sql_type_float(float_data): assert guess_sql_type(float_data) == 'FLOAT' def test_guess_sql_type_bool(bool_data): assert guess_sql_type(bool_data) == 'BOOLEAN' def test_guess_sql_type_str(text_data): assert guess_sql_type(text_data, text_len=10) == 'TEXT' assert guess_sql_type(text_data, text_len=100).startswith('VARCHAR(')
[ 11748, 12972, 9288, 198, 6738, 16343, 64, 13, 43789, 13, 44374, 62, 26791, 13, 5162, 408, 62, 25410, 62, 4906, 1330, 4724, 62, 25410, 62, 4906, 628, 198, 4299, 1332, 62, 5162, 408, 62, 25410, 62, 4906, 62, 600, 7, 600, 62, 7890, 2...
2.440367
218
# -*- coding: utf-8 -*- '''''' from flask import request from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User from model.role import identity from flask_jwt_extended import (fresh_jwt_required) def demand_activity_add(activity_id, data): '''''' for demand_id in data: demand = Demand.get(Demand.id == demand_id) if not demand.activityId: demand.activityId = activity_id # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() demand.save() def demand_activity_del(activity_id, data): '''''' for demand_id in data: demand = Demand.get(Demand.id == demand_id) if demand.activityId == activity_id: demand.activityId = None # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() demand.save() def demand_activity_done(activity_id, data): '''''' for demand_id in data: demand = Demand.get(Demand.id == demand_id) if demand.activityId == activity_id: demand.status = 1 # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute() demand.save()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 39115, 7061, 198, 198, 6738, 42903, 1330, 2581, 198, 6738, 2746, 13, 9945, 1330, 6831, 11, 24641, 11, 24641, 27608, 11, 34479, 11, 24641, 14881, 11, 4935, 27608, 11, 117...
2.488
500
# Easy # https://leetcode.com/problems/palindrome-number/ # Time Complexity: O(log(x) to base 10) # Space Complexity: O(1)
[ 2, 16789, 198, 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 18596, 521, 5998, 12, 17618, 14, 198, 2, 3862, 19157, 414, 25, 440, 7, 6404, 7, 87, 8, 284, 2779, 838, 8, 198, 2, 4687, 19157, 414, 25, 440, 7, 16, ...
2.595745
47
from .manager import Manager # NOQA from .call_manager import CallManager # NOQA from . import fast_agi # NOQA
[ 6738, 764, 37153, 1330, 9142, 220, 1303, 8005, 48, 32, 198, 6738, 764, 13345, 62, 37153, 1330, 4889, 13511, 220, 1303, 8005, 48, 32, 198, 6738, 764, 1330, 3049, 62, 18013, 220, 1303, 8005, 48, 32, 198 ]
3.081081
37
# -*- coding: utf-8 -*- """ Python library for Paessler's PRTG (http://www.paessler.com/) """ import logging import xml.etree.ElementTree as Et from urllib import request from prtg.cache import Cache from prtg.models import Sensor, Device, Status, PrtgObject from prtg.exceptions import BadTarget, UnknownResponse """ def refresh(self, query): logging.info('Refreshing content: {}'.format(content)) devices = Query(target='table', endpoint=self.endpoint, username=self.username, password=self.password, content=content, counter=content) self.connection.get_paginated_request(devices) self.cache.write_content(devices.response) def update(self, content, attribute, value, replace=False): for index, obj in enumerate(content): logging.debug('Updating object: {} with {}={}'.format(obj, attribute, value)) if attribute == 'tags': tags = value.split(',') if replace: obj.tags = value.split(',') else: obj.tags += [x for x in tags if x not in obj.tags] content[index] = obj self.cache.write_content(content, force=True) def content(self, content_name, parents=False, regex=None, attribute=None): response = list() for resp in self.cache.get_content(content_name): if not all([regex, attribute]): response.append(resp) else: if RegexMatch(resp, expression=regex, attribute=attribute): response.append(resp) if all([content_name == 'sensors', parents is True]): logging.info('Searching for parents.. this may take a while') p = list() ids = set() for index, child in enumerate(response): parent = self.cache.get_object(str(child.parentid)) # Parent device. if parent: ids.add(str(parent.objid)) # Lookup unique parent ids. else: logging.warning('Unable to find sensor parent') for parent in ids: p.append(self.cache.get_object(parent)) response = p return response """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 37906, 5888, 329, 11243, 33730, 338, 4810, 35990, 357, 4023, 1378, 2503, 13, 8957, 33730, 13, 785, 34729, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 35555...
2.278739
983
import tensorflow as tf from tensorflow.python.training.session_run_hook import SessionRunArgs # Define data loaders ##################################### # See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca # redefine summarysaverhook (for more accurate saving) def ExperimentTemplate() -> str: """A template with Markdown syntax. :return: str with Markdown template """ return """ Experiment ========== Any [markdown code](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) can be used to describe this experiment. For instance, you can find the automatically generated used settings of this run below. Current Settings ---------------- | Argument | Value | | -------- | ----- | """
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 34409, 13, 29891, 62, 5143, 62, 25480, 1330, 23575, 10987, 42035, 628, 198, 2, 2896, 500, 1366, 3440, 364, 1303, 29113, 4242, 198, 2, 4091, 3740, 1378, ...
3.444954
218
parsers = ['openmm.unit', 'pint', 'unyt'] def digest_parser(parser: str) -> str: """ Check if parser is correct.""" if parser is not None: if parser.lower() in parsers: return parser.lower() else: raise ValueError else: from pyunitwizard.kernel import default_parser return default_parser
[ 79, 945, 364, 796, 37250, 9654, 3020, 13, 20850, 3256, 705, 79, 600, 3256, 705, 403, 20760, 20520, 198, 198, 4299, 16274, 62, 48610, 7, 48610, 25, 965, 8, 4613, 965, 25, 198, 220, 220, 220, 37227, 6822, 611, 30751, 318, 3376, 526, ...
2.377483
151
''' Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py ''' import os import re import torch import subprocess from transformers import * import random pos_converter = {'NOUN':'n', 'PROPN':'n', 'VERB':'v', 'AUX':'v', 'ADJ':'a', 'ADV':'r'} #run WSD Evaluation Framework scorer within python #normalize ids list, masks to whatever the passed in length is #filters down training dataset to (up to) k examples per sense #for few-shot learning of the model #EOF
[ 7061, 6, 198, 15269, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 3237, 2489, 10395, 13, 198, 198, 1212, 2723, 2438, 318, 11971, 739, 262, 5964, 1043, 287, 262, 198, 43, 2149, 24290, 2393, 287, 262, 6808, 8619, 286, 4...
3.120536
224
#!/usr/bin/env python3 from typing import Dict, AnyStr from pathlib import Path from ontopy import get_ontology import dlite from dlite.mappings import make_instance # Setup dlite paths thisdir = Path(__file__).parent.absolute() rootdir = thisdir.parent.parent workflow1dir = rootdir / '1-simple-workflow' entitiesdir = rootdir / 'entities' atomdata = workflow1dir / 'atomscaledata.json' dlite.storage_path.append(f'{entitiesdir}/*.json') # Define the calculation def get_energy(reaction): """Calculates reaction energies with data from Substance entity data is harvested from collection and mapped to Substance according to mappings. Args: reaction: dict with names of reactants and products ase keys and stochiometric coefficient as value Negative stochiometric coefficients for reactants. Positive stochiometric coefficients for products. Returns: reaction energy """ energy = 0 for label, n in reaction.items(): inst = make_instance(Substance, coll[label], mappings, mapsTo=mapsTo) energy+=n*inst.molecule_energy return energy # Import ontologies with mappings molecules_onto = get_ontology(f'{thisdir}/mapping_mols.ttl').load() reaction_onto = get_ontology(f'{thisdir}/mapping_substance.ttl').load() # Convert to mappings to a single list of triples mappings = list(molecules_onto.get_unabbreviated_triples()) mappings.extend(list(reaction_onto.get_unabbreviated_triples())) # Obtain the Metadata to be mapped to each other Molecule = dlite.get_instance('http://onto-ns.com/meta/0.1/Molecule') Substance = dlite.get_instance('http://onto-ns.com/meta/0.1/Substance') # Find mapping relation # TODO: investigate what to do if the two cases # use a different mappings relation. As of now it is a # hard requirement that they use the same. mapsTo = molecules_onto.mapsTo.iri # Define where the molecule data is obtained from # This is a dlite collection coll = dlite.Collection(f'json://{atomdata}?mode=r#molecules', 0) # input from chemical engineer, e.g. what are reactants and products # reactants (left side of equation) have negative stochiometric coefficient # products (right side of equation) have positive stochiometric coefficient reaction1 = {'C2H6':-1, 'C2H4':1,'H2':1} reaction_energy = get_energy(reaction1) print('Reaction energy 1', reaction_energy) reaction2 = {'C3H8':-1, 'H2': -2,'CH4':3} reaction_energy2 = get_energy(reaction2) print('Reaction energy 1', reaction_energy2) # Map instance Molecule with label 'H2' to Substance #inst = make_instance(Substance, coll['H2'], mappings) #print(inst) # Map instance Molecule with label 'H2' to itself #inst2 = make_instance(Molecule, coll['H2'], mappings, strict=False) #print(inst2)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 13290, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 319, 4852, 88, 1330, 651, 62, 756, 1435, 198, 198, 11748, 288, 36890, 198, 6738, 288, ...
2.839196
995
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SubmitField, RadioField, HiddenField from wtforms.fields.html5 import DateField, IntegerField from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, NumberRange from models import Colleagues, Admins, Boxes, Ideas allowed_format = ['png', 'svg', 'jpg', "jpeg"]
[ 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 42903, 62, 86, 27110, 13, 7753, 1330, 9220, 15878, 11, 9220, 3237, 6972, 11, 9220, 37374, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 30275, 15878, 11, 41146, 15878, 11, ...
3.590551
127
from builtins import range from ..base import MLClassifierBase from ..utils import get_matrix_in_format from sklearn.neighbors import NearestNeighbors import scipy.sparse as sparse import numpy as np
[ 6738, 3170, 1040, 1330, 2837, 198, 6738, 11485, 8692, 1330, 10373, 9487, 7483, 14881, 198, 6738, 11485, 26791, 1330, 651, 62, 6759, 8609, 62, 259, 62, 18982, 198, 6738, 1341, 35720, 13, 710, 394, 32289, 1330, 3169, 12423, 46445, 32289, ...
3.553571
56
"""Constants about the Gro ontology that can be imported and re-used anywhere.""" REGION_LEVELS = { 'world': 1, 'continent': 2, 'country': 3, 'province': 4, # Equivalent to state in the United States 'district': 5, # Equivalent to county in the United States 'city': 6, 'market': 7, 'other': 8, 'coordinate': 9 } ENTITY_TYPES_PLURAL = ['metrics', 'items', 'regions', 'frequencies', 'sources', 'units'] DATA_SERIES_UNIQUE_TYPES_ID = [ 'metric_id', 'item_id', 'region_id', 'partner_region_id', 'frequency_id', 'source_id' ] ENTITY_KEY_TO_TYPE = { 'metric_id': 'metrics', 'item_id': 'items', 'region_id': 'regions', 'partner_region_id': 'regions', 'source_id': 'sources', 'frequency_id': 'frequencies', 'unit_id': 'units' } DATA_POINTS_UNIQUE_COLS = DATA_SERIES_UNIQUE_TYPES_ID + [ 'reporting_date', 'start_date', 'end_date' ]
[ 37811, 34184, 1187, 546, 262, 10299, 39585, 1435, 326, 460, 307, 17392, 290, 302, 12, 1484, 6609, 526, 15931, 198, 198, 31553, 2849, 62, 2538, 18697, 50, 796, 1391, 198, 220, 220, 220, 705, 6894, 10354, 352, 11, 198, 220, 220, 220, ...
2.227273
418
""" Period benchmarks that rely only on tslibs. See benchmarks.period for Period benchmarks that rely on other parts fo pandas. """ from pandas import Period from pandas.tseries.frequencies import to_offset
[ 37811, 198, 5990, 2101, 31747, 326, 8814, 691, 319, 256, 6649, 571, 82, 13, 220, 4091, 31747, 13, 41007, 329, 198, 5990, 2101, 31747, 326, 8814, 319, 584, 3354, 11511, 19798, 292, 13, 198, 37811, 198, 6738, 19798, 292, 1330, 18581, 19...
3.59322
59
#/usr/bin/python #-*- coding: utf-8 -*- #Refer http://www.wooyun.org/bugs/wooyun-2015-0137140 #__Author__ = #_PlugName_ = whezeip Plugin #_FileName_ = whezeip.py if __name__ == '__main__': from dummy import * audit(assign('whezeip', 'http://218.104.147.71:7001/')[1])
[ 2, 14, 14629, 14, 8800, 14, 29412, 201, 198, 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 2, 46238, 2638, 1378, 2503, 13, 21638, 726, 403, 13, 2398, 14, 32965, 14, 21638, 726, 403, 12, 4626, 12, 486, 2718, ...
1.974194
155
# Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object. # Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names. # Print list_of_names_and_dogs_names. owners = ["Jenny", "Alexus", "Sam", "Grace"] dogs_names = ["Elphonse", "Dr. Doggy DDS", "Carter", "Ralph"] names_and_dogs_names = zip(owners, dogs_names) list_of_names_and_dogs_names = list(names_and_dogs_names) print(list_of_names_and_dogs_names)
[ 2, 5765, 19974, 3419, 284, 2251, 257, 649, 7885, 1444, 3891, 62, 392, 62, 22242, 62, 14933, 326, 21001, 4393, 290, 6844, 62, 14933, 8341, 656, 257, 19974, 2134, 13, 198, 198, 2, 3244, 11, 2251, 257, 649, 7885, 3706, 1351, 62, 1659, ...
2.955801
181
# -*- coding: utf-8 - # # This file is part of couchdbkit released under the MIT license. # See the NOTICE for more information. import os import sys if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'): raise SystemExit("couchdbkit requires Python 2.5 or later.") from setuptools import setup, find_packages from couchdbkit import __version__ setup( name = 'couchdbkit', version = __version__, description = 'Python couchdb kit', long_description = file( os.path.join( os.path.dirname(__file__), 'README.rst' ) ).read(), author = 'Benoit Chesneau', author_email = 'benoitc@e-engura.com', license = 'Apache License 2', url = 'http://couchdbkit.org', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Utilities', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages = find_packages(exclude=['tests']), zip_safe = False, install_requires = [ 'restkit>=3.2', ], entry_points=""" [couchdbkit.consumers] sync=couchdbkit.consumer.sync:SyncConsumer eventlet=couchdbkit.consumer.ceventlet:EventletConsumer gevent=couchdbkit.consumer.cgevent:GeventConsumer """, test_suite='noses', )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 18507, 9945, 15813, 2716, 739, 262, 17168, 5964, 13, 220, 198, 2, 4091, 262, 28536, 329, 517, 1321, 13, 198, 198, 11748, 28686, 198, 1174...
2.496865
638
from typing import Optional from complexheart.domain.criteria import Criteria from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker from to_do_list.tasks.domain.models import Task from to_do_list.tasks.infrastructure.persistence.relational import RelationalTaskRepository, DBInstaller db_engine: Optional[Engine] = None
[ 6738, 19720, 1330, 32233, 198, 198, 6738, 3716, 11499, 13, 27830, 13, 22213, 5142, 1330, 10056, 5142, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 198, 6738, 44161, 282, 26599, 13, 18392, 1330, 7117, 198, 6738, 44161, 282, 26599, ...
3.660377
106
from jinja2.ext import Extension from jinja2 import nodes from jinja2 import Markup from wagtail.wagtailadmin.templatetags.wagtailuserbar import wagtailuserbar as original_wagtailuserbar from wagtail.wagtailimages.models import Filter, SourceImageIOError
[ 6738, 474, 259, 6592, 17, 13, 2302, 1330, 27995, 198, 6738, 474, 259, 6592, 17, 1330, 13760, 198, 6738, 474, 259, 6592, 17, 1330, 2940, 929, 198, 198, 6738, 266, 363, 13199, 13, 86, 363, 13199, 28482, 13, 11498, 489, 265, 316, 3775,...
3.083333
84
from rta.provision.utils import * from rta.provision.passwd import * from rta.provision.influxdb import * from rta.provision.grafana import * from rta.provision.kapacitor import *
[ 6738, 374, 8326, 13, 1676, 10178, 13, 26791, 1330, 1635, 198, 6738, 374, 8326, 13, 1676, 10178, 13, 6603, 16993, 1330, 1635, 198, 6738, 374, 8326, 13, 1676, 10178, 13, 10745, 22564, 9945, 1330, 1635, 198, 6738, 374, 8326, 13, 1676, 10...
2.857143
63
""" $lic$ Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. 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 BSD-3 License for more details. You should have received a copy of the Modified BSD-3 License along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>. """ import unittest from nn_dataflow.core import Network from nn_dataflow.core import Layer, InputLayer, ConvLayer, FCLayer, \ PoolingLayer, EltwiseLayer
[ 37811, 720, 677, 3, 198, 15269, 357, 34, 8, 1584, 12, 42334, 416, 309, 12215, 33061, 2059, 290, 383, 5926, 286, 9870, 2841, 286, 198, 32140, 3841, 2059, 198, 198, 1212, 1430, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14,...
3.491304
230
from django.urls import path from .views import DivisionListCreateAPIView, DivisionRetrieveUpdateDestroyAPIView, MainDivisionListAPIView urlpatterns = [ path('division/', DivisionListCreateAPIView.as_view()), path('division/<division_pk>', DivisionRetrieveUpdateDestroyAPIView.as_view()), path('division/main/', MainDivisionListAPIView.as_view()), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 33571, 1330, 7458, 8053, 16447, 2969, 3824, 769, 11, 7458, 9781, 30227, 10260, 49174, 2969, 3824, 769, 11, 8774, 24095, 1166, 8053, 2969, 3824, 769, 628, 198, 6371, 3327...
3.016529
121
from sympy import (Derivative as D, Eq, exp, sin, Function, Symbol, symbols, cos, log) from sympy.core import S from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul, pdsolve, classify_pde, checkpdesol) from sympy.testing.pytest import raises a, b, c, x, y = symbols('a b c x y')
[ 6738, 10558, 88, 1330, 357, 28532, 452, 876, 355, 360, 11, 412, 80, 11, 1033, 11, 7813, 11, 198, 220, 220, 220, 15553, 11, 38357, 11, 14354, 11, 8615, 11, 2604, 8, 198, 6738, 10558, 88, 13, 7295, 1330, 311, 198, 6738, 10558, 88, ...
2.507692
130
import torch import torch.nn.functional as F import pandas as pd import numpy as np from torch_geometric.data import Data from torch_geometric.nn import GCNConv, PairNorm from torch_geometric.utils.undirected import to_undirected import random import matplotlib.pyplot as plt data_name = 'citeseer' # 'cora' or 'citeseer' data_edge_path = f'datasets/{data_name}/{data_name}.cites' data_content_path = f'datasets/{data_name}/{data_name}.content' raw_content = pd.read_table(data_content_path, header=None, dtype={0:np.str}) raw_edge = pd.read_table(data_edge_path, header=None, dtype=np.str) paper_ids = raw_content[0] paper_id_map = {} for i, pp_id in enumerate(paper_ids): paper_id_map[pp_id] = i edge_index = torch.from_numpy(raw_edge.apply(lambda col: col.map(paper_id_map)).dropna().values).long().t().contiguous() x = torch.from_numpy(raw_content.values[:, 1:-1].astype(np.float)).float() labels = np.unique(raw_content[raw_content.keys()[-1]]).tolist() y = torch.from_numpy(raw_content[raw_content.keys()[-1]].map(lambda x: labels.index(x)).values).long() train_mask, test_mask = get_mask(y) data = Data(x=x, edge_index=edge_index, y=y, train_mask=train_mask, test_mask=test_mask) num_epochs = 100 test_cases = [ {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'relu', 'undirected':False}, # num layers {'num_layers':4, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'relu', 'undirected':False}, {'num_layers':6, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'relu', 'undirected':False}, # self loop {'num_layers':2, 'add_self_loops':False, 'use_pairnorm':False, 'drop_edge':1., 'activation':'relu', 'undirected':False}, # pair norm {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':True, 'drop_edge':1., 'activation':'relu', 'undirected':False}, {'num_layers':4, 'add_self_loops':True, 'use_pairnorm':True, 'drop_edge':1., 'activation':'relu', 'undirected':False}, {'num_layers':6, 'add_self_loops':True, 'use_pairnorm':True, 'drop_edge':1., 'activation':'relu', 'undirected':False}, # drop edge {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':0.6, 'activation':'relu', 'undirected':False}, {'num_layers':4, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':0.6, 'activation':'relu', 'undirected':False}, # activation fn {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'tanh', 'undirected':False}, {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'leaky_relu', 'undirected':False}, # undirected {'num_layers':2, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':1., 'activation':'relu', 'undirected':True}, {'num_layers':4, 'add_self_loops':True, 'use_pairnorm':True, 'drop_edge':1., 'activation':'relu', 'undirected':True}, {'num_layers':4, 'add_self_loops':True, 'use_pairnorm':False, 'drop_edge':0.8, 'activation':'relu', 'undirected':True}, ] for i_case, kwargs in enumerate(test_cases): print(f'Test Case {i_case:>2}') model = GCNNodeClassifier(x.shape[1], len(labels), **kwargs) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) history_test_acc = [] input_edge_index = to_undirected(edge_index) if kwargs['undirected'] else edge_index for i_epoch in range(0, num_epochs): print(f'Epoch {i_epoch:>3} ', end='') y_pred = model(x, input_edge_index) train_acc = eval_acc(y_pred[train_mask], y[train_mask]) # Train loss = F.cross_entropy(y_pred[train_mask], y[train_mask]) optimizer.zero_grad() loss.backward() optimizer.step() # Test test_acc = eval_acc(y_pred[test_mask], y[test_mask]) history_test_acc.append(test_acc) print(f'Train Acc = {train_acc}. Test Acc = {test_acc}') kwargs['best_acc'] = max(history_test_acc) plt.plot(list(range(num_epochs)), history_test_acc, label=f'case_{str(i_case).zfill(2)}') plt.legend() plt.savefig(f'{data_name}-HistoryAcc.jpg') pd.DataFrame(test_cases).to_csv(f'{data_name}-Result.csv')
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 62, 469, 16996, 13, 7890, 1330, 6060, 198, 6738, 28034, 62, 469, 16996, 13, 2...
2.32984
1,813
import datetime import json from django.conf import settings from django.http import Http404 from django.utils import timezone from django.views import generic from .models import Event, FlatPage, News
[ 11748, 4818, 8079, 198, 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 42625, 14208, 13, 3357...
3.696429
56
from dotenv import load_dotenv load_dotenv() from flask import Flask, flash, request, redirect, url_for from flask_ngrok import run_with_ngrok from flask_cors import CORS from werkzeug.utils import secure_filename import tensorflow as tf from tensorflow import keras from tensorflow.keras.applications import vgg16 from tensorflow.keras import layers, models, Model, optimizers from tensorflow.keras.preprocessing import image import numpy as np import os import base64 ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.secret_key = os.getenv('SECRETKEY') CORS(app) # run_with_ngrok(app) # https://github.com/gstaff/flask-ngrok/issues/2 category_names = os.getenv('CATEGORIES').split(',') nb_categories = len(category_names) type = os.getenv('MODE') if type == 'checkpoint': # Load via checkpoints img_height, img_width = 200,200 conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3)) layers = [ conv_base, layers.Dense(nb_categories, activation='softmax') ] model = models.Sequential(layers) model.load_weights('./model/cp2-0010.ckpt') else: # Load saved model model = models.load_model('./model/model_vgg16.h5') if __name__ == '__main__': app.run(host='0.0.0.0')
[ 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 2220, 62, 26518, 24330, 3419, 198, 198, 6738, 42903, 1330, 46947, 11, 7644, 11, 2581, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 42903, 62, 782, 305, 74, 1330, 1057, 62, 4480, 62,...
2.709544
482
import random import matplotlib.pyplot as plt import wandb import hydra import torch import torch.utils.data as data_utils from model import ChessPiecePredictor from torch import nn, optim from google.cloud import storage from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets import ImageFolder if __name__ == "__main__": train()
[ 11748, 4738, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 11569, 65, 198, 11748, 25039, 198, 11748, 28034, 198, 11748, 28034, 13, 26791, 13, 7890, 355, 1366, 62, 26791, 198, 6738, 2746, 1330, 25774, 47,...
3.598131
107
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib import os from abc import ABC, abstractmethod from fairseq import registry from omegaconf import DictConfig _build_scorer, register_scorer, SCORER_REGISTRY, _ = registry.setup_registry( "--scoring", default="bleu" ) # automatically import any Python files in the current directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith(".py") and not file.startswith("_"): module = file[: file.find(".py")] importlib.import_module("fairseq.scoring." + module)
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 628, ...
3.0837
227
import copy import unittest import networkx as nx import numpy as np from scipy.special import erf from dfn import Fluid, FractureNetworkThermal if __name__ == '__main__': unittest.main()
[ 11748, 4866, 198, 11748, 555, 715, 395, 198, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 20887, 1330, 1931, 69, 198, 198, 6738, 288, 22184, 1330, 1610, 27112, 11, 40548, 495, ...
2.882353
68
""" Author: Gustavo Amarante """ import numpy as np import pandas as pd from datetime import datetime
[ 37811, 198, 13838, 25, 43715, 78, 1703, 4741, 68, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628, 628 ]
3.117647
34
from configparser import ConfigParser CONFIG_INT_KEYS = { 'hadoop_max_nodes_count', 'hadoop_ebs_volumes_count', 'hadoop_ebs_volume_size', 'spark_max_nodes_count', 'spark_ebs_volumes_count', 'spark_ebs_volume_size' }
[ 6738, 4566, 48610, 1330, 17056, 46677, 198, 198, 10943, 16254, 62, 12394, 62, 7336, 16309, 796, 1391, 198, 220, 220, 220, 705, 71, 4533, 404, 62, 9806, 62, 77, 4147, 62, 9127, 3256, 198, 220, 220, 220, 705, 71, 4533, 404, 62, 68, ...
2.104348
115
from flask import Blueprint from .hooks import admin_auth from ...api_utils import * bp_admin_api = Blueprint('bp_admin_api', __name__) bp_admin_api.register_error_handler(APIError, handle_api_error) bp_admin_api.register_error_handler(500, handle_500_error) bp_admin_api.register_error_handler(400, handle_400_error) bp_admin_api.register_error_handler(401, handle_401_error) bp_admin_api.register_error_handler(403, handle_403_error) bp_admin_api.register_error_handler(404, handle_404_error) bp_admin_api.before_request(before_api_request) bp_admin_api.before_request(admin_auth) from . import v_admin
[ 6738, 42903, 1330, 39932, 198, 198, 6738, 764, 25480, 82, 1330, 13169, 62, 18439, 198, 6738, 2644, 15042, 62, 26791, 1330, 1635, 628, 198, 46583, 62, 28482, 62, 15042, 796, 39932, 10786, 46583, 62, 28482, 62, 15042, 3256, 11593, 3672, 8...
2.9
210
import pandas as pd import numpy as np import os import tensorflow as tf import functools ####### STUDENTS FILL THIS OUT ###### #Question 3 def reduce_dimension_ndc(df, ndc_df): ''' df: pandas dataframe, input dataset ndc_df: pandas dataframe, drug code dataset used for mapping in generic names return: df: pandas dataframe, output dataframe with joined generic drug name ''' ndc_df["Non-proprietary Name"]= ndc_df["Non-proprietary Name"].str.replace("Hcl", "Hydrochloride") ndc_df["Non-proprietary Name"]= ndc_df["Non-proprietary Name"].str.replace(" And ", "-") ndc_df["Non-proprietary Name"]= (ndc_df["Non-proprietary Name"].str.strip()).str.upper() # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("Tablet, Film Coated", "TABLET") # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("Tablet, Coated", "TABLET") # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("Tablet, Film Coated, Extended Release", "Tablet Extended Release") # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("Tablet, Extended Release", "Tablet Extended Release") # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("For Suspension, Extended Release", "For Suspension Extended Release") # ndc_df["Dosage Form"]= ndc_df["Dosage Form"].str.replace("Powder, Metered", "Powder Metered") # ndc_df["Dosage Form"]= (ndc_df["Dosage Form"].str.strip()).str.upper() # ndc_df["generic_drug_name"]= ndc_df["Non-proprietary Name"]+"_"+ndc_df["Dosage Form"] ndc_df["generic_drug_name"]= ndc_df["Non-proprietary Name"] df_reduce_dimension = pd.merge(df, ndc_df, on=['ndc_code'], how='inner') df_reduce_dimension['LABEL'] = 0 reduce_dim_df= df_reduce_dimension.drop(columns=['Proprietary Name', 'Non-proprietary Name', 'Dosage Form', 'Route Name', 'Company Name', 'Product Type']) return reduce_dim_df #Question 4 def select_first_encounter(df): ''' df: pandas dataframe, dataframe with all encounters return: - first_encounter_df: pandas dataframe, dataframe with only the first encounter for a given patient ''' first_encounter_df = df.sort_values('encounter_id').groupby('patient_nbr').first() first_encounter_df = first_encounter_df.reset_index() return first_encounter_df #Question 6 def patient_dataset_splitter(df, key='patient_nbr'): ''' df: pandas dataframe, input dataset that will be split patient_key: string, column that is the patient id return: - train: pandas dataframe, - validation: pandas dataframe, - test: pandas dataframe, ''' df = df.iloc[np.random.permutation(len(df))] unique_values = df[key].unique() total_values = len(unique_values) train_size = round(total_values * (1 - 0.4 )) train = df[df[key].isin(unique_values[:train_size])].reset_index(drop=True) left_size = len(unique_values[train_size:]) validation_size = round(left_size*0.5) validation = df[df[key].isin(unique_values[train_size:train_size+validation_size])].reset_index(drop=True) test = df[df[key].isin(unique_values[validation_size+train_size:])].reset_index(drop=True) return train, validation, test #Question 7 def create_tf_categorical_feature_cols(categorical_col_list, vocab_dir='./diabetes_vocab/'): ''' categorical_col_list: list, categorical field list that will be transformed with TF feature column vocab_dir: string, the path where the vocabulary text files are located return: output_tf_list: list of TF feature columns ''' output_tf_list = [] for c in categorical_col_list: vocab_file_path = os.path.join(vocab_dir, c + "_vocab.txt") ''' Which TF function allows you to read from a text file and create a categorical feature You can use a pattern like this below... tf_categorical_feature_column = tf.feature_column....... ''' tf_categorical_feature_column = tf.feature_column.categorical_column_with_vocabulary_file( key=c, vocabulary_file = vocab_file_path, num_oov_buckets=1) one_hot_origin_feature = tf.feature_column.indicator_column(tf_categorical_feature_column) output_tf_list.append(one_hot_origin_feature) return output_tf_list #Question 8 def normalize_numeric_with_zscore(col, mean, std): ''' This function can be used in conjunction with the tf feature column for normalization ''' return (col - mean)/std def create_tf_numeric_feature(col, MEAN, STD, default_value=0): ''' col: string, input numerical column name MEAN: the mean for the column in the training data STD: the standard deviation for the column in the training data default_value: the value that will be used for imputing the field return: tf_numeric_feature: tf feature column representation of the input field ''' normalizer = functools.partial(normalize_numeric_with_zscore, mean=MEAN, std=STD) tf_numeric_feature= tf.feature_column.numeric_column( key=col, default_value = default_value, normalizer_fn=normalizer, dtype=tf.float64) return tf_numeric_feature #Question 9 def get_mean_std_from_preds(diabetes_yhat): ''' diabetes_yhat: TF Probability prediction object ''' m = diabetes_yhat.mean() s = diabetes_yhat.stddev() return m, s # Question 10 def get_student_binary_prediction(df, col): ''' df: pandas dataframe prediction output dataframe col: str, probability mean prediction field return: student_binary_prediction: pandas dataframe converting input to flattened numpy array and binary labels def convert_to_binary(df, pred_field, actual_field): df['score'] = df[pred_field].apply(lambda x: 1 if x>=25 else 0 ) df['label_value'] = df[actual_field].apply(lambda x: 1 if x>=25 else 0) return df binary_df = convert_to_binary(model_output_df, 'pred', 'actual_value') binary_df.head() ''' return student_binary_prediction
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 1257, 310, 10141, 198, 198, 4242, 21017, 49348, 15365, 376, 8267, 12680, 16289, 46424, 2, 198, ...
2.591819
2,347