text
string
size
int64
token_count
int64
"""Xiaomi lumi.plug plug.""" import logging from zigpy.profiles import zha from zigpy.zcl.clusters.general import ( AnalogInput, Basic, BinaryOutput, DeviceTemperature, Groups, Identify, OnOff, Ota, PowerConfiguration, Scenes, Time, ) from zhaquirks.xiaomi import ( LUMI...
4,015
1,279
import os import sys import json import time import numpy as np import tensorflow as tf from blocks.helpers import Monitor from blocks.helpers import visualize_samples, get_nonlinearity, int_shape, get_trainable_variables, broadcast_masks_np from blocks.optimizers import adam_updates import data.load_data as load_data ...
5,193
1,843
from nose.tools import * from unittest.mock import patch, Mock from rxaws.source.sourcebase import SourceBase from botocore.client import BaseClient class BaseClient(Mock): """ mock boto BaseClient, won't really do anything""" class TestSourceBase: # inject the mock BaseClient @patch('boto3.client', retu...
993
284
import pytest from checkout_sdk.events.events import RetrieveEventsRequest from checkout_sdk.events.events_client import EventsClient @pytest.fixture(scope='class') def client(mock_sdk_configuration, mock_api_client): return EventsClient(api_client=mock_api_client, configuration=mock_sdk_configuration) class T...
1,725
532
from __future__ import print_function import os import numpy as np from tqdm import trange from models import * from utils import save_image class Trainer(object): def __init__(self, config, batch_manager): tf.compat.v1.set_random_seed(config.random_seed) self.config = config self.batch_m...
9,261
3,130
grana = float(input("Informe a quantidade de dinherio: R$")) dolar = 5.4 print(f" Dá pra comprar USS${grana / dolar} com o valor atual na sua carteira") print(f"Cotação usada: {dolar}")
188
76
from zerocopy import send_from from socket import * s = socket(AF_INET, SOCK_STREAM) s.bind(('', 25000)) s.listen(1) c,a = s.accept() import numpy a = numpy.arange(0.0, 50000000.0) send_from(a, c) c.close()
210
107
# # author: Sachin Mehta # Project Description: This repository contains source code for semantically segmenting WSIs; however, it could be easily # adapted for other domains such as natural image segmentation # File Description: This file contains the CNN models # ====================================...
22,168
9,205
""" Technically, a every problem is a program; but not every program is a problem. This distinction only really matters if we introduce nodes for For loops and whatnot. Then the problem has 'program-like' constructs. """
239
62
# Copyright 2015 Isotoma Limited # # 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...
1,526
447
#!/bin/bash # -*- coding: utf-8 -*- # Crawler Main # # Author : Tau Woo # Date : 2018-07-19 from do.crawler import Do from sys import argv if __name__ == "__main__": '''Crawler Main Start crawl websites with appointed config. ''' # You will get appointed crawler name from command. crawl...
548
211
from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog gui = Tk() gui.title('RODNET | Inzva AI Project Showcase v0.1') #logo var en son ekleriz yorumda kalabilir logo_image_path = Image.open('./images/inzva_logo.png') inzva_logo = ImageTk.PhotoImage(logo_image_path) inzva_logo_label = La...
1,660
588
# Copyright (C) 2014, 2015 University of Vienna # All rights reserved. # BSD license. # Author: Ali Baharev <ali.baharev@gmail.com> # Heap-based minimum-degree ordering with NO lookahead. # # See also min_degree.py which uses lookahead, and simple_md.py which is a # hacked version of min_degree.py that still uses re...
7,233
2,561
import json from wit import Wit access_token = "2PLFUWBVVTYQCSEL6VDJ3AFQLUCTV7ZH" client = Wit(access_token=access_token) def wit_handler(event, context): utterance = 'good morning john' response = client.message(msg=utterance) intent = None entity = None try: intent = list(response['inte...
498
175
# # Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending # import unittest from deephaven import read_csv, DHError from deephaven.plot import Color, Colors from deephaven.plot import Figure from deephaven.plot import LineEndStyle, LineStyle from tests.testbase import BaseTestCase class ColorTestCase(Base...
1,674
671
# # genmap_support.py: Multibyte Codec Map Generator # # Original Author: Hye-Shik Chang <perky@FreeBSD.org> # Modified Author: Dong-hee Na <donghee.na92@gmail.com> # class BufferedFiller: def __init__(self, column=78): self.column = column self.buffered = [] self.cline = [] self...
6,199
2,137
# Copyright 2019 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,...
3,487
1,123
""" timecompliexty = O(nlog(n)) separate start and end time into two list sort each of them use s,e represent start and end index from 0 iterate start time list by while loop compare start[s] end[e] if start >= end means after cur meeting finish another one can use the meeting room ,no need to add a new room else mea...
1,031
305
import uiza from uiza import Connection from uiza.api_resources.base.base import UizaBase from uiza.settings.config import settings from uiza.utility.utility import set_url class Entity(UizaBase): def __init__(self): self.connection = Connection(workspace_api_domain=uiza.workspace_api_domain, api_key=uiz...
3,528
1,034
# Copyright 2020 Mario Graff Guerrero # 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 wri...
15,851
4,926
#!/usr/bin/env python """ @package mi.dataset.parser.test.test_nutnrb @file marine-integrations/mi/dataset/parser/test/test_nutnrb.py @author Roger Unwin @brief Test code for a Nutnrb data parser """ import unittest import gevent from StringIO import StringIO from nose.plugins.attrib import attr from mi.core.log imp...
23,700
14,356
import numpy as np import pytest import os from modules.data import BenchmarkData, DataSetType DIR_PATH = os.path.dirname(os.path.realpath(__file__)) BASE_PATH = os.path.join(DIR_PATH, "..", "..") MNIST_PATH = os.path.join(BASE_PATH, "datasets", "mnist") class TestBenchmarkData: """ Test functionality of...
1,252
420
""" taskmaster.example ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ def get_jobs(last=0): # last_job would be sent if state was resumed # from a previous run for i in xrange(last, 20000): yield i def handle_job(i): pass ...
342
134
""" Given a file containing a list of constituent staging dirs for a DCP release (aka a manifest), verify that data has been loaded from each of them to the target DCP dataset and the count of loaded files matches the # in the staging area. Files are determined to be loaded if they exist at the desired target path and...
12,567
3,812
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Name: test_component # Purpose: Test driver for module component # # Author: Michael Amrhein (michael@adrhinum.de) # # Copyright: (c) 2014 Michael Amrhein # ------------------------------------------...
7,780
2,605
# # Copyright (C) 2018 Neal Digre. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. """Data exploration. If this file is changed, please also change the ``:lines:`` option in the following files where this code is referenced with the ``literalin...
1,112
384
# import the built in auth types so they can be registered import backend.czi_hosted.auth.auth_test # noqa: F401 import backend.czi_hosted.auth.auth_session # noqa: F401 import backend.czi_hosted.auth.auth_oauth # noqa: F401 import backend.czi_hosted.auth.auth_none # noqa: F401
284
111
import os from json import JSONDecodeError from json import dump from json import load import numpy as np from core.net_errors import JsonFileStructureIncorrect, JsonFileNotFound def upload(net_object, path): if not os.path.isfile(path): raise JsonFileNotFound() try: with open(path, 'r') as...
1,534
462
""" Django settings for analytics project. Generated by 'django-admin startproject' using Django 1.11.10. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import...
5,292
2,003
""" The Office 365 Social Engineering Email draft producer uses a customized library of methods in this master class to maintain continuous delivery. This repository is controlled by a single boolean that is set to false by default. Please ensure that the emailDraft.py file is correct. """ # Built-in Imports import os...
4,396
1,331
from datetime import datetime from csv import DictReader from numpy import mean from numpy import median import pickle import unittest from config import path_to_pickled_counter from config import path_to_tsv class TestDataMethods(unittest.TestCase): @classmethod def setUpClass(cls): with open(pa...
1,357
474
#!/usr/bin/env python import sys, serial import numpy as np from collections import deque import itertools import csv from datetime import datetime import time import rospy from std_msgs.msg import Int32MultiArray class Sensor: def __init__(self, strPort, maxLen): self.ser = serial.Serial(str...
2,950
1,044
import unittest from tic_tac_toe.TicTacToe import TicTacToe def board_starter(spot:int): game = TicTacToe() status = game.play_turn(spot) return game, status class test_play_turn(unittest.TestCase): def test_perfect_case(self): game, status = board_starter(1) board = '|x|2|3|\n-------\...
2,847
1,112
from env_wrapper import SubprocVecEnv, DummyVecEnv import numpy as np import multiagent.scenarios as scenarios from multiagent.environment import MultiAgentEnv def make_parallel_env(n_rollout_threads, seed=1): def get_env_fn(rank): def init_env(): env = make_env("simple_adversary") ...
863
281
from math import log10 from typing import List, Any from talipp.indicators.Indicator import Indicator from talipp.indicators.ATR import ATR from talipp.ohlcv import OHLCV class CHOP(Indicator): """ Choppiness Index Output: a list of OHLCV objects """ def __init__(self, period: int, input_values...
1,115
373
import time import logging from urllib.parse import urljoin from .strategy import DEFAULT_STRATEGIES from .io import UrlFetcher, Reporter from .features import Feature log = logging.getLogger(__name__) def name_instance(): import os import socket return "%s:%s" % (socket.gethostname(), os.getpid()) c...
2,177
625
# # PySNMP MIB module JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:00:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using...
269,482
139,412
import logging import os from logging import FileHandler, Formatter from logging.handlers import TimedRotatingFileHandler from pathlib import Path from rich.logging import RichHandler def my_namer(default_name): # This will be called when doing the log rotation # default_name is the default filename that wou...
2,074
689
#!/usr/bin/env python import os import sys import anyconfig import re import time import importlib import pdb from select import poll, POLLIN from statsd import StatsClient def import_class(klass): (module, klass) = klass.rsplit('.', 1) module = importlib.import_module(module) return getattr(module, klass...
3,018
1,072
#!/usr/bin/env python3 import os import time import binascii import codecs def swap_order(d, wsz=16, gsz=2 ): return "".join(["".join([m[i:i+gsz] for i in range(wsz-gsz,-gsz,-gsz)]) for m in [d[i:i+wsz] for i in range(0,len(d),wsz)]]) expected_genesis_hash = "00000009c4e61bee0e8d6236f847bb1dd23f4c61ca5240b748521...
5,523
2,455
from AlphaGo.models.policy import CNNPolicy from AlphaGo import go from AlphaGo.go import GameState from AlphaGo.ai import GreedyPolicyPlayer, ProbabilisticPolicyPlayer import numpy as np import unittest import os class TestCNNPolicy(unittest.TestCase): def test_default_policy(self): policy = CNNPolicy(["board", ...
3,311
1,348
# -*- coding: utf-8 -*- # # Copyright 2016 Matt Austin # # 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...
1,840
580
import time from anchore_engine import db from anchore_engine.db import User def add(userId, password, inobj, session=None): if not session: session = db.Session() #our_result = session.query(User).filter_by(userId=userId, password=password).first() our_result = session.query(User).filter_by...
1,879
581
import copy from abc import ABC, abstractmethod from collections import namedtuple from contextlib import contextmanager from pathlib import PurePath from typing import Any, Iterable, Iterator, Optional, Union, cast import numpy as np import segyio import segyio.tools from cached_property import cached_property from u...
10,116
3,354
""" Simple API Interface for Maggma """
40
11
import colorsys palette_size = 80 palette = [] for i in range(palette_size): t = i / (palette_size - 1) h = t * (60 / 360) l = t s = 1.0 color = colorsys.hls_to_rgb(h, l, s) color = tuple(map(lambda x: round(x * 63), color)) palette.append(color) with open('palette.asm', 'w', newline='\n'...
522
219
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * host = "training.pwnable.tw" port = 11007 r = remote(host,port) password_addr = 0x804a048 r.recvuntil("?") r.sendline(p32(password_addr) + "#" + "%10$s" + "#" ) r.recvuntil("#") p = r.recvuntil("#") password = u32(p[:4]) r.recvuntil(":") r.sendline(s...
350
170
#!/usr/bin/env python import sys from fitparse.records import Crc if sys.version_info >= (2, 7): import unittest else: import unittest2 as unittest class RecordsTestCase(unittest.TestCase): def test_crc(self): crc = Crc() self.assertEqual(0, crc.value) crc.update(b'\x0e\x10\x98\...
675
274
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") BAZEL_INSTALLER = struct( revision = "4.0.0", sha256 = "bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2", ) DEBS_TARBALL = struct( revision = "1608132805", sha256 = "7ed2d4869f19c11d8c39345bd75f908a51410bf4e512e9fc368ad...
1,420
625
if __name__ == '__main__': n = int(input()) s = set() for i in range (n): s.add(input()) print((len(s)))
143
55
# -*- coding: utf-8 -*- from sakf.sakf import main if __name__ == '__main__': main()
87
39
from sphere_engine import CompilersClientV4 from sphere_engine.exceptions import SphereEngineException import time # define access parameters accessToken = '77501c36922866a03b1822b4508a50c6' endpoint = 'dd57039c.compilers.sphere-engine.com' # initialization client = CompilersClientV4(accessToken, endpoint) # API us...
2,741
860
import tkinter as tk import gui wd = tk.Tk() gui = gui.GUI(wd) wd.mainloop()
84
41
import datetime from flask_ldap3_login import LDAP3LoginManager, AuthenticationResponseStatus from lost.settings import LOST_CONFIG, FLASK_DEBUG from flask_jwt_extended import create_access_token, create_refresh_token from lost.db.model import User as DBUser, Group from lost.db import roles class LoginManager(): de...
3,306
1,017
import os import torch import numpy as np import torch.nn as nn import matplotlib.pyplot as plt def get_param_matrix(model_prefix, model_dir): """ Grabs the parameters of a saved model and returns them as a matrix """ # Load and combine the parameters param_matrix = [] for file in os.listdir(...
1,198
373
""" Functions to anglicize integers in the range 1..19 This is a simple example for now. We will see a more complex version of this later. Author: Walker M. White Date: March 30, 2019 """ def anglicize(n): """ Returns: English equiv of n. Parameter: the integer to anglicize Precondition: n in 1....
1,103
409
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here import sys from collections import defaultd...
919
312
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root, target, K): """ :type root: TreeNode :type target: TreeNode :type K: int ...
361
111
"""Contiain the version of the package""" __version__ = "0.2.0"
64
25
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2019 Romain Boman # # 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 # #...
13,343
4,166
import numpy as np import tor4 import tor4.nn as nn def test_softmax(): a = tor4.tensor(data=[0, 0, 0.0]) a_sm = nn.functional.softmax(a, dim=0) assert not a_sm.requires_grad assert a_sm.tolist() == [1 / 3, 1 / 3, 1 / 3] def test_softmax2(): a = tor4.tensor(data=[[0, 0, 0], [0, 0, 0.0]]) a...
4,036
2,158
#coding=utf-8 __author__ = 'zxlee' __github__ = 'https://github.com/SmileZXLee/forestTool' import json import time import HttpReq from User import User from datetime import datetime,timedelta import sched import sys import os import platform from dateutil.parser import parse #是否是Windows os_is_windows = platform.system...
8,316
4,870
# -*- coding: utf-8 -*- from services.Services import Services # NFSe Provider taxId = "87654321000198" providerSubscription = "12345678" # Provider city subscription # NFSe Taker companyName = "SOME COMPANY LTDA" takerTaxId = "12345678000198" objServ = Services( certificateContent=open("../certfiles/converted...
1,207
475
# -*- coding:utf-8 -*- # @Time:2020/6/15 11:38 # @Author:TimVan # @File:leetcode.py # @Software:PyCharm # Definition for singly-linked list. # for j in range(10, 5, -1): # print(j) print('a'.find(' '))
208
106
from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer class KerasBow(object): """doc 词袋模型:我们可以为数据集中的所有单词制作一张词表,然后将每个单词和一个唯一的索引关联。 每个句子都是由一串数字组成,这串数字是词表中的独立单词对应的个数。 通过列表中的索引,我们可以统计出句子中某个单词出现的次数。 """ def __init__(self, num_words=20000, maxlen=None...
1,337
575
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-02-18 16:24 from django.db import migrations countries = { "Ma\u010farsko": "HU", "Czech Republic": "CZ", "\u010cesk\xe1 republika": "CZ", "United Kingdom": "GB", "Austria": "AT", "Madarsko": "HU", "Australia": "AU", "Srbsko":...
1,300
536
from pypsi.shell import Shell from pypsi.commands.tail import TailCommand class CmdShell(Shell): tail = TailCommand() class TestTail: def setup(self): self.shell = CmdShell() def teardown(self): self.shell.restore()
249
84
# -*- coding: utf-8 -*- ''' 常量 ''' import base64 from django.utils.translation import ugettext_lazy as _ DOMAIN_BASIC_PARAMS = ( (u"cf_limit_mailbox_cnt", _(u"限定邮箱数量")), #(u"cf_limit_alias_cnt", u"限定别名数量"), #这个开关没人用 (u"cf_limit_mailbox_size", _(u"限定邮箱空间总容量")), (u"cf_limit_netdisk_size", _(u"限定...
20,322
10,897
# SPDX-FileCopyrightText: 2020 2020 # # SPDX-License-Identifier: Apache-2.0 from __future__ import absolute_import import os import os.path as op from os.path import dirname as dn from os.path import basename as bn from shutil import copy from . import alert_actions_exceptions as aae from . import arf_consts as ac fr...
3,924
1,279
from django.db import models from django.conf import settings # Create your models here. class UserRegistrationModel(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
226
68
import json import typing from collections.abc import Collection from decimal import Decimal from functools import reduce class QueryPredicate: AND = "AND" OR = "OR" _operators = { "exact": "=", "gte": ">=", "lte": "=<", "lt": "<", "gt": ">", "is_defined": ...
2,499
771
from django.shortcuts import render, redirect from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserRegisterForm() ...
385
103
import logging from sockjs.tornado import SockJSConnection from thunderpush.sortingstation import SortingStation try: import simplejson as json except ImportError: import json logger = logging.getLogger() class ThunderSocketHandler(SockJSConnection): def on_open(self, info): logger.debug("New c...
3,155
875
# Generated by Django 3.2 on 2021-05-05 11:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('archiv', '0014_stelle_ort'), ] operations = [ migrations.AddField( model_name='stelle', name='end_date', f...
679
225
# Spam filter # Take a list of dishes from a menu and add “spam” to them. See https://en.wikipedia.org/wiki/Spam_(Monty_Python). def main(): try: dishCount = int(input('Enter number of dishes in menu > ')) dishes = [input(f'Enter Dish No.{i + 1} > ') for i in range(dishCount)] dishes = [f'{dish} spam' ...
494
181
import argparse class appOptions: show_devices = '--show-devices' clean_report = '--clean-report' device_config = '--device-config' global_config = '--global-config' test_case = '--test-case' tests_dir = '--tests-dir' device = '--device' test = '--test' service_address = '--ser...
6,816
2,050
""" Base settings to build other settings files upon. """ import environ import topobank ROOT_DIR = environ.Path(__file__) - 3 # (topobank/config/settings/base.py - 3 = topobank/) APPS_DIR = ROOT_DIR.path('topobank') env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) if REA...
20,596
6,983
import requests from teste_app import settigns def google(q: str): """Faz uma pesquisa no google""" return requests.get(settigns.GOOGLE, params={"q": q})
166
62
# github link: https://github.com/ds-praveenkumar/kaggle # Author: ds-praveenkumar # file: forcasting/prepare_train_data.py/ # Created by ds-praveenkumar at 13-06-2020 15 34 # feature: import os import pandas as pd import numpy as np import click from src.utility.timeit import timeit root = os.path.dirname(os.getcwd(...
1,275
500
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with # the License. A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file acco...
2,338
653
import psycopg2 import psycopg2.extras import sys from sqlalchemy import create_engine import pandas as pd def get_cursor(): conn_string = "host='localhost' dbname='HintereggerA' user='HintereggerA' password='root'" # print the connection string we will use to connect print("Connecting to database: {}".format(conn...
1,041
331
arguments = ["self", "info", "args"] helpstring = "lurk" minlevel = 3 def main(connection, info, args) : """Deops and voices the sender""" connection.rawsend("MODE %s -o+v %s %s\n" % (info["channel"], info["sender"], info["sender"]))
243
86
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'volume_layout.ui' # # Created: Tue Mar 26 12:40:36 2013 # by: PyQt4 UI code generator 4.7.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Dialog...
6,982
2,490
import textwrap from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, String, Boolean from .base_model import Base from .port_model import Port from .ip_address_model import IPAddress from .nse_model import nse_result_association_table class NmapResult(Base): """ Database m...
2,780
872
def main(): a = ["a", 1, "5", 2.3, 1.2j] some_condition = True for x in a: # If it's all isinstance, we can use a type switch if isinstance(x, (str, float)): print("String or float!") elif isinstance(x, int): print("Integer!") else: print("...
697
215
from sarcsdet.configs.ling_feat_config import interjections, funny_marks def funny_marks_feature(text): text_set = (str(text)).split() return sum([text_set.count(x) for x in funny_marks]) def interjections_feature(text): text_set = (str(text)).split() return sum([text_set.count(x) for x in interject...
964
307
# Author: Proloy Das <proloy@umd.edu> """Module implementing the FASTA algorithm""" import numpy as np from math import sqrt from scipy import linalg import time import logging def _next_stepsize(deltax, deltaF, t=0): """A variation of spectral descent step-size selection: 'adaptive' BB method. Reference: ...
8,887
2,967
# -*- coding: utf-8 -*- # Author: XuMing <xuming624@qq.com> # Brief: import os import pickle def load_pkl(pkl_path): """ 加载词典文件 :param pkl_path: :return: """ with open(pkl_path, 'rb') as f: result = pickle.load(f) return result def dump_pkl(vocab, pkl_path, overwrite=True): ...
607
260
import copy import _mecab from collections import namedtuple from typing import Generator from mecab import MeCabError from domain.mecab_domain import MecabWordFeature def delete_pattern_from_string(string, pattern, index, nofail=False): """ 문자열에서 패턴을 찾아서 *로 변환해주는 기능 """ # raise an error if index is outsid...
5,839
2,413
import pkg_resources from subprocess import call packages = [dist.project_name for dist in pkg_resources.working_set] call( f"pip install --upgrade --no-cache-dir {' '.join(packages)}", shell=True )
206
67
from abc import abstractmethod from typing import TypeVar from yaga_ga.evolutionary_algorithm.operators.base import GeneticOperator IndividualType = TypeVar("IndividualType") GeneType = TypeVar("GeneType") class SingleIndividualOperator(GeneticOperator[IndividualType, GeneType]): @abstractmethod def __call_...
385
110
import logging import os import struct import binascii import gevent from gevent import socket, ssl from gevent.event import Event from gevent.queue import Queue from ..base.service import BaseService from .notification import APNSNotification INITIAL_TIMEOUT = 5 MAX_TIMEOUT = 600 logger = logging.getLogger(__nam...
7,746
2,176
#!/usr/bin/python # -*- coding: utf-8 -*- import warnings import json import os import decimal import re from MySQLdb import escape_string def to_unicode(obj, encoding='utf-8'): if isinstance(obj, basestring): if not isinstance(obj, unicode): obj = unicode(obj, encoding) if isinstance(obj,...
36,295
10,379
import MySQLdb from urllib import parse class PySQL: """ For making Mariadb / Mysql db queries """ FILTER_COMMANDS = { "$eq":" = %s ", "$in":" IN (%s) ", "$nin":" NOT IN (%s) ", "$neq":" != %s ", "$lt":" < %s ", "$lte":" <= %s ", "$gt":" ...
17,976
5,585
from tensorflow.keras.preprocessing import image from tensorflow.keras.models import model_from_json import numpy as np import tensorflow.keras.models as models def predict(temp_file): test_image = image.load_img(temp_file, target_size = (224, 224)) test_image = image.img_to_array(test_image) test_image = ...
634
213
from pyrogram import Client, Filters @Client.on_message(Filters.command(["help"])) async def start(client, message): helptxt = f"Currently Only supports Youtube Single (No playlist) Just Send Youtube Url But You must join my Updation channel👉👉 @Mega_Bots_Updates" await message.reply_text(helptxt)
310
109
#!/usr/bin/env python3 ############################################################################## ## This file is part of 'PGP PCIe APP DEV'. ## It is subject to the license terms in the LICENSE.txt file found in the ## top-level directory of this distribution and at: ## https://confluence.slac.stanford.edu/disp...
4,865
1,542
import inspect import json from .serialisation import JsonObjHelper, JsonTypeError class RpcMethod: """Encapsulate argument/result (de)serialisation for a function based on a type-annotated function signature and name. """ def __init__(self, name, signature, doc=None): if ( signat...
3,446
941
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_descrip...
1,567
501
import os from django.core.mail import send_mail from django.urls import reverse from django.contrib.sites.models import Site from django.template.loader import render_to_string def email_all_users_an_email(user, showlist): #Gets the current domain name domain = Site.objects.get_current().domain # revers...
2,506
784