content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from portfolios.factories.skill_factory import create_skills_with_factory from django.db import transaction from django.core.management.base import BaseCommand
[ 6738, 47837, 13, 22584, 1749, 13, 42401, 62, 69, 9548, 1330, 2251, 62, 8135, 2171, 62, 4480, 62, 69, 9548, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 628 ]
3.833333
42
import unittest import mock import requests import httpretty import settings from bitfinex.client import Client, TradeClient API_KEY = settings.API_KEY API_SECRET = settings.API_SECRET
[ 11748, 555, 715, 395, 198, 11748, 15290, 198, 11748, 7007, 198, 11748, 2638, 16100, 198, 11748, 6460, 198, 198, 6738, 1643, 38125, 87, 13, 16366, 1330, 20985, 11, 9601, 11792, 198, 198, 17614, 62, 20373, 796, 6460, 13, 17614, 62, 20373,...
3.481481
54
import networkx as nx import pickle from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models.graphs import from_networkx processed_data_folder = 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\data\\processed\\' filename = processed_data_folder + 'graph_and_labels' with open (filename, 'rb') as fp: graph_mat, topic_labels = pickle.load(fp) G = nx.from_numpy_matrix(graph_mat) pos=nx.spring_layout(G) nx.relabel_nodes(G,topic_labels) nx.draw(G,pos) nx.draw_networkx_labels(G,pos,topic_labels,font_size=16) plot = figure(title="Blog Curator Demo", x_range=(-2.1,2.1), y_range=(-2.1,2.1), tools="", toolbar_location=None) graph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0)) plot.renderers.append(graph) output_file("networkx_graph.html") show(plot)
[ 11748, 3127, 87, 355, 299, 87, 198, 11748, 2298, 293, 198, 6738, 1489, 365, 71, 13, 952, 1330, 905, 11, 5072, 62, 7753, 198, 6738, 1489, 365, 71, 13, 29487, 889, 1330, 3785, 198, 6738, 1489, 365, 71, 13, 27530, 13, 34960, 82, 1330...
2.474777
337
#!/usr/bin/env python # encoding=utf-8 from inspect import getblock import json import os from os import read from numpy.core.fromnumeric import mean import numpy as np import paddlehub as hub import six import math import random import sys from util import read_file from config import Config # conf = Config() def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?") def get_data(file_path): """ gen datasets, convert word into word ids. :param file_path: :return: [[query, pos sample, 4 neg sample]], shape = [n, 6] """ data_map = {'query': [], 'query_len': [], 'doc_pos': [], 'doc_pos_len': [], 'doc_neg': [], 'doc_neg_len': []} with open(file_path, encoding='utf8') as f: for line in f.readlines(): spline = line.strip().split('\t') if len(spline) < 4: continue prefix, query_pred, title, tag, label = spline if label == '0': continue cur_arr, cur_len = [], [] query_pred = json.loads(query_pred) # only 4 negative sample for each in query_pred: if each == title: continue cur_arr.append(convert_word2id(each, conf.vocab_map)) each_len = len(each) if len(each) < conf.max_seq_len else conf.max_seq_len cur_len.append(each_len) if len(cur_arr) >= 4: data_map['query'].append(convert_word2id(prefix, conf.vocab_map)) data_map['query_len'].append(len(prefix) if len(prefix) < conf.max_seq_len else conf.max_seq_len) data_map['doc_pos'].append(convert_word2id(title, conf.vocab_map)) data_map['doc_pos_len'].append(len(title) if len(title) < conf.max_seq_len else conf.max_seq_len) data_map['doc_neg'].extend(cur_arr[:4]) data_map['doc_neg_len'].extend(cur_len[:4]) pass return data_map def get_data_siamese_rnn(file_path): """ gen datasets, convert word into word ids. :param file_path: :return: [[query, pos sample, 4 neg sample]], shape = [n, 6] """ data_arr = [] with open(file_path, encoding='utf8') as f: for line in f.readlines(): spline = line.strip().split('\t') if len(spline) < 4: continue prefix, _, title, tag, label = spline prefix_seq = convert_word2id(prefix, conf.vocab_map) title_seq = convert_word2id(title, conf.vocab_map) data_arr.append([prefix_seq, title_seq, int(label)]) return data_arr def get_data_bow(file_path): """ gen datasets, convert word into word ids. :param file_path: :return: [[query, prefix, label]], shape = [n, 3] """ data_arr = [] with open(file_path, encoding='utf8') as f: for line in f.readlines(): spline = line.strip().split('\t') if len(spline) < 4: continue prefix, _, title, tag, label = spline prefix_ids = convert_seq2bow(prefix, conf.vocab_map) title_ids = convert_seq2bow(title, conf.vocab_map) data_arr.append([prefix_ids, title_ids, int(label)]) return data_arr def trans_lcqmc(dataset): """ """ out_arr, text_len = [], [] for each in dataset: t1, t2, label = each.text_a, each.text_b, int(each.label) t1_ids = convert_word2id(t1, conf.vocab_map) t1_len = conf.max_seq_len if len(t1) > conf.max_seq_len else len(t1) t2_ids = convert_word2id(t2, conf.vocab_map) t2_len = conf.max_seq_len if len(t2) > conf.max_seq_len else len(t2) # t2_len = len(t2) out_arr.append([t1_ids, t1_len, t2_ids, t2_len, label]) # out_arr.append([t1_ids, t1_len, t2_ids, t2_len, label, t1, t2]) text_len.extend([len(t1), len(t2)]) pass print("max len", max(text_len), "avg len", mean(text_len), "cover rate:", np.mean([x <= conf.max_seq_len for x in text_len])) return out_arr def get_lcqmc(): """ LCQMCword_id """ dataset = hub.dataset.LCQMC() train_set = trans_lcqmc(dataset.train_examples) dev_set = trans_lcqmc(dataset.dev_examples) test_set = trans_lcqmc(dataset.test_examples) return train_set, dev_set, test_set # return test_set, test_set, test_set def trans_lcqmc_bert(dataset:list, vocab:Vocabulary, is_merge=0): """ """ out_arr, text_len = [], [] for each in dataset: t1, t2, label = each.text_a, each.text_b, int(each.label) if is_merge: out_ids1, mask_ids1, seg_ids1, seq_len1 = vocab._transform_2seq2bert_id(t1, t2, padding=1) out_arr.append([out_ids1, mask_ids1, seg_ids1, seq_len1, label]) text_len.extend([len(t1) + len(t2)]) else: out_ids1, mask_ids1, seg_ids1, seq_len1 = vocab._transform_seq2bert_id(t1, padding=1) out_ids2, mask_ids2, seg_ids2, seq_len2 = vocab._transform_seq2bert_id(t2, padding=1) out_arr.append([out_ids1, mask_ids1, seg_ids1, seq_len1, out_ids2, mask_ids2, seg_ids2, seq_len2, label]) text_len.extend([len(t1), len(t2)]) pass print("max len", max(text_len), "avg len", mean(text_len), "cover rate:", np.mean([x <= conf.max_seq_len for x in text_len])) return out_arr def get_lcqmc_bert(vocab:Vocabulary, is_merge=0): """ LCQMCqueryword_id """ dataset = hub.dataset.LCQMC() train_set = trans_lcqmc_bert(dataset.train_examples, vocab, is_merge) dev_set = trans_lcqmc_bert(dataset.dev_examples, vocab, is_merge) test_set = trans_lcqmc_bert(dataset.test_examples, vocab, is_merge) return train_set, dev_set, test_set # test_set = test_set[:100] # return test_set, test_set, test_set if __name__ == '__main__': # prefix, query_prediction, title, tag, label # query_prediction json file_train = './data/oppo_round1_train_20180929.txt' file_vali = './data/oppo_round1_vali_20180929.txt' # data_train = get_data(file_train) # data_train = get_data(file_vali) # print(len(data_train['query']), len(data_train['doc_pos']), len(data_train['doc_neg'])) dataset = get_lcqmc() print(dataset[1][:3]) for each in get_batch(dataset[1][:3], batch_size=2): t1_ids, t1_len, t2_ids, t2_len, label = each print(each) pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 28, 40477, 12, 23, 198, 6738, 10104, 1330, 651, 9967, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 28686, 1330, 1100, 198, 6738, 299, 32152, 13, 7295, 13, 6738, 77, 39223...
2.074477
3,397
""" GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar LICENSE: MIT """ from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import StaleElementReferenceException from webdriver_manager.chrome import ChromeDriverManager import argparse import logging import sys from datetime import datetime import time from groupfuncs import * import os # suppress webdriver manager logs os.environ['WDM_LOG_LEVEL'] = '0' IGNORE_DIV = ['your feed', 'discover', 'your notifications'] FB_GROUP_URL = 'https://www.facebook.com/groups/feed/' def display_intro(): ''' Displays intro of the script ''' intro = """ GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar """ print(intro) def time_taken(start_time, logger): ''' Calculates the time difference from now and start time ''' end_time = time.time() logger.info(f"Total time taken: {round(end_time - start_time, 4)} seconds") def cleanup_and_quit(driver): ''' Quits driver and exits the script ''' if driver: driver.quit() sys.exit() start_time = time.time() # ==================================================== # Argument parsing # ==================================================== description = "Leave your Facebook groups quietly" usage = "groupbunk.py username password [-h] [-eg FILE] [-et TIMEOUT] [-sw WAIT] [-gr RETRYCOUNT] [-dg FILE]" examples=""" Examples: groupbunk.py bob101@email.com bobspassword101 groupbunk.py bob101@email.com bobspassword101 -eg keepgroups.txt groupbunk.py bob101@email.com bobspassword101 -et 60 --scrollwait 10 -gr 7 groupbunk.py bob101@email.com bobspassword101 --dumpgroups mygroup.txt --groupretry 5 """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=description, usage=usage, epilog=examples, prog='groupbunk') # required arguments parser.add_argument('username', type=str, help='Facebook username') parser.add_argument('password', type=str, help='Facebook password') # optional arguments parser.add_argument('-eg', '--exgroups', type=str, metavar='', help='file with group names to exclude (one group per line)') parser.add_argument('-et', '--eltimeout', type=int, metavar='', help='max timeout for elements to be loaded', default=30) parser.add_argument('-sw', '--scrollwait', type=int, metavar='', help='time to wait after each scroll', default=4) parser.add_argument('-gr', '--groupretry', type=int, metavar='', help='retry count while recapturing group names', default=5) parser.add_argument('-dg', '--dumpgroups', type=str, metavar='', help='do not leave groups; only dump group names to a file') parser.add_argument('-v', '--version', action='version', version='%(prog)s v.1.2') args = parser.parse_args() # ==================================================== # Setting up logger # ===================================================== logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s:%(name)s:%(lineno)d:%(levelname)s:%(message)s") file_handler = logging.FileHandler(f'groupbunk_{datetime.now().strftime("%d_%m_%Y__%H_%M_%S")}.log', 'w', 'utf-8') file_handler.setFormatter(formatter) stdout_formatter = logging.Formatter("[*] => %(message)s") stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(stdout_formatter) logger.addHandler(file_handler) logger.addHandler(stdout_handler) #======================================================= try: display_intro() logger.info("script started") # loading group names to be excluded if args.exgroups: logger.info("Loading group names to be excluded") excluded_group_names = get_excluded_group_names(args.exgroups) IGNORE_DIV.extend(excluded_group_names) options = Options() # supresses notifications options.add_argument("--disable-notifications") options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_argument("--log-level=3") logger.info("Downloading latest chrome webdriver") # UNCOMMENT TO SPECIFY DRIVER LOCATION # driver = webdriver.Chrome("D:/chromedriver/98/chromedriver.exe", options=options) driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) if not driver: raise Exception('Unable to download chrome webdriver for your version of Chrome browser') logger.info("Successfully downloaded chrome webdriver") wait = WebDriverWait(driver, args.eltimeout) logger.info(f"Opening FB GROUPS URL: {FB_GROUP_URL}") driver.get(FB_GROUP_URL) logger.info("Sending username") wait.until(EC.visibility_of_element_located((By.ID, 'email'))).send_keys(args.username) logger.info("Sending password") driver.find_element(By.ID, 'pass').send_keys(args.password) logger.info("Clicking on Log In") wait.until(EC.presence_of_element_located((By.ID, 'loginbutton'))).click() # get all the links inside divs representing group names group_links = get_group_link_elements(driver, wait) if not group_links: raise Exception("Unable to find links") no_of_currently_loaded_links = 0 logger.info(f"Initial link count: {len(group_links)-3}") logger.info("Scrolling down to capture all the links") # scroll until no new group links are loaded while len(group_links) > no_of_currently_loaded_links: no_of_currently_loaded_links = len(group_links) logger.info(f"Updated link count: {no_of_currently_loaded_links-3}") scroll_into_view(driver, group_links[no_of_currently_loaded_links-1]) time.sleep(args.scrollwait) # re-capturing group_links = get_group_link_elements(driver, wait) logger.info(f"Total number of links found: {len(group_links)-3}") # only show the group names and exit if args.dumpgroups: logger.info('Only dumping group names to file. Not leaving groups') logger.info(f"Dumping group names to: {args.dumpgroups}") dump_groups(group_links, args.dumpgroups) time_taken(start_time, logger) cleanup_and_quit(driver) # first 3 links are for Your feed, 'Discover, Your notifications i = 0 save_state = 0 no_of_retries = 0 failed_groups = [] total_groups = len(group_links) while i < total_groups: try: # need only the group name and not Last Active group_name = group_links[i].text.split('\n')[0] # if group name not in ignore list if group_name.lower() not in IGNORE_DIV: logger.info(f"Leaving group: {group_name}") link = group_links[i].get_attribute('href') logger.info(f"Opening group link: {link}") switch_tab(driver, open_new_tab(driver)) driver.get(link) if not leave_group(wait): logger.info('Unable to leave the group. You might not be a member of this group.') driver.close() switch_tab(driver, driver.window_handles[0]) else: if group_name.lower() not in ['your feed', 'discover', 'your notifications']: logger.info(f"Skipping group : {group_name}") i += 1 except StaleElementReferenceException: logger.error('Captured group elements gone stale. Recapturing...') if no_of_retries > args.groupretry: logger.error('Reached max number of retry attempts') break save_state = i group_links = get_group_link_elements(driver, wait) no_of_retries += 1 except Exception as ex: logger.error(f"Unable to leave group {group_name}. Error: {ex}") failed_groups.append(group_name) i += 1 total_no_of_groups = len(group_links)-3 total_no_failed_groups = len(failed_groups) logger.info(f"Total groups: {total_no_of_groups}") logger.info(f"No. of groups failed to leave: {total_no_failed_groups}") logger.info(f"Success percentage: {((total_no_of_groups - total_no_failed_groups)/total_no_of_groups) * 100} %") if failed_groups: failed_group_names = ", ".join(failed_groups) logger.info(f"Failed groups: \n{failed_group_names}") except Exception as ex: logger.error(f"Script ended with exception: {ex}") finally: time_taken(start_time, logger) cleanup_and_quit(driver)
[ 37811, 198, 13247, 33, 2954, 410, 13, 16, 13, 17, 198, 198, 35087, 534, 3203, 2628, 12703, 220, 198, 198, 13838, 25, 41249, 9180, 461, 44844, 198, 38, 10060, 25, 3740, 1378, 12567, 13, 785, 14, 19489, 12, 33708, 461, 44844, 198, 198...
2.664845
3,294
import numpy as np import numpy.linalg as la from MdlUtilities import Field, FieldList import MdlUtilities as mdl
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 299, 32152, 13, 75, 1292, 70, 355, 8591, 201, 198, 6738, 337, 25404, 18274, 2410, 1330, 7663, 11, 7663, 8053, 201, 198, 11748, 337, 25404, 18274, 2410, 355, 285, 25404, 201, 198, 201, 19...
2.344828
58
"""Test converting an image to a pyramid. """ import numpy as np import napari points = np.random.randint(100, size=(50_000, 2)) with napari.gui_qt(): viewer = napari.view_points(points, face_color='red')
[ 37811, 14402, 23202, 281, 2939, 284, 257, 27944, 13, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25422, 2743, 198, 198, 13033, 796, 45941, 13, 25120, 13, 25192, 600, 7, 3064, 11, 2546, 16193, 1120, 62, 830, 11, 36...
2.826667
75
from unittest import TestCase from mock import patch from .. import constants
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 15290, 1330, 8529, 198, 198, 6738, 11485, 1330, 38491, 628, 198 ]
3.904762
21
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015, 2016, 2017 Daniel Rodriguez # # 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/>. # ############################################################################### from __future__ import (absolute_import, division, print_function, unicode_literals) from backtrader import Indicator from backtrader.functions import * # The modules below should/must define __all__ with the Indicator objects # of prepend an "_" (underscore) to private classes/variables from .basicops import * # base for moving averages from .mabase import * # moving averages (so envelope and oscillators can be auto-generated) from .sma import * from .ema import * from .smma import * from .wma import * from .dema import * from .kama import * from .zlema import * from .hma import * from .zlind import * from .dma import * # depends on moving averages from .deviation import * # depend on basicops, moving averages and deviations from .atr import * from .aroon import * from .bollinger import * from .cci import * from .crossover import * from .dpo import * from .directionalmove import * from .envelope import * from .heikinashi import * from .lrsi import * from .macd import * from .momentum import * from .oscillator import * from .percentchange import * from .percentrank import * from .pivotpoint import * from .prettygoodoscillator import * from .priceoscillator import * from .psar import * from .rsi import * from .stochastic import * from .trix import * from .tsi import * from .ultimateoscillator import * from .williams import * from .rmi import * from .awesomeoscillator import * from .accdecoscillator import * from .dv2 import * # depends on percentrank # Depends on Momentum from .kst import * from .ichimoku import * from .hurst import * from .ols import * from .hadelta import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 26, 12972, 12, 521, 298, 12, 28968, 25, 19, 532, 9, 12, 198, 29113, 29113, 7804, 4242, 21017, 198, 2, 198, 2, 15069, 357, 34, 8, 185...
3.46206
738
import pytest from array import array from game_map import GameMap from tests.conftest import get_relative_path sample_map_data = tuple( reversed( ( array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)), array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)), array("I", (1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1)), array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1)), array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), array("I", (1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1)), array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)), array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)), ) ) )
[ 11748, 12972, 9288, 198, 198, 6738, 7177, 1330, 7177, 198, 6738, 983, 62, 8899, 1330, 3776, 13912, 198, 6738, 5254, 13, 1102, 701, 395, 1330, 651, 62, 43762, 62, 6978, 628, 198, 39873, 62, 8899, 62, 7890, 796, 46545, 7, 198, 220, 22...
1.565118
1,313
# encoding: utf-8 from __future__ import unicode_literals import six from django.db.models import Manager from django.db.models.query import QuerySet from .compat import (ANNOTATION_SELECT_CACHE_NAME, ANNOTATION_TO_AGGREGATE_ATTRIBUTES_MAP, chain_query, chain_queryset, ModelIterable, ValuesQuerySet) from .exceptions import QueryablePropertyDoesNotExist, QueryablePropertyError from .query import QueryablePropertiesQueryMixin from .utils import get_queryable_property from .utils.internal import InjectableMixin, QueryPath, QueryablePropertyReference def _resolve_update_kwargs(self, **kwargs): """ Look for the names of queryable properties in the given keyword arguments for an update query and correctly resolve them into their actual keyword arguments. :param kwargs: Keyword arguments of an update query. :return: A dictionary containing the resolved arguments. :rtype: dict """ original_names = set(kwargs) for original_name in original_names: try: prop = get_queryable_property(self.model, original_name) except QueryablePropertyDoesNotExist: continue if not prop.get_update_kwargs: raise QueryablePropertyError('Queryable property "{}" does not implement queryset updating.' .format(prop)) # Call the method recursively since queryable properties can build # upon each other. additional_kwargs = self._resolve_update_kwargs( **prop.get_update_kwargs(self.model, kwargs.pop(original_name))) # Make sure that there are no conflicting values after resolving # the update keyword arguments of the queryable properties. for additional_name, value in six.iteritems(additional_kwargs): if additional_name in kwargs and kwargs[additional_name] != value: raise QueryablePropertyError( 'Updating queryable property "{prop}" would change field "{field}", but a conflicting value ' 'was set for this field by another queryable property or explicitly in the update arguments.' .format(prop=prop, field=additional_name) ) kwargs[additional_name] = value return kwargs def select_properties(self, *names): """ Add the annotations of the queryable properties with the specified names to this query. The annotation values will be cached in the properties of resulting model instances, regardless of the regular caching behavior of the queried properties. :param names: Names of queryable properties. :return: A copy of this queryset with the added annotations. :rtype: QuerySet """ queryset = chain_queryset(self) for name in names: property_ref = QueryablePropertyReference(get_queryable_property(self.model, name), self.model, QueryPath()) # A full GROUP BY is required if the query is not limited to # certain fields. Since only certain types of queries had the # _fields attribute in old Django versions, fall back to checking # for existing selection, on which the GROUP BY would be based. full_group_by = not getattr(self, '_fields', self.query.select) with queryset.query._add_queryable_property_annotation(property_ref, full_group_by, select=True): pass return queryset def iterator(self, *args, **kwargs): # Recent Django versions use the associated iterable class for the # iterator() implementation, where the QueryablePropertiesModelIterable # will be already mixed in. In older Django versions, use a standalone # QueryablePropertiesModelIterable instead to perform the queryable # properties processing. iterable = super(QueryablePropertiesQuerySetMixin, self).iterator(*args, **kwargs) if '_iterable_class' not in self.__dict__: # pragma: no cover return iter(QueryablePropertiesIterable(self, iterable=iterable)) return iterable def update(self, **kwargs): # Resolve any queryable properties into their actual update kwargs # before calling the base update method. kwargs = self._resolve_update_kwargs(**kwargs) return super(QueryablePropertiesQuerySetMixin, self).update(**kwargs) class QueryablePropertiesQuerySet(QueryablePropertiesQuerySetMixin, QuerySet): """ A special queryset class that allows to use queryable properties in its filter conditions, annotations and update queries. """ pass if hasattr(Manager, 'from_queryset'): QueryablePropertiesManager = Manager.from_queryset(QueryablePropertiesQuerySet) else: # pragma: no cover
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 2237, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 9142, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, ...
2.658485
1,874
from __future__ import print_function, absolute_import import unittest, math import pandas as pd import numpy as np from . import *
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 4112, 62, 11748, 201, 198, 201, 198, 11748, 555, 715, 395, 11, 10688, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 764, 1330, ...
3.088889
45
import os import sys from setuptools import find_packages, setup, Extension try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from setuptools_rust import RustExtension except ImportError: import subprocess errno = subprocess.call( [sys.executable, '-m', 'pip', 'install', 'setuptools-rust']) if errno: print("Please install setuptools-rust package") raise SystemExit(errno) else: from setuptools_rust import RustExtension ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) version = __import__('rsglob').VERSION setup_requires = ['setuptools-rust>=0.6.0'] install_requires = get_requirements('requirements.txt') test_requires = get_requirements('requirements-test.txt') rust_extensions = [RustExtension('rsglob._rsglob', 'Cargo.toml')] setup( name='rsglob', version=version, url='https://github.com/wdv4758h/rsglob', author='Chiu-Hsiang Hsu', author_email='wdv4758h@gmail.com', description=('Python glob in Rust'), long_description=open("README.rst").read(), download_url="https://github.com/wdv4758h/rsglob/archive/v{}.zip".format( version ), license='BSD', tests_require=test_requires, install_requires=install_requires, packages=find_packages(), rust_extensions=rust_extensions, zip_safe=False, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', # 'Programming Language :: Python :: 2', # 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', # 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 11, 27995, 198, 198, 28311, 25, 220, 220, 220, 1303, 329, 7347, 18189, 838, 198, 220, 220, 220, 422, 7347, 13557, 32538, 13, 42180, 1330, ...
2.622016
754
import numpy as np import math import pyrobot.utils.util as prutil import rospy import habitat_sim.agent as habAgent import habitat_sim.utils as habUtils from habitat_sim.agent.controls import ActuationSpec import habitat_sim.errors import quaternion from tf.transformations import euler_from_quaternion, euler_from_matrix
[ 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 12972, 305, 13645, 13, 26791, 13, 22602, 355, 778, 22602, 198, 11748, 686, 2777, 88, 198, 11748, 20018, 62, 14323, 13, 25781, 355, 387, 65, 36772, 198, 11748, 20018, 62, 1432...
3.282828
99
from django.contrib import admin from .models import Chat admin.site.register(Chat, ChatAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 24101, 628, 198, 198, 28482, 13, 15654, 13, 30238, 7, 30820, 11, 24101, 46787, 8, 628, 198 ]
3.258065
31
# -*- coding: utf-8 -*- from pythainlp.tokenize import etcc print(etcc.etcc("")) # //
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 279, 5272, 391, 34431, 13, 30001, 1096, 1330, 2123, 535, 198, 198, 4798, 7, 316, 535, 13, 316, 535, 7203, 48774, 220, 1303, 3373, 198 ]
2.170732
41
#!/usr/bin/env python from cumulogenesis.interfaces import cli cli.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 10973, 377, 25908, 13, 3849, 32186, 1330, 537, 72, 198, 198, 44506, 13, 5143, 3419, 198 ]
2.777778
27
from __future__ import division import logging from nanpy.i2c import I2C_Master from nanpy.memo import memoized import time log = logging.getLogger(__name__)
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 18931, 198, 6738, 15709, 9078, 13, 72, 17, 66, 1330, 314, 17, 34, 62, 18254, 198, 6738, 15709, 9078, 13, 11883, 78, 1330, 16155, 1143, 198, 11748, 640, 628, 198, 6404, 796, 18931, ...
3.075472
53
import logging import argh import pygna.command as cmd import pygna.painter as paint import pygna.utils as utils import pygna.block_model as bm import pygna.degree_model as dm """ autodoc """ logging.basicConfig(level=logging.INFO) if __name__ == "__main__": """ MAIN """ main()
[ 11748, 18931, 198, 11748, 610, 456, 198, 11748, 12972, 70, 2616, 13, 21812, 355, 23991, 198, 11748, 12972, 70, 2616, 13, 35436, 353, 355, 7521, 198, 11748, 12972, 70, 2616, 13, 26791, 355, 3384, 4487, 198, 11748, 12972, 70, 2616, 13, ...
2.533898
118
""" PyColourChooser Copyright (C) 2002 Michael Gilfix <mgilfix@eecs.tufts.edu> This file is part of PyColourChooser. This version of PyColourChooser is open source; you can redistribute it and/or modify it under the licensed terms. 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. """ # 12/14/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatibility update. # # 12/21/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o wxPyColorChooser -> PyColorChooser # o wxPyColourChooser -> PyColourChooser # # Tags: phoenix-port import wx
[ 37811, 198, 20519, 5216, 454, 22164, 13416, 198, 15269, 357, 34, 8, 6244, 3899, 10689, 13049, 1279, 11296, 346, 13049, 31, 68, 721, 82, 13, 28047, 35594, 13, 15532, 29, 198, 198, 1212, 2393, 318, 636, 286, 9485, 5216, 454, 22164, 1341...
2.914894
235
import json import csv import pandas as pd from isic_api import ISICApi from pandas.io.json import json_normalize # Initialize the API; no login is necessary for public data api = ISICApi(username="SkinCare", password="unbdeeplearning") outputFileName = 'imagedata' imageList = api.getJson('image?limit=25000&offset=0&sort=name') print('Fetching metadata for %s images' % len(imageList)) imageDetails = [] i = 0 for image in imageList: print(' ', image['name']) # Pull image details imageDetail = api.getJson('image/%s' % image['_id']) imageDetails.append(imageDetail) """ # Testing Parameters print("****************************") print(imageDetails[0]['meta']['clinical']['anatom_site_general']) print("****************************") data = json_normalize(imageDetails[0]) print(data.loc[0]) data = json_normalize(imageDetails[0]) print(data.loc[0]) print("========================================================") print(data.loc[0]['dataset.name']) """ # Determine the union of all image metadata fields metadataFields = set( field for imageDetail in imageDetails for field in imageDetail['meta']['clinical'].keys() ) metadataFields = ['isic_id'] + sorted(metadataFields) # print(metadataFields) outputFilePath = './metadata.csv' # Write Metadata to a CSV print('Writing metadata to CSV: %s' % 'metadata.csv') with open(outputFilePath, 'w') as outputStream: csvWriter = csv.DictWriter(outputStream, fieldnames=metadataFields) csvWriter.writeheader() # Columns Names for imageDetail in imageDetails: rowDict = imageDetail['meta']['clinical'].copy() rowDict['isic_id'] = imageDetail['name'] # rowDict['anatom_site_general'] = imageDetail['meta']['clinical']['anatom_site_general'] # Subjective csvWriter.writerow(rowDict)
[ 11748, 33918, 198, 11748, 269, 21370, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 318, 291, 62, 15042, 1330, 3180, 25241, 14415, 198, 6738, 19798, 292, 13, 952, 13, 17752, 1330, 33918, 62, 11265, 1096, 198, 198, 2, 20768, 1096, 2...
2.923948
618
#!/usr/bin/env python """ generate-all-graphs.py python generate-all-graphs.py | gzip -c > all-graphs.gz """ import sys import json import itertools import numpy as np from tqdm import tqdm from nasbench.lib import graph_util from joblib import delayed, Parallel max_vertices = 7 num_ops = 3 max_edges = 9 adjs = [] for vertices in range(2, max_vertices+1): for bits in range(2 ** (vertices * (vertices-1) // 2)): adjs.append((vertices, bits)) adjs = [adjs[i] for i in np.random.permutation(len(adjs))] jobs = [delayed(make_graphs)(*adj) for adj in adjs] res = Parallel(n_jobs=40, backend='multiprocessing', verbose=10)(jobs) for r in res: for rr in r: print(json.dumps(rr))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 220, 7716, 12, 439, 12, 34960, 82, 13, 9078, 198, 220, 220, 198, 220, 21015, 7716, 12, 439, 12, 34960, 82, 13, 9078, 930, 308, 13344, 532, 66, 1875, 477, 12, 34960...
2.487719
285
# FIXME: fix all "happy paths coding" issues import liblo from threading import Thread
[ 2, 44855, 11682, 25, 4259, 477, 366, 34191, 13532, 19617, 1, 2428, 198, 198, 11748, 9195, 5439, 198, 6738, 4704, 278, 1330, 14122, 628 ]
3.708333
24
import json import os import pytest from datetime import datetime, timedelta import boto3 from httmock import urlmatch, HTTMock from moto import mock_s3 from app import storage as test_storage from data import model, database from data.logs_model import logs_model from storage import S3Storage, StorageContext, DistributedStorage from workers.exportactionlogsworker import ExportActionLogsWorker, POLL_PERIOD_SECONDS from test.fixtures import * _TEST_CONTENT = os.urandom(1024) _TEST_BUCKET = "somebucket" _TEST_USER = "someuser" _TEST_PASSWORD = "somepassword" _TEST_PATH = "some/cool/path" _TEST_CONTEXT = StorageContext("nyc", None, None, None)
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 11748, 275, 2069, 18, 198, 198, 6738, 1841, 76, 735, 1330, 19016, 15699, 11, 7154, 15972, 735, 198, 6738...
3.036866
217
""" The base top-level plot model class. From this all data and plotting flow. """ from pageplot.exceptions import PagePlotParserError from pathlib import Path from typing import Any, Optional, Dict, List, Union from pageplot.extensionmodel import PlotExtension from pageplot.extensions import built_in_extensions from pageplot.io.spec import IOSpecification from pageplot.config import GlobalConfig from pageplot.mask import get_mask import matplotlib.pyplot as plt import numpy as np import unyt import attr
[ 37811, 198, 464, 2779, 1353, 12, 5715, 7110, 2746, 1398, 13, 198, 198, 4863, 428, 477, 1366, 290, 29353, 5202, 13, 198, 37811, 198, 198, 6738, 2443, 29487, 13, 1069, 11755, 1330, 7873, 43328, 46677, 12331, 198, 6738, 3108, 8019, 1330, ...
3.626761
142
from bs4 import BeautifulSoup as soup from selenium import webdriver
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 355, 17141, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230 ]
3.777778
18
#!/usr/bin/python3 """qsubm -- generic queue submission for task-oriented batch scripts Environment variables: MCSCRIPT_DIR should specify the directory in which the mcscript package is installed, i.e., the directory where the file qsubm.py is found. (Note that qsubm uses this information to locate certain auxiliary script files used as part of the job submission process.) MCSCRIPT_RUN_HOME must specify the directory in which job files are found. MCSCRIPT_WORK_HOME should specify the parent directory in which run scratch directories should be made. MCSCRIPT_INSTALL_HOME must specify the directory in which executables are found. MCSCRIPT_LAUNCH_HOME (optional) should specify the parent directory in which run subdirectories for qsub invocation and output logging should be made. Otherwise, this will default to MCSCRIPT_WORK_HOME. MCSCRIPT_PYTHON should give the full qualified filename (i.e., including path) to the Python 3 executable for running run script files. A typical value will simply be "python3", assuming the Python 3 executable is in the shell's command search PATH. However, see note on "Availability of Python" in INSTALL.md. MCSCRIPT_RUN_PREFIX should specify the prefix for run names, e.g., set to "run" if your scripts are to be named run<XXXX>.py. Requires local definitions file config.py to translate options into arguments for local batch server. See directions in readme.txt. Your local definitions might not make use of or support all the parallel environment options. Language: Python 3 M. A. Caprio University of Notre Dame + 3/6/13 (mac): Based on earlier qsubm csh script. + 7/4/13 (mac): Support for multiple cluster flavors via qsubm_local. + 1/22/14 (mac): Python 3 update. + 10/27/14 (mac): Updates to --archive handling. + 5/14/15 (mac): - Insert "future" statements for Python 2 legacy support. - Add --noredirect switch. - Mandatory environment variable QSUBM_PYTHON. + 8/4/15 (mac): Make user environment variable definitions into option. + 6/13/16 (mac): Rename environment variables to MCSCRIPT_*. + 6/22/16 (mac): Update to use config.py for local configuration. + 12/14/16 (mac): Add --here option. + 12/29/16 (mac): - Add --spread option. - Remove --pernode option. - Make --opt option repeatable. + 1/16/17 (mac): Add --serialthreads option. + 2/23/17 (mac): Switch from os.mkdir to mcscript.utils.mkdir. + 3/16/17 (mac): - Add --setup option. - Change environment interface to pass MCSCRIPT_TASK_MODE. + 3/18/17 (mac): - Revise to support updated hybrid run parameters. - Rename option --setup to --prerun. + 5/22/17 (mac): Fix processing of boolean option --redirect. + 10/11/17 (pjf): Add --switchwaittime option. + 01/05/18 (pjf): Sort arguments into groups. + 02/11/18 (pjf): - Pass through MCSCRIPT_INSTALL_HOME. - Use job_environ for submission. + 07/06/18 (pjf): - Pass queue via MCSCRIPT_RUN_QUEUE. - Remove MCSCRIPT_HYBRID_NODESIZE. + 06/04/19 (pjf): - Add hook for individual configurations to add command-line arguments. - Move --switchwaittime option into config-slurm-nersc.py. + 09/11/19 (pjf): Add expert mode argument. """ import argparse import os import shutil import subprocess import sys import mcscript.config # local configuration (usually symlink) import mcscript.utils ################################################################ # argument parsing ################################################################ parser = argparse.ArgumentParser( description="Queue submission for numbered run.", usage= "%(prog)s [option] run queue|RUN wall [var1=val1, ...]\n", formatter_class=argparse.ArgumentDefaultsHelpFormatter, epilog= """Simply omit the queue name and leave off the wall time for a local interactive run. Environment variables for qsubm are described in INSTALL.md. Note that qsubm relies upon code in the local `config.py` configuration file for the system or cluster you are running on, in order to interpret the following arguments and translate them into arguments for your local batch system. Your local configuration file might not make use of or support all the parallel environment options listed below. """ ) # general arguments parser.add_argument("run", help="Run number (e.g., 0000 for run0000)") # latter arguments are made optional to simplify bare-bones syntax for --toc, etc., calls parser.add_argument("queue", nargs='?', help="Submission queue, or RUN for direct interactive run", default="RUN") parser.add_argument("wall", type=int, nargs='?', help="Wall time (minutes)", default=60) ##parser.add_argument("vars", nargs="?", help="Environment variables to pass to script, with optional values, comma delimited (e.g., METHOD2, PARAM=1.0)") parser.add_argument("--here", action="store_true", help="Force run in current working directory") parser.add_argument("--vars", help="Environment variables to pass to script, with optional values, comma delimited (e.g., --vars=METHOD2, PARAM=1.0)") ## parser.add_argument("--stat", action="store_true", help="Display queue status information") parser.add_argument("--num", type=int, default=1, help="Number of repetitions") parser.add_argument("--opt", action="append", help="Additional option arguments to be passed to job submission command (e.g., --opt=\"-m ae\" or --opt=\"--mail-type=END,FAIL\"), may be repeated (e.g., --opt=\"-A acct\" --opt=\"-a 1200\"); beware the spaces may be important to the job submission command") parser.add_argument("--expert", action="store_true", help="Run mcscript in expert mode") # serial run parallelization parameters serial_group = parser.add_argument_group("serial run options (single-node, non-MPI)") serial_group.add_argument("--serialthreads", type=int, default=1, help="OMP threads") # hybrid run parallelization parameters # # Not all local configuration files need necessarily require or # respect all of the following parameters. hybrid_group = parser.add_argument_group("hybrid run options") hybrid_group.add_argument("--nodes", type=int, default=1, help="number of nodes") hybrid_group.add_argument("--ranks", type=int, default=1, help="number of MPI ranks") hybrid_group.add_argument("--threads", type=int, default=1, help="OMP threads per rank)") hybrid_group.add_argument("--nodesize", type=int, default=0, help="logical threads available per node" " (might instead be interpreted physical CPUs depending on local config file)") ##hybrid_group.add_argument("--undersubscription", type=int, default=1, help="undersubscription factor (e.g., spread=2 requests twice the cores needed)") # multi-task interface: invocation modes task_mode_group = parser.add_mutually_exclusive_group() task_mode_group.add_argument("--toc", action="store_true", help="Invoke run script to generate task table of contents") task_mode_group.add_argument("--unlock", action="store_true", help="Delete any .lock or .fail flags for tasks") task_mode_group.add_argument("--archive", action="store_true", help="Invoke archive-generation run") task_mode_group.add_argument("--prerun", action="store_true", help="Invoke prerun mode, for argument validation and file staging only") task_mode_group.add_argument("--offline", action="store_true", help="Invoke offline mode, to create batch scripts for later submission instead of running compute codes") # multi-task interface: task selection task_selection_group = parser.add_argument_group("multi-task run options") task_selection_group.add_argument("--pool", help="Set task pool (or ALL) for task selection") task_selection_group.add_argument("--phase", type=int, default=0, help="Set task phase for task selection") task_selection_group.add_argument("--start", type=int, help="Set starting task number for task selection") task_selection_group.add_argument("--limit", type=int, help="Set task count limit for task selection") task_selection_group.add_argument("--redirect", default="True", choices=["True", "False"], help="Allow redirection of standard" " output/error to file (may want to disable for interactive debugging)") # some special options (deprecated?) ##parser.add_argument("--epar", type=int, default=None, help="Width for embarassingly parallel job") ##parser.add_argument("--nopar", action="store_true", help="Disable parallel resource requests (for use on special serial queues)") # site-local options try: mcscript.config.qsubm_arguments(parser) except AttributeError: # local config doesn't provide arguments, ignore gracefully pass ##parser.print_help() ##print args = parser.parse_args() ##printargs ################################################################ # special mode: status display ################################################################ # TODO # will have to modify argument processing to allow no arguments, local # customization for qstat # @ i = 0 # while (($i == 0) || ($loop)) # @ i++ # clear # echo "****************************************************************" # qstat -u $user # if ($loop) sleep 5 # end ## if (args.stat): ## pass ################################################################ # environment processing ################################################################ if (args.here): run_home = os.environ["PWD"] elif ("MCSCRIPT_RUN_HOME" in os.environ): run_home = os.environ["MCSCRIPT_RUN_HOME"] else: print("MCSCRIPT_RUN_HOME not found in environment") exit(1) if (args.here): work_home = os.environ["PWD"] elif ("MCSCRIPT_WORK_HOME" in os.environ): work_home = os.environ["MCSCRIPT_WORK_HOME"] else: print("MCSCRIPT_WORK_HOME not found in environment") exit(1) if (args.here): launch_home = os.environ["PWD"] elif ("MCSCRIPT_LAUNCH_HOME" in os.environ): launch_home = os.environ["MCSCRIPT_LAUNCH_HOME"] else: launch_home = work_home if ("MCSCRIPT_RUN_PREFIX" in os.environ): run_prefix = os.environ["MCSCRIPT_RUN_PREFIX"] else: print("MCSCRIPT_RUN_PREFIX not found in environment") exit(1) if ("MCSCRIPT_PYTHON" in os.environ): python_executable = os.environ["MCSCRIPT_PYTHON"] else: print("MCSCRIPT_PYTHON not found in environment") exit(1) if ("MCSCRIPT_DIR" in os.environ): qsubm_path = os.environ["MCSCRIPT_DIR"] else: print("MCSCRIPT_DIR not found in environment") exit(1) ################################################################ # argument processing ################################################################ # set run name run = run_prefix + args.run print("Run:", run) # ...and process run file script_extensions = [".py", ".csh"] job_file = None for extension in script_extensions: filename = os.path.join(run_home, run+extension) if (filename): job_file = filename job_extension = extension break print(" Run home:", run_home) # useful to report now, in case job file missing if (job_file is None): print("No job file %s.* found with an extension in the set %s." % (run, script_extensions)) exit(1) print(" Job file:", job_file) # set queue and flag batch or local mode # force local run for task.py toc mode if ((args.queue == "RUN") or args.toc or args.unlock): run_mode = "local" run_queue = "local" print(" Mode:", run_mode) else: run_mode = "batch" run_queue = args.queue print(" Mode:", run_mode, "(%s)" % args.queue) # set wall time wall_time_min = args.wall print(" Wall time (min): {:d}".format(wall_time_min)) wall_time_sec = wall_time_min*60 # environment definitions: general run parameters environment_definitions = [ "MCSCRIPT_RUN={:s}".format(run), "MCSCRIPT_JOB_FILE={:s}".format(job_file), "MCSCRIPT_RUN_MODE={:s}".format(run_mode), "MCSCRIPT_RUN_QUEUE={:s}".format(run_queue), "MCSCRIPT_WALL_SEC={:d}".format(wall_time_sec) ] # environment definitions: serial run parameters environment_definitions += [ "MCSCRIPT_SERIAL_THREADS={:d}".format(args.serialthreads) ] # environment definitions: hybrid run parameters environment_definitions += [ "MCSCRIPT_HYBRID_NODES={:d}".format(args.nodes), "MCSCRIPT_HYBRID_RANKS={:d}".format(args.ranks), "MCSCRIPT_HYBRID_THREADS={:d}".format(args.threads), ] # set multi-task run parameters if (args.toc): task_mode = mcscript.task.TaskMode.kTOC elif (args.unlock): task_mode = mcscript.task.TaskMode.kUnlock elif (args.archive): task_mode = mcscript.task.TaskMode.kArchive elif (args.prerun): task_mode = mcscript.task.TaskMode.kPrerun elif (args.offline): task_mode = mcscript.task.TaskMode.kOffline else: task_mode = mcscript.task.TaskMode.kRun # TODO (mac): neaten up so that these arguments are always provided # (and simplify this code to a simple list += as above) environment_definitions.append("MCSCRIPT_TASK_MODE={:d}".format(task_mode.value)) if (args.pool is not None): environment_definitions.append("MCSCRIPT_TASK_POOL={:s}".format(args.pool)) if (args.phase is not None): environment_definitions.append("MCSCRIPT_TASK_PHASE={:d}".format(args.phase)) if (args.start is not None): environment_definitions.append("MCSCRIPT_TASK_START_INDEX={:d}".format(args.start)) if (args.limit is not None): environment_definitions.append("MCSCRIPT_TASK_COUNT_LIMIT={:d}".format(args.limit)) environment_definitions.append("MCSCRIPT_TASK_REDIRECT={:s}".format(args.redirect)) # pass through install directory if os.environ.get("MCSCRIPT_INSTALL_HOME"): environment_definitions += [ "MCSCRIPT_INSTALL_HOME={:s}".format(os.environ["MCSCRIPT_INSTALL_HOME"]) ] elif os.environ.get("MCSCRIPT_INSTALL_DIR"): # TODO remove deprecated environment variable print("****************************************************************") print("MCSCRIPT_INSTALL_DIR is now MCSCRIPT_INSTALL_HOME.") print("Please update your environment variables.") print("****************************************************************") environment_definitions += [ "MCSCRIPT_INSTALL_HOME={:s}".format(os.environ["MCSCRIPT_INSTALL_DIR"]) ] else: print("MCSCRIPT_INSTALL_HOME not found in environment") exit(1) # include additional environment setup if defined if os.environ.get("MCSCRIPT_SOURCE"): environment_definitions += [ "MCSCRIPT_SOURCE={:s}".format(os.environ["MCSCRIPT_SOURCE"]) ] # set user-specified variable definitions # Note conditional is required since "".split(", ") is [""] rather than []. if (args.vars is None): user_environment_definitions = [] else: user_environment_definitions = args.vars.split(",") print(" User environment definitions:", user_environment_definitions) environment_definitions += user_environment_definitions ################################################################ # directory setup ################################################################ # set up scratch directory (for batch job work) # name is defined here, but creation is left up to job script, # in case scratch is local to the compute note work_dir = os.path.join(work_home, run) ## if ( not os.path.exists(work_dir)): ## mcscript.utils.mkdir(work_dir) environment_definitions.append("MCSCRIPT_WORK_DIR=%s" % work_dir) # set up run launch directory (for batch job output logging) launch_dir_parent = os.path.join(launch_home, run) if ( not os.path.exists(launch_home)): mcscript.utils.mkdir(launch_home) if ( not os.path.exists(launch_dir_parent)): mcscript.utils.mkdir(launch_dir_parent) if (args.archive): # archive mode # launch in archive directory rather than usual batch job output directory # (important since if batch job server directs output to the # regular output directory while tar is archiving that directory, # tar will return with an error code, torpedoing the archive task) launch_dir = os.path.join(launch_home, run, "archive") else: # standard run mode launch_dir = os.path.join(launch_home, run, "batch") if ( not os.path.exists(launch_dir)): mcscript.utils.mkdir(launch_dir) environment_definitions.append("MCSCRIPT_LAUNCH_DIR=%s" % launch_dir) ################################################################ # job environment setup ################################################################ # construct job name job_name = "%s" % run ##job_name += "-w%d" % args.width if (args.pool is not None): job_name += "-%s" % args.pool job_name += "-%s" % args.phase print(" Job name:", job_name) # process environment definitions # regularize environment definitions # Convert all plain variable name definitions "VAR" into definition # as null string "VAR=". Note that "VAR" would be an environment # variable pass-through request to qsub, but it causes trouble with # defining an environment for local execution. So doing this # regularization simplifies further processing and ensures # uniformity of the environment between batch and local runs. for i in range(len(environment_definitions)): if (not "=" in environment_definitions[i]): environment_definitions[i] += "=" print() print("Vars:", ",".join(environment_definitions)) # for local run job_environ=os.environ environment_keyvalues = [ entry.split("=") for entry in environment_definitions ] job_environ.update(dict(environment_keyvalues)) ################################################################ # run invocation ################################################################ # flush script output before invoking job print() sys.stdout.flush() # handle batch run if (run_mode == "batch"): # set local qsub arguments (submission_args, submission_input_string, repetitions) = mcscript.config.submission(job_name, job_file, qsubm_path, environment_definitions, args) # notes: options must come before command on some platforms (e.g., Univa) print(" ".join(submission_args)) print(submission_input_string) print() print("-"*64) for i in range(repetitions): process = subprocess.Popen( submission_args, stdin=subprocess.PIPE, # to take input from communicate stdout=subprocess.PIPE, # to send output to communicate -- default merged stderr env=job_environ, cwd=launch_dir ) stdout_bytes = process.communicate(input=submission_input_string)[0] stdout_string = stdout_bytes.decode("utf-8") print(stdout_string) # handle interactive run # Note: We call interpreter rather than trying to directly execute # job file since this saves us from bothering with execute permissions. # But, beware the interpreter enforced by the script's shebang line might # be different from the version of the interpreter found in the below invocation, # especially in a "module" environment. elif (run_mode == "local"): if (extension == ".py"): popen_args = [python_executable, job_file] elif (extension == ".csh"): popen_args = ["csh", job_file] print() print("-"*64) process = subprocess.Popen(popen_args, cwd=launch_dir, env=job_environ) process.wait()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 37811, 80, 7266, 76, 1377, 14276, 16834, 14498, 329, 4876, 12, 17107, 15458, 14750, 628, 220, 220, 220, 9344, 9633, 25, 628, 220, 220, 220, 13122, 6173, 46023, 62, 34720, 815, 11986, 262,...
3.079816
6,302
from ctypes import * Node._fields_ = [ ("leaf", c_int), ("g", c_float), ("min_samples", c_int), ("split_ind", c_int), ("split", c_float), ("left", POINTER(Node)), ("right", POINTER(Node))] trees = CDLL("./trees.so") trees.get_root.argtypes = (c_int, ) trees.get_root.restype = POINTER(Node) if __name__ == '__main__': tree = Tree()
[ 6738, 269, 19199, 1330, 1635, 198, 19667, 13557, 25747, 62, 796, 685, 198, 220, 220, 220, 5855, 33201, 1600, 269, 62, 600, 828, 198, 220, 220, 220, 5855, 70, 1600, 269, 62, 22468, 828, 198, 220, 220, 220, 5855, 1084, 62, 82, 12629, ...
2.197605
167
# Copyright 2016-present CERN European Organization for Nuclear Research # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qf_lib.backtesting.contract.contract import Contract from qf_lib.backtesting.order.execution_style import ExecutionStyle from qf_lib.backtesting.order.time_in_force import TimeInForce
[ 2, 220, 220, 220, 220, 15069, 1584, 12, 25579, 327, 28778, 220, 3427, 12275, 329, 19229, 4992, 198, 2, 198, 2, 220, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 2...
3.376984
252
# coding: utf-8 """ Pure Storage FlashBlade REST 1.12 Python SDK Pure Storage FlashBlade REST 1.12 Python SDK. Compatible with REST API versions 1.0 - 1.12. Developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/). OpenAPI spec version: 1.12 Contact: info@purestorage.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, MultiProtocolRule): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 17129, 20514, 9973, 47520, 30617, 352, 13, 1065, 11361, 26144, 628, 220, 220, 220, 17129, 20514, 9973, 47520, 30617, 352, 13, 1065, 11361, 26144, 13, 3082, 16873, 35...
2.641089
404
import pytest from tests.actions.support.mouse import assert_move_to_coordinates, get_center from tests.actions.support.refine import get_events, filter_dict _DBLCLICK_INTERVAL = 640 # Using local fixtures because we want to start a new session between # each test, otherwise the clicks in each test interfere with each other. def test_dblclick_with_pause_after_second_pointerdown(dblclick_session, mouse_chain): outer = dblclick_session.find.css("#outer", all=False) center = get_center(outer.rect) mouse_chain \ .pointer_move(int(center["x"]), int(center["y"])) \ .click() \ .pointer_down() \ .pause(_DBLCLICK_INTERVAL + 10) \ .pointer_up() \ .perform() events = get_events(dblclick_session) expected = [ {"type": "mousedown", "button": 0}, {"type": "mouseup", "button": 0}, {"type": "click", "button": 0}, {"type": "mousedown", "button": 0}, {"type": "mouseup", "button": 0}, {"type": "click", "button": 0}, {"type": "dblclick", "button": 0}, ] assert len(events) == 8 filtered_events = [filter_dict(e, expected[0]) for e in events] assert expected == filtered_events[1:] def test_no_dblclick(dblclick_session, mouse_chain): outer = dblclick_session.find.css("#outer", all=False) center = get_center(outer.rect) mouse_chain \ .pointer_move(int(center["x"]), int(center["y"])) \ .click() \ .pause(_DBLCLICK_INTERVAL + 10) \ .click() \ .perform() events = get_events(dblclick_session) expected = [ {"type": "mousedown", "button": 0}, {"type": "mouseup", "button": 0}, {"type": "click", "button": 0}, {"type": "mousedown", "button": 0}, {"type": "mouseup", "button": 0}, {"type": "click", "button": 0}, ] assert len(events) == 7 filtered_events = [filter_dict(e, expected[0]) for e in events] assert expected == filtered_events[1:]
[ 11748, 12972, 9288, 198, 198, 6738, 5254, 13, 4658, 13, 11284, 13, 35888, 1330, 6818, 62, 21084, 62, 1462, 62, 37652, 17540, 11, 651, 62, 16159, 198, 6738, 5254, 13, 4658, 13, 11284, 13, 5420, 500, 1330, 651, 62, 31534, 11, 8106, 62...
2.176
1,000
from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from utils import convert_timestamp from rasa_sdk.events import AllSlotsReset import datetime from datetime import timedelta, date import dateutil.parser import boto3 from boto3.dynamodb.conditions import Key # class ActionHelloWorld(Action): # # def name(self) -> Text: # return "action_hello_world" # # def run(self, dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # dispatcher.utter_message(text="Hello World!") # return [] # class ActionSearchRestaurant(Action): # def name(self) -> Text: # return "action_search_restaurant" # def run(self, dispatcher: CollectingDispatcher, # tracker: Tracker, # domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # entities = tracker.latest_message['entities'] # print(entities) # for e in entities: # if e['entity'] == 'type': # name = e['value'] # if name == 'indian': # message = "Items: Indian1, Indian2, Indian3, Indian4" # dispatcher.utter_message(text=message) # return [] param_arr = ["salinity", "solarRad", "airTemp", "aeration", "potassium", "moisture", "soilTemp", "respiration", "pressure", "phosphorus", "pH", "humidity", "nitrogen", "evapotranspiration(ET)"]
[ 6738, 19720, 1330, 4377, 11, 8255, 11, 360, 713, 11, 7343, 198, 6738, 374, 15462, 62, 21282, 74, 1330, 7561, 11, 26885, 198, 6738, 374, 15462, 62, 21282, 74, 13, 18558, 38409, 1330, 9745, 278, 7279, 8071, 2044, 198, 6738, 3384, 4487, ...
2.571956
542
from scripts.downloader import * import fiona from shapely.geometry import shape import geopandas as gpd import matplotlib.pyplot as plt from pprint import pprint import requests import json import time import os # Constant variables input_min_lat = 50.751797561 input_min_lon = 5.726110232 input_max_lat = 50.938216069 input_max_lon = 6.121604582 route_search_url = "https://api.routeyou.com/2.0/json/Route/k-9aec2fc1705896b901c3ea17d6223f0a/mapSearch" route_search_headers = {"Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "nl,en-US;q=0.7,en;q=0.3", "Connection": "keep-alive", "Content-Length": "331", "Content-Type": "text/plain;charset=UTF-8", "DNT": "1", "Host": "api.routeyou.com", "Origin": "https://www.routeyou.com", "Referer": "https://www.routeyou.com/route/search/2/walking-route-search", "TE": "Trailers", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0"} default_headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "nl,en-US;q=0.7,en;q=0.3", "Connection": "test", "Cookie": "rtysid=5gf59rik6gf8o7b5an7nalcsh0; " "_ga=GA1.2.1811204879.1553438381; _" "gid=GA1.2.1815573989.1553438381; __" "gads=ID=fab95f7aaf65227e:T=1553438384:S=ALNI_MaIjkdo1dKpYiyQKfWZEymqT7HgUQ", "Host": "download.routeyou.com", "Referer": "https://www.routeyou.com/nl-be/route/view/5653357/wandelroute/" "in-het-spoor-van-napoleon-kasteel-reinhardstein-en-de-stuwdam-van-robertville", "TE": "Trailers", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"} # # Setup script # bounding_boxes_list = create_bounding_boxes(input_min_lat, input_min_lon, input_max_lat, input_max_lon, # nr_of_rows=12, nr_of_columns=12) # for index, bounding_box in enumerate(bounding_boxes_list): # route_search_data = '{"jsonrpc":"2.0","id":"3","method":"searchAdvanced","params":' \ # '[{"bounds":{"min":{"lat":%s,"lon":%s},"max":{"lat":%s,"lon":%s}},' \ # '"type.id":2,"score.min":0.5,"bounds.comparator":"geometry"},null,100,0,' \ # '{"clusters":false,"addLanguage":"en","media":false,"description":false}]}' \ # % (bounding_box['min_lat'], bounding_box['min_lon'], bounding_box['max_lat'], bounding_box['max_lon']) # response = requests.post(url=route_search_url, headers=route_search_headers, # data=route_search_data) # with open("D:/Wandelroutes/Text/routes_{}.txt".format(index), "wb") as file: # file.write(response.content) # data = json.loads(response.content) # print("Index / routes count / total routes: ", index, "/", len(data['result']['routes']), "/", data['result']['total']) # # for route in data['result']['routes']: # time.sleep(0.5) # route_url = "https://download.routeyou.com/k-9aec2fc1705896b901c3ea17d6223f0a/route/{}.gpx?language=nl".format(route['id']) # filepath = "D:/Wandelroutes/GPX/{}.gpx".format(route['id']) # download_to_file(route_url, default_headers, filepath) dir_filepath = "D:/Wandelroutes/GPX" filenames = os.listdir(dir_filepath) rows_list = [] for filename in filenames: layer = fiona.open(os.path.join(dir_filepath, filename), layer='tracks') geom = layer[0] route_name = geom['properties']['name'] route_geodata = {'type': 'MultiLineString', 'coordinates': geom['geometry']['coordinates']} route_geometry = shape(route_geodata) route_id = os.path.splitext(os.path.basename(filename))[0] route_dict = {'id': str(route_id), 'name': route_name, 'url': "https://www.routeyou.com/nl-nl/route/view/" + str(route_id), 'geometry': route_geometry} rows_list.append(route_dict) routes_gdf = gpd.GeoDataFrame(rows_list) routes_gdf.crs = {'init': 'epsg:4326', 'no_defs': True} routes_gdf.to_file("D:/Wandelroutes/walking_routes.shp")
[ 6738, 14750, 13, 15002, 263, 1330, 1635, 198, 11748, 277, 32792, 198, 6738, 5485, 306, 13, 469, 15748, 1330, 5485, 198, 11748, 30324, 392, 292, 355, 27809, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2...
1.905691
2,460
""" Script for serving a trained chatbot model over http """ import datetime import click from os import path from flask import Flask, request, send_from_directory from flask_cors import CORS from flask_restful import Resource, Api import general_utils import chat_command_handler from chat_settings import ChatSettings from chatbot_model import ChatbotModel from vocabulary import Vocabulary app = Flask(__name__) CORS(app)
[ 37811, 198, 7391, 329, 7351, 257, 8776, 8537, 13645, 2746, 625, 2638, 198, 37811, 198, 11748, 4818, 8079, 198, 11748, 3904, 198, 6738, 28686, 1330, 3108, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 3758, 62, 6738, 62, 34945, 198, 6738,...
3.803571
112
import twilltestlib import twill from twill import namespaces, commands from twill.errors import TwillAssertionError from mechanize import BrowserStateError
[ 11748, 665, 359, 9288, 8019, 198, 11748, 665, 359, 198, 6738, 665, 359, 1330, 3891, 43076, 11, 9729, 198, 6738, 665, 359, 13, 48277, 1330, 1815, 359, 8021, 861, 295, 12331, 198, 6738, 3962, 1096, 1330, 34270, 9012, 12331, 628, 198 ]
3.878049
41
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import pybind a = pybind.vec3(1.0, 2.0, 3.0) b = pybind.vec3(2.0, 1.0, 3.0) t1 = test(pybind.dot) t2 = test(dummy) print t1/t2
[ 2, 15069, 2813, 20320, 43050, 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, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.157205
229
enru=open('en-ru.txt','r') input=open('input.txt','r') output=open('output.txt','w') s=enru.read() x='' prov={'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'} slovar={} s=s.replace('\t-\t',' ') while len(s)>0: slovar[s[:s.index(' ')]]=s[s.index(' '):s.index('\n')] s=s[s.index('\n')+1:] print(slovar) s=input.read() s=s.lower() while len(s)>0: a=s[0] if a not in prov: if x in slovar: print(slovar[x],a, file=output, sep='',end='') else: print(x,a, file=output, sep='',end='') x='' else: x+=a s=s[1:]
[ 268, 622, 28, 9654, 10786, 268, 12, 622, 13, 14116, 41707, 81, 11537, 198, 15414, 28, 9654, 10786, 15414, 13, 14116, 41707, 81, 11537, 198, 22915, 28, 9654, 10786, 22915, 13, 14116, 41707, 86, 11537, 198, 82, 28, 268, 622, 13, 961, ...
1.719895
382
#!/usr/bin/env python """ Siamese networks ================ """ import random import numpy as np import matplotlib.pyplot as plt from matplotlib import offsetbox import deeppy as dp # Fetch MNIST data dataset = dp.dataset.MNIST() x_train, y_train, x_test, y_test = dataset.data(flat=True, dp_dtypes=True) # Normalize pixel intensities scaler = dp.StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) # Generate image pairs n_pairs = 100000 x1 = np.empty((n_pairs, 28*28), dtype=dp.float_) x2 = np.empty_like(x1, dtype=dp.float_) y = np.empty(n_pairs, dtype=dp.int_) n_imgs = x_train.shape[0] n = 0 while n < n_pairs: i = random.randint(0, n_imgs-1) j = random.randint(0, n_imgs-1) if i == j: continue x1[n, ...] = x_train[i] x2[n, ...] = x_train[j] if y_train[i] == y_train[j]: y[n] = 1 else: y[n] = 0 n += 1 # Prepare network inputs train_input = dp.SupervisedSiameseInput(x1, x2, y, batch_size=128) # Setup network w_gain = 1.5 w_decay = 1e-4 net = dp.SiameseNetwork( siamese_layers=[ dp.FullyConnected( n_out=1024, weights=dp.Parameter(dp.AutoFiller(w_gain), weight_decay=w_decay), ), dp.ReLU(), dp.FullyConnected( n_out=1024, weights=dp.Parameter(dp.AutoFiller(w_gain), weight_decay=w_decay), ), dp.ReLU(), dp.FullyConnected( n_out=2, weights=dp.Parameter(dp.AutoFiller(w_gain)), ), ], loss=dp.ContrastiveLoss(margin=1.0), ) # Train network trainer = dp.StochasticGradientDescent( max_epochs=15, learn_rule=dp.RMSProp(learn_rate=0.01), ) trainer.train(net, train_input) # Plot 2D embedding test_input = dp.Input(x_test) x_test = np.reshape(x_test, (-1,) + dataset.img_shape) feat = net.features(test_input) feat -= np.min(feat, 0) feat /= np.max(feat, 0) plt.figure() ax = plt.subplot(111) shown_images = np.array([[1., 1.]]) for i in range(feat.shape[0]): dist = np.sum((feat[i] - shown_images)**2, 1) if np.min(dist) < 6e-4: # don't show points that are too close continue shown_images = np.r_[shown_images, [feat[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(x_test[i], zoom=0.6, cmap=plt.cm.gray_r), xy=feat[i], frameon=False ) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) plt.title('Embedding from the last layer of the network')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 42801, 1047, 68, 7686, 198, 4770, 198, 198, 37811, 198, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, ...
2.069109
1,201
# # 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. # """ Integration tests for pySparkling for Spark running in YARN mode """ from integ_test_utils import IntegTestSuite import test_utils if __name__ == '__main__': test_utils.run_tests([YarnIntegTestSuite], file_name="py_integ_yarn_tests_report")
[ 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428, 670, 329, 3224, 1321, 5115, 6634, 9238, 13, 198, 2, 383, ...
3.714286
280
from twisted.internet import defer, task from twisted.python.failure import Failure from exchanges.base import ExchangeService from exchange import calcVirtualOrderBooks import copy import time if __name__ == '__main__': from exchanges.bitfinex.BitfinexService import bitfinex VirtualExchange(bitfinex, ('ETH',) )
[ 6738, 19074, 13, 37675, 1330, 29135, 11, 4876, 198, 6738, 19074, 13, 29412, 13, 32165, 495, 1330, 25743, 198, 198, 6738, 14525, 13, 8692, 1330, 12516, 16177, 198, 6738, 5163, 1330, 42302, 37725, 18743, 30650, 198, 198, 11748, 4866, 198, ...
3.6
90
import os from schema import Or from testplan.common.config import ConfigOption from ..base import ProcessRunnerTest, ProcessRunnerTestConfig from ...importers.cppunit import CPPUnitResultImporter, CPPUnitImportedResult
[ 11748, 28686, 198, 198, 6738, 32815, 1330, 1471, 198, 198, 6738, 1332, 11578, 13, 11321, 13, 11250, 1330, 17056, 19722, 198, 198, 6738, 11485, 8692, 1330, 10854, 49493, 14402, 11, 10854, 49493, 14402, 16934, 198, 6738, 2644, 320, 1819, 10...
3.813559
59
import discord.ext.commands as dec import database.song from commands.common import *
[ 11748, 36446, 13, 2302, 13, 9503, 1746, 355, 875, 198, 198, 11748, 6831, 13, 34050, 198, 6738, 9729, 13, 11321, 1330, 1635, 628 ]
3.826087
23
""" main.py Main driver for the Linear Error Analysis program. Can be run using `lea.sh`. Can choose which plots to see by toggling on/off `show_fig` param. Author(s): Adyn Miles, Shiqi Xu, Rosie Liang """ import os import matplotlib.pyplot as plt import numpy as np import config import libs.gta_xch4 as gta_xch4 import libs.photon_noise as pn from errors import Errors from forward import Forward from isrf import ISRF from optim import Optim if __name__ == "__main__": cfg = config.parse_config() forward = Forward(cfg) surface, molec, atm, sun_lbl = forward.get_atm_params() optics = forward.opt_properties() ( wave_meas, rad_tot, rad_ch4, rad_co2, rad_h2o, d_rad_ch4, d_rad_co2, d_rad_h2o, rad_conv_tot, rad_conv_ch4, rad_conv_co2, rad_conv_h2o, dev_conv_ch4, dev_conv_co2, dev_conv_h2o, ) = forward.plot_transmittance(show_fig=False) state_vector = forward.produce_state_vec() isrf = ISRF(cfg) isrf_func = isrf.define_isrf(show_fig=False) isrf_conv = isrf.convolve_isrf(rad_tot, show_fig=False) lea = Errors(cfg, wave_meas) sys_errors = lea.sys_errors() rand_errors = lea.rand_errors() # sys_nonlinearity = lea.sys_err_vector(1) # sys_stray_light = lea.sys_err_vector(2) # sys_crosstalk = lea.sys_err_vector(3) # sys_flat_field = lea.sys_err_vector(4) # sys_bad_px = lea.sys_err_vector(5) # sys_key_smile = lea.sys_err_vector(6) # sys_striping = lea.sys_err_vector(7) # sys_memory = lea.sys_err_vector(8) ecm = lea.error_covariance() path_root = os.path.dirname(os.path.dirname(__file__)) np.savetxt(os.path.join(path_root, "outputs", "ecm.csv"), ecm, delimiter=",") optim = Optim(cfg, wave_meas) jacobian = optim.jacobian(dev_conv_ch4, dev_conv_co2, dev_conv_h2o, show_fig=False) gain = optim.gain(ecm) modified_meas_vector = optim.modify_meas_vector(state_vector, rad_conv_tot, ecm) spectral_res, snr = optim.state_estimate(ecm, modified_meas_vector, sys_errors) print("Estimated Solution: " + str(spectral_res)) print("Uncertainty of Solution: " + str(snr)) # plot interpolated photon noise # plt.plot(lea.wave_meas, lea.photon_noise_interp) # plt.title("Interpolated Photon Noise") # plt.xlabel("Wavelength (nm)") # plt.ylabel("Photon Noise (UNITS?)") # TODO # plt.show()
[ 37811, 198, 12417, 13, 9078, 198, 198, 13383, 4639, 329, 262, 44800, 13047, 14691, 1430, 13, 198, 6090, 307, 1057, 1262, 4600, 293, 64, 13, 1477, 44646, 198, 6090, 3853, 543, 21528, 284, 766, 416, 284, 1130, 1359, 319, 14, 2364, 4600,...
2.180212
1,132
"""Enum for amino acid.""" from enum import Enum from typing import Dict, TypedDict amino_acid: Dict[str, AminoAcidProperty] = { "A": { "code": AminoAcidToInt["A"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": 1.8, "acidity_basicity": AcidityBasicity["U"].value, "mass": 89.09, "isoelectric_point": 6.00, "charge": Charge["U"].value, }, "C": { "code": AminoAcidToInt["C"].value, "hydropathy": Hydropathy["M"].value, "hydropathy_index": 2.5, "acidity_basicity": AcidityBasicity["U"].value, "mass": 121.16, "isoelectric_point": 5.02, "charge": Charge["U"].value, }, "D": { "code": AminoAcidToInt["D"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -3.5, "acidity_basicity": AcidityBasicity["A"].value, "mass": 133.10, "isoelectric_point": 2.77, "charge": Charge["N"].value, }, "E": { "code": AminoAcidToInt["E"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -3.5, "acidity_basicity": AcidityBasicity["A"].value, "mass": 147.13, "isoelectric_point": 3.22, "charge": Charge["N"].value, }, "F": { "code": AminoAcidToInt["F"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": 2.8, "acidity_basicity": AcidityBasicity["U"].value, "mass": 165.19, "isoelectric_point": 5.44, "charge": Charge["U"].value, }, "G": { "code": AminoAcidToInt["G"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": -0.4, "acidity_basicity": AcidityBasicity["U"].value, "mass": 75.07, "isoelectric_point": 5.97, "charge": Charge["U"].value, }, "H": { "code": AminoAcidToInt["H"].value, "hydropathy": Hydropathy["M"].value, "hydropathy_index": -3.2, "acidity_basicity": AcidityBasicity["B"].value, "mass": 155.16, "isoelectric_point": 7.47, "charge": Charge["P"].value, }, "I": { "code": AminoAcidToInt["I"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": 4.5, "acidity_basicity": AcidityBasicity["U"].value, "mass": 131.8, "isoelectric_point": 5.94, "charge": Charge["U"].value, }, "K": { "code": AminoAcidToInt["K"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -3.9, "acidity_basicity": AcidityBasicity["B"].value, "mass": 146.19, "isoelectric_point": 9.59, "charge": Charge["P"].value, }, "L": { "code": AminoAcidToInt["L"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": 3.8, "acidity_basicity": AcidityBasicity["U"].value, "mass": 131.18, "isoelectric_point": 5.98, "charge": Charge["U"].value, }, "M": { "code": AminoAcidToInt["M"].value, "hydropathy": Hydropathy["M"].value, "hydropathy_index": 1.9, "acidity_basicity": AcidityBasicity["U"].value, "mass": 149.21, "isoelectric_point": 5.74, "charge": Charge["U"].value, }, "N": { "code": AminoAcidToInt["N"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -3.5, "acidity_basicity": AcidityBasicity["U"].value, "mass": 132.12, "isoelectric_point": 5.41, "charge": Charge["U"].value, }, "P": { "code": AminoAcidToInt["P"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": -1.6, "acidity_basicity": AcidityBasicity["U"].value, "mass": 115.13, "isoelectric_point": 6.30, "charge": Charge["U"].value, }, "Q": { "code": AminoAcidToInt["Q"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -3.5, "acidity_basicity": AcidityBasicity["U"].value, "mass": 146.15, "isoelectric_point": 5.65, "charge": Charge["N"].value, }, "R": { "code": AminoAcidToInt["R"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -4.5, "acidity_basicity": AcidityBasicity["B"].value, "mass": 174.20, "isoelectric_point": 11.15, "charge": Charge["P"].value, }, "S": { "code": AminoAcidToInt["S"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -0.8, "acidity_basicity": AcidityBasicity["U"].value, "mass": 165.09, "isoelectric_point": 5.68, "charge": Charge["U"].value, }, "T": { "code": AminoAcidToInt["T"].value, "hydropathy": Hydropathy["HL"].value, "hydropathy_index": -0.7, "acidity_basicity": AcidityBasicity["U"].value, "mass": 119.12, "isoelectric_point": 5.64, "charge": Charge["U"].value, }, "V": { "code": AminoAcidToInt["V"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": 4.2, "acidity_basicity": AcidityBasicity["U"].value, "mass": 117.15, "isoelectric_point": 5.96, "charge": Charge["U"].value, }, "W": { "code": AminoAcidToInt["W"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": -0.9, "acidity_basicity": AcidityBasicity["U"].value, "mass": 204.23, "isoelectric_point": 5.89, "charge": Charge["U"].value, }, "Y": { "code": AminoAcidToInt["Y"].value, "hydropathy": Hydropathy["HB"].value, "hydropathy_index": -1.3, "acidity_basicity": AcidityBasicity["U"].value, "mass": 181.19, "isoelectric_point": 5.66, "charge": Charge["U"].value, }, }
[ 37811, 4834, 388, 329, 23206, 7408, 526, 15931, 198, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 360, 713, 11, 17134, 276, 35, 713, 628, 628, 628, 198, 198, 321, 2879, 62, 46309, 25, 360, 713, 58, 2536, 11, 39869, 78,...
1.891627
3,165
import logging import os import re import sublime # external dependencies (see dependencies.json) import jsonschema import yaml # pyyaml # This plugin generates a hidden syntax file containing rules for additional # chainloading commands defined by the user. The syntax is stored in the cache # directory to avoid the possibility of it falling under user version control in # the usual packages directory userSyntaxName = 'execline-user-chainload.sublime-syntax' pkgName = 'execline' settingsName = 'execline.sublime-settings' mainSyntaxPath = 'Packages/{}/execline.sublime-syntax'.format(pkgName) schemaPath = 'Packages/{}/execline.sublime-settings.schema.json'.format(pkgName) ruleNamespaces = { 'keyword': 'keyword.other', 'function': 'support.function', } ruleContexts = { 'argument': { 'generic': 'command-call-common-arg-aside-&pop', 'variable': 'command-call-common-variable-&pop', 'pattern': 'command-call-common-glob-&pop', }, 'block': { 'program': 'block-run-prog', 'arguments': 'block-run-arg', 'trap': 'block-trap', 'multidefine': 'block-multidefine', }, 'options': { 'list': 'command-call-common-opt-list-&pop', 'list-with-args': { 'match': '(?=-[{}])', 'push': 'command-call-common-opt-arg-&pop', 'include': 'command-call-common-opt-list-&pop', }, }, } logging.basicConfig() logger = logging.getLogger(__name__) # Fully resolve the name of a context in the main syntax file # Create a match rule describing a command of a certain type, made of a list of # elements
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 41674, 198, 198, 2, 7097, 20086, 357, 3826, 20086, 13, 17752, 8, 198, 11748, 44804, 684, 2395, 2611, 198, 11748, 331, 43695, 1303, 12972, 88, 43695, 628, 198, 2, 770, 13877, ...
2.894834
542
import os import numpy as np import sys sys.path.append("../") for model in ['lenet1', 'lenet4', 'lenet5']: for attack in ['fgsm', 'cw', 'jsma']: for mu_var in ['gf', 'nai', 'ns', 'ws']: os.system('CUDA_VISIBLE_DEVICES=0 python retrain_mu_mnist.py --datasets=mnist --attack=' + attack + ' --model_name=' + model + ' --mu_var=' + mu_var + ' --epochs=50')
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 4943, 198, 198, 1640, 2746, 287, 37250, 11925, 316, 16, 3256, 705, 11925, 316, 19, 3256, 705, 11925, 316, 20, 6, 5974, ...
2.290909
165
#!/usr/bin/env python3 from __future__ import print_function import gzip import json import re import sys # import time from argparse import ArgumentParser # from datetime import datetime TWITTER_TS_FORMAT = '%a %b %d %H:%M:%S +0000 %Y' #Tue Apr 26 08:57:55 +0000 2011 # def parse_ts(ts_str, fmt=TWITTER_TS_FORMAT): # try: # time_struct = time.strptime(ts_str, fmt) # except TypeError: # return int(ts_str) # epoch millis # return datetime.fromtimestamp(time.mktime(time_struct)) def extract_text(tweet): """Gets the full text from a tweet if it's short or long (extended).""" if 'retweeted_status' in tweet: rt = tweet['retweeted_status'] return extract_text(rt) # return 'RT @%s: %s' % (rt['user']['screen_name'], extract_text(rt)) # if 'quoted_status' in tweet: # qt = tweet['quoted_status'] # return get_available_text(tweet) + " --> " + extract_text(qt) return get_available_text(tweet) def fetch_lines(file=None): """Gets the lines from the given file or stdin if it's None or '' or '-'.""" if file and file != '-': with gzip.open(file, 'rt') if file[-1] in 'zZ' else open(file, 'r', encoding='utf-8') as f: return [l.strip() for l in f.readlines()] else: return [l.strip() for l in sys.stdin] def eprint(*args, **kwargs): """Print to stderr""" print(*args, file=sys.stderr, **kwargs) DEBUG=False if __name__=='__main__': options = Options() opts = options.parse(sys.argv[1:]) DEBUG=opts.verbose tweets_file = opts.tweets_file # pretty = opts.pretty tweets = [json.loads(l) for l in fetch_lines(tweets_file)] log(f'read: {len(tweets)} tweets') hashtags_only = 0 hashtags_plus_url = 0 mentions_plus_hashtags = 0 mentions_hashtags_plus_url = 0 ht_splitter_re = '[a-zA-Z#]+' me_splitter_re = '[a-zA-Z@]+' htme_splitter_re = '[a-zA-Z#@]+' X = 0 for t in tweets: text = extract_text(t) # hashtag(s) only if '#' in text: tokens = extract_tokens(ht_splitter_re, text) if len(tokens) == count_tokens_starting_with('#', tokens): hashtags_only += 1 log(tokens) # hashtag(s) and URL if '#' in text and 'http' in text: tokens = extract_tokens(htme_splitter_re, text[:text.index('http')]) if len(tokens) == count_tokens_starting_with('#', tokens): hashtags_plus_url += 1 # print(tokens) log(text) # mention(s) and hashtag(s) if '#' in text and '@' in text: tokens = extract_tokens(htme_splitter_re, text) if len(tokens) == count_tokens_starting_with('#@', tokens): mentions_plus_hashtags += 1 log(tokens) # mention(s), hashtag(s) and URL if '#' in text and '@' in text and 'http' in text: tokens = extract_tokens(htme_splitter_re, text[:text.index('http')]) if len(tokens) == count_tokens_starting_with('#@', tokens): mentions_hashtags_plus_url += 1 # print(tokens) log(text) print(f'All: {len(tweets):,}') print(f'HT: {hashtags_only:>6} ({float(hashtags_only)/len(tweets):.1%})') print(f'HT+URL: {hashtags_plus_url:>6} ({float(hashtags_plus_url)/len(tweets):.1%})') print(f'@m+HT: {mentions_plus_hashtags:>6} ({float(mentions_plus_hashtags)/len(tweets):.1%})') print(f'@m+HT+URL: {mentions_hashtags_plus_url:>6} ({float(mentions_hashtags_plus_url)/len(tweets):.1%})')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 308, 13344, 198, 11748, 33918, 198, 11748, 302, 198, 11748, 25064, 198, 2, 1330, 640, 198, 198, 6738, 1822, 29572, 1...
2.090909
1,749
import inspect import hashlib import logging import os from django.core.files.uploadedfile import TemporaryUploadedFile from django.db.models import FieldDoesNotExist from django.db.models.fields.files import FileField from django.http import QueryDict from django.utils.datastructures import MultiValueDict logger = logging.getLogger(__name__) def parse_distutils_request(request): """Parse the `request.body` and update the request POST and FILES attributes . """ sep = request.body.splitlines()[1] request.POST = QueryDict('', mutable=True) try: request._files = MultiValueDict() except Exception: pass for part in filter(lambda e: e.strip(), request.body.split(sep)): try: header, content = part.lstrip().split('\n', 1) except Exception: continue if content.startswith('\n'): content = content[1:] if content.endswith('\n'): content = content[:-1] headers = parse_header(header) if "name" not in headers: continue if "filename" in headers and headers['name'] == 'content': dist = TemporaryUploadedFile(name=headers["filename"], size=len(content), content_type="application/gzip", charset='utf-8') dist.write(content) dist.seek(0) request.FILES.appendlist('distribution', dist) else: # Distutils sends UNKNOWN for empty fields (e.g platform) # [russell.sim@gmail.com] if content == 'UNKNOWN': content = None request.POST.appendlist(headers["name"], content) def delete_files(sender, **kwargs): """Signal callback for deleting old files when database item is deleted""" for fieldname in sender._meta.get_all_field_names(): try: field = sender._meta.get_field(fieldname) except FieldDoesNotExist: continue if isinstance(field, FileField): instance = kwargs['instance'] fieldfile = getattr(instance, fieldname) if not hasattr(fieldfile, 'path'): return if not os.path.exists(fieldfile.path): return # Check if there are other instances which reference this fle is_referenced = ( instance.__class__._default_manager .filter(**{'%s__exact' % fieldname: fieldfile}) .exclude(pk=instance._get_pk_val()) .exists()) if is_referenced: return try: field.storage.delete(fieldfile.path) except Exception: logger.exception( 'Error when trying to delete file %s of package %s:' % ( instance.pk, fieldfile.path)) def md5_hash_file(fh): """Return the md5 hash of the given file-object""" md5 = hashlib.md5() while True: data = fh.read(8192) if not data: break md5.update(data) return md5.hexdigest()
[ 11748, 10104, 198, 11748, 12234, 8019, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 16624, 13, 25850, 276, 7753, 1330, 46042, 41592, 276, 8979, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 7663,...
2.118421
1,520
# coding=utf-8 from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from bika.lims.browser.bika_listing import BikaListingTable from bika.lims.browser.worksheet.views.analyses import AnalysesView
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 18675, 13, 20029, 13, 40259, 13, 79, 363, 316, 368, 6816, 7753, 1330, 3582, 9876, 30800, 8979, 198, 6738, 275, 9232, 13, 2475, 82, 13, 40259, 13, 65, 9232, 62, 4868, 278, 1330, 347, 9232, 80...
3.144928
69
from rest_framework import viewsets from .models import User, Photo from .serializers import UserSerializer, PhotoSerializer from .mixins import RequestLogViewMixin from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
[ 6738, 1334, 62, 30604, 1330, 5009, 1039, 198, 6738, 764, 27530, 1330, 11787, 11, 5555, 198, 6738, 764, 46911, 11341, 1330, 11787, 32634, 7509, 11, 5555, 32634, 7509, 198, 6738, 764, 19816, 1040, 1330, 19390, 11187, 7680, 35608, 259, 198, ...
4.426667
75
b = input().split() N = int(input()) a = [input() for _ in range(N)] t = {b[i]: str(i) for i in range(10)} a.sort(key = lambda x: conv(x)) print(*a, sep='\n')
[ 198, 65, 796, 5128, 22446, 35312, 3419, 198, 45, 796, 493, 7, 15414, 28955, 198, 64, 796, 685, 15414, 3419, 329, 4808, 287, 2837, 7, 45, 15437, 198, 198, 83, 796, 1391, 65, 58, 72, 5974, 965, 7, 72, 8, 329, 1312, 287, 2837, 7, ...
2.236111
72
#!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages with open("README.adoc") as fh_readme: readme = fh_readme.read() install_reqs = [] setup( author="Sven Wilhelm", author_email='refnode@gmail.com', python_requires='>=3.8', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', ], description="Spartakiade 2021 Session Effective Python", install_requires=install_reqs, long_description=readme, include_package_data=True, keywords='spartakiade-2021-session-effective-python', name='spartakiade-2021-session-effective-python', packages=find_packages(where="src"), url='https://github.com/refnode/spartakiade-2021-session-effective-python', version='0.1.0', zip_safe=False, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 464, 9058, 4226, 526, 15931, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 324, 420, 4943, 355, 277, 71,...
2.629428
367
'''*-----------------------------------------------------------------------*--- Author: Jason Ma Date : Oct 18 2018 TODO File Name : pid.py Description: TODO ---*-----------------------------------------------------------------------*''' import time import matplotlib.animation as anim import matplotlib.pyplot as plt import threading import math import numpy as np '''[Global Vars]------------------------------------------------------------''' ORIGIN_X = 0.0 ORIGIN_Y = 0.0 C_R = 10 #plt.autoscale(enable=True, axis="both") fig = plt.figure() ax = fig.add_subplot(2,1,1) ax2 = fig.add_subplot(2,1,2) scat = ax.scatter([], []) ax.set_xlim([-1 * C_R - 1, C_R + 1]) ax.set_ylim([-1 * C_R - 1, C_R + 1]) scat.set_facecolors(['g', 'r']) scat.set_sizes([31, 31]) prev_time = time.time() vel = np.array([0.0, 0.0]) errors = [0, 1] error_plot, = ax2.plot([i for i in range(len(errors))], errors, color="g") d = drone([ORIGIN_X + C_R, ORIGIN_Y], [0.0, 0.0]) #def pid_angle(x, y, ref_x, ref_y, d): # return math.atan(-1 * (C_R - dist(x, y, ORIGIN_X, ORIGIN_Y)) / d) + math.atan((y - ORIGIN_Y) / (x - ORIGIN_X)) + math.pi / 2 if __name__ == '__main__': #main() a = anim.FuncAnimation(fig, update, range(1000), interval=1, blit=False, repeat=False) plt.show()
[ 7061, 6, 9, 10097, 26866, 9, 6329, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
2.188361
653
# Copyright 2021 Google LLC # # 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. """Fire Manager module. Used for CLI-specific commands and flags. Built to work with Python Fire: https://github.com/google/python-fire. """ import codecs import enum import inspect import json import logging import os.path import pydoc import re import sys import textwrap import time from typing import Any, Collection, Optional, Type from gazoo_device import config from gazoo_device import decorators from gazoo_device import errors from gazoo_device import gdm_logger from gazoo_device import manager from gazoo_device import package_registrar from gazoo_device import testbed from gazoo_device.utility import parallel_utils from gazoo_device.utility import usb_utils logger = gdm_logger.get_logger() HEALTHY_DEVICE_HEALTH = { "is_healthy": True, "unhealthy_reason": "", "err_type": "", "checks_passed": [], "properties": {} } MAX_TIME_TO_WAIT_FOR_INITATION = 5 _DOC_INDENT_SIZE = 4 # Capability attributes visible on device summary man page # (e.g. "man cambrionix"). _VISIBLE_CAPABILITY_ATTRIBUTES = [ AttributeClassification.PROPERTY, AttributeClassification.PUBLIC_METHOD ] def _log_man_warning_for_multiple_flavors( capability_classes: Collection[Type[Any]], capability_name: str, device_type: str, capability_class: Type[Any]) -> None: """Logs 'gdm man' warning when multiple capability flavors are available. Args: capability_classes: All available capability flavors. capability_name: Name of the capability. device_type: Type of the device with this capability. capability_class: Capability flavor selected to print documentation for. Capabilities can have multiple flavors in one device class, although this is somewhat rare. The flavor used is determined based on device firmware at runtime. Since we don't know which flavor will be used without an attached device, log a warning and print documentation for any single flavor. """ flavors = [a_cls.__name__ for a_cls in capability_classes] logger.warning( f"{len(flavors)} flavors ({flavors}) of capability {capability_name!r} " f"are available for {device_type}.\n" f"Showing documentation for flavor {capability_class}.\n")
[ 2, 15069, 33448, 3012, 11419, 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, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.307876
838
from __future__ import absolute_import, division import os import fitsio import argparse import numpy as np from desiutil.log import get_logger from desispec.io import read_fiberflat,write_fiberflat,findfile,read_frame from desispec.io.fiberflat_vs_humidity import get_humidity,read_fiberflat_vs_humidity from desispec.calibfinder import CalibFinder from desispec.fiberflat_vs_humidity import compute_humidity_corrected_fiberflat
[ 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 198, 198, 11748, 28686, 198, 11748, 11414, 952, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 748, 72, 22602, 13, 6404, 1330, 651, 62, 6404, ...
3.06338
142
IS_TEST = True REPOSITORY = 'cms-sw/cmssw' CERN_SSO_CERT_FILE = 'private/cert.pem' CERN_SSO_KEY_FILE = 'private/cert.key' CERN_SSO_COOKIES_LOCATION = 'private/' TWIKI_CONTACTS_URL = 'https://ppdcontacts.web.cern.ch/PPDContacts/ppd_contacts' TWIKI_TAG_COLLECTOR_URL = 'https://twiki.cern.ch/twiki/bin/edit/CMS/DQMP5TagCollector?nowysiwyg=1' TWIKI_TAG_COLLECTOR_CANCEL_EDIT_URL = 'https://twiki.cern.ch/twiki/bin/save/CMS/DQMP5TagCollector' CATEGORIES_MAP_URL = 'https://raw.githubusercontent.com/cms-sw/cms-bot/master/categories_map.py' TWIKI_TIMEOUT_SECONDS = 10 __github_client_id = None __github_client_secret = None
[ 1797, 62, 51, 6465, 796, 6407, 198, 198, 35316, 2640, 2043, 15513, 796, 705, 46406, 12, 2032, 14, 11215, 824, 86, 6, 198, 198, 34, 28778, 62, 5432, 46, 62, 34, 17395, 62, 25664, 796, 705, 19734, 14, 22583, 13, 79, 368, 6, 198, 3...
2.200704
284
from enum import Enum from typing import Generator, Tuple, Iterable, Dict, List import cv2 import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.ndimage import label, generate_binary_structure from scipy.ndimage.morphology import distance_transform_edt as dist_trans import trainer.lib as lib def split_into_regions(arr: np.ndarray, mode=0) -> List[np.ndarray]: """ Splits an array into its coherent regions. :param mode: 0 for orthogonal connection, 1 for full connection :param arr: Numpy array with shape [W, H] :return: A list with length #NumberOfRegions of arrays with shape [W, H] """ res = [] if mode == 0: rs, num_regions = label(arr) elif mode == 1: rs, num_regions = label(arr, structure=generate_binary_structure(2, 2)) else: raise Exception("Please specify a valid Neighborhood mode for split_into_regions") for i in range(1, num_regions + 1): res.append(rs == i) return res def normalize_im(im: np.ndarray, norm_type=ImageNormalizations.UnitRange) -> np.ndarray: """ Currently just normalizes an image with pixel intensities in range [0, 255] to [-1, 1] :return: The normalized image """ if norm_type == ImageNormalizations.UnitRange: return (im.astype(np.float32) / 127.5) - 1 else: raise Exception("Unknown Normalization type") def one_hot_to_cont(x: np.ndarray) -> np.ndarray: """ Convert a one hot encoded image into the same image with integer representations. :param x: np.ndarray with (C, W, H) :return: np.ndarray with (W, H) """ return np.argmax(x, axis=len(x.shape) - 3) def reduce_by_attention(arr: np.ndarray, att: np.ndarray): """ Reduce an array by a field of attention, such that the result is a rectangle with the empty borders cropped. :param arr: Target array. The last two dimensions need to be of the same shape as the attention field :param att: field of attention :return: cropped array """ assert arr.shape[-2] == att.shape[0] and arr.shape[-1] == att.shape[1] ones = np.argwhere(att) lmost, rmost = np.min(ones[:, 0]), np.max(ones[:, 0]) + 1 bmost, tmost = np.min(ones[:, 1]), np.max(ones[:, 1]) + 1 grid_slice = [slice(None) for _ in range(len(arr.shape) - 2)] grid_slice.extend([slice(lmost, rmost), slice(bmost, tmost)]) return arr[tuple(grid_slice)], att[lmost:rmost, bmost:tmost], (lmost, rmost, bmost, tmost) if __name__ == '__main__': fit = insert_np_at(np.ones((10, 10)), np.ones((3, 3)) * 2, (2, 3)) too_big1 = insert_np_at(np.ones((10, 10)), np.ones((3, 10)) * 2, (2, 3)) too_big = insert_np_at(np.ones((10, 10)), np.ones((10, 10)) * 2, (2, 3)) # def put_array(big_arr: np.ndarray, small_arr: np.ndarray, offset=(0, 0)) -> np.ndarray: # """ # Puts the small array into the big array. Ignores problems and does its best to fulfill the task # """ # b, t = # big_arr[] # big_arr = np.putmask(big_arr, ) # if __name__ == '__main__': # # a = np.zeros((10, 10)) # # b = np.random.random((4, 4)) # # c = put_array(a, b) # # lib.logger.debug_var(c)
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 35986, 11, 309, 29291, 11, 40806, 540, 11, 360, 713, 11, 7343, 198, 198, 11748, 269, 85, 17, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, ...
2.528108
1,263
from PyQt5.QtCore import Qt, pyqtSignal, QSize from PyQt5.QtWidgets import ( QLabel, QWidget, QTreeWidgetItem, QHeaderView, QVBoxLayout, QHBoxLayout, ) from .ImageLabel import ImageLabel from .AdaptiveTreeWidget import AdaptiveTreeWidget
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 33734, 11, 12972, 39568, 11712, 282, 11, 1195, 10699, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 357, 198, 220, 220, 220, 1195, 33986, 11, 1195, 38300, 11, 1195,...
2.755556
90
import argparse import data_helper from sklearn.model_selection import train_test_split import re import lstm from lstm import * import time from viterbi import Viterbi xrange = range def simple_cut(text,dh,lm,viterbi): """text""" if text: #print("text: %s" %text) text_len = len(text) X_batch = dh.text2ids(text) # batch fetches = [lm.y_pred] feed_dict = {lm.X_inputs:X_batch, lm.lr:1.0, lm.batch_size:1, lm.keep_prob:1.0} _y_pred = sess.run(fetches, feed_dict)[0][:text_len] # padding nodes = [dict(zip(['s','b','m','e'], each[1:])) for each in _y_pred] #print(type(dh.labels)) #print(dh.labels) tags = viterbi.viterbi(nodes) words = [] for i in range(len(text)): if tags[i] in ['s', 'b']: words.append(text[i]) else: words[-1] += text[i] return words else: return [] def cut_word(sentence,dh,lm,viterbi): """sentence/text""" not_cuts = re.compile(u'([0-9\da-zA-Z ]+)|[.\.\?,!]') result = [] start = 0 for seg_sign in not_cuts.finditer(sentence): result.extend(simple_cut(sentence[start:seg_sign.start()],dh,lm,viterbi)) result.append(sentence[seg_sign.start():seg_sign.end()]) start = seg_sign.end() result.extend(simple_cut(sentence[start:],dh,lm,viterbi)) return result if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 1366, 62, 2978, 525, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 11748, 302, 198, 11748, 300, 301, 76, 198, 6738, 300, 301, 76, 1330, 1635, 198, 11748, 640, 198, ...
1.989071
732
# -*- coding: utf-8 -*- """ Created on Sat Feb 24 23:18:54 2018 @author: Rupesh """ # Multiple Linear Regression import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.style.use("ggplot") # loading dependies df = pd.read_csv("50_Startups.csv") df.head() X = df.iloc[:, :-1].values y = df.iloc[:, 4].values from sklearn.preprocessing import LabelEncoder, OneHotEncoder X_cat = LabelEncoder() X[:, 3] = X_cat.fit_transform(X[:, 3]) onehot = OneHotEncoder(categorical_features = [3]) X = onehot.fit_transform(X).toarray() # avoiding the dummy variable trap X = X[:, 1:] # train test split from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) # model from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.fit(X_train, y_train) # predict y_pred = reg.predict(X_test) import skl
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 3158, 1987, 2242, 25, 1507, 25, 4051, 2864, 198, 198, 31, 9800, 25, 371, 929, 5069, 198, 37811, 628, 198, 198, 2, 20401, 220, 44800, 3310...
2.619718
355
#!/usr/bin/env python ''' Advent of Code 2021 - Day 9: Smoke Basin (Part 1) https://adventofcode.com/2021/day/9 ''' import numpy as np if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 198, 2782, 1151, 286, 6127, 33448, 532, 3596, 860, 25, 25416, 32666, 357, 7841, 352, 8, 198, 5450, 1378, 324, 1151, 1659, 8189, 13, 785, 14, 1238, 2481, 14, 820, 14, ...
2.4
75
"""Trigonometric and Hyperbolic Functions""" from typing import Callable import numpy from pipda import register_func from ..core.contexts import Context from ..core.types import FloatOrIter from .constants import pi def _register_trig_hb_func(name: str, np_name: str, doc: str) -> Callable: """Register trigonometric and hyperbolic function""" np_fun = getattr(numpy, np_name) if name.endswith("pi"): func = lambda x: np_fun(x * pi) else: # ufunc cannot set context func = lambda x: np_fun(x) func = register_func(None, context=Context.EVAL, func=func) func.__name__ = name func.__doc__ = doc return func sin = _register_trig_hb_func( "sin", "sin", doc="""The sine function Args: x: a numeric value or iterable Returns: The sine value of `x` """, ) cos = _register_trig_hb_func( "cos", "cos", doc="""The cosine function Args: x: a numeric value or iterable Returns: The cosine value of `x` """, ) tan = _register_trig_hb_func( "tan", "tan", doc="""The tangent function Args: x: a numeric value or iterable Returns: The tangent value of `x` """, ) acos = _register_trig_hb_func( "acos", "arccos", doc="""The arc-cosine function Args: x: a numeric value or iterable Returns: The arc-cosine value of `x` """, ) asin = _register_trig_hb_func( "acos", "arcsin", doc="""The arc-sine function Args: x: a numeric value or iterable Returns: The arc-sine value of `x` """, ) atan = _register_trig_hb_func( "acos", "arctan", doc="""The arc-sine function Args: x: a numeric value or iterable Returns: The arc-sine value of `x` """, ) sinpi = _register_trig_hb_func( "sinpi", "sin", doc="""The sine function Args: x: a numeric value or iterable, which is the multiple of pi Returns: The sine value of `x` """, ) cospi = _register_trig_hb_func( "cospi", "cos", doc="""The cosine function Args: x: a numeric value or iterable, which is the multiple of pi Returns: The cosine value of `x` """, ) tanpi = _register_trig_hb_func( "tanpi", "tan", doc="""The tangent function Args: x: a numeric value or iterable, which is the multiple of pi Returns: The tangent value of `x` """, ) cosh = _register_trig_hb_func( "cosh", "cosh", doc="""Hyperbolic cosine Args: x: a numeric value or iterable Returns: The hyperbolic cosine value of `x` """, ) sinh = _register_trig_hb_func( "sinh", "sinh", doc="""Hyperbolic sine Args: x: a numeric value or iterable Returns: The hyperbolic sine value of `x` """, ) tanh = _register_trig_hb_func( "tanh", "tanh", doc="""Hyperbolic tangent Args: x: a numeric value or iterable Returns: The hyperbolic tangent value of `x` """, ) acosh = _register_trig_hb_func( "acosh", "arccosh", doc="""Hyperbolic arc-cosine Args: x: a numeric value or iterable Returns: The hyperbolic arc-cosine value of `x` """, ) asinh = _register_trig_hb_func( "asinh", "arcsinh", doc="""Hyperbolic arc-sine Args: x: a numeric value or iterable Returns: The hyperbolic arc-sine value of `x` """, ) atanh = _register_trig_hb_func( "atanh", "arctanh", doc="""Hyperbolic arc-tangent Args: x: a numeric value or iterable Returns: The hyperbolic arc-tangent value of `x` """, )
[ 37811, 2898, 37107, 16996, 290, 15079, 65, 4160, 40480, 37811, 198, 198, 6738, 19720, 1330, 4889, 540, 198, 198, 11748, 299, 32152, 198, 6738, 7347, 6814, 1330, 7881, 62, 20786, 198, 198, 6738, 11485, 7295, 13, 22866, 82, 1330, 30532, 1...
2.292135
1,513
# Implementation of Randomised Selection """ Naive Approach --------- Parameters --------- An arry with n distinct numbers --------- Returns --------- i(th) order statistic, i.e: i(th) smallest element of the input array --------- Time Complexity --------- O(n.logn) --------- Test Cases --------- [1, 20, 6, 4, 5] => [1, 4, 5, 6, 20] """ import random if __name__ == "__main__": # user_input = input("Enter the list of numbers: \n").strip() # unsorted_array = [int(item) for item in user_input.split(",")] print(randomised_selection([1, 23, 3, 43, 5], 5, 3))
[ 2, 46333, 286, 14534, 1417, 29538, 198, 198, 37811, 198, 220, 220, 220, 11013, 425, 38066, 628, 220, 220, 220, 45337, 198, 220, 220, 220, 40117, 198, 220, 220, 220, 45337, 198, 220, 220, 220, 1052, 610, 563, 351, 299, 7310, 3146, 62...
2.616
250
import re from .common import regex_labels, re_number, re_string keywords = ['TODO'] re_keyword = re.compile(r'\b({})\b'.format('|'.join(keywords)))
[ 11748, 302, 198, 6738, 764, 11321, 1330, 40364, 62, 23912, 1424, 11, 302, 62, 17618, 11, 302, 62, 8841, 198, 198, 2539, 10879, 796, 37250, 51, 3727, 46, 20520, 198, 198, 260, 62, 2539, 4775, 796, 302, 13, 5589, 576, 7, 81, 6, 59, ...
2.508197
61
#!/usr/bin/env python import cgitb; cgitb.enable() print('Content-type: text/html\n') print( """<html> <head> <title>CGI 4 - CSS</title> <link rel="stylesheet" type="text/css" href="../css/estilo1.css"> </head> <body> <h1>Colocando CSS em um script a parte</h1> <hr> <p>Ola imagens CGI!</p> <div class="wraptocenter"> <img id="imagem" src="../imagens/evil.jpg" border=1 alt="Piadinha idiota" width=350 height=500> </div> <hr> </body> </html> """ )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 269, 18300, 65, 26, 269, 18300, 65, 13, 21633, 3419, 198, 4798, 10786, 19746, 12, 4906, 25, 2420, 14, 6494, 59, 77, 11537, 198, 4798, 7, 198, 220, 220, 220, 37227, 27, 6494, ...
2.121212
231
""" GNG vs SOM comparison example for PLASTK. This script shows how to: - Train PLASTK vector quantizers (SOM and GNG) - Set default parameters - Create a simple agent and environment. - Run an interaction between the agent and the environment with a GUI. $Id: gngsom.py,v 1.3 2006/02/17 19:40:09 jp Exp $ """ # Import what we need from PLASTK # All the top-level modules from plastk import * # Kohonen SOMs from plastk.vq.som import SOM,SOM2DDisplay # Growing Neural Gas from plastk.vq.gng import EquilibriumGNG, GNG2DDisplay # the python debugger import pdb ################################################################### # Set the PLASTK parameter defaults # [ help('plastk.params') for more info on parameters ] # # SOM Defaults: 10x10 SOM, with 2-D inputs # SOM.xdim = 10 SOM.ydim = 10 SOM.dim = 2 # # GNG defaults: 2-D inputs, maintain average discounted error below # 0.002, grow at most every 200 steps, max connection age 100. # EquilibriumGNG.dim = 2 EquilibriumGNG.rmin = 0 EquilibriumGNG.rmax = 100 EquilibriumGNG.error_threshold = 0.002 EquilibriumGNG.lambda_ = 200 EquilibriumGNG.max_age = 50 EquilibriumGNG.e_b = 0.05 EquilibriumGNG.e_n = 0.001 EquilibriumGNG.print_level = base.VERBOSE # Overwrite old data files, instead of renaming it. LoggingRLI.rename_old_data = False ################################################################ # Create the agent and environment # ################################################ # Run the an interaction between the agent and environment. # # Instantiate an agent and an environment agent = SOMTestAgent() env = SOMTestEnvironment() # Instantiate a Reinforcement Learning Interface. An RLI controls the # interaction between agent and environment, passing sensation and # reward from the environment to the agent, and actions from the agent # to the environment. In this experiment, the actions and reward are # meaningless, and only the sensations, 2D vectors, are important. # # The LoggingRLI class includes variable logging and GUI capabilities. rli = LoggingRLI(name = 'GNGvSOM_experiment') # Init the RLI rli.init(agent,env) # Run the RLI gui with two components, a SOM display and a GNG # display. The RLI gui takes a list of functions that take two # parameters, a the rli's GUI frame (root) and the rli object (rli), and return # instances of Tkinter.Frame that can be packed into the RLI's GUI frame. # rli.gui(lambda root,rli:SOM2DDisplay(root,rli.agent.som), lambda root,rli:GNG2DDisplay(root,gng=rli.agent.gng))
[ 37811, 198, 38, 10503, 3691, 42121, 7208, 1672, 329, 9297, 11262, 42, 13, 198, 198, 1212, 4226, 2523, 703, 284, 25, 198, 220, 532, 16835, 9297, 11262, 42, 15879, 5554, 11341, 357, 50, 2662, 290, 402, 10503, 8, 198, 220, 532, 5345, 4...
3.24968
781
import sublime from ui.read import settings as read_settings from ui.write import write, highlight as write_highlight from lookup import file_type as lookup_file_type from ui.read import x as ui_read from ui.read import spots as read_spots from ui.read import regions as ui_regions from core.read import read as core_read from structs.general_thread import * from structs.thread_handler import * from structs.highlight_list import * from structs.flag_region import * from core.analyse import analyse
[ 11748, 41674, 198, 6738, 334, 72, 13, 961, 1330, 6460, 355, 1100, 62, 33692, 198, 6738, 334, 72, 13, 13564, 1330, 3551, 11, 7238, 355, 3551, 62, 8929, 2971, 198, 6738, 35847, 1330, 2393, 62, 4906, 355, 35847, 62, 7753, 62, 4906, 198...
3.445946
148
from __future__ import absolute_import, division, print_function, unicode_literals import braintree from postgres.orm import Model
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 865, 2913, 631, 198, 6738, 1281, 34239, 13, 579, 1330, 9104, 628 ]
3.8
35
""" Defines a form to provide validations for course-specific configuration. """ from django import forms from openedx.core.djangoapps.video_config.forms import CourseSpecificFlagAdminBaseForm from openedx.core.djangoapps.video_pipeline.models import ( CourseVideoUploadsEnabledByDefault, VEMPipelineIntegration, )
[ 37811, 198, 7469, 1127, 257, 1296, 284, 2148, 4938, 602, 329, 1781, 12, 11423, 8398, 13, 198, 37811, 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 4721, 87, 13, 7295, 13, 28241, 14208, 18211, 13, 15588, 62, 11250, 13, 23914, 13...
3.431579
95
import os from os.path import dirname from unittest import TestCase import src.superannotate as sa
[ 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 12351, 13, 16668, 34574, 378, 355, 473, 198 ]
3.448276
29
import os import functools CORPUS_DIR = str(os.getcwd())[:str(os.getcwd()).index('spellingcorrector/')] \ + 'data/corpus.txt' NWORD = {} def getTrain(): """ simple singleton implement """ global NWORD if len(NWORD) == 0: train() return NWORD if __name__ == "__main__": getTrain() print CORPUS_DIR print os.path.isfile(CORPUS_DIR) print len(NWORD)
[ 11748, 28686, 198, 11748, 1257, 310, 10141, 628, 198, 44879, 47, 2937, 62, 34720, 796, 965, 7, 418, 13, 1136, 66, 16993, 28955, 58, 25, 2536, 7, 418, 13, 1136, 66, 16993, 3419, 737, 9630, 10786, 4125, 2680, 30283, 273, 14, 11537, 60...
2.160622
193
import logging from rhasspy_weather.data_types.request import WeatherRequest from rhasspy_weather.parser import rhasspy_intent from rhasspyhermes.nlu import NluIntent log = logging.getLogger(__name__) def parse_intent_message(intent_message: NluIntent) -> WeatherRequest: """ Parses any of the rhasspy weather intents. Args: intent_message: a Hermes NluIntent Returns: WeatherRequest object """ return rhasspy_intent.parse_intent_message(intent_message.to_rhasspy_dict())
[ 11748, 18931, 198, 198, 6738, 9529, 562, 9078, 62, 23563, 13, 7890, 62, 19199, 13, 25927, 1330, 15615, 18453, 198, 6738, 9529, 562, 9078, 62, 23563, 13, 48610, 1330, 9529, 562, 9078, 62, 48536, 198, 6738, 9529, 562, 9078, 372, 6880, 1...
2.925714
175
""" 59.40% """
[ 37811, 198, 3270, 13, 1821, 4, 628, 198, 37811, 198 ]
1.7
10
import logging log = logging.getLogger(__name__) import json import requests import requests.exceptions import botologist.plugin BASE_URL = 'https://qdb.lutro.me'
[ 11748, 18931, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 11748, 33918, 198, 11748, 7007, 198, 11748, 7007, 13, 1069, 11755, 198, 11748, 10214, 7451, 13, 33803, 198, 198, 33, 11159, 62, 21886, 796, 70...
3.017857
56
from pyldapi.renderer import Renderer from pyldapi.view import View from flask import render_template, Response from rdflib import Graph, URIRef, BNode import skos from skos.common_properties import CommonPropertiesMixin from config import Config
[ 6738, 12972, 335, 15042, 13, 10920, 11882, 1330, 28703, 11882, 198, 6738, 12972, 335, 15042, 13, 1177, 1330, 3582, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 18261, 198, 6738, 374, 67, 2704, 571, 1330, 29681, 11, 37902, 4663, 891, 11,...
3.623188
69
# Copyright 2019-2020 the .NET Foundation # Distributed under the terms of the revised (3-clause) BSD license. """Interacting with the WWT Communities APIs.""" import json import os.path import requests import sys from urllib.parse import parse_qs, urlparse from . import APIRequest, Client, enums __all__ = ''' CommunitiesAPIRequest CommunitiesClient CreateCommunityRequest DeleteCommunityRequest GetCommunityInfoRequest GetLatestCommunityRequest GetMyProfileRequest GetProfileEntitiesRequest IsUserRegisteredRequest interactive_communities_login '''.split() LIVE_OAUTH_AUTH_SERVICE = "https://login.live.com/oauth20_authorize.srf" LIVE_OAUTH_TOKEN_SERVICE = "https://login.live.com/oauth20_token.srf" LIVE_OAUTH_DESKTOP_ENDPOINT = "https://login.live.com/oauth20_desktop.srf" LIVE_AUTH_SCOPES = ['wl.emails', 'wl.signin'] WWT_CLIENT_ID = '000000004015657B' OAUTH_STATE_BASENAME = 'communities-oauth.json' CLIENT_SECRET_BASENAME = 'communities-client-secret.txt' # TODO: we're not implementing the "isEdit" mode where you can update # community info. # Command-line utility for initializing the OAuth state. def interactive_communities_login(args): import argparse parser = argparse.ArgumentParser() parser.add_argument( '--secret-file', metavar = 'PATH', help = 'Path to a file from which to read the WWT client secret', ) parser.add_argument( '--secret-env', metavar = 'ENV-VAR-NAME', help = 'Name of an environment variable containing the WWT client secret', ) settings = parser.parse_args(args) # Make sure we actually have a secret to work with. if settings.secret_file is not None: with open(settings.secret_file) as f: client_secret = f.readline().strip() elif settings.secret_env is not None: client_secret = os.environ.get(settings.secret_env) else: print('error: the WWT \"client secret\" must be provided; ' 'use --secret-file or --secret-env', file=sys.stderr) sys.exit(1) if not client_secret: print('error: the WWT \"client secret\" is empty or unset', file=sys.stderr) sys.exit(1) # Ready to go ... CommunitiesClient( Client(), oauth_client_secret = client_secret, interactive_login_if_needed = True, ) print('OAuth flow successfully completed.') if __name__ == '__main__': interactive_communities_login(sys.argv[1:])
[ 2, 15069, 13130, 12, 42334, 262, 764, 12884, 5693, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 15556, 357, 18, 12, 565, 682, 8, 347, 10305, 5964, 13, 198, 198, 37811, 9492, 27362, 351, 262, 13505, 51, 35530, 23113, 526, 15931, 198...
2.693145
919
import pytest
[ 11748, 12972, 9288, 628 ]
3.75
4
#!/usr/bin/env python3 import socket HOST = '127.0.0.1' # IP PORT = 10009 # with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: print(s) s.connect((HOST, PORT)) s.sendall(b'Hello, world') print(s) data = s.recv(1024) print('Received', repr(data))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 17802, 198, 198, 39, 10892, 796, 705, 16799, 13, 15, 13, 15, 13, 16, 6, 220, 1303, 220, 6101, 220, 198, 15490, 796, 8576, 24, 220, 1303, 220, 198, 198, 4480, 17802,...
2.111111
135
import requests import Mark from colorama import Fore from util.plugins.common import print_slow, getheaders, proxy
[ 11748, 7007, 198, 11748, 2940, 198, 6738, 3124, 1689, 1330, 4558, 198, 198, 6738, 7736, 13, 37390, 13, 11321, 1330, 3601, 62, 38246, 11, 651, 50145, 11, 15741 ]
4.142857
28
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from hashlib import sha256 from recipe_engine import recipe_test_api
[ 2, 15069, 13130, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 6738...
3.774194
62
import sklearn.mixture import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker import matplotlib.patheffects as mpatheffects
[ 11748, 1341, 35720, 13, 76, 9602, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 2603, 29487, 8019, 1330, 4378, 263, 201, 198, 11748, 2603, 29487, 8019, 13, ...
2.478261
69
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : upsert Case Name : upsertfor update Description : 1 2session1for update20s 3session15ssession2session1update 4session1session2 5session1 6session2session1update Expect : 1 2session1for update20ssession1 3session15ssession2session1updatesession2 4session1session2session210s 5session1 6selectsession1updatesession2 History : """ import time import unittest from testcase.utils.ComThread import ComThread from testcase.utils.CommonSH import CommonSH from testcase.utils.Constant import Constant from testcase.utils.Logger import Logger
[ 37811, 198, 15269, 357, 66, 8, 33160, 43208, 21852, 1766, 1539, 43, 8671, 13, 198, 198, 9654, 35389, 1046, 318, 11971, 739, 17996, 272, 6599, 43, 410, 17, 13, 198, 1639, 460, 779, 428, 3788, 1864, 284, 262, 2846, 290, 3403, 286, 262...
2.897436
390
#!/usr/bin/python3 import tkinter as tk from tkinter import messagebox as msg from tkinter.ttk import Notebook from tkinter import ttk import tkinter.font as font import requests if __name__ == "__main__": translatebook = TranslateBook() english_tab = LanguageTab(translatebook, "Ingls", "en") translatebook.add_new_tab(english_tab) # german_tab = LanguageTab(translatebook, "Alemn", "de") # translatebook.add_new_tab(german_tab) translatebook.mainloop() # cdigos de lenguages --> https://www.labnol.org/code/19899-google-translate-languages
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 256, 74, 3849, 1330, 3275, 3524, 355, 31456, 198, 6738, 256, 74, 3849, 13, 926, 74, 1330, 5740, 2070, 198, 6738, 256, 74, 3849, 133...
2.728571
210
""" This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `development`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ import django_heroku from split_settings.tools import include base_settings = [ 'components/middleware.py', # middleware configuration 'components/apps.py', # installed applications 'components/database.py', # database settings 'components/pyuploadcare.py', # pyuploadcare settings 'components/rest_framework.py', # rest framework settings 'components/allauth.py', # allauth rest_auth settings 'components/currency.py', # currency settings 'components/email.py', # email settings 'components/rest_framework.py', # rest framework settings 'components/common.py', # standard django settings 'components/cors_configuration.py', # configuration for Access Control Allow Origin 'components/graphene.py', # sendy config 'components/sendy.py' ] # Include settings: include(*base_settings) django_heroku.settings(locals())
[ 37811, 198, 1212, 318, 257, 42625, 14208, 12, 35312, 12, 33692, 1388, 2393, 13, 198, 1890, 517, 1321, 1100, 428, 25, 198, 198, 5450, 1378, 12567, 13, 785, 14, 568, 2127, 2768, 77, 14, 28241, 14208, 12, 35312, 12, 33692, 198, 19463, ...
3.100817
367
from django.conf.urls import patterns, url, include from django.contrib import admin from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import template_test urlpatterns = patterns( '', url(r'^test/', template_test, name='template_test'), url(r'^test2/', include('testapp.another_urls', namespace='foo', app_name='faa')) ) admin.autodiscover() urlpatterns += patterns( '', url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() import debug_toolbar urlpatterns += patterns( url(r'^__debug__/', include(debug_toolbar.urls)), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 19016, 11, 2291, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 12708, 16624,...
2.708661
254
from typing import Sequence, Union import numpy as np from scipy.ndimage.interpolation import rotate as np_rotate from PIL.Image import Image from torch import Tensor, tensor from torchvision.transforms.functional import rotate
[ 6738, 19720, 1330, 45835, 11, 4479, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 358, 9060, 13, 3849, 16104, 341, 1330, 23064, 355, 45941, 62, 10599, 378, 198, 6738, 350, 4146, 13, 5159, 1330, 7412, 198, 6738,...
3.698413
63
# Course: CS261 - Data Structures # Author: Mohamed Al-Hussein # Assignment: 06 # Description: Directed graph implementation. from collections import deque import heapq
[ 2, 20537, 25, 9429, 30057, 532, 6060, 32112, 942, 198, 2, 6434, 25, 27469, 978, 12, 39, 385, 20719, 198, 2, 50144, 25, 9130, 198, 2, 12489, 25, 4128, 276, 4823, 7822, 13, 198, 198, 6738, 17268, 1330, 390, 4188, 198, 11748, 24575, ...
3.8
45
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time: 2020/5/14 20:41 # @Author: Mecthew import time import numpy as np import pandas as pd import scipy from sklearn.svm import LinearSVC from sklearn.linear_model import logistic from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import accuracy_score from sklearn.preprocessing import OneHotEncoder import scipy.sparse as sp from utils.logger import get_logger logger = get_logger("INFO") def prepredict(graph_df, train_indices, use_valid, use_ohe=False): t1 = time.time() fea_table = graph_df['fea_table'].set_index(keys="node_index") train_indices = train_indices if use_valid: valid_indices = list(set(graph_df['train_indices']) - set(train_indices)) test_indices = graph_df['test_indices'] + valid_indices else: test_indices = graph_df['test_indices'] train_label = graph_df['train_label'].set_index('node_index').loc[train_indices][['label']] x_train, y_train = fea_table.loc[train_indices].to_numpy(), train_label.to_numpy() x_test = fea_table.loc[test_indices].to_numpy() lr = LR() lr.fit(x_train, y_train) if use_ohe: ohe = OneHotEncoder(handle_unknown="ignore").fit(y_train.reshape(-1, 1)) x_train_feat, x_test_feat = ohe.transform(np.argmax(lr.predict(x_train), axis=1).reshape(-1, 1)).toarray(), \ ohe.transform(np.argmax(lr.predict(x_test), axis=1).reshape(-1, 1)).toarray() else: x_train_feat, x_test_feat = lr.predict(x_train), \ lr.predict(x_test) pre_feat = np.concatenate([x_train_feat, x_test_feat], axis=0) total_indices = np.concatenate([train_indices, test_indices], axis=0) train_predict = np.argmax(x_train_feat, axis=1) train_acc = accuracy_score(y_true=y_train, y_pred=train_predict) t2 = time.time() logger.info("Time cost for training {}: {}s, train acc {}".format(lr.name, t2-t1, train_acc)) return pd.DataFrame(data=pre_feat, index=total_indices) def lpa_predict(graph_df, n_class, train_indices, use_valid, max_iter=100, tol=1e-3, use_ohe=False): t1 = time.time() train_indices = train_indices if use_valid: valid_indices = list(set(graph_df['train_indices']) - set(train_indices)) test_indices = graph_df['test_indices'] + valid_indices else: test_indices = graph_df['test_indices'] train_label = graph_df['train_label'].set_index('node_index').loc[train_indices][['label']].to_numpy() print("Train label shape {}".format(train_label.shape)) train_label = train_label.reshape(-1) edges = graph_df['edge_file'][['src_idx', 'dst_idx', 'edge_weight']].to_numpy() edge_index = edges[:, :2].astype(np.int).transpose() # transpose to (2, num_edges) edge_weight = edges[:, 2].astype(np.float) num_nodes = len(train_indices) + len(test_indices) t2 = time.time() total_indices = np.concatenate([train_indices, test_indices], axis=0) adj = sp.coo_matrix((edge_weight, edge_index), shape=(num_nodes, num_nodes)).tocsr() adj = adj[total_indices] # reorder adj = adj[:, total_indices] t3 = time.time() logger.debug("Time cost for transform adj {}s".format(t3 - t2)) row_sum = np.array(adj.sum(axis=1), dtype=np.float) d_inv = np.power(row_sum, -1).flatten() d_inv[np.isinf(d_inv)] = 0. normal_adj = sp.diags(d_inv).dot(adj).tocsr().transpose() Pll = normal_adj[:len(train_indices), :len(train_indices)].copy() Plu = normal_adj[:len(train_indices), len(train_indices):].copy() Pul = normal_adj[len(train_indices):, :len(train_indices)].copy() Puu = normal_adj[len(train_indices):, len(train_indices):].copy() label_mat = np.eye(n_class)[train_label] label_mat_prob = label_mat.copy() print("Pul shape {}, label_mat shape {}".format(Pul.shape, label_mat_prob.shape)) Pul_dot_lable_mat = Pul.dot(label_mat) unlabel_mat = np.zeros(shape=(len(test_indices), n_class)) iter, changed = 0, np.inf t4 = time.time() logger.debug("Time cost for prepare matrix {}s".format(t4-t3)) while iter < max_iter and changed > tol: if iter % 10 == 0: logger.debug("---> Iteration %d/%d, changed: %f" % (iter, max_iter, changed)) iter += 1 pre_unlabel_mat = unlabel_mat unlabel_mat = Puu.dot(unlabel_mat) + Pul_dot_lable_mat label_mat_prob = Pll.dot(label_mat_prob) + Plu.dot(pre_unlabel_mat) changed = np.abs(pre_unlabel_mat - unlabel_mat).sum() logger.debug("Time cost for training lpa {}".format(time.time() - t4)) # preds = np.argmax(np.array(unlabel_mat), axis=1) # unlabel_mat = np.eye(n_class)[preds] train_acc = accuracy_score(y_true=train_label, y_pred=np.argmax(label_mat_prob, axis=1)) logger.info("LPA training acc {}".format(train_acc)) logger.info("Time cost for LPA {}s".format(time.time() - t1)) total_indices = np.concatenate([train_indices, test_indices], axis=0) if use_ohe: ohe = OneHotEncoder(handle_unknown="ignore").fit(train_label.reshape(-1, 1)) label_mat_ohe = ohe.transform(np.argmax(label_mat_prob, axis=1).reshape(-1, 1)).toarray() unlabel_mat_ohe = ohe.transform(np.argmax(unlabel_mat, axis=1).reshape(-1, 1)).toarray() lu_mat_ohe = np.concatenate([label_mat_ohe, unlabel_mat_ohe], axis=0) return pd.DataFrame(data=lu_mat_ohe, index=total_indices), train_acc else: unlabel_mat_prob = unlabel_mat lu_mat_prob = np.concatenate([label_mat_prob, unlabel_mat_prob], axis=0) return pd.DataFrame(data=lu_mat_prob, index=total_indices), train_acc def is_nonnegative_integer(x_feats): is_nonnegative = (x_feats >= 0).all() is_integer = True for feat in x_feats: feat_int_sum = np.array(feat, dtype=np.int).sum() feat_sum = np.array(feat, dtype=np.float).sum() is_integer = (feat_int_sum == feat_sum) if is_integer is False: break return is_nonnegative and is_integer
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 25, 220, 220, 220, 12131, 14, 20, 14, 1415, 1160, 25, 3901, 198, 2, 2488, 13838, 25, 220, 337, 478, ...
2.266144
2,679
import os import scrapy from scrapy.crawler import CrawlerProcess import requests from disaster_data.sources.noaa_coast.utils import get_geoinfo, get_fgdcinfo
[ 11748, 28686, 198, 198, 11748, 15881, 88, 198, 6738, 15881, 88, 13, 66, 39464, 1330, 20177, 1754, 18709, 198, 11748, 7007, 198, 198, 6738, 9336, 62, 7890, 13, 82, 2203, 13, 3919, 7252, 62, 1073, 459, 13, 26791, 1330, 651, 62, 469, 7...
3.176471
51
import pytest from rlo import factory
[ 11748, 12972, 9288, 198, 198, 6738, 374, 5439, 1330, 8860, 628, 628 ]
3.5
12
# coding=utf-8 # Copyright 2014 Dirk Dittert # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need # fine tuning. base = 'Console' executables = [ Executable('probe.py', copyDependentFiles=True) ] includefiles = [] packages = ['pyprobe', 'psutil'] includes = [] setup(name='pyprobe', version='1.0', description='x', options={ 'build_exe': { 'include_files': includefiles, 'packages': packages, 'excludes': [], 'includes': ['requests'] }, 'bdist_mac': { 'bundle_name': 'pyprobe' } }, executables=executables, requires=['requests', 'psutil'])
[ 2, 19617, 28, 40477, 12, 23, 198, 198, 2, 15069, 1946, 42761, 360, 1967, 83, 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, ...
2.671518
481
# Copyright 2019 Jeremiah Sanders. # # 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. """dlae/gui/view_menu/layer_list.py""" import tkinter as tk
[ 2, 15069, 13130, 40192, 5831, 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, 351, 262, 13789, 13, 198, 2, 921, 743,...
3.68
175
""" DATA DESCRIPTION sentiment140 dataset. It contains 1,600,000 tweets extracted using the twitter api . The tweets have been annotated (0 = negative, 4 = positive) and they can be used to detect sentiment . It contains the following 6 fields: target: the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive) ids: The id of the tweet ( 2087) date: the date of the tweet (Sat May 16 23:58:44 UTC 2009) flag: The query (lyx). If there is no query, then this value is NO_QUERY. user: the user that tweeted (robotickilldozr) text: the text of the tweet (Lyx is cool) """ #import libraries import pandas as pd data = pd.read_csv('training.1600000.processed.noemoticon.csv',encoding = 'latin', header=None, nrows=25) #Adding header to data data = data.rename(columns={0: 'target', 1: 'id', 2: 'TimeStamp', 3: 'query', 4: 'username', 5: 'content'}) #Dropping unncessary columns data.drop(['id','TimeStamp','query'], axis=1, inplace=True) print(data.to_string())
[ 37811, 198, 26947, 22196, 40165, 198, 198, 34086, 3681, 15187, 27039, 13, 632, 4909, 352, 11, 8054, 11, 830, 12665, 21242, 1262, 262, 17044, 40391, 764, 383, 12665, 423, 587, 24708, 515, 357, 15, 796, 4633, 11, 604, 796, 3967, 8, 290,...
3.053125
320
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import redirect, request, session from werkzeug.exceptions import NotFound from indico.core.db import db from indico.modules.events.management.controllers import RHManageEventBase from indico.modules.events.static.models.static import StaticSite, StaticSiteState from indico.modules.events.static.tasks import build_static_site from indico.modules.events.static.views import WPStaticSites from indico.web.flask.util import url_for
[ 2, 770, 2393, 318, 636, 286, 1423, 3713, 13, 198, 2, 15069, 357, 34, 8, 6244, 532, 12131, 327, 28778, 198, 2, 198, 2, 1423, 3713, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 13096, 340, 739, 262, 2846,...
3.51
200
from csapp.models import Kruptos from rest_framework import viewsets, permissions from rest_framework.response import Response from rest_framework import status from .serializers import KruptosSerializer
[ 6738, 50115, 1324, 13, 27530, 1330, 509, 3622, 418, 201, 198, 6738, 1334, 62, 30604, 1330, 5009, 1039, 11, 21627, 201, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 201, 198, 6738, 1334, 62, 30604, 1330, 3722, 201, 198, 6738, 76...
4.078431
51
from os import path import autolens as al import autolens.plot as aplt from test_autogalaxy.simulators.imaging import instrument_util test_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "..", "..") def pixel_scale_from_instrument(instrument): """ Returns the pixel scale from an instrument type based on real observations. These options are representative of VRO, Euclid, HST, over-sampled HST and Adaptive Optics image. Parameters ---------- instrument : str A string giving the resolution of the desired instrument (VRO | Euclid | HST | HST_Up | AO). """ if instrument in "vro": return (0.2, 0.2) elif instrument in "euclid": return (0.1, 0.1) elif instrument in "hst": return (0.05, 0.05) elif instrument in "hst_up": return (0.03, 0.03) elif instrument in "ao": return (0.01, 0.01) else: raise ValueError("An invalid instrument was entered - ", instrument) def grid_from_instrument(instrument): """ Returns the `Grid` from an instrument type based on real observations. These options are representative of VRO, Euclid, HST, over-sampled HST and Adaptive Optics image. Parameters ---------- instrument : str A string giving the resolution of the desired instrument (VRO | Euclid | HST | HST_Up | AO). """ if instrument in "vro": return al.GridIterate.uniform(shape_2d=(80, 80), pixel_scales=0.2) elif instrument in "euclid": return al.GridIterate.uniform(shape_2d=(120, 120), pixel_scales=0.1) elif instrument in "hst": return al.GridIterate.uniform(shape_2d=(200, 200), pixel_scales=0.05) elif instrument in "hst_up": return al.GridIterate.uniform(shape_2d=(300, 300), pixel_scales=0.03) elif instrument in "ao": return al.GridIterate.uniform(shape_2d=(800, 800), pixel_scales=0.01) else: raise ValueError("An invalid instrument was entered - ", instrument) def psf_from_instrument(instrument): """ Returns the *PSF* from an instrument type based on real observations. These options are representative of VRO, Euclid, HST, over-sampled HST and Adaptive Optics image. Parameters ---------- instrument : str A string giving the resolution of the desired instrument (VRO | Euclid | HST | HST_Up | AO). """ if instrument in "vro": return al.Kernel.from_gaussian( shape_2d=(31, 31), sigma=0.5, pixel_scales=0.2, renormalize=True ) elif instrument in "euclid": return al.Kernel.from_gaussian( shape_2d=(31, 31), sigma=0.1, pixel_scales=0.1, renormalize=True ) elif instrument in "hst": return al.Kernel.from_gaussian( shape_2d=(31, 31), sigma=0.05, pixel_scales=0.05, renormalize=True ) elif instrument in "hst_up": return al.Kernel.from_gaussian( shape_2d=(31, 31), sigma=0.05, pixel_scales=0.03, renormalize=True ) elif instrument in "ao": return al.Kernel.from_gaussian( shape_2d=(31, 31), sigma=0.025, pixel_scales=0.01, renormalize=True ) else: raise ValueError("An invalid instrument was entered - ", instrument) def simulator_from_instrument(instrument): """ Returns the *Simulator* from an instrument type based on real observations. These options are representative of VRO, Euclid, HST, over-sampled HST and Adaptive Optics image. Parameters ---------- instrument : str A string giving the resolution of the desired instrument (VRO | Euclid | HST | HST_Up | AO). """ grid = grid_from_instrument(instrument=instrument) psf = psf_from_instrument(instrument=instrument) if instrument in "vro": return al.SimulatorImaging( exposure_time=100.0, psf=psf, background_sky_level=1.0, add_poisson_noise=True, ) elif instrument in "euclid": return al.SimulatorImaging( exposure_time=2260.0, psf=psf, background_sky_level=1.0, add_poisson_noise=True, ) elif instrument in "hst": return al.SimulatorImaging( exposure_time=2000.0, psf=psf, background_sky_level=1.0, add_poisson_noise=True, ) elif instrument in "hst_up": return al.SimulatorImaging( exposure_time=2000.0, psf=psf, background_sky_level=1.0, add_poisson_noise=True, ) elif instrument in "ao": return al.SimulatorImaging( exposure_time=1000.0, psf=psf, background_sky_level=1.0, add_poisson_noise=True, ) else: raise ValueError("An invalid instrument was entered - ", instrument)
[ 6738, 28686, 1330, 3108, 201, 198, 11748, 1960, 349, 641, 355, 435, 201, 198, 11748, 1960, 349, 641, 13, 29487, 355, 257, 489, 83, 201, 198, 201, 198, 6738, 1332, 62, 2306, 519, 282, 6969, 13, 14323, 24325, 13, 320, 3039, 1330, 8875...
2.198433
2,298
from .conftest import GoProCameraTest from socket import timeout from urllib import error
[ 6738, 764, 1102, 701, 395, 1330, 49789, 35632, 14402, 198, 198, 6738, 17802, 1330, 26827, 198, 6738, 2956, 297, 571, 1330, 4049, 628 ]
4
23
from utils import CanadianScraper, CanadianPerson as Person COUNCIL_PAGE = 'http://www.abbotsford.ca/city_hall/mayor_and_council/city_council.htm' CONTACT_PAGE = 'http://www.abbotsford.ca/contact_us.htm'
[ 6738, 3384, 4487, 1330, 5398, 3351, 38545, 11, 5398, 15439, 355, 7755, 198, 198, 34, 2606, 7792, 4146, 62, 4537, 8264, 796, 705, 4023, 1378, 2503, 13, 6485, 1747, 3841, 13, 6888, 14, 19205, 62, 18323, 14, 11261, 273, 62, 392, 62, 66...
2.607595
79
from anchorecli.cli import repo
[ 6738, 12619, 382, 44506, 13, 44506, 1330, 29924, 198 ]
3.555556
9
''' nome = input('Insira seu nome: ') if nome == 'Mendes': print('Que nome lindo voc tem!') else: print('Seu nome to normal!') print('Bom dia {}!'.format(nome)) ''' #DESAFIO_28 ''' from random import randint from time import sleep x = randint(0,5) y = int(input('Digite um nmero de 0 5: ')) print('Loading...') sleep(2) if x == y: print('Parabns, voc venceu!') else: print('Tente novamente, voc perdeu!') print(x) ''' #DESAFIO_29 ''' velocity = int(input('Qual a velocidade atual do seu carro em Km/h? ')) if velocity > 80: print('Voc foi multado por excesso de velocidade!') print('Velocidade permitia: 80km/h') print('Velocidade ultrapassada: {}km/h'.format(velocity)) infraction = (velocity - 80) * 7 print('Valor da multa: R${},00'.format(infraction)) ''' #DESAFIO_30 ''' number = int(input('Insira um nmero inteiro: ')) if number % 2 == 0: print('Seu nmero PAR!') else: print('Seu nmero MPAR!') ''' #DESAFIO_31 ''' distance = int(input('Qual a distncia em Km que deseja viajar? ')) if distance <= 200: final_value = distance * 0.50 else: final_value = distance * 0.45 print('Valor da passagem: R${:.2f}'.format(final_value)) ''' #DESAFIO_32 ''' from datetime import date year = int(input('Insira um ano (Coloque "0" caso queira analisar a data atual): ')) if year == 0: year = date.today().year if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(year, ' um ano BISSEXTO!') else: print(year, 'no um ano BISSEXTO!') ''' #DESAFIO_33 ''' x = int(input('Digite o primeiro nmero: ')) y = int(input('Digite o segundo nmero: ')) z = int(input('Digite o terceiro nmero: ')) number_max = max(x,y,z) number_min = min(x,y,z) print('Maior nmero:',number_max) print('Menor nmero:',number_min) ''' #DESAFIO_34 ''' wage = float(input('Insira seu salrio: R$')) if wage > 1250: salary_increase = ((10/100) * wage) + wage percent = 10 else: salary_increase = ((15/100) * wage) + wage percent = 15 print() print('Salrio atual: R${:.2f}'.format(wage)) print('Aumento de {}%'.format(percent)) print('Salrio final: R${:.2f}'.format(salary_increase)) ''' #DESAFIO_35 ''' line1 = float(input('Insira o comprimento da primeira reta: ')) line2 = float(input('Insira o comprimento da segunda reta: ')) line3 = float(input('Insira o comprimento da terceira reta: ')) if line1 < line2 + line3 and line2 < line1 + line3 and line3 < line1 + line2: print('Podem formar um tringulo!') else: print('No podem formar um tringulo!') ''' #PROVA ''' s = 'prova de python' x = len(s) print(x) x = 'curso de python no cursoemvideo' y = x[:5] print(y) ''' x = 3 * 5 + 4 ** 2 print(x)
[ 7061, 6, 198, 77, 462, 796, 5128, 10786, 20376, 8704, 384, 84, 299, 462, 25, 705, 8, 198, 361, 299, 462, 6624, 705, 44, 437, 274, 10354, 198, 220, 220, 220, 3601, 10786, 15681, 299, 462, 300, 521, 78, 12776, 2169, 0, 11537, 198, ...
2.310764
1,152