text
string
size
int64
token_count
int64
import numpy as np import keras import keras.layers as layers from get_mnist import get_mnist_preproc ### --- hyperparameterrs --- ### epochs = 48 batch_size = 64 num_classes = 10 reg = 3e-3 ### --- hyperparams end --- ### ### --- setup data --- ### traini, trainl, vali, vall, testi, testl = get_mnist_preproc() ...
2,529
921
import config import controller import hwrtc import network import web_server import wlan def main(): if config.wlan_ssid and config.wlan_password: wlan.initialize_wlan() wlan.connect_to_wlan() hwrtc.initialize_hwrtc() hwrtc.initialize_ds3231() hwrtc.synchronize_hwrtc_ds3231() co...
539
198
# -*- coding: utf-8 -*- # Copyright (c) 2011-2016, Camptocamp SA # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this #...
25,480
7,879
import sys import pathlib from datetime import datetime current_dir = pathlib.Path(__file__).resolve().parent sys.path.append( str(current_dir) + '/../../' ) from app.database import BASE, ENGINE, session_scope from app.models.todos import Todo from app.models.users import User def generate_seed_data(): BASE.met...
1,102
347
# -*- coding: UTF-8 -*- import os import os.path import json import platform import tempfile import logging if platform.python_version() < '2.7': import unittest2 as unittest else: import unittest from rogue_scores.web import app from rogue_scores.web.app import index, scores_upload, scores_json class FakeR...
3,217
1,093
from math import factorial n = 86 k = 8 res = factorial(n)/factorial(n-k)%1e6 print int(res)
95
45
""" Investment created by Herman Tai 3/20/2008 """ from math import * TOLERANCE = 0.0000001 def equals(n1,n2): return abs(n1-n2) <TOLERANCE def calculate_monthly_payment(principle,year,rate_percent): terms = year * 12.0 rate = rate_percent/100.0 monthly_rate = rate/12.0 # special case if mo...
3,162
1,197
import requests import json from Sakurajima.models import base_models as bm class RecommendationEntry(object): def __init__(self, data_dict, headers, cookies, api_url): self.__headers = headers self.__cookies = cookies self.__API_URL = api_url self.title = data_dict.get("title", No...
1,544
490
"""Events separate segements of data. A model is fitted to each segment independently""" import numpy as np class InvalidPeriod(Exception): pass class event(object): def __init__(self, date): self.date = date def period_range(min_date, max_date, events, index): if index > len(events): raise InvalidPe...
3,620
1,140
from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler import numpy as np from .param_tuning import ParamTuning class LogisticRegressionTuning(ParamTuning): """ サポートベクター分類チューニング用クラス """ # 共通定数 SEED = 42 # デフォルト乱...
2,388
1,302
import os os.environ['MPLCONFIGDIR'] = os.getcwd() + "/configs/" import matplotlib import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('medical_examination.csv') df['overweight'] = (df['weight'] / (df['height']/100)**2).apply(lambda x: 1 if x > 25 else 0) df['...
1,578
641
import pygame from gui.guielement import GuiElement HORIZONTAL = 0 VERTICAL = 1 class GuiScrollbar(GuiElement): """ scrollbar / slider """ def __init__(self, x, y, width, height, fontObj, value=0.0, orientation=HORIZONTAL, barLength=30): GuiElement.__init__(self, x, y, width, ...
2,785
965
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- """ Naturalunit system. The natural system comes from "setting c = 1, hbar = 1". From the computer point of view it means that we use velocity and action instead of length and time. Moreover instead of mass we use energy. """ from __future__ import division from sympy...
1,785
617
import random import uuid import os class RandomRequest(object): @classmethod def get_random_user_agent(cls): with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files/supported_ios_versions.txt')) as f: ios_versions = f.read().splitlines() with open(os.path.join(...
816
279
from typing import Union __all__ = [ 'num', ] num = Union[int, float]
76
30
from pylint.reporters.json import JSONReporter def json_reporter_handle_message(self, msg): """Manage message of different type and in the context of path.""" self.messages.append({ 'path': msg.path, 'abspath': msg.abspath, 'line': msg.line, 'column': msg.column, 'modul...
867
283
from nltk.stem import SnowballStemmer from nltk.stem.api import StemmerI import nltk import json class ParticleStemmer(SnowballStemmer): def __init__(self, language="english", ignore_stopwords=False, suffix_rule_list={}): super().__init__(language=language, ignore_stopwords=ignore_stopwords) if language == "engl...
12,492
5,695
import os from abacusevents.utils import env, lowercase_first def test_env_is_short_for_os_dot_environ(): os.environ['FOO'] = 'BAR' assert env('FOO') == 'BAR' def test_env_lets_you_specify_a_default_value(): default = env('NOT_THERE', 'FOO') assert default == 'FOO' def test_env_wont_explode(): ...
700
253
#!/usr/bin/env python # coding: utf-8 # In[ ]: def LoadnClean (path): import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np df = ( pd.read_csv(path,index_col = 0) ) df1 = ( df .replace("",float("NaN")) ...
6,340
2,203
from flask import Flask import os templates_folder = os.path.abspath("application/view/templates") static_folder = os.path.abspath("application/view/static") app = Flask(__name__,template_folder=templates_folder,static_folder=static_folder) from application.controller import hello_controller
305
93
#Just a simple script to automate the YAML front matter in new posts import datetime import os title = raw_input('\nEnter title: ') fileName= title.replace(" ", "_").lower() + '.md' print fileName + '\n' text = """--- layout: project title: {} date: Feb 2015 thumbnail: http://devchuk.github.io/devchukV1/res/img/porti...
664
220
# -*- coding: utf-8 -*- '''pre load default TSP city data into database''' from django.db.transaction import atomic from ..models import * import os @atomic def atomic_save(items): for item in items: item.save() # Load default city data def load_cities(cities_folder_path, delete=False): ''' Load data fi...
1,820
566
# Copyright 2019 Netskope, Inc. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. ...
11,725
3,886
def test_response_is_json(self): from json import loads response = self.client.{{ request.method|lower }}('{{ request.path }}', data={{ request.data|safe }}) self.assertFalse(response.streaming) # rather than F, this will E content = loads(response.content) expected =...
413
113
import mysql.connector mydb = mysql.connector.connect( host="databaseurl", user="username", password="password", database="database_name", ) mycursor = mydb.cursor() code = input("Enter SQL code here ") sql = code mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record inserted.")
308
102
""" URL: https://codeforces.com/problemset/problem/451/B Author: Safiul Kabir [safiulanik at gmail.com] Tags: implementation, sortings, *1300 """ def main(): n = int(input()) ll = list(map(int, input().split())) start, end = -1, -1 for i in range(n - 1): if ll[i] > ll[i + 1]: sta...
941
352
from .ibm_cos import IBMCloudObjectStorageBackend as StorageBackend
68
18
# -*- coding: utf-8 -*- """ Created on Tue Dec 7 22:03:24 2021 @author: lankuohsing """ import numpy as np import torch.utils.data as Data import torch from collections import OrderedDict from torchsummary import summary # In[] data1=[] labels1=[] data2=[] labels2=[] with open("./dataset/4_class_data_2d.txt",'r',enc...
2,877
1,120
# /usr/bin/env python # -*- coding: utf-8 -*- def ErrorMessage(modulename=None): print(f'Import Can\'t Module "{modulename}"') print('Read the .md file') print('pip -r requirements.txt') import inspect,sqlite3 # load module from py.sheet.sheet import * try: # PostgreSQL import psycopg2 except Mo...
7,476
2,249
from TabularTrainer import * from RandomPlayer import * from TicTacToe import * import matplotlib.pyplot as plt action_to_coordinate = {0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (1, 0), 4: (1, 1), 5: (1, 2), 6: (2, 0), 7: (2, 1), 8: (2, 2)} NUM_OF_BATTLES = 10 NUM_OF_GAMES = ...
6,543
2,164
import os import sys from core.math_tool.coordinate_system import CoordSys import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import cv2 def _update_element(obj,data,is_Point=False): if is_Point: obj.set_data(data[0], data[1]) obj.set_3d_properties(data[2], z...
3,402
1,397
# -*- coding: utf-8 -*- from .utils import exists, nlargest, removeMultiple from .spell import Spell class KeyboardSpell(Spell): def __init__(self, spelldic=None, corpusfile=None, suffixfile=None, language=None, encoding=None, keyboardlayoutfile=None, weightObjFun=None): # call the parent constructor ...
7,134
2,212
# encoding: UTF-8 import cv2 import numpy as np class ImFilterPipeline: def __init__(self): # init pipeline self._pipeline = { "rotated": 0, "blur": 0, "gaussianBlur": 0, "resize": 0 } @property def pipeline(self): return s...
2,262
794
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../")) import unittest from karura.database_api import DatabaseAPI class TestDatabaseAPI(unittest.TestCase): DBNAME = "test_database_uri" API = None @classmethod def setUpClass(cls): cls.API = DatabaseAPI(alterna...
2,052
655
#!/usr/bin/python import pandas as pd import sys def main(): # fle_path = '/home/alex/workspace/ReportGen/python/BigBenchTimes.csv' file_path = sys.argv[1] df = pd.read_csv(file_path, sep=';') df.to_excel("BigBenchTimes.xlsx") print df.to_string() if __name__ == '__main__': main()
310
122
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup import nameparser import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() README = read('README.rst') setup(name='nameparser', packages = ['nameparser'...
1,225
328
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 4 17:41:56 2018 @author: hubert kyeremateng-boateng """ import numpy as np import pandas as pd recipes = pd.read_csv('arp_dataset.csv', header=None) recipes.rename(columns={0: 'name'}, inplace=True) print(np.transpose(recipes))
300
125
import roll_dice as r #importing RollDice module COUNT = 0 #initializing count while True: roll = input("Enter your choice(d/u/l/r): ").lower() #Pick your choice if roll == 'down' or roll == 'd': r.dice_down(r.res) COUNT+=1 elif roll == 'up'or roll =='u': ...
973
348
from flask import render_template, redirect, url_for, flash, request from werkzeug.urls import url_parse from flask_login import login_user, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, DecimalField, BooleanField, SelectField, SubmitField from wtforms.validat...
2,756
717
import matplotlib.pyplot as plt import numpy as np divisions = ['Admin', 'Development', 'Lead', 'HR'] salary = [10, 14,20, 12] age = [28, 30, 45, 32] index = np.arange(4) width = 0.3 plt.bar(index, salary, width, color='green', label='Salary') plt.bar(index+width, age, width, color='blue', label='Age') plt.title('Di...
457
198
from string import * import json, sys from urllib.request import urlopen #parameters params1 = "<||^{tss+^=r]^/\A/+|</`[+^r]`;s.+|+s#r&sA/+|</`y_w" params2 = ':#%:%!,"' params3 = "-#%&!&')&:-/$,)+-.!:-::-" params4 = params2 + params3 params_id = "j+^^=.w" unit = [ "k", "atm"] data1 = printable data2 = punctuation...
1,951
775
# # 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 ...
2,309
788
#!/usr/bin/env python # Copyright (C) 2014 Open Data ("Open Data" refers to # one or more of the following companies: Open Data Partners LLC, # Open Data Research LLC, or Open Data Capital LLC.) # # This file is part of Hadrian. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this...
1,913
779
import warnings import click from ai.backend.cli.extensions import ExtendedCommandGroup from ai.backend.client import __version__ from ai.backend.client.output import get_output_handler from ai.backend.client.config import APIConfig, set_config from ai.backend.client.cli.types import CLIContext, OutputMode @click.g...
1,414
415
""" The country module contains the processing_country class. """ from os import path import geoip2.database from cybercaptain.utils.exceptions import ValidationError from cybercaptain.processing.base import processing_base from cybercaptain.utils.jsonFileHandler import json_file_reader, json_file_writer class process...
4,849
1,372
# Generated by Django 3.0.2 on 2020-01-21 06:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('persons', '0010_attendee_address'), ('whereabouts', '0008_room'), ] operations = [ migrations.AddField( model_name='addr...
473
163
# skeleton class Car: def __init__(self, name, mileage, max_fuel): self.name = name self.mileage = mileage self.max_fuel = max_fuel self.fuel = self.max_fuel self.dist = 0 def status(self): ''' Show the current status of the car it should be called after brrr() and gas_statation() ...
1,411
527
import socket import pynput from gevent import pywsgi from flask_sockets import Sockets from flask import Flask, request, render_template from geventwebsocket.handler import WebSocketHandler app = Flask(__name__) sockets = Sockets(app) mouse = pynput.mouse.Controller() @app.route("/", methods=['GET', 'POST']) def i...
1,855
686
from pathlib import Path from typing import Tuple from netCDF4 import Dataset import xarray import numpy as np from datetime import datetime, timedelta from dateutil.parser import parse def load( fn: Path, tlim: Tuple[datetime, datetime] = None, elevlim: Tuple[float, float] = None ) -> xarray.Dataset: """ ...
2,652
970
# -*- encoding: utf-8 -*- # # Copyright © 2017 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
1,402
468
# This implementation as of July 19 2017 has these resource utilizations of the mongodb container: # - 2 million entries: 1.50 Gb # - 3 million entries: 2.05 Gb # The entire docker application was given 6 Gb to use, when given the default 2 Gb, # the process would frequently crash before 1 million entries were down...
2,735
868
"""Module describes a :class:`DatabaseSource` for local postgres databases.""" import subprocess from galaxy.util import unicodify from planemo.io import communicate from .interface import DatabaseSource class ExecutesPostgresSqlMixin: def list_databases(self): """Use `psql --list` to generate a list ...
3,740
1,069
#!/usr/bin/env python # Copyright 2017 British Broadcasting Corporation # # 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...
2,029
603
from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Post from .forms import PostForm @login_required def add_post_view(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=Fa...
882
308
""" Utilities - CVPRO BY: MOHAK BAJAJ CODING HEAVEN """ import math import time import logging import cv2 import numpy as np import copy def stackImages(_imgList, cols, scale): """ Stack Images together to display in a single window :param _imgList: list of images to stack :param co...
14,019
5,329
""" Library of functions to retrieve frequency information from a Gaussian 09e output file. Frequencies currently supported: (1) Harmonic Vibrational Frequencies (2) Harmonic Zero-Point Vibrational Energy """ __authors__ = "Kevin Moore, Andreas Copan" __updated__ = "2019-01-15" from ..rere import parse as repar fro...
3,664
1,340
import time import sys from graphics import GraphApp, GraphWin, Text, Point, _root from menu import MainMenu from graphs import Graph, ShortestPaths from maps import RoadMap from cars import Car, CarShape, CarFactory from gps import GPS from info_window import InfoWindow, RoadInfoWindow from collision import GridColli...
7,460
2,324
""" 这个文件修改自原文件,修改内容包括: 1. 删除quadratic algorithm的使用,因为还没想好该怎么用 2. 从原来的单扰动改为多扰动 """ ''' >>> This file creates modules that can do forward, backward pass as well as bound propagation ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from abc import ABCMeta, ab...
11,116
4,245
""" main.py ---------- """ import argparse import os import runpy import sys from . import console parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="Description", ) parser.add_argument( "source", nargs="?", help="""Name of the script to be run a...
1,050
318
#python Libraries from StringIO import StringIO from collections import namedtuple import Queue import os # Third-party Libraries try: import pexpect except ImportError as error: #print error pass # apetools Libraries from apetools.baseclass import BaseClass from apetools.commons.errors import Connection...
4,779
1,337
import os import logging import xml.etree.ElementTree as ET from . import Security, Ldap class Nexus: def __init__(self): self.log = logging.getLogger(__name__) self.path = None self.repos = None self.repomap = None self.dirty = True self.ldap = Ldap() self.s...
5,167
1,497
# implementation of card game - Memory import simplegui import random # for repeatition check # helper function to initialize globals def new_game(): cards1 = range(0,8) cards2 = range(0,8) random.shuffle(cards1) random.shuffle(cards2) global cardDeck cardDeck = cards1 + cards2 random.shu...
2,523
917
''' Created on Mar 22, 2018 @author: msanchez ''' import requests from html.parser import HTMLParser import urllib class WebUtilities(object): def __init__(self): ''' Utility class. Has everything that has to do with web download / requests. It may also create static HTML web pages. ...
2,547
680
import abc import logging from typing import List, Optional from asyncio import Queue import zmq.asyncio from zmq.error import ZMQBaseError from schematics import Model from schematics.types import StringType, IntType, ListType class BaseSheep(metaclass=abc.ABCMeta): """ A base class for container adapters -...
2,585
746
class MetaVarList(list): def __new__(cls, data=None, formatter=None): cls._formatter = formatter obj = super(MetaVarList, cls).__new__(cls, data) return obj def __str__(self): return 'myList(%s)' % list(self) def __format__(self, spec): print(spec) #...
1,546
538
import theano import unittest import numpy from nose.plugins.skip import SkipTest from theano import tensor as T from theano.tensor.nnet import conv2d from theano.sandbox import mkl numpy.random.seed(123) if not mkl.mkl_available: raise SkipTest('Optional package MKL disabled') if theano.config.mode == 'FAST_COM...
4,462
1,665
"""Run tests against our custom views.""" from flask.ext.stormpath.models import User from .helpers import StormpathTestCase class TestRegister(StormpathTestCase): """Test our registration view.""" def test_default_fields(self): # By default, we'll register new users with first name, last name, ...
12,142
3,517
x = 9 y = 3 # Arithmetic Operators print(x+y) #addtion print(x-y) #subtraction print(x*y) #multiplication print(x/y) #division print(x%y) #modulus provides remainder after we do long divison print(x**y) #Exponentiation x = 9.191823 print("Floor divide:", x//y) #Floor divison, how many times does a nu...
1,097
463
from django.db import models # Create your models here. class Car(models.Model): car_name = models.CharField(max_length=50) car_hostname = models.CharField(max_length=50) car_state = models.CharField(max_length=50) def __str__(self): return self.car_name def get_hostname(self): ...
404
130
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import argparse import cv2 from maskrcnn_benchmark.config import cfg from predictor import COCODemo import torch import time from PIL import Image import numpy from matplotlib import pyplot def combine_masks_tuple(input_model): # type: (Tuple[...
7,340
2,774
#coding:utf-8 from flask import request,render_template, redirect,session from . import app from dbutil import DB from collections import OrderedDict import json import datetime # 基础 from dell_racadm import check_client_ip,check_dell_racadm_ip,dell_racadm_achieve_ip_info,achieve_dell_cacadm_comman,check_dell_racadm_in...
8,736
3,904
import os from configparser import RawConfigParser import constants import utils class Config(RawConfigParser): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.disclaimer_section_header = "disclaimer" self.telegram_section_header = "telegram" self.teleg...
5,275
1,643
from libs.primelib import Prime import cProfile import time # Test variable's primeindex = 100000 primecheck = 1000000000000 def main(): prime = Prime() print('test 1:') start = time.clock() value = prime.getByIndex(primeindex) end = time.clock() print('value: ' + str(value)) print('time:...
1,430
519
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ROS import rospy from std_msgs.msg import String # Robonomics communication from robonomics_msgs.msg import Demand, Result from ipfs_common.msg import Multihash from ipfs_common.ipfs_rosbag import IpfsRosBag class WorkerNode: def __init__(self): rospy.ini...
1,579
529
#!/usr/bin/env python # encoding: utf-8 """ copyright (c) 2016-2017 Earth Advantage. All rights reserved. ..codeauthor::Paul Munday <paul@paulmunday.net> Unit tests for dubplate. """ # Imports from Standard Library import datetime import json import sys import six import unittest # Imports from Third Party Modules fr...
14,009
4,454
import subprocess import cli def ask(message, choices=None, options=None): options = {"text": f"<big>{message}</big>"} | (options or {}) if choices is None: res = run("entry", options=options) res = res and res.strip() elif isinstance(choices, list): res = ask_choices(choices, op...
1,582
518
# DISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited. # # This material is based upon work supported by the Assistant Secretary of Defense for Research and # Engineering under Air Force Contract No. FA8721-05-C-0002 and/or FA8702-15-D-0001. Any opinions, # findings, conclusions or recommendat...
7,425
2,424
import discord from config import * class ShutDown: def __init__(self,message : discord.Message, bot : discord.Client()): self.bot = bot self.message = message async def run(self): if self.message.author.id in OWNER: await self.message.channel.send('Shut down') ...
354
103
import textwrap import click def show_ugraph(ugraph, oneline=False, ignore_unknown_op=False): from utensor_cgen.backend.utensor.code_generator.legacy._operators import OperatorFactory unknown_ops = set([]) if oneline: tmpl = click.style("{op_name} ", fg='yellow', bold=True) + \ "op_type: {op_type}, ...
2,018
725
# board.py # abstract class for zorg and edge import time from ocan import * class Board(): can_id = None pause = True ocan = None def __init__(self, manifest): self.manifest = manifest self.ocan = OCan() self.init_board() self.init_filters() self.boot() ...
1,396
383
import rob import sys # 1404927386.fasta analyzed_sequences.txt annotations.txt # faf=None try: faf=sys.argv[1] except IndexError: sys.stderr.write("Please provide a fasta file\n") sys.exit(0) fa = rob.readFasta(faf) analyzed=[] with open('analyzed_sequences.txt', 'r') as asf: for line in asf...
962
375
import os import tqdm import torch import numpy as np from parser import parse_args from scene.data import DataSet from torchtext.data import Iterator from scene.data.loaders import BatchWrapper from scene.models import BiLSTM def predict(model, loader): model.eval() predictions = [] for data in tqdm....
1,403
498
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ email_set = set() for email in emails: local, domain = email.split('@') local = local.replace('.', '') if '+' in local: l...
423
119
# -*- coding: utf-8 -*- """ Unit tests for the RandomTester class. @author: m.utting@uq.edu.au """ import unittest import random from pathlib import Path import sklearn.utils.estimator_checks from typing import Tuple, List, Set, Dict, Optional, Any import agilkia THIS_DIR = Path(__file__).parent WSDL_EG = "http://...
9,926
3,436
# extract the Salamunnicar data from the XLS file import pandas as pd import pkg_resources import logging import os def extract_salamuniccar(filename, tables=None, output_prefix=None, output_filename=None): """Extract the lat,long, diameter from the Salamuniccar ca...
2,576
787
from ARLO.environment.environment import *
42
11
from typing import Optional from dagster import solid, Int, Failure, Nothing, configured, String, DagsterLogManager from dagster.core.execution.context.compute import AbstractComputeExecutionContext from dagster_utils.typing import DagsterConfigDict from data_repo_client import JobModel, ApiException, RepositoryApi f...
3,558
1,141
# # Author: Igor Ivanov # 2019 # import time import os from termcolor import colored from datetime import datetime import colorama colorama.init() """ Small print tool for implementing chat in the terminal """ class print_chat: def _clear_screen(self): os.system('cls' if os.name == 'nt' else 'clear') ...
10,533
3,237
""" This class is used by test_pageobjects """ from cumulusci.robotframework.pageobjects import ListingPage, pageobject # The point of this class is to test out using an alias @pageobject(page_type="Listing", object_name="Custom Object") class CustomObjectListingPage(ListingPage): _object_name = "CustomObject__c"...
321
95
logreg_params = dict(multi_class='ovr', class_weight=None, random_state=43, max_iter=300, n_jobs=-1, penalty='l2', C=0.5) rnn_params = dict( # Пути к данным df="../coleridgeinitiative-s...
850
308
from typing import NoReturn, Union import ziopy.services.console as console import ziopy.services.system as system from ziopy.environments import ConsoleSystemEnvironment from ziopy.services.console import Console, LiveConsole from ziopy.zio import ZIO, ZIOMonad, monadic, unsafe_run, Environment @monadic def program...
1,741
610
import os import struct import unittest import numpy as np # # based on https://gist.github.com/akesling/5358964 # Which contains comment. # > Loosely inspired by http://abel.ee.ucla.edu/cvxopt/_downloads/mnist.py # > which is GPL licensed. # class MNistLoader: @classmethod def read_mnist(cls, ...
1,872
685
from .gotypes import Player, Point __all__ = ['HASH_CODE', 'EMPTY_BOARD'] HASH_CODE = { (Point(row=1, col=1), Player.black): 5769035980899136028, (Point(row=1, col=1), Player.white): 4195353792250980257, (Point(row=1, col=2), Player.black): 2939556709560817954, (Point(row=1, col=2), Player.white): 770...
45,542
28,156
import h5py import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Load in data: filename = input('Enter data filename: ') data_file = h5py.File('../../data/{}.hdf5'.format(filename), 'r') psi_plus = data_file['wavefunction/psi_plus'] psi_0 = data_file['wavefunction/psi_0'] psi_...
3,321
1,502
import attr import yaml from boltun.engine import Engine @attr.s class YamlProcessor(object): engine = attr.ib(default=attr.Factory(Engine)) def __enable__(self, tag="!boltun", resolver=False): yaml.add_constructor(tag, self) if resolver: yaml.add_implicit_resolver(tag, self._ma...
618
186
from abstract.apps import AbstractConfig from .loader import CVK2015Loader from .elastic_models import ElasticCVK2015Model, cvk_2015_idx class CVK2015Config(AbstractConfig): name = "cvk_2015" verbose_name = "Учасники місцевих виборів 2015-го року" short_name = "Регіони" loader_class = CVK2015Loader ...
681
253
# -*- coding: UTF-8 -*- """ 使用PIL lib生成验证码(前提:pip install PIL) """ from PIL import Image,ImageFont,ImageDraw,ImageFilter import os import random import time import json def gen_special_img(text, file_path, width, height): # 生成img文件 fontSize = 16 backGroundColor = (102,142,107) fontColor = (112,66,60) ...
2,296
929
import os import time import csv import pickle import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data.dataloader import DataLoader from torch.nn.utils import clip_grad_norm_ as clip_grad_norm from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt...
30,022
9,673
import psycopg2 # import sqlite3 DB_NAME = "ekasuicm" DB_USER = "ekasuicm" DB_PASSWORD = "5xL04dTyJuqjmPNeDPWsHjZsCnMmqpbM" DB_HOST = "ruby.db.elephantsql.com" connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST) print("CONNECTION", ...
561
225
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) from telegram import Updater from commands import history, cat, cd, get, ls, pwd, save from sett...
3,414
1,136