content
stringlengths
7
928k
avg_line_length
float64
3.5
33.8k
max_line_length
int64
6
139k
alphanum_fraction
float64
0.08
0.96
licenses
sequence
repository_name
stringlengths
7
104
path
stringlengths
4
230
size
int64
7
928k
lang
stringclasses
1 value
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bwscoind will dump mempool on shutdown and then reload it on startup. This can be overridden with the -persistmempool=0 command line option. Test is as follows: - start node0, node1 and node2. node1 has -persistmempool=0 - create 5 transactions on node2 to its own address. Note that these are not sent to node0 or node1 addresses because we don't want them to be saved in the wallet. - check that node0 and node1 have 5 transactions in their mempools - shutdown all nodes. - startup node0. Verify that it still has 5 transactions in its mempool. Shutdown node0. This tests that by default the mempool is persistent. - startup node1. Verify that its mempool is empty. Shutdown node1. This tests that with -persistmempool=0, the mempool is not dumped to disk when the node is shut down. - Restart node0 with -persistmempool=0. Verify that its mempool is empty. Shutdown node0. This tests that with -persistmempool=0, the mempool is not loaded from disk on start up. - Restart node0 with -persistmempool. Verify that it has 5 transactions in its mempool. This tests that -persistmempool=0 does not overwrite a previously valid mempool stored on disk. - Remove node0 mempool.dat and verify savemempool RPC recreates it and verify that node1 can load it and has 5 transaction in its mempool. - Verify that savemempool throws when the RPC is called if node1 can't write to disk. """ import os import time from test_framework.test_framework import BWScoinTestFramework from test_framework.util import * class MempoolPersistTest(BWScoinTestFramework): def set_test_params(self): self.num_nodes = 3 self.extra_args = [[], ["-persistmempool=0"], []] def run_test(self): chain_height = self.nodes[0].getblockcount() assert_equal(chain_height, 200) self.log.debug("Mine a single block to get out of IBD") self.nodes[0].generate(1) self.sync_all() self.log.debug("Send 5 transactions from node2 (to its own address)") for i in range(5): self.nodes[2].sendtoaddress(self.nodes[2].getnewaddress(), Decimal("10")) self.sync_all() self.log.debug("Verify that node0 and node1 have 5 transactions in their mempools") assert_equal(len(self.nodes[0].getrawmempool()), 5) assert_equal(len(self.nodes[1].getrawmempool()), 5) self.log.debug("Stop-start node0 and node1. Verify that node0 has the transactions in its mempool and node1 does not.") self.stop_nodes() self.start_node(0) self.start_node(1) # Give bwscoind a second to reload the mempool time.sleep(1) wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.log.debug("Stop-start node0 with -persistmempool=0. Verify that it doesn't load its mempool.dat file.") self.stop_nodes() self.start_node(0, extra_args=["-persistmempool=0"]) # Give bwscoind a second to reload the mempool time.sleep(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.log.debug("Stop-start node0. Verify that it has the transactions in its mempool.") self.stop_nodes() self.start_node(0) wait_until(lambda: len(self.nodes[0].getrawmempool()) == 5) mempooldat0 = os.path.join(self.options.tmpdir, 'node0', 'regtest', 'mempool.dat') mempooldat1 = os.path.join(self.options.tmpdir, 'node1', 'regtest', 'mempool.dat') self.log.debug("Remove the mempool.dat file. Verify that savemempool to disk via RPC re-creates it") os.remove(mempooldat0) self.nodes[0].savemempool() assert os.path.isfile(mempooldat0) self.log.debug("Stop nodes, make node1 use mempool.dat from node0. Verify it has 5 transactions") os.rename(mempooldat0, mempooldat1) self.stop_nodes() self.start_node(1, extra_args=[]) wait_until(lambda: len(self.nodes[1].getrawmempool()) == 5) self.log.debug("Prevent bwscoind from writing mempool.dat to disk. Verify that `savemempool` fails") # to test the exception we are setting bad permissions on a tmp file called mempool.dat.new # which is an implementation detail that could change and break this test mempooldotnew1 = mempooldat1 + '.new' with os.fdopen(os.open(mempooldotnew1, os.O_CREAT, 0o000), 'w'): pass assert_raises_rpc_error(-1, "Unable to dump mempool to disk", self.nodes[1].savemempool) os.remove(mempooldotnew1) if __name__ == '__main__': MempoolPersistTest().main()
44.558559
127
0.694703
[ "MIT" ]
bwsnetwork/bwscoin
test/functional/mempool_persist.py
4,946
Python
# Copyright (c) 2015 Nicolas JOUANIN # # See the file license.txt for copying permission. import logging from functools import partial class EventLoggerPlugin: def __init__(self, context): self.context = context async def log_event(self, *args, **kwargs): self.context.logger.info("### '%s' EVENT FIRED ###", kwargs['event_name'].replace('old', '')) def __getattr__(self, name): if name.startswith("on_"): return partial(self.log_event, event_name=name) class PacketLoggerPlugin: def __init__(self, context): self.context = context async def on_mqtt_packet_received(self, *args, **kwargs): packet = kwargs.get('packet') session = kwargs.get('session', None) if self.context.logger.isEnabledFor(logging.DEBUG): if session: self.context.logger.debug("%s <-in-- %r", session.client_id, packet) else: self.context.logger.debug("<-in-- %r", packet) async def on_mqtt_packet_sent(self, *args, **kwargs): packet = kwargs.get('packet') session = kwargs.get('session', None) if self.context.logger.isEnabledFor(logging.DEBUG): if session: self.context.logger.debug("%s -out-> %r", session.client_id, packet) else: self.context.logger.debug("-out-> %r", packet)
32.325581
101
0.615827
[ "MIT" ]
norwood867/distmqtt
distmqtt/plugins/logging.py
1,390
Python
""" WSGI config for share_all project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "share_all.settings") application = get_wsgi_application()
23.294118
78
0.787879
[ "MIT" ]
yingshaoxo/Share_All
share_all/wsgi.py
396
Python
RAW_DATA_PATH = 'data/raw' PROCESSED_DATA_PATH = 'data/processed' OUTPUT_DATA_PATH = 'data/output' MODELS_PATH = 'models' REPORTS_PATH = 'reports' continuous = ['temp', 'atemp','hum', 'windspeed', 'registered', 'cnt', 'casual', 'yr'] cyclic = ['season', 'mnth', 'hr', 'weekday'] categorical = ['holiday', 'workingday', 'weathersit'] drop = ['instant', 'dteday'] all_cols = continuous + cyclic + categorical + drop
32
86
0.685096
[ "MIT" ]
carlomazzaferro/scikit-hts-examples
src/settings.py
416
Python
# Copyright (C) 2019-2020 Intel Corporation # # SPDX-License-Identifier: MIT import attr from contextlib import ExitStack from distutils.util import strtobool as str_to_bool # pylint: disable=unused-import from functools import partial, wraps from itertools import islice from typing import Iterable, Tuple NOTSET = object() def find(iterable, pred=lambda x: True, default=None): return next((x for x in iterable if pred(x)), default) def cast(value, type_conv, default=None): if value is None: return default try: return type_conv(value) except Exception: return default def to_snake_case(s): if not s: return '' name = [s[0].lower()] for idx, char in enumerate(s[1:]): idx = idx + 1 if char.isalpha() and char.isupper(): prev_char = s[idx - 1] if not (prev_char.isalpha() and prev_char.isupper()): # avoid "HTML" -> "h_t_m_l" name.append('_') name.append(char.lower()) else: name.append(char) return ''.join(name) def pairs(iterable): a = iter(iterable) return zip(a, a) def take_by(iterable, count): """ Returns elements from the input iterable by batches of N items. ('abcdefg', 3) -> ['a', 'b', 'c'], ['d', 'e', 'f'], ['g'] """ it = iter(iterable) while True: batch = list(islice(it, count)) if len(batch) == 0: break yield batch def filter_dict(d, exclude_keys): return { k: v for k, v in d.items() if k not in exclude_keys } def parse_str_enum_value(value, enum_class, default=NOTSET, unknown_member_error=None): if value is None and default is not NOTSET: value = default elif isinstance(value, str): try: value = enum_class[value] except KeyError: raise ValueError((unknown_member_error or "Unknown element of {cls} '{value}'. " "The only known are: {available}") \ .format( cls=enum_class.__name__, value=value, available=', '.join(e.name for e in enum_class) ) ) elif isinstance(value, enum_class): pass else: raise TypeError("Expected value type string or %s, but got %s" % \ (enum_class.__name__, type(value).__name__)) return value def escape(s: str, escapes: Iterable[Tuple[str, str]]) -> str: """ 'escapes' is an iterable of (pattern, substitute) pairs """ for pattern, sub in escapes: s = s.replace(pattern, sub) return s def unescape(s: str, escapes: Iterable[Tuple[str, str]]) -> str: """ 'escapes' is an iterable of (pattern, substitute) pairs """ for pattern, sub in escapes: s = s.replace(sub, pattern) return s def optional_arg_decorator(fn): @wraps(fn) def wrapped_decorator(*args, **kwargs): if len(args) == 1 and callable(args[0]) and not kwargs: return fn(args[0], **kwargs) else: def real_decorator(decoratee): return fn(decoratee, *args, **kwargs) return real_decorator return wrapped_decorator class Rollback: @attr.attrs class Handler: callback = attr.attrib() enabled = attr.attrib(default=True) ignore_errors = attr.attrib(default=False) def __call__(self): if self.enabled: try: self.callback() except: # pylint: disable=bare-except if not self.ignore_errors: raise def __init__(self): self._handlers = {} self._stack = ExitStack() self.enabled = True def add(self, callback, *args, name=None, enabled=True, ignore_errors=False, fwd_kwargs=None, **kwargs): if args or kwargs or fwd_kwargs: if fwd_kwargs: kwargs.update(fwd_kwargs) callback = partial(callback, *args, **kwargs) name = name or hash(callback) assert name not in self._handlers handler = self.Handler(callback, enabled=enabled, ignore_errors=ignore_errors) self._handlers[name] = handler self._stack.callback(handler) return name do = add # readability alias def enable(self, name=None): if name: self._handlers[name].enabled = True else: self.enabled = True def disable(self, name=None): if name: self._handlers[name].enabled = False else: self.enabled = False def clean(self): self.__exit__(None, None, None) def __enter__(self): return self # pylint: disable=redefined-builtin def __exit__(self, type=None, value=None, traceback=None): if type is None: return if not self.enabled: return self._stack.__exit__(type, value, traceback) # pylint: enable=redefined-builtin @optional_arg_decorator def error_rollback(func, arg_name='on_error', implicit=False): @wraps(func) def wrapped_func(*args, **kwargs): with Rollback() as manager: if implicit: fglobals = func.__globals__ has_arg = arg_name in fglobals old_val = fglobals.get(arg_name) fglobals[arg_name] = manager try: func(*args, **kwargs) finally: if has_arg: func.__globals__[arg_name] = old_val else: func.__globals__.pop(arg_name) else: kwargs[arg_name] = manager func(*args, **kwargs) return wrapped_func
28.444444
83
0.564708
[ "MIT" ]
AdaptiveCity/datumaro
datumaro/util/__init__.py
5,888
Python
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.models import ModelForm from .models import Image,Comment,Profile class RegisterUserForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username','first_name','last_name','email','password1','password2') class ImageForm(ModelForm): class Meta: model = Image fields = ['image','name','caption','location' ] class ProfileForm(ModelForm): class Meta: model = Profile fields = ['bio','profile_pic' ] class CommentForm(ModelForm): class Meta: model = Comment fields =['content'] widgets = { 'content':forms.Textarea(attrs={'rows':2,'placeholder':'write comment'}), }
25.475
86
0.624141
[ "MIT" ]
kipsang01/bonga-app
bongaapp/forms.py
1,019
Python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/saver.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow/core/protobuf/saver.proto', package='tensorflow', syntax='proto3', serialized_options=b'\n\023org.tensorflow.utilB\013SaverProtosP\001ZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\370\001\001', create_key=_descriptor._internal_create_key, serialized_pb=b'\n$tensorflow/core/protobuf/saver.proto\x12\ntensorflow\"\x9e\x02\n\x08SaverDef\x12\x1c\n\x14\x66ilename_tensor_name\x18\x01 \x01(\t\x12\x18\n\x10save_tensor_name\x18\x02 \x01(\t\x12\x17\n\x0frestore_op_name\x18\x03 \x01(\t\x12\x13\n\x0bmax_to_keep\x18\x04 \x01(\x05\x12\x0f\n\x07sharded\x18\x05 \x01(\x08\x12%\n\x1dkeep_checkpoint_every_n_hours\x18\x06 \x01(\x02\x12=\n\x07version\x18\x07 \x01(\x0e\x32,.tensorflow.SaverDef.CheckpointFormatVersion\"5\n\x17\x43heckpointFormatVersion\x12\n\n\x06LEGACY\x10\x00\x12\x06\n\x02V1\x10\x01\x12\x06\n\x02V2\x10\x02\x42q\n\x13org.tensorflow.utilB\x0bSaverProtosP\x01ZHgithub.com/tensorflow/tensorflow/tensorflow/go/core/core_protos_go_proto\xf8\x01\x01\x62\x06proto3' ) _SAVERDEF_CHECKPOINTFORMATVERSION = _descriptor.EnumDescriptor( name='CheckpointFormatVersion', full_name='tensorflow.SaverDef.CheckpointFormatVersion', filename=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, values=[ _descriptor.EnumValueDescriptor( name='LEGACY', index=0, number=0, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), _descriptor.EnumValueDescriptor( name='V1', index=1, number=1, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), _descriptor.EnumValueDescriptor( name='V2', index=2, number=2, serialized_options=None, type=None, create_key=_descriptor._internal_create_key), ], containing_type=None, serialized_options=None, serialized_start=286, serialized_end=339, ) _sym_db.RegisterEnumDescriptor(_SAVERDEF_CHECKPOINTFORMATVERSION) _SAVERDEF = _descriptor.Descriptor( name='SaverDef', full_name='tensorflow.SaverDef', filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='filename_tensor_name', full_name='tensorflow.SaverDef.filename_tensor_name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='save_tensor_name', full_name='tensorflow.SaverDef.save_tensor_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='restore_op_name', full_name='tensorflow.SaverDef.restore_op_name', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='max_to_keep', full_name='tensorflow.SaverDef.max_to_keep', index=3, number=4, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='sharded', full_name='tensorflow.SaverDef.sharded', index=4, number=5, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='keep_checkpoint_every_n_hours', full_name='tensorflow.SaverDef.keep_checkpoint_every_n_hours', index=5, number=6, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), _descriptor.FieldDescriptor( name='version', full_name='tensorflow.SaverDef.version', index=6, number=7, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], nested_types=[], enum_types=[ _SAVERDEF_CHECKPOINTFORMATVERSION, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=53, serialized_end=339, ) _SAVERDEF.fields_by_name['version'].enum_type = _SAVERDEF_CHECKPOINTFORMATVERSION _SAVERDEF_CHECKPOINTFORMATVERSION.containing_type = _SAVERDEF DESCRIPTOR.message_types_by_name['SaverDef'] = _SAVERDEF _sym_db.RegisterFileDescriptor(DESCRIPTOR) SaverDef = _reflection.GeneratedProtocolMessageType('SaverDef', (_message.Message,), { 'DESCRIPTOR' : _SAVERDEF, '__module__' : 'tensorflow.core.protobuf.saver_pb2' # @@protoc_insertion_point(class_scope:tensorflow.SaverDef) }) _sym_db.RegisterMessage(SaverDef) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
44.482993
727
0.768466
[ "Apache-2.0" ]
alexeygrigorev/tensorflow-protobuf
tensorflow/core/protobuf/saver_pb2.py
6,539
Python
import urllib.request, urllib.parse, urllib.error import json url = input('Web page: ') print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read().decode() info = json.loads(data) # info é um dict do tipo: # {'note': 'This file contains the sample data for testing', 'comments': [{'name': 'Romina', 'cou ... # * print(info['comments']) # a primeira subdivisao é entre 'notes' e 'comments' total = list() for item in info['comments']: # * print(item) # cada item é um dict com 'name' e 'count' total.append(int(item['count'])) total2 = [int(item['count']) for item in info['comments']] # list Comprehensions é mais legal print(sum(total2))
23.7
102
0.632911
[ "MIT" ]
Felipe-Tommaselli/Python4everbody_Michigan
book3/s6_ex3.py
715
Python
#Embedded file name: ACEStream\Player\BaseApp.pyo import os import sys import time import shutil import urllib import hashlib import binascii import random import subprocess import struct import pickle import cookielib from operator import itemgetter from base64 import b64encode, encodestring from types import DictType, StringType if sys.platform == 'win32': import win32file import win32api from ACEStream.Core.Utilities.win32regchecker import Win32RegChecker, HKLM, HKCU from threading import enumerate, currentThread, Lock, Timer from traceback import print_stack, print_exc from ACEStream.Video.utils import svcextdefaults from ACEStream.Core.Utilities.odict import odict from ACEStream.Core.Utilities.timeouturlopen import urlOpenTimeout if sys.platform == 'darwin': os.chdir(os.path.abspath(os.path.dirname(sys.argv[0]))) from ACEStream.__init__ import DEFAULT_SESSION_LISTENPORT from ACEStream.version import VERSION, VERSION_REV from ACEStream.env import TS_ENV_PLATFORM from ACEStream.GlobalConfig import globalConfig from ACEStream.Core.API import * from ACEStream.Policies.RateManager import UserDefinedMaxAlwaysOtherwiseEquallyDividedRateManager from ACEStream.Utilities.Instance2Instance import * from ACEStream.Utilities.TimedTaskQueue import TimedTaskQueue from ACEStream.Core.BitTornado.__init__ import createPeerID from ACEStream.Video.utils import videoextdefaults from ACEStream.Core.Utilities.logger import log, log_exc from ACEStream.Core.Utilities.unicode import unicode2str_safe from ACEStream.Core.Ads.Manager import AdManager from ACEStream.Core.TS.Service import TSService from ACEStream.Core.Utilities.mp4metadata import clear_mp4_metadata_tags_from_file from ACEStream.Core.Statistics.GoogleAnalytics import GoogleAnalytics from ACEStream.Core.Statistics.TNS import TNS, TNSNotAllowedException from ACEStream.Core.Statistics.Settings import RemoteStatisticsSettings from ACEStream.Core.Statistics.TrafficStatistics import TrafficStatistics from ACEStream.Core.APIImplementation.FakeDownload import FakeDownload from ACEStream.Utilities.HardwareIdentity import get_hardware_key from ACEStream.Utilities.LSO import LSO if sys.platform == 'win32': TNS_ENABLED = True else: TNS_ENABLED = False DEVELOPER_MODE = False DEBUG = False DEBUG_AD_STORAGE = False DEBUG_HIDDEN_DOWNLOADS = False DEBUG_SERVICE_REQUESTS = False DEBUG_STATS_TO_FILE = False DEBUG_PREMIUM = False RATELIMITADSL = False DOWNLOADSPEED = 300 DEFAULT_DISKSPACE_LIMIT = 10737418240L import os current_file_path = os.path.dirname(os.path.realpath(__file__)) downloadlimitvalue_file = os.path.join(os.path.split(current_file_path)[0],"values","downloadlimit.txt") f = open(downloadlimitvalue_file, "r") string = f.read() if int(string) == 0: DEFAULT_DOWNLOAD_RATE_LIMIT = 100000000000.0 else: DEFAULT_DOWNLOAD_RATE_LIMIT = int(string) DOWNLOAD_STATES_DISPLAY_INTERVAL = 600 SHOW_HIDDEN_DOWNLOADS_INFO = False MIN_PROGRESS_KEEP = 0.001 DOWNLOAD_STATS_INTERVAL = 1800 PREMIUM_PREVIEW_TIMEOUT = 15 CHECK_AUTH_INTERVAL_REGULAR = 3600 CHECK_AUTH_INTERVAL_ERROR = 600 CHECK_AUTH_INTERVAL_PREMIUM = 60 CHECK_AUTH_MAX_ERRORS = 5 CHECK_PRELOAD_ADS_INTERVAL = 86400 CLEANUP_HIDDEN_DOWNLOADS_INTERVAL = 86400 import os current_file_path = os.path.dirname(os.path.realpath(__file__)) vodbuffervalue_file = os.path.join(os.path.split(current_file_path)[0],"values","vodbuffer.txt") f = open(vodbuffervalue_file, "r") string = f.read() DEFAULT_PLAYER_BUFFER_TIME = int(string) import os current_file_path = os.path.dirname(os.path.realpath(__file__)) livebuffervalue_file = os.path.join(os.path.split(current_file_path)[0],"values","livebuffer.txt") f = open(livebuffervalue_file, "r") string = f.read() DEFAULT_LIVE_BUFFER_TIME = int(string) CACHE_DIR_NAME = '_acestream_cache_' DEFAULT_AD_STORAGE_LIMIT = 536870912L AD_STORAGE_LIMIT_SMALL = 536870912L AD_STORAGE_LIMIT_BIG = 1073741824L AD_STORAGE_MIN_FREE_SPACE = 52428800L AD_STORAGE_MAX_AGE = 2592000 class BaseApp(InstanceConnectionHandler): def __init__(self, wrapper, redirectstderrout, appname, appversion, params, installdir, i2i_port, session_port): self.apptype = globalConfig.get_value('apptype') self.ext_version = self.check_integrity() if DEVELOPER_MODE: self.ext_version = True debug_level = 0 skip_metadata = False skip_mediainfo = False use_libavi = False if self.apptype == 'torrentstream': encrypted_storage = True self.registry_key = 'TorrentStream' else: encrypted_storage = True self.registry_key = 'ACEStream' ip = None vod_live_max_pop_time = None piece_picker_buffering_delay = None try: for param in params: if param.startswith('--debug='): _, level = param.split('=') debug_level = int(level) elif param == '--skip-metadata': skip_metadata = True elif param == '--skip-mediainfo': skip_mediainfo = True elif param == '--use-libavi': use_libavi = True elif param.startswith('--vod-live-max-pop-time='): _, vod_live_max_pop_time = param.split('=') elif param.startswith('--buffering-delay='): _, piece_picker_buffering_delay = param.split('=') except: print_exc() self.debug_systray = False self.debug_level = 0 self.ip = ip globalConfig.set_value('encrypted_storage', encrypted_storage) globalConfig.set_value('use_libavi', use_libavi) if vod_live_max_pop_time is not None: try: vod_live_max_pop_time = int(vod_live_max_pop_time) if vod_live_max_pop_time < 1: vod_live_max_pop_time = 1 globalConfig.set_value('vod_live_max_pop_time', vod_live_max_pop_time) except: pass if piece_picker_buffering_delay is not None: try: a = piece_picker_buffering_delay.split(',') if len(a) >= 2: _min = int(a[0]) _max = int(a[1]) if len(a) >= 3: _offset = int(a[2]) else: _offset = 0 piece_picker_buffering_delay = (_min, _max, _offset) if DEBUG: log('baseapp::__init__: piece_picker_buffering_delay', piece_picker_buffering_delay) globalConfig.set_value('piece_picker_buffering_delay', piece_picker_buffering_delay) except: pass self.set_debug_level(debug_level) ACEStream.Core.Video.VideoOnDemand.DEBUG_SKIP_METADATA = skip_metadata ACEStream.Core.Video.VideoStatus.DEBUG_SKIP_METADATA = skip_metadata ACEStream.Core.Video.VideoOnDemand.DO_MEDIAINFO_ANALYSIS = not skip_mediainfo if DEBUG_STATS_TO_FILE: self.debug_counter = 0 self.appname = appname self.appversion = appversion self.params = params self.installdir = installdir self.i2i_port = i2i_port self.session_port = session_port self.error = None self.s = None self.wrapper = wrapper self.auth_data = {'last_success': None, 'errors': 0} self.playerconfig = {} self.download_states_display_counter = 0 self.user_profile = None self.downloads_in_vodmode = {} self.downloads_in_admode = {} self.dlinfo_lock = Lock() self.cleanup_hidden_downloads_lock = Lock() self.check_preload_ads_lock = Lock() self.timers = {} self.playing_premium_content = False self.download_stats = {} self.last_download_stats = 0 import os current_file_path = os.path.dirname(os.path.realpath(__file__)) downloadlimitvalue_file = os.path.join(os.path.split(current_file_path)[0],"values","downloadlimit.txt") f = open(downloadlimitvalue_file, "r") string = f.read() self.max_download_rate = int(string) import os current_file_path = os.path.dirname(os.path.realpath(__file__)) uploadlimitvalue_file = os.path.join(os.path.split(current_file_path)[0],"values","uploadlimit.txt") f = open(uploadlimitvalue_file, "r") string = f.read() self.max_upload_rate = int(string) self.avg_download_rate = 0 self.avg_download_rate_sum = 0 self.avg_download_rate_count = 0 self.avg_upload_rate = 0 self.avg_upload_rate_sum = 0 self.avg_upload_rate_count = 0 self.ratelimiter = None self.ratelimit_update_count = 0 self.playermode = DLSTATUS_DOWNLOADING self.getpeerlistcount = 2 self.shuttingdown = False self.tqueue = TimedTaskQueue(nameprefix='BGTaskQueue') self.OnInitBase() if self.i2i_port == 0: port_file = os.path.join(self.installdir, 'acestream.port') else: port_file = None self.i2i_listen_server = Instance2InstanceServer(self.i2i_port, self, timeout=86400.0, port_file=port_file) self.i2i_listen_server.start() InstanceConnectionHandler.__init__(self, self.i2ithread_readlinecallback) self.check_license() def check_license(self): try: path = os.path.join(self.installdir, '..', 'LICENSE.txt') if not os.path.isfile(path): return size = os.path.getsize(path) if size < 1024: return import locale lang_code, encoding = locale.getdefaultlocale() lang_code = lang_code.lower() if lang_code.startswith('en'): lang_code = 'en' elif lang_code.startswith('ru'): lang_code = 'ru' else: lang_code = 'en' if lang_code == 'ru': txt = '\xd0\x9b\xd0\xb8\xd1\x86\xd0\xb5\xd0\xbd\xd0\xb7\xd0\xb8\xd0\xbe\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb5 \xd1\x81\xd0\xbe\xd0\xb3\xd0\xbb\xd0\xb0\xd1\x88\xd0\xb5\xd0\xbd\xd0\xb8\xd0\xb5 \xd0\xbf\xd1\x80\xd0\xb5\xd0\xb4\xd1\x81\xd1\x82\xd0\xb0\xd0\xb2\xd0\xbb\xd0\xb5\xd0\xbd\xd0\xbe \xd0\xbd\xd0\xb0 \xd1\x81\xd0\xb0\xd0\xb9\xd1\x82\xd0\xb5: http://www.acestream.org/license' else: txt = 'License agreement presented on the site: http://www.acestream.org/license' f = open(path, 'w') f.write(txt) f.close() except: pass def test_ads(self): affiliate_id = 0 zone_id = 0 developer_id = 0 include_interruptable_ads = False provider_key = None provider_content_id = None content_ext = 'mp4' content_duration = 3600 user_login = self.s.get_ts_login() content_id = '1234567890123456789012345678901234567890' ads = self.ad_manager.get_ads(device_id=self.device_id, user_login=user_login, user_level=2, content_type=DLTYPE_TORRENT, content_id=content_id, content_ext=content_ext, content_duration=content_duration, affiliate_id=affiliate_id, zone_id=zone_id, developer_id=developer_id, include_interruptable_ads=include_interruptable_ads, is_live=False, user_profile=self.user_profile, provider_key=provider_key, provider_content_id=provider_content_id) print >> sys.stderr, '>>>test_ads:', ads def set_debug_level(self, debug_level): if not DEVELOPER_MODE: return if debug_level == self.debug_level: return self.debug_level = debug_level log('set_debug_level:', debug_level) ACEStream.Plugin.BackgroundProcess.DEBUG2 = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.DEBUG = debug_level == -1 or debug_level & 1 != 0 ACEStream.Core.Session.DEBUG = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.DEBUG_HIDDEN_DOWNLOADS = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.DEBUG_AD_STORAGE = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.DEBUG_SERVICE_REQUESTS = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.DEBUG_PREMIUM = debug_level == -1 or debug_level & 1 != 0 ACEStream.Player.BaseApp.SHOW_HIDDEN_DOWNLOADS_INFO = debug_level == -1 or debug_level & 1 != 0 ACEStream.Core.Ads.Manager.DEBUG = debug_level == -1 or debug_level & 1 != 0 ACEStream.Core.TS.Service.DEBUG = debug_level == -1 or debug_level & 1 != 0 ACEStream.Core.APIImplementation.DirectDownload.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.APIImplementation.DownloadImpl.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.APIImplementation.LaunchManyCore.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.APIImplementation.SingleDownload.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.BitTornado.download_bt1.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.BitTornado.BT1.GetRightHTTPDownloader.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.DirectDownload.Downloader.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.DirectDownload.Storage.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.DirectDownload.VODTransporter.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.Statistics.GoogleAnalytics.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.TorrentDef.DEBUG = False ACEStream.Core.TS.domutils.DEBUG = False ACEStream.Core.Utilities.mp4metadata.DEBUG = debug_level == -1 or debug_level & 2 != 0 ACEStream.Video.VideoServer.DEBUGLOCK = debug_level == -1 or debug_level & 2 != 0 ACEStream.Core.Video.PiecePickerStreaming.DEBUG = debug_level == -1 or debug_level & 4 != 0 ACEStream.Core.Video.PiecePickerStreaming.DEBUGPP = debug_level == -1 or debug_level & 4 != 0 ACEStream.Core.BitTornado.SocketHandler.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Choker.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Connecter.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Connecter.DEBUG_UT_PEX = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Downloader.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Uploader.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Encrypter.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Encrypter.DEBUG_CLOSE = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Rerequester.DEBUG = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Rerequester.DEBUG_DHT = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.BitTornado.BT1.Rerequester.DEBUG_CHECK_NETWORK_CONNECTION = debug_level == -1 or debug_level & 8 != 0 ACEStream.Core.Video.VideoOnDemand.DEBUG_HOOKIN = debug_level == -1 or debug_level & 16 != 0 ACEStream.Core.Video.LiveSourceAuth.DEBUG = debug_level == -1 or debug_level & 16 != 0 ACEStream.Core.Video.PiecePickerStreaming.DEBUG_LIVE = debug_level == -1 or debug_level & 16 != 0 ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG_LIVE = debug_level == -1 or debug_level & 16 != 0 try: ACEStream.Core.Video.VideoSource.DEBUG = debug_level == -1 or debug_level & 16 != 0 except: pass ACEStream.Core.Video.VideoOnDemand.DEBUG = debug_level == -1 or debug_level & 32 != 0 ACEStream.Core.Video.VideoStatus.DEBUG = debug_level == -1 or debug_level & 32 != 0 ACEStream.Video.VideoServer.DEBUG = debug_level == -1 or debug_level & 32 != 0 ACEStream.Video.VideoServer.DEBUGCONTENT = debug_level == -1 or debug_level & 32 != 0 ACEStream.Core.NATFirewall.NatCheck.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Core.NATFirewall.UPnPThread.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Core.NATFirewall.UDPPuncture.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Core.NATFirewall.upnp.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Core.NATFirewall.ConnectionCheck.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Core.BitTornado.natpunch.DEBUG = debug_level == -1 or debug_level & 64 != 0 ACEStream.Player.BaseApp.DEBUG_STATS_TO_FILE = debug_level == -1 or debug_level & 128 != 0 ACEStream.WebUI.WebUI.DEBUG = debug_level == -1 or debug_level & 256 != 0 ACEStream.Core.BitTornado.RawServer.DEBUG = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.RawServer.DEBUG2 = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.ServerPortHandler.DEBUG = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.ServerPortHandler.DEBUG2 = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.HTTPHandler.DEBUG = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.HTTPHandler.DEBUG2 = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.SocketHandler.DEBUG = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.SocketHandler.DEBUG2 = debug_level == -1 or debug_level & 512 != 0 ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG = debug_level == -1 or debug_level & 8192 != 0 ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG_WRITE = False ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG_HASHCHECK = debug_level == -1 or debug_level & 8192 != 0 ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG_REQUESTS = debug_level == -1 or debug_level & 8192 != 0 ACEStream.Core.BitTornado.BT1.FileSelector.DEBUG = debug_level == -1 or debug_level & 8192 != 0 ACEStream.Core.BitTornado.download_bt1.DEBUG_ENCRYPTION = debug_level == -1 or debug_level & 8192 != 0 ACEStream.Core.BitTornado.BT1.Storage.DEBUG = debug_level == -1 or debug_level & 16384 != 0 ACEStream.Core.BitTornado.BT1.Storage.DEBUG_RESTORE = debug_level == -1 or debug_level & 16384 != 0 ACEStream.Core.Utilities.EncryptedStorage.DEBUG = debug_level == -1 or debug_level & 32768 != 0 ACEStream.Core.BitTornado.BT1.StorageWrapper.DEBUG_ENCRYPTED_STORAGE = debug_level == -1 or debug_level & 32768 != 0 ACEStream.Core.BitTornado.download_bt1.DEBUG_ENCRYPTION = debug_level == -1 or debug_level & 32768 != 0 ACEStream.Core.CacheDB.SqliteCacheDBHandler.DEBUG = debug_level == -1 or debug_level & 65536 != 0 ACEStream.Utilities.LSO.DEBUG = debug_level == -1 or debug_level & 131072 != 0 ACEStream.Core.Statistics.Settings.DEBUG = debug_level == -1 or debug_level & 131072 != 0 ACEStream.Core.Statistics.TNS.DEBUG = debug_level == -1 or debug_level & 131072 != 0 ACEStream.Core.Statistics.TrafficStatistics.DEBUG = debug_level == -1 or debug_level & 131072 != 0 def OnInitBase(self): state_dir = Session.get_default_state_dir() self.state_dir = state_dir if DEBUG: log('baseapp::init: state_dir', state_dir) if globalConfig.get_mode() != 'client_console': from ACEStream.Player.UtilityStub import UtilityStub self.utility = UtilityStub(self.installdir, state_dir) self.utility.app = self log('build', VERSION_REV) log('version', VERSION) self.iconpath = os.path.join(self.installdir, 'data', 'images', 'engine.ico') self.logopath = os.path.join(self.installdir, 'data', 'images', 'logo.png') self.load_playerconfig(state_dir) self.statFrame = None self.live_frame = None self.init_hardware_key() cfgfilename = Session.get_default_config_filename(state_dir) if DEBUG: log('baseapp::init: session config', cfgfilename) try: self.sconfig = SessionStartupConfig.load(cfgfilename) if self.session_port != DEFAULT_SESSION_LISTENPORT: if DEBUG: log('baseapp::init: non-default port specified, overwrite saved session port:', self.session_port) self.sconfig.set_listen_port(self.session_port) elif DEBUG: log('baseapp::init: use session saved port', self.sconfig.get_listen_port()) except: if DEBUG: log('baseapp::init: cannot load config file', cfgfilename, 'Use default config') self.sconfig = SessionStartupConfig() self.sconfig.set_state_dir(state_dir) self.sconfig.set_listen_port(self.session_port) self.configure_session() self.s = Session(self.sconfig, on_error=self.on_error) self.s.set_download_states_callback(self.sesscb_states_callback) self.device_id = b64encode(self.s.get_permid()) node_id = self.device_id if self.hardware_key is not None: node_id += ':' + self.hardware_key self.node_id = hashlib.sha1(node_id).hexdigest() self.traffic_stats = TrafficStatistics(TrafficStatistics.NODE_CLIENT, self.node_id) if RATELIMITADSL: self.ratelimiter = UserDefinedMaxAlwaysOtherwiseEquallyDividedRateManager() self.ratelimiter.set_global_max_speed(DOWNLOAD, DOWNLOADSPEED) self.ratelimiter.set_global_max_speed(UPLOAD, 90) try: self.s.load_checkpoint(initialdlstatus=DLSTATUS_STOPPED) except: log_exc() ga = lambda : GoogleAnalytics.send_event('client', 'startup', VERSION) self.run_delayed(ga) self.tsservice = TSService(self) self.run_delayed(self.check_auth_level, 0.1) self.cookie_file = os.path.join(self.state_dir, 'cookies.pickle') self.cookie_jar = cookielib.CookieJar() self.load_cookies() self.stat_settings = RemoteStatisticsSettings() self.run_delayed(self.check_statistics_settings, 1) if TNS_ENABLED: try: lso = LSO('source.mmi.bemobile.ua', 'mmi') self.tns_uid = lso.get_uid() except: if DEBUG: print_exc() self.check_user_profile() self.ad_manager = AdManager(self, self.cookie_jar) if TS_ENV_PLATFORM == 'dune': default_enabled = False else: default_enabled = True preload_ads_enabled = self.get_preload_ads_enabled(default_enabled) if DEBUG: log('baseapp::init: preload_ads_enabled', preload_ads_enabled) self.run_delayed(self.cleanup_hidden_downloads_task, 1.0) self.run_delayed(self.remove_unknown_downloads, 20.0) self.run_delayed(self.check_preload_ads, 1.0, 'check_preload_ads') if sys.platform == 'win32': self.run_delayed(self.start_updater, 60.0) disk_cache_limit = self.get_playerconfig('disk_cache_limit') if disk_cache_limit is None: content_dir = self.get_default_destdir() total, avail, used = self.get_disk_info(content_dir) if total is not None: disk_cache_limit = long(total * 0.5) else: disk_cache_limit = DEFAULT_DISKSPACE_LIMIT self.set_playerconfig('disk_cache_limit', disk_cache_limit) if DEBUG: log('baseapp::init: set disk_cache_limit:', disk_cache_limit) elif DEBUG: log('baseapp::init: got disk_cache_limit:', disk_cache_limit) ad_storage_limit = self.get_playerconfig('ad_storage_limit') if ad_storage_limit is None: ads_dir = self.s.get_ads_dir() total, avail, used = self.get_disk_info(ads_dir) if total is not None: if avail < 10485760: ad_storage_limit = AD_STORAGE_LIMIT_SMALL else: ad_storage_limit = AD_STORAGE_LIMIT_BIG else: ad_storage_limit = DEFAULT_AD_STORAGE_LIMIT self.set_playerconfig('ad_storage_limit', ad_storage_limit) if DEBUG: log('baseapp::init: set ad_storage_limit:', ad_storage_limit) elif DEBUG: log('baseapp::init: got ad_storage_limit:', ad_storage_limit) self.set_playerconfig('enable_http_support', True) if DEBUG_STATS_TO_FILE: try: for f in os.listdir(self.installdir): if f.startswith('stat_snapshot_'): os.remove(os.path.join(self.installdir, f)) except: pass def on_error(self, exception): try: errmsg = str(exception) except: errmsg = 'Unexpected error' try: self.wrapper.on_error(errmsg, exit=True) except: print_exc() def run_delayed(self, func, delay = 0.0, task_id = None, daemon = True, args = []): if task_id is not None: if self.timers.has_key(task_id): self.timers[task_id].cancel() t = Timer(delay, func, args) if task_id is not None: self.timers[task_id] = t t.daemon = daemon t.name = 'Timer-' + t.name t.start() return t def start_updater(self): if sys.platform != 'win32': return if self.apptype == 'torrentstream': exename = 'tsupdate.exe' else: exename = 'ace_update.exe' updater_path = os.path.join(self.installdir, '..', 'updater', exename) if DEBUG: log('baseapp::start_updater: updater_path', updater_path) if os.path.exists(updater_path): try: subprocess.Popen(updater_path, close_fds=True) except: if DEBUG: print_exc() def remove_unknown_downloads(self): try: known_files = [] downloads = self.s.get_all_downloads() for d in downloads: if not d.is_hidden(): continue destfiles = d.get_dest_files(get_all=True) if destfiles: for filename, savepath in destfiles: known_files.append(savepath) path = self.s.get_ads_dir() filelist = os.listdir(path) if DEBUG_AD_STORAGE: log('baseapp::remove_unknown_downloads: known_files', known_files, 'filelist', filelist) for basename in filelist: filename = os.path.join(path, basename) if filename not in known_files: if DEBUG_AD_STORAGE: log('baseapp::remove_unknown_downloads: remove: filename', filename) os.remove(filename) except: if DEBUG: print_exc() def get_ad_storage_limit(self): ad_storage_limit = self.get_playerconfig('ad_storage_limit', DEFAULT_AD_STORAGE_LIMIT) ads_dir = self.s.get_ads_dir() total, avail, used = self.get_disk_info(ads_dir) if avail is None: avail = ad_storage_limit + AD_STORAGE_MIN_FREE_SPACE if DEBUG_AD_STORAGE: log('baseapp::get_ad_storage_limit: failed to get disk info, set fake avail: avail', avail) if avail < ad_storage_limit + AD_STORAGE_MIN_FREE_SPACE: storage_limit = avail - AD_STORAGE_MIN_FREE_SPACE else: storage_limit = ad_storage_limit if DEBUG_AD_STORAGE: log('baseapp::get_ad_storage_limit: storage_limit', storage_limit, 'total', total, 'avail', avail, 'used', used) return storage_limit def cleanup_unused_ad_downloads(self, keep_hash_list): if DEBUG_AD_STORAGE: log('baseapp::cleanup_unused_ad_downloads: keep_hash_list', keep_hash_list) downloads = self.s.get_all_downloads() for d in downloads: if not d.is_hidden(): continue if d.get_hash() not in keep_hash_list: if DEBUG_AD_STORAGE: log('baseapp::cleanup_unused_ad_downloads: remove unused download: hash', binascii.hexlify(d.get_hash())) self.s.remove_download(d, removecontent=True) def cleanup_hidden_downloads_task(self): self.cleanup_hidden_downloads() self.run_delayed(self.cleanup_hidden_downloads_task, CLEANUP_HIDDEN_DOWNLOADS_INTERVAL) def cleanup_hidden_downloads(self, needed = 0, priority = -1): self.cleanup_hidden_downloads_lock.acquire() try: total_size = 0 dllist = [] downloads = self.s.get_all_downloads() for d in downloads: if not d.is_hidden(): continue destfiles = d.get_dest_files(get_all=True) download_priority = d.get_extra('priority', 0) download_size = d.get_content_length() download_last_access = 0 for filename, savepath in destfiles: if os.path.exists(savepath): stat = os.stat(savepath) if stat.st_ctime > download_last_access: download_last_access = stat.st_ctime last_seen = self.get_ad_last_seen(d.get_hash()) if last_seen is not None: download_last_access = last_seen if download_size > 0: total_size += download_size dlinfo = (download_last_access, download_priority, download_size, d) dllist.append(dlinfo) dllist.sort(key=itemgetter(1, 0)) storage_limit = self.get_ad_storage_limit() free_up = total_size + needed - storage_limit if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: storage_limit', storage_limit, 'total_size', total_size, 'needed', needed, 'free_up', free_up, 'dllist', dllist) for last_access, dlpriority, size, d in dllist: remove = False if priority != -1 and dlpriority >= priority: if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: do not remove download with higher priority: hash', binascii.hexlify(d.get_hash()), 'dlpriority', dlpriority, 'priority', priority) continue if d in self.downloads_in_vodmode: if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: do not remove playing download: hash', binascii.hexlify(d.get_hash())) continue is_ad = False for maind_d, ads in self.downloads_in_admode.iteritems(): if d in ads: is_ad = True break if is_ad: if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: do not remove download in admode: hash', binascii.hexlify(d.get_hash())) continue now = long(time.time()) if last_access < now - AD_STORAGE_MAX_AGE: if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: remove outdated download: hash', binascii.hexlify(d.get_hash()), 'last_access', last_access, 'now', now, 'max_age', AD_STORAGE_MAX_AGE) remove = True if not remove and free_up > 0: remove = True free_up -= size if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: remove download to free space: hash', binascii.hexlify(d.get_hash()), 'size', size, 'free_up', free_up) if remove: self.s.remove_download(d, removecontent=True) if DEBUG_AD_STORAGE: log('baseapp::cleanup_hidden_downloads: done: free_up', free_up) return free_up <= 0 except: log_exc() finally: self.cleanup_hidden_downloads_lock.release() def check_preload_ads(self): self.check_preload_ads_lock.acquire() try: preload_ads = self.ad_manager.get_preload_ads(self.device_id, self.s.get_ts_login(), self.get_playerconfig('enable_interruptable_ads', True), user_profile=self.user_profile) if preload_ads == False: return self.add_preload_ads(preload_ads, True) except: log_exc() finally: self.check_preload_ads_lock.release() self.run_delayed(self.check_preload_ads, CHECK_PRELOAD_ADS_INTERVAL, 'check_preload_ads') def add_preload_ads(self, preload_ads, remove_unused): dl_hash_list = [] for ad in preload_ads: if ad['dltype'] == DLTYPE_TORRENT: ad['dlhash'] = ad['tdef'].get_infohash() ad['size'] = ad['tdef'].get_length() elif ad['dltype'] == DLTYPE_DIRECT: tdef = self.get_torrent_from_url(ad['url']) if tdef is None: ad['dlhash'] = hashlib.sha1(ad['url']).digest() ad['size'] = 0 else: ad['tdef'] = tdef ad['dlhash'] = tdef.get_infohash() ad['size'] = tdef.get_length() ad['dltype'] = DLTYPE_TORRENT if DEBUG: log('baseapp::add_preload_ads: got torrent from url: url', ad['url'], 'infohash', binascii.hexlify(ad['dlhash'])) else: raise ValueError('Unknown download type ' + str(ad['dltype'])) dl_hash_list.append(ad['dlhash']) if remove_unused: self.cleanup_unused_ad_downloads(dl_hash_list) preload_ads.sort(key=lambda ad: ad['priority'], reverse=True) for ad in preload_ads: d = self.s.get_download(ad['dltype'], ad['dlhash']) if d is not None: pass else: if DEBUG: log('baseapp::add_preload_ads: start new preload download: type', ad['dltype'], 'hash', binascii.hexlify(ad['dlhash']), 'priority', ad['priority'], 'size', ad['size']) if not self.cleanup_hidden_downloads(needed=ad['size'], priority=ad['priority']): if DEBUG: log('baseapp::add_preload_ads: not enough space: hash', binascii.hexlify(ad['dlhash']), 'size', ad['size']) continue dcfg = DownloadStartupConfig() dcfg.set_dest_dir(self.s.get_ads_dir()) dcfg.set_max_conns(10) dcfg.set_max_conns_to_initiate(10) dcfg.set_hidden(True) dcfg.set_extra('priority', ad['priority']) if ad['dltype'] == DLTYPE_TORRENT: self.s.start_download(ad['tdef'], dcfg, initialdlstatus=DLSTATUS_STOPPED) elif ad['dltype'] == DLTYPE_DIRECT: self.s.start_direct_download(ad['url'], dcfg, initialdlstatus=DLSTATUS_STOPPED) def check_auth_level(self, forceconnect = False): got_error = False try: ts_login = unicode2str_safe(self.s.get_ts_login()) ts_password = unicode2str_safe(self.s.get_ts_password()) if len(ts_login) == 0 or len(ts_password) == 0: self.s.set_authlevel(0) return if self.auth_data['last_success'] is None or forceconnect: action = 'cn' else: action = 'chk' new_authlevel = self.tsservice.get_user_level(ts_login, ts_password, action, self.device_id, self.hardware_key) if new_authlevel is not None: self.auth_data['last_success'] = time.time() self.auth_data['errors'] = 0 if DEBUG: log('baseapp::check_auth_level: got user level:', new_authlevel) else: got_error = True self.auth_data['errors'] += 1 log('baseapp::check_auth_level: failed, error count', self.auth_data['errors']) if self.auth_data['errors'] >= CHECK_AUTH_MAX_ERRORS: log('baseapp::check_auth_level: max errors reached, reset user level') new_authlevel = 0 if new_authlevel is not None: current_authlevel = self.s.get_authlevel() if new_authlevel != current_authlevel: if DEBUG: log('baseapp::check_auth_level: set new user level: current', current_authlevel, 'new', new_authlevel) self.s.set_authlevel(new_authlevel) for socket, ic in self.singsock2ic.iteritems(): ic.auth(new_authlevel) except: if DEBUG: log_exc() finally: if got_error: interval = CHECK_AUTH_INTERVAL_ERROR if DEBUG: log('baseapp::check_auth_level: got error, next try in', interval) elif self.playing_premium_content: interval = CHECK_AUTH_INTERVAL_PREMIUM if DEBUG: log('baseapp::check_auth_level: got premium, next try in', interval) else: interval = CHECK_AUTH_INTERVAL_REGULAR if DEBUG: log('baseapp::check_auth_level: regular next try in', interval) self.run_delayed(self.check_auth_level, interval, task_id='check_auth_level') def configure_session(self): self.sconfig.set_install_dir(self.installdir) if self.ip is not None: if DEBUG: log('baseapp::configure_session: set ip', self.ip) self.sconfig.set_ip_for_tracker(self.ip) self.sconfig.set_megacache(True) import os current_file_path = os.path.dirname(os.path.realpath(__file__)) maxconnections_file = os.path.join(os.path.split(current_file_path)[0],"values","maxconnections.txt") f = open(maxconnections_file, "r") self.sconfig.set_max_socket_connections(self.get_playerconfig('total_max_connects', int(string))) self.sconfig.set_overlay(False) self.sconfig.set_torrent_checking(False) self.sconfig.set_buddycast(False) self.sconfig.set_download_help(False) self.sconfig.set_torrent_collecting(False) self.sconfig.set_dialback(False) self.sconfig.set_social_networking(False) self.sconfig.set_remote_query(False) self.sconfig.set_bartercast(False) self.sconfig.set_crawler(False) self.sconfig.set_multicast_local_peer_discovery(False) self.sconfig.set_subtitles_collecting(False) def _get_poa(self, tdef): from ACEStream.Core.ClosedSwarm import ClosedSwarm, PaymentIntegration print >> sys.stderr, 'Swarm_id:', encodestring(tdef.infohash).replace('\n', '') try: poa = ClosedSwarm.trivial_get_poa(self.s.get_state_dir(), self.s.get_permid(), tdef.infohash) poa.verify() if not poa.torrent_id == tdef.infohash: raise Exception('Bad POA - wrong infohash') print >> sys.stderr, 'Loaded poa from ', self.s.get_state_dir() except: swarm_id = encodestring(tdef.infohash).replace('\n', '') my_id = encodestring(self.s.get_permid()).replace('\n', '') try: poa = PaymentIntegration.wx_get_poa(None, swarm_id, my_id, swarm_title=tdef.get_name()) except Exception as e: print >> sys.stderr, 'Failed to get POA:', e poa = None try: ClosedSwarm.trivial_save_poa(self.s.get_state_dir(), self.s.get_permid(), tdef.infohash, poa) except Exception as e: print >> sys.stderr, 'Failed to save POA', e if poa: if not poa.torrent_id == tdef.infohash: raise Exception('Bad POA - wrong infohash') return poa def start_download(self, tdef, dlfile, extra_files_indexes = [], developer_id = 0, affiliate_id = 0, zone_id = 0, poa = None, supportedvodevents = None): if poa: from ACEStream.Core.ClosedSwarm import ClosedSwarm if not poa.__class__ == ClosedSwarm.POA: raise InvalidPOAException('Not a POA') destdir = self.get_default_destdir() try: enough_space = True length = tdef.get_length([dlfile]) if tdef.get_live(): length = long(length / 8 * 1.2) if not self.free_up_diskspace_by_downloads(tdef.get_infohash(), length): log('BaseApp::start_download: Not enough free diskspace') enough_space = False except: log_exc() if not enough_space: raise Exception('Not enough disk space') dcfg = DownloadStartupConfig() import os current_file_path = os.path.dirname(os.path.realpath(__file__)) maxconnectionsstream_file = os.path.join(os.path.split(current_file_path)[0],"values","maxconnectionsstream.txt") f = open(maxconnectionsstream_file, "r") string = f.read() dcfg.set_max_conns(self.get_playerconfig('download_max_connects', int(string))) if poa: dcfg.set_poa(poa) print >> sys.stderr, 'POA:', dcfg.get_poa() else: dcfg.set_poa(None) if supportedvodevents is None: supportedvodevents = self.get_supported_vod_events() if DEBUG: log('BaseApp::start_download: supportedvodevents', supportedvodevents) dcfg.set_video_events(supportedvodevents) prefix, ext = os.path.splitext(dlfile) if ext != '' and ext[0] == '.': content_ext = ext[1:] else: content_ext = '' content_duration = None if tdef.is_multifile_torrent(): svcdlfiles = self.is_svc(dlfile, tdef) if svcdlfiles is not None: dcfg.set_video_event_callback(self.sesscb_vod_event_callback, dlmode=DLMODE_SVC) dcfg.set_selected_files(svcdlfiles) else: dcfg.set_video_event_callback(self.sesscb_vod_event_callback) dcfg.set_selected_files([dlfile]) dcfg.set_extra_files(extra_files_indexes) try: p = [-1] * len(tdef.get_files()) total_duration = 0 content_length = 0 videofiles = tdef.get_files(exts=videoextdefaults) for videofile in videofiles: idx = tdef.get_index_of_file_in_files(videofile) if videofile == dlfile or idx in extra_files_indexes: p[idx] = 1 content_length += tdef.get_length(videofile) duration = tdef.get_ts_duration(idx) if duration is not None: total_duration += duration if total_duration > 0: content_duration = total_duration idx = tdef.get_index_of_file_in_files(dlfile) if DEBUG: log('BaseApp::start_download: bitrate', tdef.get_ts_bitrate(idx)) dcfg.set_files_priority(p) if DEBUG: log('BaseApp::start_download: got multi: dlfile', dlfile, 'priority', dcfg.get_files_priority, 'bitrate', tdef.get_ts_bitrate(idx), 'size', content_length, 'duration', content_duration, 'ext', content_ext) except: log_exc() else: dcfg.set_video_event_callback(self.sesscb_vod_event_callback) content_duration = tdef.get_ts_duration() content_length = tdef.get_length() if DEBUG: log('BaseApp::start_download: got single: bitrate', tdef.get_ts_bitrate(), 'size', content_length, 'duration', content_duration, 'ext', content_ext) if content_duration is None: content_duration = self.guess_duration_from_size(content_length) if DEBUG: log('baseapp::start_download: guess duration: size', content_length, 'duration', content_duration) if tdef.get_live(): include_interruptable_ads = False else: include_interruptable_ads = self.get_playerconfig('enable_interruptable_ads', True) newd_params = {} provider_key = tdef.get_provider() provider_content_id = tdef.get_content_id() premium = tdef.get_premium() if premium != 0 and provider_key is not None: if DEBUG_PREMIUM: log('baseapp::start_download: check premium status: provider_key', provider_key, 'content_id', provider_content_id) if self.check_premium_status(provider_key, provider_content_id, tdef.get_infohash()): newd_params['premium'] = True newd_params['report_interval'] = 60 newd_params['user_check_interval'] = 60 auth_level = self.s.get_authlevel() if DEBUG_PREMIUM: log('baseapp::start_download: got premium content: provider_key', provider_key, 'content_id', provider_content_id, 'auth_level', auth_level) if auth_level < 2: newd_params['user_check_interval'] = 15 ads = self.ad_manager.get_ads(device_id=self.device_id, user_login=self.s.get_ts_login(), user_level=self.s.get_authlevel(), content_type=DLTYPE_TORRENT, content_id=binascii.hexlify(tdef.get_infohash()), content_ext=content_ext, content_duration=content_duration, affiliate_id=affiliate_id, zone_id=zone_id, developer_id=developer_id, include_interruptable_ads=include_interruptable_ads, is_live=tdef.get_live(), user_profile=self.user_profile, provider_key=provider_key, provider_content_id=provider_content_id) if ads == False: if DEBUG: log('baseapp::start_download: failed to get ads, exit') raise Exception, 'Cannot start playback' dcfg.set_dest_dir(destdir) rate = self.get_playerconfig('total_max_download_rate', DEFAULT_DOWNLOAD_RATE_LIMIT) if DEBUG: log('BaseApp::start_download: set download limit to', rate, 'Kb/s') dcfg.set_max_speed(DOWNLOAD, rate, self.get_playerconfig('auto_download_limit', False)) dcfg.set_wait_sufficient_speed(self.get_playerconfig('wait_sufficient_speed', False)) dcfg.set_http_support(self.get_playerconfig('enable_http_support', True)) dcfg.set_player_buffer_time(self.get_playerconfig('player_buffer_time', DEFAULT_PLAYER_BUFFER_TIME)) dcfg.set_live_buffer_time(self.get_playerconfig('live_buffer_time', DEFAULT_LIVE_BUFFER_TIME)) infohash = tdef.get_infohash() newd = None for d in self.s.get_downloads(): if d.get_def().get_infohash() == infohash: log('BaseApp::start_download: Reusing old duplicate download', infohash) newd = d if poa: d.set_poa(poa) self.s.lm.h4xor_reset_init_conn_counter() initialdlstatus = None got_uninterruptable_ad = False if len(ads): for ad in ads: if not ad['interruptable']: got_uninterruptable_ad = True break if got_uninterruptable_ad: initialdlstatus = DLSTATUS_STOPPED if newd is None: log('BaseApp::start_download: starting new download: infohash', infohash, 'initialdlstatus', initialdlstatus) newd = self.s.start_download(tdef, dcfg, initialdlstatus) else: newd.set_video_events(self.get_supported_vod_events()) newd.set_wait_sufficient_speed(dcfg.get_wait_sufficient_speed()) newd.set_http_support(dcfg.get_http_support()) newd.set_max_speed(UPLOAD, dcfg.get_max_speed(UPLOAD)) newd.set_max_speed(DOWNLOAD, dcfg.get_max_speed(DOWNLOAD), dcfg.get_auto_download_limit()) import os current_file_path = os.path.dirname(os.path.realpath(__file__)) maxconnectionsstream_file = os.path.join(os.path.split(current_file_path)[0],"values","maxconnectionsstream.txt") f = open(maxconnectionsstream_file, "r") string = f.read() newd.set_max_conns(self.get_playerconfig('download_max_connects', int(string))) svcdlfiles = self.is_svc(dlfile, tdef) if svcdlfiles is not None: newd.set_video_event_callback(self.sesscb_vod_event_callback, dlmode=DLMODE_SVC) newd.set_selected_files(svcdlfiles) else: newd.set_video_event_callback(self.sesscb_vod_event_callback) newd.set_player_buffer_time(self.get_playerconfig('player_buffer_time', DEFAULT_PLAYER_BUFFER_TIME)) newd.set_live_buffer_time(self.get_playerconfig('live_buffer_time', DEFAULT_LIVE_BUFFER_TIME)) if tdef.is_multifile_torrent(): newd.set_selected_files([dlfile]) newd.set_extra_files(extra_files_indexes) newd.set_files_priority(dcfg.get_files_priority()) if initialdlstatus is None: if DEBUG: log('BaseApp::start_download: restarting existing download: infohash', binascii.hexlify(infohash)) newd.restart(new_tdef=tdef) else: ds = newd.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status != DLSTATUS_STOPPED: if DEBUG: log('BaseApp::start_download: existing download is active, stop it and wait for ads: infohash', binascii.hexlify(infohash)) newd.stop() elif DEBUG: log('BaseApp::start_download: skip restarting existing download, wait for ads: infohash', binascii.hexlify(infohash)) if DEBUG: log('BaseApp::start_download: saving content to', newd.get_dest_files()) self.dlinfo_lock.acquire() try: if newd in self.downloads_in_vodmode: self.downloads_in_vodmode[newd].update(newd_params) else: newd_params['start'] = time.time() newd_params['download_id'] = hashlib.sha1(b64encode(self.s.get_ts_login()) + b64encode(tdef.get_infohash()) + str(time.time()) + str(random.randint(1, sys.maxint))).hexdigest() if TNS_ENABLED: if self.stat_settings.check_content('tns', tdef): try: newd_params['tns'] = TNS(self.stat_settings.get_url_list('tns'), self.stat_settings.get_options('tns'), self.tns_uid, self.cookie_jar, tdef) newd_params['tns'].start() except TNSNotAllowedException: pass except: if DEBUG: print_exc() elif DEBUG: log('baseapp::start_download: tns disabled: infohash', binascii.hexlify(tdef.get_infohash())) self.downloads_in_vodmode[newd] = newd_params if newd in self.downloads_in_admode: if DEBUG: log('baseapp::start_ad_downloads: remove old ad downloads on start') del self.downloads_in_admode[newd] if len(ads): if got_uninterruptable_ad: if DEBUG: log('baseapp::start_download: got uninterruptable ad, start ads immediatelly') start_ad_downloads_lambda = lambda : self.start_ad_downloads(newd, ads) self.run_delayed(start_ad_downloads_lambda, 0.5) else: if DEBUG: log('baseapp::start_download: no uninterruptable ad, start ads when main started') start_ad_downloads_when_main_started_lambda = lambda : self.start_ad_downloads_when_main_started(newd, ads) self.run_delayed(start_ad_downloads_when_main_started_lambda, 0.5) finally: self.dlinfo_lock.release() func = lambda : GoogleAnalytics.send_event('client', 'play', VERSION) self.run_delayed(func) return newd def start_ad_downloads_when_main_started(self, maind, ads): self.dlinfo_lock.acquire() try: if maind not in self.downloads_in_vodmode: if DEBUG: log('baseapp::start_ad_downloads_when_main_started: download is not in vod mode, stop trying: hash', binascii.hexlify(maind.get_hash())) return ds = maind.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) dlstatus = ds.get_status() is_vod = ds.is_vod() playable = ds.get_vod_playable() if DEBUG: log('baseapp::start_ad_downloads_when_main_started: hash', binascii.hexlify(maind.get_hash()), 'status', dlstatus_strings[dlstatus], 'is_vod', is_vod, 'playable', playable) if dlstatus == DLSTATUS_STOPPED_ON_ERROR: if DEBUG: log('baseapp::start_ad_downloads_when_main_started: download cannot start, stop trying: hash', binascii.hexlify(maind.get_hash()), 'error', ds.get_error()) return start_ads = False if dlstatus == DLSTATUS_DOWNLOADING and is_vod: if playable: if DEBUG: log('baseapp::start_ad_downloads_when_main_started: download is playable, stop trying: hash', binascii.hexlify(maind.get_hash())) return if DEBUG: log('baseapp::start_ad_downloads_when_main_started: download is not playable, start ads: hash', binascii.hexlify(maind.get_hash())) start_ads = True else: if dlstatus == DLSTATUS_SEEDING: if DEBUG: log('baseapp::start_ad_downloads_when_main_started: download is finished, stop trying: hash', binascii.hexlify(maind.get_hash())) return if DEBUG: log('baseapp::start_ad_downloads_when_main_started: keep trying: hash', binascii.hexlify(maind.get_hash())) if start_ads: self.start_ad_downloads(maind, ads) else: start_ad_downloads_when_main_started_lambda = lambda : self.start_ad_downloads_when_main_started(maind, ads) self.run_delayed(start_ad_downloads_when_main_started_lambda, 1.0) finally: self.dlinfo_lock.release() def start_ad_downloads(self, newd, ads): ds = newd.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) main_dlstatus = ds.get_status() main_progress = ds.get_progress() if DEBUG: log('baseapp::start_ad_downloads: start ads: main', binascii.hexlify(newd.get_hash()), 'status', dlstatus_strings[main_dlstatus], 'progress', main_progress) noninterruptable_ads = [] noninterruptable_ads_hash_list = [] interruptable_ads = [] for ad in ads: if ad['dltype'] == DLTYPE_TORRENT: ad['dlhash'] = ad['tdef'].get_infohash() ad['size'] = ad['tdef'].get_length() elif ad['dltype'] == DLTYPE_DIRECT: tdef = None if tdef is None: ad['dlhash'] = hashlib.sha1(ad['url']).digest() ad['size'] = 0 else: ad['tdef'] = tdef ad['dlhash'] = tdef.get_infohash() ad['size'] = tdef.get_length() ad['dltype'] = DLTYPE_TORRENT if DEBUG: log('baseapp::start_ad_downloads: got torrent from url: url', ad['url'], 'infohash', binascii.hexlify(ad['dlhash'])) else: raise ValueError('Unknown download type ' + str(ad['dltype'])) if not ad.has_key('priority'): if ad['interruptable']: ad['priority'] = 0 else: ad['priority'] = -1 if ad['interruptable']: interruptable_ads.append(ad) else: noninterruptable_ads.append(ad) noninterruptable_ads_hash_list.append(ad['dlhash']) def start_ad(ad): d = self.s.get_download(ad['dltype'], ad['dlhash']) if d is None: if ad['interruptable'] or ad['wait_preload']: if DEBUG: log('baseapp::start_ad_downloads: interruptable or preload ad download is not in downloads, skip: dlhash', binascii.hexlify(ad['dlhash'])) return False if DEBUG: log('baseapp::start_ad_downloads: start new ad download: main', binascii.hexlify(newd.get_hash()), 'ad', binascii.hexlify(ad['dlhash'])) if not self.cleanup_hidden_downloads(needed=ad['size'], priority=ad['priority']): if DEBUG: log('baseapp::start_ad_downloads: not enough space: hash', binascii.hexlify(ad['dlhash']), 'size', ad['size']) return False dcfg = DownloadStartupConfig() dcfg.set_video_event_callback(lambda d, event, params: self.sesscb_vod_event_callback(d, event, params, newd)) dcfg.set_dest_dir(self.s.get_ads_dir()) dcfg.set_player_buffer_time(1) dcfg.set_max_conns(50) dcfg.set_max_conns_to_initiate(60) dcfg.set_hidden(True) if ad['dltype'] == DLTYPE_TORRENT: d = self.s.start_download(ad['tdef'], dcfg) elif ad['dltype'] == DLTYPE_DIRECT: dcfg.set_download_failed_callback(self.download_failed_callback) if ad['predownload']: dcfg.set_predownload(True) d = self.s.start_direct_download(ad['url'], dcfg) else: if ad['interruptable']: if main_progress == 1.0: if DEBUG: log('baseapp::start_ad_downloads: main content is completed, skip interruptable ad: dlhash', binascii.hexlify(ad['dlhash'])) return False if ad['interruptable'] or ad['wait_preload']: ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) progress = ds.get_progress() if progress != 1.0: if DEBUG: log('baseapp::start_ad_downloads: interruptable or preload ad download is not completed, skip: dlhash', binascii.hexlify(ad['dlhash']), 'progress', progress) return False used_by_another_vod = False for main_d, ads in self.downloads_in_admode.iteritems(): if d in ads: used_by_another_vod = True if DEBUG: log('baseapp::start_ad_downloads: ad download is used by another vod: main', binascii.hexlify(newd.get_hash()), 'other', binascii.hexlify(main_d.get_hash()), 'ad', binascii.hexlify(d.get_hash())) break if used_by_another_vod: start_ad_download_when_seeding_lambda = lambda d = d, newd = newd: self.start_ad_download_when_seeding(d, newd) self.run_delayed(start_ad_download_when_seeding_lambda, 0.1) else: if DEBUG: log('baseapp::start_ad_downloads: restart existing ad download: main', binascii.hexlify(newd.get_hash()), 'ad', binascii.hexlify(ad['dlhash'])) d.set_video_event_callback(lambda d, event, params: self.sesscb_vod_event_callback(d, event, params, newd)) d.set_player_buffer_time(1) d.set_max_conns(10) d.set_max_conns_to_initiate(10) d.set_hidden(True) if d.get_type() == DLTYPE_DIRECT: d.set_download_failed_callback(self.download_failed_callback) d.restart() self.downloads_in_admode.setdefault(newd, odict())[d] = {'ad': ad, 'start_params': None, 'completed': False, 'started': None, 'finished': None, 'failed': False} return True started_noninterruptable_ads = 0 started_interruptable_ads = 0 for ad in noninterruptable_ads: if start_ad(ad): started_noninterruptable_ads += 1 for ad in interruptable_ads: if start_ad(ad): started_interruptable_ads += 1 if DEBUG: log('baseapp::start_ad_downloads: started_noninterruptable_ads', started_noninterruptable_ads, 'started_interruptable_ads', started_interruptable_ads) if started_noninterruptable_ads == 0 and started_interruptable_ads == 0 and main_dlstatus == DLSTATUS_STOPPED: if DEBUG: log('baseapp::start_ad_downloads: no ads started, start main download: main', binascii.hexlify(newd.get_hash())) newd.restart() self.add_preload_ads(interruptable_ads, False) def guess_duration_from_size(self, content_length): if content_length >= 734003200: content_duration = 5400 elif content_length >= 314572800: content_duration = 2700 elif content_length >= 104857600: content_duration = 900 else: content_duration = 300 return content_duration def start_ad_download_when_seeding(self, d, main_d): if DEBUG: log('baseapp::start_ad_download_when_seeding: main', binascii.hexlify(main_d.get_hash()), 'ad', binascii.hexlify(d.get_hash())) if main_d not in self.downloads_in_admode: if DEBUG: log('baseapp::start_ad_download_when_seeding: main download is not in admode, exit') return ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) dlstatus = ds.get_status() if dlstatus != DLSTATUS_SEEDING: if DEBUG: log('baseapp::start_ad_download_when_seeding: not seeding, reschedule: dlstatus', dlstatus, 'main', binascii.hexlify(main_d.get_hash()), 'ad', binascii.hexlify(d.get_hash())) start_ad_download_when_seeding_lambda = lambda : self.start_ad_download_when_seeding(d, main_d) self.run_delayed(start_ad_download_when_seeding_lambda, 1.0) return if DEBUG: log('baseapp::start_ad_download_when_seeding: ad download is seeding, restart') d.set_video_event_callback(lambda d, event, params: self.sesscb_vod_event_callback(d, event, params, main_d)) d.set_player_buffer_time(1) d.set_max_conns(10) d.set_max_conns_to_initiate(10) d.set_hidden(True) d.restart() def start_direct_download(self, main_url, download_url, developer_id, affiliate_id, zone_id): destdir = self.get_default_destdir() urlhash = hashlib.sha1(main_url).digest() if DEBUG: log('baseapp::start_direct_download: urlhash', binascii.hexlify(urlhash), 'main_url', main_url) newd = self.s.get_download(DLTYPE_DIRECT, urlhash) content_duration = 0 if newd is not None: content_size = newd.get_content_length() if content_size is not None: content_duration = self.guess_duration_from_size(content_size) ads = self.ad_manager.get_ads(device_id=self.device_id, user_login=self.s.get_ts_login(), user_level=self.s.get_authlevel(), content_type=DLTYPE_DIRECT, content_id=binascii.hexlify(urlhash), content_ext='', content_duration=content_duration, affiliate_id=affiliate_id, zone_id=zone_id, developer_id=developer_id, include_interruptable_ads=self.get_playerconfig('enable_interruptable_ads', True), user_profile=self.user_profile) if ads == False: if DEBUG: log('baseapp::start_direct_download: failed to get ads, exit') raise Exception, 'Cannot start playback' initialdlstatus = None got_uninterruptable_ad = False if len(ads): for ad in ads: if not ad['interruptable']: got_uninterruptable_ad = True break if got_uninterruptable_ad: initialdlstatus = DLSTATUS_STOPPED if newd is None: dcfg = DownloadStartupConfig() dcfg.set_dest_dir(destdir) dcfg.set_wait_sufficient_speed(self.get_playerconfig('wait_sufficient_speed', False)) dcfg.set_player_buffer_time(self.get_playerconfig('player_buffer_time', DEFAULT_PLAYER_BUFFER_TIME)) dcfg.set_live_buffer_time(self.get_playerconfig('live_buffer_time', DEFAULT_LIVE_BUFFER_TIME)) dcfg.set_video_event_callback(self.sesscb_vod_event_callback) dcfg.set_direct_download_url(download_url) dcfg.set_download_finished_callback(lambda url, download_url, urlhash, fileinfo, developer_id = developer_id, affiliate_id = affiliate_id, zone_id = zone_id: self.direct_download_finished(url, download_url, urlhash, fileinfo, developer_id, affiliate_id, zone_id)) newd = self.s.start_direct_download(main_url, dcfg, initialdlstatus) else: newd.set_wait_sufficient_speed(self.get_playerconfig('wait_sufficient_speed', False)) newd.set_player_buffer_time(self.get_playerconfig('player_buffer_time', DEFAULT_PLAYER_BUFFER_TIME)) newd.set_live_buffer_time(self.get_playerconfig('live_buffer_time', DEFAULT_LIVE_BUFFER_TIME)) newd.set_video_event_callback(self.sesscb_vod_event_callback) newd.set_direct_download_url(download_url) newd.set_download_finished_callback(lambda url, download_url, urlhash, fileinfo, developer_id = developer_id, affiliate_id = affiliate_id, zone_id = zone_id: self.direct_download_finished(url, download_url, urlhash, fileinfo, developer_id, affiliate_id, zone_id)) if initialdlstatus is None: if DEBUG: log('BaseApp::start_direct_download: restarting existing download: urlhash', binascii.hexlify(urlhash)) newd.restart() else: ds = newd.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status != DLSTATUS_STOPPED: if DEBUG: log('BaseApp::start_direct_download: existing download is active, stop it and wait for ads: urlhash', binascii.hexlify(urlhash)) newd.stop() elif DEBUG: log('BaseApp::start_direct_download: skip restarting existing download, wait for ads: urlhash', binascii.hexlify(urlhash)) self.dlinfo_lock.acquire() try: self.downloads_in_vodmode[newd] = {} if newd in self.downloads_in_admode: if DEBUG: log('baseapp::start_ad_downloads: remove old ad downloads on start') del self.downloads_in_admode[newd] if len(ads): if got_uninterruptable_ad: if DEBUG: log('baseapp::start_download: got uninterruptable ad, start ads immediatelly') self.start_ad_downloads(newd, ads) else: if DEBUG: log('baseapp::start_download: no uninterruptable ad, start ads when main started') start_ad_downloads_when_main_started_lambda = lambda : self.start_ad_downloads_when_main_started(newd, ads) self.run_delayed(start_ad_downloads_when_main_started_lambda, 0.5) finally: self.dlinfo_lock.release() func = lambda : GoogleAnalytics.send_event('client', 'play', VERSION) self.run_delayed(func) return newd def get_encrypted_file_metainfo(self, path): f = None try: f = open(path, 'rb') meta_len = f.read(4) meta_len, = struct.unpack('l', meta_len) if DEBUG: log('baseapp::get_encrypted_file_metainfo: meta_len', meta_len) meta = f.read(meta_len) meta = pickle.loads(meta) if DEBUG: log('baseapp::get_encrypted_file_metainfo: meta', meta) offset_fix = 4 + meta_len - meta['offset'] return (meta, offset_fix) finally: if f is not None: f.close() def play_encrypted_file(self, path, affiliate_id = 0, zone_id = 0, developer_id = 0): if DEBUG: log('baseapp::play_encrypted_file: path', path) if not os.path.isfile(path): if DEBUG: log('baseapp::play_encrypted_file: play_encrypted_file') meta, offset_fix = self.get_encrypted_file_metainfo(path) content_duration = meta['duration'] if content_duration == 0: content_duration = self.guess_duration_from_size(meta['file_length']) ads = self.ad_manager.get_ads(device_id=self.device_id, user_login=self.s.get_ts_login(), user_level=self.s.get_authlevel(), content_type=DLTYPE_ENCRYPTED_FILE, content_id=binascii.hexlify(meta['hash']), content_ext='', content_duration=content_duration, affiliate_id=affiliate_id, zone_id=zone_id, developer_id=developer_id, include_interruptable_ads=False, provider_key=meta['provider'], user_profile=self.user_profile) if ads == False: if DEBUG: log('baseapp::play_encrypted_file: failed to get ads, exit') raise Exception, 'Cannot start playback' got_uninterruptable_ad = False if len(ads): for ad in ads: if not ad['interruptable']: got_uninterruptable_ad = True break newd = FakeDownload(DLTYPE_ENCRYPTED_FILE, path, meta, offset_fix, self.sesscb_vod_event_callback) self.dlinfo_lock.acquire() try: self.downloads_in_vodmode[newd] = {} if newd in self.downloads_in_admode: if DEBUG: log('baseapp::play_encrypted_file: remove old ad downloads on start') del self.downloads_in_admode[newd] if len(ads) and got_uninterruptable_ad: if DEBUG: log('baseapp::play_encrypted_file: got uninterruptable ad, start ads immediatelly') self.start_ad_downloads(newd, ads) else: newd.restart() finally: self.dlinfo_lock.release() return newd def direct_download_finished(self, url, download_url, urlhash, fileinfo, developer_id, affiliate_id, zone_id): try: if DEBUG: log('baseapp::direct_download_finished: url', url, 'download_url', download_url, 'fileinfo', fileinfo, 'd', developer_id, 'a', affiliate_id, 'z', zone_id) path = os.path.join(fileinfo['destdir'], fileinfo['filename']) piecelen = 524288 tracker = 'http://tracker.publicbt.com:80/announce' trackers = [['http://t1.torrentstream.net:2710/announce'], ['http://t2.torrentstream.net:2710/announce'], ['http://tracker.publicbt.com:80/announce'], ['http://tracker.openbittorrent.com:80/announce']] if DEBUG: log('baseapp::direct_download_finished: create torrent: path', path, 'piecelen', piecelen, 'trackers', trackers) if fileinfo['mimetype'] == 'video/mp4': cleared_mp4_metatags = clear_mp4_metadata_tags_from_file(path, ['gssd', 'gshh']) if DEBUG: log('baseapp::direct_download_finished: cleared_mp4_metatags', cleared_mp4_metatags) else: cleared_mp4_metatags = [] tdef = TorrentDef() tdef.add_content(path) tdef.set_piece_length(piecelen) tdef.set_tracker(tracker) tdef.set_tracker_hierarchy(trackers) if download_url is None: tdef.set_urllist([url]) if fileinfo.has_key('duration') and fileinfo['duration'] is not None: tdef.set_ts_duration(0, fileinfo['duration']) if len(cleared_mp4_metatags): tdef.set_ts_replace_mp4_metatags(0, ','.join(cleared_mp4_metatags)) tdef.finalize() infohash = tdef.get_infohash() if not self.s.download_exists(DLTYPE_TORRENT, infohash): if DEBUG: log('baseapp::direct_download_finished: add new torrent to downloads') dcfg = DownloadStartupConfig() dcfg.set_dest_dir(fileinfo['destdir']) d = self.s.start_download(tdef, dcfg) elif DEBUG: log('baseapp::direct_download_finished: torrent already exists in downloads: infohash', binascii.hexlify(infohash)) player_id, torrent_checksum = self.send_torrent_to_server(tdef, developer_id, affiliate_id, zone_id) if player_id is not None: self.save_player_data_to_db(player_id, torrent_checksum, infohash, developer_id, affiliate_id, zone_id) self.save_url2torrent(url, infohash) self.s.save_ts_metadata_db(infohash, tdef.get_ts_metadata()) except: if DEBUG: print_exc() def got_ts_metadata(self, tdef, metadata): if len(metadata) == 0: return if DEBUG: log('baseapp::got_ts_metadata: infohash', binascii.hexlify(tdef.get_infohash()), 'metadata', metadata) if metadata.has_key('duration'): tdef.set_ts_duration(metadata['index'], metadata['duration']) if metadata.has_key('prebuf_pieces'): tdef.set_ts_prebuf_pieces(metadata['index'], metadata['prebuf_pieces']) self.s.save_ts_metadata_db(tdef.get_infohash(), tdef.get_ts_metadata()) self.save_ts_metadata_server(tdef.get_infohash(), tdef.get_ts_metadata()) def save_ts_metadata_server(self, infohash, metadata): if metadata is None: return if DEBUG: log('baseapp::save_ts_metadata_server: infohash', binascii.hexlify(infohash), 'metadata', metadata) lambda_save_ts_metadata_server = lambda : self._save_ts_metadata_server(infohash, metadata) self.run_delayed(lambda_save_ts_metadata_server) def _save_ts_metadata_server(self, infohash, metadata): if DEBUG: log('baseapp::_save_ts_metadata_server: infohash', binascii.hexlify(infohash), 'metadata', metadata) try: self.tsservice.send_metadata(infohash, metadata) except: if DEBUG: log_exc() def send_torrent_to_server(self, tdef, developer_id = 0, affiliate_id = 0, zone_id = 0): if DEBUG_SERVICE_REQUESTS: log('baseapp::send_torrent_to_server: infohash', binascii.hexlify(tdef.get_infohash()), 'd', developer_id, 'a', affiliate_id, 'z', zone_id) torrent_data = tdef.save() torrent_checksum = hashlib.sha1(torrent_data).digest() protected = tdef.get_protected() if protected: infohash = tdef.get_infohash() else: infohash = None player_id = self.tsservice.send_torrent(torrent_data, developer_id, affiliate_id, zone_id, protected, infohash) if player_id is None: return if DEBUG_SERVICE_REQUESTS: log('baseapp::send_torrent_to_server: torrent saved: infohash', binascii.hexlify(tdef.get_infohash()), 'checksum', binascii.hexlify(torrent_checksum), 'd', developer_id, 'a', affiliate_id, 'z', zone_id, 'player_id', player_id) self.save_player_data_to_db(player_id, torrent_checksum, tdef.get_infohash(), developer_id, affiliate_id, zone_id) return (player_id, torrent_checksum) def update_torrent(self, tdef, developer_id = 0, affiliate_id = 0, zone_id = 0): lambda_update_torrent = lambda : self._update_torrent(tdef, developer_id, affiliate_id, zone_id) self.run_delayed(lambda_update_torrent) def _update_torrent(self, tdef, developer_id, affiliate_id, zone_id): try: torrent_data = tdef.save() torrent_checksum = hashlib.sha1(torrent_data).digest() ret = self.tsservice.check_torrent(torrent_checksum=torrent_checksum, infohash=tdef.get_infohash(), developer_id=developer_id, affiliate_id=affiliate_id, zone_id=zone_id) if ret is None: if DEBUG_SERVICE_REQUESTS: log('baseapp::_update_torrent: check_torrent failed') return player_id, metadata, http_seeds = ret if DEBUG_SERVICE_REQUESTS: log('baseapp::_update_torrent: torrent saved: infohash', binascii.hexlify(tdef.get_infohash()), 'checksum', binascii.hexlify(torrent_checksum), 'player_id', player_id, 'metadata', metadata, 'http_seeds', http_seeds) if player_id is None: player_id, torrent_checksum = self.send_torrent_to_server(tdef, developer_id, affiliate_id, zone_id) else: self.save_player_data_to_db(player_id, torrent_checksum, tdef.get_infohash(), developer_id, affiliate_id, zone_id) if metadata is not None: self.s.save_ts_metadata_db(tdef.get_infohash(), metadata) try: for d in self.s.get_downloads(): if d.get_hash() == tdef.get_infohash(): if DEBUG_SERVICE_REQUESTS: log('baseapp::_update_torrent: send metadata to download: hash', binascii.hexlify(d.get_hash()), 'metadata', metadata) d.got_metadata(metadata) except: pass if http_seeds is not None: self.s.set_ts_http_seeds(tdef.get_infohash(), http_seeds) try: for d in self.s.get_downloads(): if d.get_hash() == tdef.get_infohash(): if DEBUG_SERVICE_REQUESTS: log('baseapp::_update_torrent: send http seeds to download: hash', binascii.hexlify(d.get_hash()), 'http_seeds', http_seeds) d.got_http_seeds(http_seeds) except: pass except: if DEBUG: log_exc() def get_torrent_from_server(self, infohash = None, player_id = None): if infohash is None and player_id is None: raise ValueError, 'infohash or player id must be specified' if infohash is not None and player_id is not None: raise ValueError, 'Both infohash and player id cannot be specified at the same time' if DEBUG_SERVICE_REQUESTS: if infohash is not None: log('baseapp::get_torrent_from_server: infohash', binascii.hexlify(infohash)) elif player_id is not None: log('baseapp::get_torrent_from_server: player_id', player_id) player_data = self.tsservice.get_torrent(infohash=infohash, player_id=player_id) if player_data is None: return tdef = player_data['tdef'] self.s.save_torrent_local(tdef, player_data['checksum']) self.s.save_ts_metadata_db(tdef.get_infohash(), tdef.get_ts_metadata()) return player_data def get_torrent_from_adid(self, adid): infohash = self.get_infohash_from_adid(adid) if infohash is None: return ret = self.get_torrent_by_infohash(infohash) if ret is None: return return ret['tdef'] def get_infohash_from_adid(self, adid): infohash = None infohash = self.get_infohash_from_adid_db(adid) if infohash is not None: return infohash infohash = self.get_infohash_from_adid_server(adid) if infohash is not None: self.save_adid2infohash_db(adid, infohash) return infohash def get_infohash_from_adid_db(self, adid): if DEBUG_SERVICE_REQUESTS: t = time.time() db = self.s.open_dbhandler(NTFY_ADID2INFOHASH) if db is None: return infohash = db.get(adid) self.s.close_dbhandler(db) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_infohash_from_adid_db: adid', adid, 'infohash', infohash, 'time', time.time() - t) return infohash def get_ad_last_seen(self, infohash): db = self.s.open_dbhandler(NTFY_ADID2INFOHASH) if db is None: return last_seen = db.get_last_seen(infohash) self.s.close_dbhandler(db) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_ad_last_seen: infohash', binascii.hexlify(infohash), 'last_seen', last_seen) return last_seen def get_infohash_from_adid_server(self, adid): return self.tsservice.get_infohash_from_adid(adid) def save_adid2infohash_db(self, adid, infohash): if DEBUG_SERVICE_REQUESTS: log('baseapp::save_adid2infohash_db: adid', adid, 'infohash', binascii.hexlify(infohash)) db = self.s.open_dbhandler(NTFY_ADID2INFOHASH) if db is None: if DEBUG_SERVICE_REQUESTS: log('baseapp::save_adid2infohash_db: no db') return db.put(adid, infohash) self.s.close_dbhandler(db) def get_torrent_from_url(self, url): infohash = self.get_infohash_from_url(url) if infohash is None: return ret = self.get_torrent_by_infohash(infohash) if ret is None: return return ret['tdef'] def get_infohash_from_url(self, url): infohash = None infohash = self.get_infohash_from_url_db(url) if infohash is not None: return infohash infohash = self.get_infohash_from_url_server(url) if infohash is not None: self.save_url2torrent_db(url, infohash) return infohash def get_infohash_from_url_db(self, url): db = self.s.open_dbhandler(NTFY_URL2TORRENT) if db is None: return infohash = db.get(url) self.s.close_dbhandler(db) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_infohash_from_url: url', url, 'infohash', infohash) return infohash def get_infohash_from_url_server(self, url): return self.tsservice.get_infohash_from_url(url) def save_url2torrent(self, url, infohash): try: self.save_url2torrent_db(url, infohash) except: log_exc() try: self.save_url2torrent_server(url, infohash) except: log_exc() def save_url2torrent_db(self, url, infohash): if DEBUG_SERVICE_REQUESTS: log('baseapp::save_url2torrent: url', url, 'infohash', binascii.hexlify(infohash)) db = self.s.open_dbhandler(NTFY_URL2TORRENT) if db is None: if DEBUG_SERVICE_REQUESTS: log('baseapp::save_url2torrent: no db') return db.put(url, infohash) self.s.close_dbhandler(db) def save_url2torrent_server(self, url, infohash): self.tsservice.save_url2infohash(url, infohash) def get_torrent_from_db(self, checksum = None, infohash = None): if checksum is None and infohash is None: return torrent_db = None tdef = None try: if DEBUG_SERVICE_REQUESTS: t = time.time() torrent_db = self.s.open_dbhandler(NTFY_TORRENTS) if torrent_db is None: return if checksum is not None: torrent = torrent_db.getTorrent(checksum=checksum, keys=['torrent_file_name']) else: torrent = torrent_db.getTorrent(infohash=infohash, keys=['torrent_file_name']) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_from_db: infohash', infohash, 'checksum', checksum, 'torrent', torrent, 'time', time.time() - t) if torrent is None: return torrent_dir = torrent_db.getTorrentDir() path = os.path.join(torrent_dir, torrent['torrent_file_name']) if os.path.exists(path): if DEBUG_SERVICE_REQUESTS: t = time.time() tdef = TorrentDef.load(path) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_from_db: load torrent from file: path', path, 'time', time.time() - t) else: if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_from_db: torrent file removed, update db: path', path) torrent_db.deleteTorrent(infohash) return {'tdef': tdef, 'infohash': torrent['infohash'], 'checksum': torrent['checksum']} except: log_exc() return finally: if torrent_db is not None: self.s.close_dbhandler(torrent_db) def get_torrent_by_infohash(self, infohash): if DEBUG_SERVICE_REQUESTS: t = time.time() ret = self.get_torrent_from_db(infohash=infohash) if ret is not None: if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_by_infohash: got from db: infohash', binascii.hexlify(infohash), 'time', time.time() - t) return {'tdef': ret['tdef'], 'checksum': ret['checksum']} if DEBUG_SERVICE_REQUESTS: t = time.time() player_data = self.get_torrent_from_server(infohash=infohash) if player_data is not None: if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_by_infohash: got from server: infohash', binascii.hexlify(infohash), 'time', time.time() - t) return {'tdef': player_data['tdef'], 'checksum': player_data['checksum']} if DEBUG_SERVICE_REQUESTS: log('baseapp::get_torrent_by_infohash: not found: infohash', binascii.hexlify(infohash)) def get_player_data_from_db(self, player_id): try: db = self.s.open_dbhandler(NTFY_TS_PLAYERS) if db is None: return player_data = db.get(player_id) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_player_data_from_db: player_id', player_id, 'player_data', player_data) return player_data except: log_exc() return finally: if db is not None: self.s.close_dbhandler(db) def get_player_id_from_db(self, checksum, infohash, developer_id, affiliate_id, zone_id): try: db = self.s.open_dbhandler(NTFY_TS_PLAYERS) if db is None: return player_id = db.getPlayerId(checksum, infohash, developer_id, affiliate_id, zone_id) if DEBUG_SERVICE_REQUESTS: log('baseapp::get_player_id_from_db: player_id', player_id, 'checksum', checksum, 'infohash', binascii.hexlify(infohash), 'developer_id', developer_id, 'affiliate_id', affiliate_id, 'zone_id', zone_id) return player_id except: log_exc() return finally: if db is not None: self.s.close_dbhandler(db) def save_player_data_to_db(self, player_id, checksum, infohash, developer_id, affiliate_id, zone_id): if DEBUG_SERVICE_REQUESTS: log('baseapp::save_player_data_to_db: player_id', player_id, 'checksum', binascii.hexlify(checksum), 'infohash', binascii.hexlify(infohash), 'developer_id', developer_id, 'affiliate_id', affiliate_id, 'zone_id', zone_id) try: db = self.s.open_dbhandler(NTFY_TS_PLAYERS) if db is None: return db.put(player_id, checksum, infohash, developer_id, affiliate_id, zone_id) except: log_exc() finally: if db is not None: self.s.close_dbhandler(db) def get_player_data(self, player_id): player_data = self.get_player_data_from_db(player_id) if player_data is not None: ret = self.get_torrent_from_db(checksum=player_data['checksum']) if ret is not None: if DEBUG_SERVICE_REQUESTS: log('baseapp::get_player_data: got from db: player_id', player_id, 'checksum', binascii.hexlify(player_data['checksum']), 'player_data', player_data) player_data['tdef'] = ret['tdef'] return player_data player_data = self.get_torrent_from_server(player_id=player_id) if player_data is not None: if DEBUG_SERVICE_REQUESTS: log('baseapp::get_player_data: got from server: player_id', player_id, 'checksum', binascii.hexlify(player_data['checksum']), 'player_data', player_data) self.save_player_data_to_db(player_id, player_data['checksum'], player_data['tdef'].get_infohash(), player_data['developer_id'], player_data['affiliate_id'], player_data['zone_id']) return player_data if DEBUG_SERVICE_REQUESTS: log('baseapp::get_player_data: not found: player_id', player_id) def check_user_profile(self): if self.user_profile is None: self.user_profile = self.get_user_profile() return self.user_profile is not None def get_user_profile(self): db = None try: db = self.s.open_dbhandler(NTFY_USER_PROFILE) if db is None: return profile = db.get_active_profile() if DEBUG_SERVICE_REQUESTS: log('baseapp::get_user_profile: profile', str(profile)) return profile except: log_exc() return finally: if db is not None: self.s.close_dbhandler(db) def sesscb_vod_event_callback(self, d, event, params, main_download = None): pass def get_supported_vod_events(self): pass def get_drive_list(self): try: drives = win32api.GetLogicalDriveStrings() drives = [ drivestr for drivestr in drives.split('\x00') if drivestr ] return drives except: return [] def format_drive_name(self, drive): if drive is None: return '' if len(drive) < 2: return '' drive = drive[:2].lower() if not drive.endswith(':'): return '' return drive def get_disk_info(self, path): try: folder = path if sys.platform == 'win32': free_bytes, total_bytes, _ = win32file.GetDiskFreeSpaceEx(folder) used_bytes = total_bytes - free_bytes else: st = os.statvfs(folder) free_bytes = st.f_bavail * st.f_frsize total_bytes = st.f_blocks * st.f_frsize used_bytes = (st.f_blocks - st.f_bfree) * st.f_frsize return (total_bytes, free_bytes, used_bytes) except: if DEBUG: log('baseapp::get_disk_info: cannot get disk info: path', path) return (None, None, None) def free_up_diskspace_by_downloads(self, infohash = None, needed = 0): disk_cache_limit = self.get_playerconfig('disk_cache_limit', DEFAULT_DISKSPACE_LIMIT) content_dir = self.get_default_destdir() total, avail, used = self.get_disk_info(content_dir) if avail is None: if disk_cache_limit == 0: if DEBUG: log('baseapp::free_up_diskspace_by_downloads: cannot get disk info and disk cache is unlimited') return True avail = disk_cache_limit if DEBUG: log('BaseApp::free_up_diskspace_by_downloads: needed', needed, 'avail', avail, 'disk_cache_limit', disk_cache_limit) if disk_cache_limit < needed < avail: if DEBUG: log('BaseApp::free_up_diskspace_by_downloads: no cleanup for bigguns') return True inuse = 0L timelist = [] if self.apptype == 'acestream': known_files = [] for d in self.s.get_downloads(): destfiles = d.get_dest_files(exts=videoextdefaults, get_all=True) if self.apptype == 'acestream': for filename, savepath in destfiles: if os.path.exists(savepath): known_files.append(savepath) if infohash is not None and infohash == d.get_hash(): continue if d in self.downloads_in_vodmode: continue if d.is_hidden(): continue if DEBUG: log('BaseApp::free_up_diskspace_by_downloads: downloaded content', destfiles) dinuse = 0L max_ctime = 0 for filename, savepath in destfiles: dirname = os.path.dirname(savepath) if dirname != content_dir: if DEBUG: log('baseapp::free_up_diskspace_by_downloads: skip dir:', dirname) continue if os.path.exists(savepath): stat = os.stat(savepath) dinuse += stat.st_size if stat.st_ctime > max_ctime: max_ctime = stat.st_ctime if dinuse > 0: inuse += dinuse timerec = (max_ctime, dinuse, d) timelist.append(timerec) if self.apptype == 'acestream': try: filelist = os.listdir(content_dir) except: if DEBUG: print_exc() filelist = [] if DEBUG: log('baseapp::free_up_diskspace_by_downloads: known_files', known_files, 'filelist', filelist) for basename in filelist: if basename == '.lock': continue if infohash is not None and basename == binascii.hexlify(infohash): if DEBUG: log('baseapp::free_up_diskspace_by_downloads: keep file: basename', basename, 'infohash', binascii.hexlify(infohash)) continue filename = os.path.join(content_dir, basename) if filename not in known_files: if DEBUG: log('baseapp::free_up_diskspace_by_downloads: remove unknown file: filename', filename) try: os.remove(filename) except: if DEBUG: print_exc() if disk_cache_limit == 0: limit = avail else: limit = min(avail, disk_cache_limit) if inuse + needed < limit: if DEBUG: log('BaseApp::free_up_diskspace_by_downloads: enough avail: inuse', inuse, 'needed', needed, 'limit', limit, 'avail', avail) return True timelist.sort() if DEBUG: log('baseapp::free_up_diskspace_by_downloads: timelist', timelist) to_free = inuse + needed - limit if DEBUG: log('baseapp::free_up_diskspace_by_downloads: to_free', to_free, 'limit', limit, 'inuse', inuse, 'needed', needed) for ctime, dinuse, d in timelist: if DEBUG: log('baseapp::free_up_diskspace_by_downloads: remove download: hash', binascii.hexlify(d.get_hash()), 'dinuse', dinuse, 'ctime', ctime) self.s.remove_download(d, removecontent=True) to_free -= dinuse if DEBUG: log('baseapp::free_up_diskspace_by_downloads: remove done: to_free', to_free, 'limit', limit, 'inuse', inuse, 'needed', needed) if to_free <= 0: return True return False def sesscb_states_callback(self, dslist): if self.debug_systray: getpeerlist = True haspeerlist = True else: getpeerlist = False haspeerlist = False gui_states_callback_wrapper_lambda = lambda : self.gui_states_callback_wrapper(dslist, haspeerlist) self.run_delayed(gui_states_callback_wrapper_lambda) return (1.0, getpeerlist) def gui_states_callback_wrapper(self, dslist, haspeerlist): try: self.gui_states_callback(dslist, haspeerlist) except: log_exc() def gui_states_callback(self, dslist, haspeerlist): if self.shuttingdown: return ({}, [], 0, 0) playermode = self.playermode totalspeed = {UPLOAD: 0.0, DOWNLOAD: 0.0} totalhelping = 0 display_stats = self.download_states_display_counter % DOWNLOAD_STATES_DISPLAY_INTERVAL == 0 self.download_states_display_counter += 1 all_dslist = {} playing_dslist = {} hidden_dslist = {} all_playing_are_seeding = True playing_premium_content = False self.dlinfo_lock.acquire() try: for ds in dslist: d = ds.get_download() all_dslist[d] = ds is_vod_download = False vod_download_params = None if d.is_hidden(): hidden_dslist[d] = ds if d in self.downloads_in_vodmode: is_vod_download = True vod_download_params = self.downloads_in_vodmode[d] playing_dslist[d] = ds if all_playing_are_seeding and ds.get_status() != DLSTATUS_SEEDING: all_playing_are_seeding = False if is_vod_download and vod_download_params.get('premium', False): playing_premium_content = True provider_key = d.get_def().get_provider() provider_content_id = d.get_def().get_content_id() if not self.report_premium_download(provider_key, provider_content_id, vod_download_params): if time.time() > vod_download_params['start'] + PREMIUM_PREVIEW_TIMEOUT and not vod_download_params.has_key('stopped_preview'): if DEBUG_PREMIUM: log('baseapp::gui_states_callback: user auth failed for premium content, stop') vod_download_params['stopped_preview'] = True self.stop_download(d, 'http://acestream.net/embed/premium', 'This content is available for premium users only') if DEBUG and display_stats: log('baseapp::gui_states_callback: dlinfo: vod=%i type=%d hash=%s hidden=%i priority=%d status=%s paused=%i progress=%.1f%% error=%s' % (is_vod_download, d.get_type(), binascii.hexlify(d.get_hash()), d.is_hidden(), d.get_extra('priority', 0), dlstatus_strings[ds.get_status()], ds.get_paused(), 100.0 * ds.get_progress(), ds.get_error())) self.update_download_stats(ds) if not d.is_hidden() or SHOW_HIDDEN_DOWNLOADS_INFO: for dir in [UPLOAD, DOWNLOAD]: totalspeed[dir] += ds.get_current_speed(dir) totalhelping += ds.get_num_peers() for main_download, ad_downloads in self.downloads_in_admode.iteritems(): if not playing_dslist.has_key(main_download): if DEBUG: log('baseapp::gui_states_callback: main download in ad mode is not in vod downloads: infohash', binascii.hexlify(main_download.get_hash())) else: main_ds = playing_dslist[main_download] if main_ds.get_status() == DLSTATUS_STOPPED: all_ads_completed = True for d in ad_downloads.keys(): if not all_dslist.has_key(d): if DEBUG: log('baseapp::gui_states_callback: ad download not found in downloads: infohash', binascii.hexlify(d.get_hash())) else: ds = all_dslist[d] if DEBUG: log('baseapp::gui_states_callback: check ad download: main', binascii.hexlify(main_download.get_hash()), 'ad', binascii.hexlify(d.get_hash()), 'status', ds.get_status(), 'progress', ds.get_progress()) status = ds.get_status() if status == DLSTATUS_STOPPED_ON_ERROR: ad_downloads[d]['failed'] = True elif status == DLSTATUS_STOPPED: if DEBUG: log('!!!! baseapp::gui_states_callback: ad download is stopped, mark as failed !!!!') ad_downloads[d]['failed'] = True elif status == DLSTATUS_SEEDING: ad_downloads[d]['completed'] = True else: all_ads_completed = False if all_ads_completed: if DEBUG: log('baseapp::gui_states_callback: all ads are completed, restart download: infohash', binascii.hexlify(main_download.get_hash())) main_download.restart() finally: self.dlinfo_lock.release() if haspeerlist: try: for ds in playing_dslist.values(): peerlist = ds.get_peerlist() vodstats = ds.get_vod_stats() stats = ds.get_stats() if peerlist and self.statFrame: self.statFrame.updateStats(spew=peerlist, statistics=stats, vod_stats=vodstats) if DEBUG_STATS_TO_FILE: self.save_state_to_file(spew=peerlist, statistics=stats, vod_stats=vodstats) break except: log_exc() if self.live_frame is not None: try: for ds in playing_dslist.values(): peerlist = ds.get_peerlist() vodstats = ds.get_vod_stats() stats = ds.get_stats() self.live_frame.update(spew=peerlist, statistics=stats, vod_stats=vodstats) break except: print_exc() txt = self.appname + '\n\n' txt += 'DL: %.1f\n' % totalspeed[DOWNLOAD] txt += 'UL: %.1f\n' % totalspeed[UPLOAD] txt += 'Helping: %d\n' % totalhelping self.OnSetSysTrayTooltip(txt) if totalspeed[DOWNLOAD] > self.max_download_rate: self.max_download_rate = totalspeed[DOWNLOAD] if totalspeed[UPLOAD] > self.max_upload_rate: self.max_upload_rate = totalspeed[UPLOAD] self.avg_download_rate_sum += totalspeed[DOWNLOAD] self.avg_download_rate_count += 1 self.avg_download_rate = self.avg_download_rate_sum / float(self.avg_download_rate_count) self.avg_upload_rate_sum += totalspeed[UPLOAD] self.avg_upload_rate_count += 1 self.avg_upload_rate = self.avg_upload_rate_sum / float(self.avg_upload_rate_count) if self.playing_premium_content != playing_premium_content: if DEBUG_PREMIUM: log('baseapp::gui_states_callback: playing_premium_content changed to', playing_premium_content) self.playing_premium_content = playing_premium_content if playing_premium_content: self.run_delayed(self.check_auth_level, 1.0, task_id='check_auth_level') if all_playing_are_seeding: if self.get_playerconfig('enable_interruptable_ads', True): max_progress = -1 max_priority = -1 download_to_restart = None for d, ds in hidden_dslist.iteritems(): status = ds.get_status() if status == DLSTATUS_STOPPED or status == DLSTATUS_STOPPED_ON_ERROR: priority = d.get_extra('priority', 0) if ds.get_progress() == 1.0: if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::gui_states_callback: restart completed hidden download: hash', binascii.hexlify(d.get_hash()), 'status', dlstatus_strings[status], 'progress', ds.get_progress()) d.restart() elif priority > max_priority: download_to_restart = d max_progress = ds.get_progress() max_priority = priority elif ds.get_progress() > max_progress: download_to_restart = d max_progress = ds.get_progress() max_priority = priority elif status == DLSTATUS_HASHCHECKING or ds.get_progress() != 1.0: if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::gui_states_callback: got running hidden download: hash', binascii.hexlify(d.get_hash()), 'status', dlstatus_strings[status], 'progress', ds.get_progress()) download_to_restart = None break if download_to_restart is not None: import os current_file_path = os.path.dirname(os.path.realpath(__file__)) downloadlimitvalue_file = os.path.join(os.path.split(current_file_path)[0],"values","downloadlimit.txt") f = open(downloadlimitvalue_file, "r") string = f.read() max_speed = self.get_playerconfig('max_download_rate', int(string)) if max_speed == 0: max_speed = self.max_download_rate limit_speed = max_speed / 3 download_to_restart.set_max_speed(DOWNLOAD, limit_speed) if DEBUG_HIDDEN_DOWNLOADS: ds = hidden_dslist[download_to_restart] log('baseapp::gui_states_callback: restart hidden download: hash', binascii.hexlify(download_to_restart.get_hash()), 'status', dlstatus_strings[ds.get_status()], 'progress', ds.get_progress(), 'max_speed', max_speed, 'limit_speed', limit_speed) download_to_restart.restart() if playermode == DLSTATUS_DOWNLOADING: if DEBUG: log('BaseApp::gui_states_callback: all playing download are seeding, restart others') t = time.time() self.restart_other_downloads() if DEBUG: log('BaseApp::gui_states_callback: restart others: time', time.time() - t) elif playermode == DLSTATUS_SEEDING: if DEBUG: log('BaseApp::gui_states_callback: not all playing download are seeding, stop others') t = time.time() self.stop_other_downloads() if DEBUG: log('BaseApp::gui_states_callback: stop others: time', time.time() - t) if len(playing_dslist) == 0: return ({}, [], 0, 0) return (all_dslist, playing_dslist.values(), totalhelping, totalspeed) def update_download_stats(self, ds, force = False): try: if not force and time.time() - self.last_download_stats < DOWNLOAD_STATS_INTERVAL: return self.last_download_stats = time.time() d = ds.get_download() download_id = d.get_download_id() if download_id is None: return if d.get_type() != DLTYPE_TORRENT: return tdef = d.get_def() if not self.stat_settings.check_content('ts', tdef): return downloaded = ds.get_total_transferred(DOWNLOAD) uploaded = ds.get_total_transferred(UPLOAD) if not self.download_stats.has_key(download_id): self.download_stats[download_id] = {'downloaded': 0, 'uploaded': 0} if self.download_stats[download_id]['downloaded'] != downloaded or self.download_stats[download_id]['uploaded'] != uploaded: self.download_stats[download_id]['downloaded'] = downloaded self.download_stats[download_id]['uploaded'] = uploaded infohash = binascii.hexlify(tdef.get_infohash()) provider_key = tdef.get_provider() provider_content_id = tdef.get_content_id() self.traffic_stats.send_event(download_id, 'keepalive', downloaded, uploaded, infohash, provider_key, provider_content_id) except: if DEBUG: print_exc() def save_state_to_file(self, spew, statistics = None, vod_stats = None): info = '' if spew is not None: tot_uprate = 0.0 tot_downrate = 0.0 tot_downloaded = 0 for x in range(len(spew)): peerdata = [''] * 17 if spew[x]['optimistic'] == 1: a = '*' else: a = ' ' peerdata[0] = a peerdata[2] = spew[x]['ip'].ljust(15) peerdata[3] = spew[x]['direction'] peerdata[4] = ('%.0f kB/s' % (float(spew[x]['uprate']) / 1000)).ljust(10) tot_uprate += spew[x]['uprate'] if spew[x]['uinterested'] == 1: a = '*' else: a = ' ' peerdata[5] = a if spew[x]['uchoked'] == 1: a = '*' else: a = ' ' peerdata[6] = a bitrate = None if vod_stats['videostatus'] is not None: bitrate = vod_stats['videostatus'].bitrate str_downrate = '%.0f' % (spew[x]['downrate'] / 1024.0) if 'short_downrate' in spew[x]: if bitrate is None: str_downrate += ' (%.0f)' % (spew[x]['short_downrate'] / 1024 / 0.0) else: str_downrate += ' (%.0f, %.1f)' % (spew[x]['short_downrate'] / 1024.0, spew[x]['short_downrate'] / float(bitrate)) peerdata[7] = str_downrate.ljust(15) tot_downrate += spew[x]['downrate'] if spew[x]['dinterested'] == 1: a = '*' else: a = ' ' peerdata[8] = a if spew[x]['dchoked'] == 1: a = '*' else: a = ' ' peerdata[9] = a if spew[x]['snubbed'] == 1: a = '*' else: a = ' ' peerdata[10] = a tot_downloaded += spew[x]['dtotal'] peerdata[11] = ('%.2f MiB' % (float(spew[x]['dtotal']) / 1048576)).ljust(10) if spew[x]['utotal'] is not None: a = '%.2f MiB' % (float(spew[x]['utotal']) / 1048576) else: a = '' peerdata[12] = a.ljust(10) peerdata[13] = ('%.1f%%' % (float(int(spew[x]['completed'] * 1000)) / 10)).ljust(5) if spew[x]['speed'] is not None: a = '%.0f' % (float(spew[x]['speed']) / 1024) if 'speed_proxy' in spew[x]: a += ' | p:%.0f' % (float(spew[x]['speed_proxy']) / 1024) if 'speed_non_proxy' in spew[x]: a += ' | r:%.0f' % (float(spew[x]['speed_non_proxy']) / 1024) else: a = '' peerdata[14] = a.ljust(15) peerdata[15] = str(spew[x]['last_requested_piece']).ljust(4) peerdata[16] = str(spew[x]['last_received_piece']).ljust(4) info += '\t'.join(peerdata) + '\n' info += '\n\nTOTALS: up=' + '%.0f kB/s' % (float(tot_uprate) / 1024) + ' down=' + '%.0f kB/s' % (float(tot_downrate) / 1024) + ' downloaded=' + '%.2f MiB' % (float(tot_downloaded) / 1048576) + '\n\n' if vod_stats is not None: for pos, data in vod_stats['proxybuf'].iteritems(): length = len(data) info += str(pos) + ' ' for i in xrange(length / 131072): info += '-' info += str(pos + length - 1) + '\n' info += 'buf: ' + str(vod_stats['outbuf']) + '\n' if vod_stats['videostatus'] is not None: vs = vod_stats['videostatus'] info += ' >> idx: ' + str(vs.fileindex) info += ', br: ' + str(vs.bitrate / 1024) info += ', len: ' + str(vs.piecelen / 1024) info += ', first: ' + str(vs.first_piece) info += ', last: ' + str(vs.last_piece) info += ', have: ' + str(vs.numhave) info += ', comp: %.2f' % vs.completed info += ', prebuf: ' + str(vs.prebuffering) info += ', pos: ' + str(vs.playback_pos) info += ', hp: ' + str(vs.prebuf_high_priority_pieces) info += ', pp: ' + str(vs.prebuf_missing_pieces) have = vs.have[:] have.sort() info += ', pieces: ' + str(have) for vs in vod_stats['extra_videostatus']: info += '\n index: ' + str(vs.fileindex) info += ', first piece: ' + str(vs.first_piece) info += ', last piece: ' + str(vs.last_piece) info += ', numhave: ' + str(vs.numhave) info += ', completed: %.2f' % vs.completed info += ', prebuf: ' + str(vs.prebuffering) info += ', hp: ' + str(vs.prebuf_high_priority_pieces) info += ', pp: ' + str(vs.prebuf_missing_pieces) have = vs.have[:] have.sort() info += ', pieces: ' + str(have) if statistics is not None: for piece in xrange(len(statistics.storage_inactive_list)): inactive = statistics.storage_inactive_list[piece] if inactive is None: inactive = 'all' elif inactive == 1: inactive = 'none' else: inactive = str(len(inactive)) info += '\n' + str(piece) + ': inactive=' + inactive + ' active=' + str(statistics.storage_active_list[piece]) + ' dirty=' + str(statistics.storage_dirty_list[piece]) if len(info): self.debug_counter += 1 try: filename = 'stat_snapshot_' + str(self.debug_counter).rjust(4, '0') + '_' + str(int(time.time())) + '.txt' f = open(os.path.join(self.installdir, filename), 'w') f.write(info) f.close() except: raise def OnSetSysTrayTooltip(self, txt): try: self.wrapper.set_icon_tooltip(txt) except: pass def restart_other_downloads(self): if self.shuttingdown: return if DEBUG: log('baseapp::restart_other_downloads: ---') self.playermode = DLSTATUS_SEEDING self.ratelimiter = UserDefinedMaxAlwaysOtherwiseEquallyDividedRateManager() self.set_ratelimits() dlist = self.s.get_downloads() for d in dlist: if d.is_hidden(): ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status() != DLSTATUS_STOPPED: if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::restart_other_downloads: unpause hidden download: hash', binascii.hexlify(d.get_hash())) d.pause(False) continue if d not in self.downloads_in_vodmode: ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status() == DLSTATUS_STOPPED and ds.get_progress() == 1.0: if DEBUG: log('baseapp::restart_other_downloads: start seeding: infohash', binascii.hexlify(d.get_hash())) d.set_mode(DLMODE_NORMAL) d.restart() else: d.pause(False) def stop_other_downloads(self): if self.shuttingdown: return if DEBUG: log('baseapp::stop_other_downloads: ---') self.playermode = DLSTATUS_DOWNLOADING dlist = self.s.get_downloads() for d in dlist: if d in self.downloads_in_vodmode: continue is_ad = False for maind_d, ads in self.downloads_in_admode.iteritems(): if d in ads: is_ad = True break if is_ad: continue ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status() == DLSTATUS_STOPPED: continue if DEBUG: log('baseapp::stop_other_downloads: stop: infohash', binascii.hexlify(d.get_hash()), 'status', dlstatus_strings[ds.get_status()], 'progress', ds.get_progress()) if ds.get_status() == DLSTATUS_SEEDING: d.pause(True, close_connections=True) else: d.stop() def stop_hidden_downloads(self): if self.shuttingdown: return if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::stop_hidden_downloads: ---') dlist = self.s.get_downloads() for d in dlist: if not d.is_hidden(): continue if d in self.downloads_in_vodmode: continue is_ad = False for maind_d, ads in self.downloads_in_admode.iteritems(): if d in ads: is_ad = True break if is_ad: continue ds = d.network_get_state(usercallback=None, getpeerlist=False, sessioncalling=True) if ds.get_status() == DLSTATUS_STOPPED: if ds.get_progress() == 0.0: if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::stop_hidden_downloads: remove: infohash', binascii.hexlify(d.get_hash()), 'status', dlstatus_strings[ds.get_status()], 'progress', ds.get_progress()) self.s.remove_download(d, removecontent=True) continue if DEBUG_HIDDEN_DOWNLOADS: log('baseapp::stop_hidden_downloads: stop: infohash', binascii.hexlify(d.get_hash())) d.stop() def remove_downloads_in_vodmode_if_not_complete(self): if DEBUG: log('BaseApp::remove_downloads_in_vodmode_if_not_complete: Removing playing download if not complete') for d in self.downloads_in_vodmode: d.set_state_callback(self.sesscb_remove_playing_callback) def sesscb_remove_playing_callback(self, ds): if DEBUG: d = ds.get_download() dlhash = binascii.hexlify(d.get_hash()) log('BaseApp::sesscb_remove_playing_callback: type', d.get_type(), 'hash', dlhash, 'status', dlstatus_strings[ds.get_status()], 'progress', ds.get_progress()) self.update_download_stats(ds, True) d = ds.get_download() if d.get_type() == DLTYPE_TORRENT: live = d.get_def().get_live() else: live = False if live: remove_content = True elif ds.get_status() == DLSTATUS_DOWNLOADING and ds.get_progress() >= MIN_PROGRESS_KEEP: remove_content = False elif ds.get_status() == DLSTATUS_SEEDING: remove_content = False elif ds.get_status() == DLSTATUS_HASHCHECKING: remove_content = False else: remove_content = True if not remove_content: if ds.get_status() == DLSTATUS_SEEDING: can_remove = self.can_remove_playing_download(d) if can_remove: self.remove_download_info(d) if DEBUG: log('baseapp::sesscb_remove_playing_callback: download is seeding, do not stop: dlhash', dlhash, 'remove_dlinfo', can_remove) else: if DEBUG: log('BaseApp::sesscb_remove_playing_callback: keeping: dlhash', dlhash) remove_playing_download_lambda = lambda : self.remove_playing_download(d, removecontent=False, stop=True) self.run_delayed(remove_playing_download_lambda, 0.1) else: if DEBUG: log('BaseApp::sesscb_remove_playing_callback: voting for removing: dlhash', dlhash) if self.shuttingdown: if DEBUG: log('BaseApp::sesscb_remove_playing_callback: shuttingdown, call remove_playing_download immediately') self.remove_playing_download(d, removecontent=True) else: if DEBUG: log('BaseApp::sesscb_remove_playing_callback: schedule remove_playing_download') remove_playing_download_lambda = lambda : self.remove_playing_download(d, removecontent=True) self.run_delayed(remove_playing_download_lambda, 0.1) return (-1.0, False) def remove_playing_download(self, d, removecontent): if self.s is not None: if DEBUG: log('BaseApp::remove_playing_download: dlhash', binascii.hexlify(d.get_hash()), 'removecontent', removecontent) try: self.s.remove_download(d, removecontent) self.remove_download_info(d) except: log_exc() elif DEBUG: log('BaseApp::remove_playing_download: s is None') def stop_playing_download(self, d): if DEBUG: log('BaseApp::stop_playing_download: dlhash', binascii.hexlify(d.get_hash())) try: d.stop() self.remove_download_info(d) except: log_exc() def remove_download_info(self, d): if DEBUG: log('baseapp::remove_download_info: remove download: hash', binascii.hexlify(d.get_hash())) if d in self.downloads_in_vodmode: params = self.downloads_in_vodmode[d] if params.has_key('tns'): if DEBUG: log('baseapp::remove_download_info: stop tns: hash', binascii.hexlify(d.get_hash())) params['tns'].stop() del self.downloads_in_vodmode[d] if d in self.downloads_in_admode: del self.downloads_in_admode[d] def set_ratelimits(self): import os current_file_path = os.path.dirname(os.path.realpath(__file__)) uploadlimitvalue_file = os.path.join(os.path.split(current_file_path)[0],"values","uploadlimit.txt") f = open(uploadlimitvalue_file, "r") uploadrate = float(self.get_playerconfig('total_max_upload_rate', int(string))) if DEBUG: log('BaseApp::set_ratelimits: Setting max upload rate to', uploadrate) if self.ratelimiter is not None: self.ratelimiter.set_global_max_speed(UPLOAD, uploadrate) self.ratelimiter.set_global_max_seedupload_speed(uploadrate) def ratelimit_callback(self, dslist): if self.ratelimiter is None: return adjustspeeds = False if self.ratelimit_update_count % 4 == 0: adjustspeeds = True self.ratelimit_update_count += 1 if adjustspeeds: self.ratelimiter.add_downloadstatelist(dslist) self.ratelimiter.adjust_speeds() def load_playerconfig(self, state_dir): self.playercfgfilename = os.path.join(state_dir, 'playerconf.pickle') self.playerconfig = {} if not os.path.isfile(self.playercfgfilename): return try: f = open(self.playercfgfilename, 'rb') self.playerconfig = pickle.load(f) f.close() except: print_exc() self.playerconfig = {} def save_playerconfig(self): try: f = open(self.playercfgfilename, 'wb') pickle.dump(self.playerconfig, f) f.close() except: log_exc() def set_playerconfig(self, key, value): if self.playerconfig.has_key(key): old_value = self.playerconfig[key] else: old_value = None self.playerconfig[key] = value if key == 'total_max_upload_rate': try: self.set_ratelimits() except: log_exc() return old_value def update_playerconfig(self, changed_config_params): if 'enable_interruptable_ads' in changed_config_params: value = self.get_playerconfig('enable_interruptable_ads') if DEBUG: log('baseapp::update_playerconfig: enable_interruptable_ads changed: value', value) if value: self.run_delayed(self.check_preload_ads, 3.0, 'check_preload_ads') else: self.run_delayed(self.stop_hidden_downloads, 3.0) if 'disk_cache_limit' in changed_config_params: if DEBUG: log('baseapp::update_playerconfig: disk cache limit changed:', self.get_playerconfig('disk_cache_limit')) self.free_up_diskspace_by_downloads() for d in self.downloads_in_vodmode: d.set_wait_sufficient_speed(self.get_playerconfig('wait_sufficient_speed')) d.set_http_support(self.get_playerconfig('enable_http_support')) d.set_player_buffer_time(self.get_playerconfig('player_buffer_time')) d.set_live_buffer_time(self.get_playerconfig('live_buffer_time')) d.set_max_speed(UPLOAD, self.get_playerconfig('total_max_upload_rate')) d.set_max_speed(DOWNLOAD, self.get_playerconfig('total_max_download_rate'), self.get_playerconfig('auto_download_limit')) d.set_max_conns(self.get_playerconfig('download_max_connects')) def get_playerconfig(self, key, default = None): if key in self.playerconfig: return self.playerconfig[key] return default def OnExit(self): log('BaseApp::OnExit:', currentThread().getName()) self.shuttingdown = True self.remove_downloads_in_vodmode_if_not_complete() if self.max_download_rate > 0: if DEBUG: log('baseapp::onexit: save max down rate:', self.max_download_rate) self.set_playerconfig('max_download_rate', self.max_download_rate) self.save_playerconfig() self.i2i_listen_server.shutdown() if globalConfig.get_mode() != 'client_console': time.sleep(2) if self.s is not None: try: state_dir = self.s.get_state_dir() cfgfilename = Session.get_default_config_filename(state_dir) if DEBUG: log('baseapp::onexit: save SessionStartupConfig to', cfgfilename) scfg = SessionStartupConfig.load(cfgfilename) scfg.set_authlevel(self.s.get_authlevel()) scfg.save(cfgfilename) except: pass self.s.shutdown(hacksessconfcheckpoint=False) self.save_cookies() if DEBUG: self.debug_threads() def debug_threads_task(self): try: self.debug_threads() finally: self.run_delayed(self.debug_threads_task, 600) def debug_threads(self): log('baseapp::debug_threads: ---') count = 0 for t in enumerate(): log('baseapp::debug_threads: thread is running', t.name, 'daemon', t.daemon) count += 1 log('baseapp::debug_threads: count', count) def clear_session_state(self): try: if self.s is not None: dlist = self.s.get_downloads(DLTYPE_TORRENT) for d in dlist: if not d.is_hidden(): self.s.remove_download(d, removecontent=True) dlist = self.s.get_downloads(DLTYPE_DIRECT) for d in dlist: if not d.is_hidden(): self.s.remove_download(d, removecontent=True) if self.apptype == 'acestream': time.sleep(3) path = self.get_default_destdir() shutil.rmtree(path, True) if DEBUG: log('baseapp::clear_session_state: delete cache dir:', path) except: log_exc() time.sleep(1) def show_error(self, msg): log('baseapp::show_error:', msg) def get_default_destdir(self): dest_dir = self.get_playerconfig('download_dir') if dest_dir is not None: if DEBUG: print >> sys.stderr, 'get_default_destdir: get from config:', dest_dir, type(dest_dir) elif sys.platform == 'win32': registry = Win32RegChecker() dest_dir = registry.readKey(HKCU, 'Software\\' + self.registry_key, 'DataDir', ignore_errors=True) if dest_dir is None: dest_dir = registry.readKey(HKLM, 'Software\\' + self.registry_key, 'DataDir', ignore_errors=True) if DEBUG: print >> sys.stderr, 'get_default_destdir: get from registry:', dest_dir, type(dest_dir) if self.apptype == 'acestream': if sys.platform == 'win32' and dest_dir is not None: if len(dest_dir) < 2: dest_dir = None else: drive = dest_dir[:2] if not drive.endswith(':'): dest_dir = None else: dest_dir = os.path.join(drive + '\\', CACHE_DIR_NAME) if not self.check_dest_dir(dest_dir, make_hidden=True): dest_dir = self.select_dest_dir() if DEBUG: log('baseapp::get_default_destdir: check_dest_dir() failed, selected:', dest_dir) else: if dest_dir is not None: if not self.check_dest_dir(dest_dir, make_hidden=False): dest_dir = None if dest_dir is None: state_dir = Session.get_default_state_dir() dest_dir = os.path.join(state_dir, 'downloads') if not self.check_dest_dir(dest_dir, make_hidden=False): dest_dir = None if dest_dir is None and sys.platform != 'win32': dest_dir = os.path.join('/tmp', '.ACEStream', 'downloads') if not self.check_dest_dir(dest_dir, make_hidden=False): dest_dir = None if dest_dir is None: raise Exception, 'Cannot select dest dir' self.set_playerconfig('download_dir', dest_dir) return dest_dir def check_dest_dir(self, dest_dir, make_hidden): if dest_dir is None: return False if not os.path.isdir(dest_dir): if DEBUG: log('baseapp::check_dest_dir: dest dir is not a directory:', dest_dir) try: os.makedirs(dest_dir) except: if DEBUG: log('baseapp::check_dest_dir: failed to create dest dir:', dest_dir) return False if make_hidden and sys.platform == 'win32': try: p = os.popen('attrib +h ' + dest_dir) p.close() except: if DEBUG: print_exc() try: lock = os.path.join(dest_dir, '.lock') f = open(lock, 'w') f.close() except: if DEBUG: log('baseapp::check_dest_dir: cannot write to dest dir:', dest_dir) return False return True def select_dest_dir(self): dest_dir = None if sys.platform == 'win32': candidates = [] drive_list = self.get_drive_list() if DEBUG: log('>>>drive_list', drive_list) for drive in drive_list: if DEBUG: log('>>>drive1', drive) drive = self.format_drive_name(drive) + '\\' if DEBUG: log('>>>drive2', drive) total, free, used = self.get_disk_info(drive) if free is not None: path = os.path.join(drive, CACHE_DIR_NAME) candidates.append((free, path)) candidates.sort(reverse=True) if DEBUG: log('baseapp::select_dest_dir: candidates', candidates) for free, path in candidates: if self.check_dest_dir(path, True): dest_dir = path break else: state_dir = Session.get_default_state_dir() path = os.path.join(state_dir, 'cache') if self.check_dest_dir(path, True): dest_dir = path if dest_dir is None: path = os.path.join('/tmp', '.ACEStream', 'cache') if self.check_dest_dir(path, make_hidden=True): dest_dir = path if DEBUG: log('baseapp::select_dest_dir: dest dir selected:', dest_dir) return dest_dir def get_preload_ads_enabled(self, default_value = True): enabled = self.get_playerconfig('enable_interruptable_ads') if enabled is None: if sys.platform == 'win32': registry = Win32RegChecker() enabled = registry.readKey(HKCU, 'Software\\' + self.registry_key, 'EnablePreload', ignore_errors=True) if DEBUG: log('baseapp::get_preload_ads_enabled: get from registry HKCU:', enabled) if enabled is None: enabled = registry.readKey(HKLM, 'Software\\' + self.registry_key, 'EnablePreload', ignore_errors=True) if DEBUG: log('baseapp::get_preload_ads_enabled: get from registry HKLM:', enabled) if enabled is None: enabled = default_value else: try: enabled = int(enabled) enabled = enabled != 0 except: enabled = default_value else: enabled = default_value self.set_playerconfig('enable_interruptable_ads', enabled) elif DEBUG: log('baseapp::get_preload_ads_enabled: get from config:', enabled) return enabled def is_svc(self, dlfile, tdef): svcfiles = None if tdef.is_multifile_torrent(): enhancement = tdef.get_files(exts=svcextdefaults) if enhancement: enhancement.sort() if tdef.get_length(enhancement[0]) == tdef.get_length(dlfile): svcfiles = [dlfile] svcfiles.extend(enhancement) return svcfiles def i2ithread_readlinecallback(self, ic, cmd): pass def make_provider_stream_cache_key(self, provider_key, infohash, device_id, user_login, user_password, user_key): return '-'.join([provider_key, binascii.hexlify(infohash), device_id, user_login, hashlib.sha1(user_password).hexdigest(), user_key]) def update_provider_stream_cache(self, provider_key, infohash, device_id, user_login, user_password, user_key): key = self.make_provider_stream_cache_key(provider_key, infohash, device_id, user_login, user_password, user_key) if DEBUG: log('baseapp::update_provider_stream_cache: save data to provider stream cache: key', key) self.provider_stream_cache.setdefault(key, {'last_success': 0}) self.provider_stream_cache[key]['last_success'] = time.time() def check_provider_stream_cache(self, provider_key, infohash, device_id, user_login, user_password, user_key): key = self.make_provider_stream_cache_key(provider_key, infohash, device_id, user_login, user_password, user_key) if key not in self.provider_stream_cache: return False else: last_success = self.provider_stream_cache[key]['last_success'] if DEBUG: log('baseapp::check_provider_stream_cache: got data from provider stream cache: key', key, 'last_success', last_success) if time.time() - last_success > STREAM_CACHE_TTL: if DEBUG: log('baseapp::check_provider_stream_cache: data from provider stream cache expired: key', key, 'last_success', last_success) del self.provider_stream_cache[key] return False if DEBUG: log('baseapp::check_provider_stream_cache: got valid data from provider stream cache: key', key, 'last_success', last_success) return True def load_cookies(self): try: f = open(self.cookie_file, 'r') data = pickle.load(f) f.close() for c in data: if DEBUG: log('baseapp::load_cookies: add cookie:', c) self.cookie_jar.set_cookie(c) return True except: if DEBUG: log('baseapp::load_cookies: cannot load cookies file:', self.cookie_file) return False def save_cookies(self): try: cookies = [] for c in self.cookie_jar: cookies.append(c) if DEBUG: log('baseapp::save_cookies: file', self.cookie_file, 'cookies', cookies) f = open(self.cookie_file, 'w') pickle.dump(cookies, f) f.close() return True except: if DEBUG: log('baseapp::save_cookies: cannot save to file', self.cookie_file) return False def check_premium_status(self, provider_key, content_id, infohash): if content_id is None: if DEBUG_PREMIUM: log('baseapp::check_premium_status: empty content id') return False status = self.tsservice.check_premium_status(provider_key, content_id, infohash) if DEBUG_PREMIUM: log('baseapp::check_premium_status: provider_key', provider_key, 'content_id', content_id, 'status', status) if status is None: if DEBUG_PREMIUM: log('baseapp::check_premium_status: request failed, consider premium: provider_key', provider_key, 'content_id', content_id) return True return status == 1 def report_premium_download(self, provider_key, content_id, params): report = False check_user = False user_ok = True if not params.has_key('last_report'): if DEBUG_PREMIUM: log('baseapp::report_premium_download: not yet reported') report = True elif params['last_report'] < time.time() - params['report_interval']: if DEBUG_PREMIUM: log('baseapp::report_premium_download: time to report: last', params['last_report'], 'now', time.time(), 'interval', params['report_interval']) report = True if not params.has_key('last_user_check'): if DEBUG_PREMIUM: log('baseapp::report_premium_download: user not checked') check_user = True elif params['last_user_check'] < time.time() - params['user_check_interval']: if DEBUG_PREMIUM: log('baseapp::report_premium_download: time to check user: last', params['last_user_check'], 'now', time.time(), 'interval', params['user_check_interval']) check_user = True if report: params['last_report'] = time.time() user_login = self.s.get_ts_login() self.tsservice.report_premium_download(params['download_id'], provider_key, content_id, user_login) if check_user: params['last_user_check'] = time.time() user_level = self.s.get_authlevel() if user_level != 2: if DEBUG_PREMIUM: log('baseapp::report_premium_download: user auth failed: level', user_level) user_ok = False return user_ok def check_statistics_settings(self): if DEBUG: log('baseapp::check_statistics_settings: ---') try: timeout = self.stat_settings.check_settings() self.traffic_stats.set_url_list(self.stat_settings.get_url_list('ts')) except: if DEBUG: print_exc() timeout = 3600 finally: if DEBUG: log('baseapp::check_statistics_settings: next run in', timeout) self.run_delayed(self.check_statistics_settings, timeout) def tns_send_event(self, d, event, event_data = None, delay = 0): try: if d in self.downloads_in_vodmode: dparams = self.downloads_in_vodmode[d] if dparams.has_key('tns'): dparams['tns'].send_event(event, event_data, delay) except: print_exc() def init_hardware_key(self): try: self.hardware_key = get_hardware_key() if DEBUG: log('baseapp::init_hardware_key: got key:', self.hardware_key) except: if DEBUG: print_exc() self.hardware_key = None def check_integrity(self): if sys.platform != 'win32': return True if not self.check_string('.Torrent Stream', '64048011141141110101' + '1611230380611411101790901'): if DEVELOPER_MODE: log('string failed') return False selfpath = sys.argv[0] exename = os.path.basename(selfpath) if self.apptype == 'torrentstream': check_exe1 = 'tsengine.exe' check_exe2 = 'tsengine' check_exe3 = '61151110101130150' + '1011101640101021101' check_exe4 = '61151110' + '1011301501011101' else: check_exe1 = 'ace_engine.exe' check_exe2 = 'ace_engine' check_exe3 = '79099010159' + '0101011301501011101640101021101' check_exe4 = '790990101590101011' + '301501011101' if exename != check_exe1 and exename != check_exe2: if DEVELOPER_MODE: log('exename failed:', exename) return False if not (self.check_string(exename, check_exe3) or self.check_string(exename, check_exe4)): if DEVELOPER_MODE: log('exename failed 2') return False base = os.path.abspath(os.path.dirname(selfpath)) if DEVELOPER_MODE: log('selfpath', selfpath, 'exename', exename, 'base', base) files = [] files.append({'path': 'lib\\pycompat27.pyd', 'path2': '801501890290211121990111901211790611050550640211121001'}) files.append({'path': '..\\updater\\tsupdate.exe', 'path2': '640640290711211001790611101411290611511711211001790611101640101021101'}) files.append({'path': '..\\player\\npts_plugin.dll', 'path2': '640640290211801790121101411290011211611511590211801711301501011640001801801'}) files.append({'path': '..\\player\\tsplayer.exe', 'path2': '640640290211801790121101411290611511211801790121101411640101021101'}) files.append({'path': 'python27.dll', 'path2': '211121611401111011050550640001801801', 'check': '4cad50ea762261d7f1361f7095cc6c740c2aa1b6', 'check2': '250990790001350840101790550450050050450940001550201940150450940201550840750350990990450990550250840990050790790940890450'}) files.append({'path': 'lib\\_ctypes.pyd', 'path2': '801501890290590990611121211101511640211121001', 'check': '616293e45730b2d4b49002d65cac9fb319c44aa2', 'check2': '450940450050750150101250350550150840890050001250890250750840840050001450350990790990750201890150940750990250250790790050'}) files.append({'path': 'lib\\_hashlib.pyd', 'path2': '801501890290590401790511401801501890640211121001', 'check': '3e5e42e2ff2bfdfa36fad0a14d18a5508717ee47', 'check2': '150101350101250050101050201201050890201001201790150450201790001840790940250001940650790350350840650550940550101101250550'}) files.append({'path': 'lib\\_socket.pyd', 'path2': '801501890290590511111990701101611640211121001', 'check': '95deea9dbbf5c19d8042439bd676c2c3e6b47328', 'check2': '750350001101101790750001890890201350990940750001650840250050250150750890001450550450990050990150101450890250550150050650'}) files.append({'path': 'lib\\_sqlite3.pyd', 'path2': '801501890290590511311801501611101150640211121001', 'check': 'dc0dadc7e0a73ca83c7f6fa21e807b5eb8ff67e1', 'check2': '001990840001790001990550101840790550150990790650150990550201450201790050940101650840550890350101890650201201450550101940'}) files.append({'path': 'lib\\_ssl.pyd', 'path2': '801501890290590511511801640211121001', 'check': '7d656f10b4d9d7f6d55caaa626e5975422637466', 'check2': '550001450350450201940840890250001750001550201450001350350990790790790450050450101350750550350250050050450150550250450450'}) files.append({'path': 'lib\\LIBEAY32.dll', 'path2': '801501890290670370660960560980150050640001801801', 'check': '3fc80784b3f0714a1859521f990965b949a71536', 'check2': '150201990650840550650250890150201840550940250790940650350750350050940201750750840750450350890750250750790550940350150450'}) files.append({'path': 'lib\\M2Crypto.__m2crypto.pyd', 'path2': '801501890290770050760411121211611111640590590901050990411121211611111640211121001', 'check': '01a2dbcfe59602b45fa9c389cb604570ca71dbf1', 'check2': '840940790050001890990201101350750450840050890250350201790750990150650750990890450840250350550840990790550940001890201940'}) files.append({'path': 'lib\\pycompat.pyd', 'path2': '801501890290211121990111901211790611640211121001', 'check': 'e282471605acb12f842fe1047ca445e819297762', 'check2': '101050650050250550940450840350790990890940050201650250050201101940840250550990790250250350101650940750050750550550450050'}) files.append({'path': 'lib\\SSLEAY32.dll', 'path2': '801501890290380380670960560980150050640001801801', 'check': '42323e4435bc986c45c9a2b841e7da7b6a98b228', 'check2': '250050150050150101250250150350890990750650450990250350990750790050890650250940101550001790550890450790750650890050050650'}) files.append({'path': 'lib\\wxbase28uh_vc.dll', 'path2': '801501890290911021890790511101050650711401590811990640001801801', 'check': '22a7683af988f5d0bef8abe4934dba03a093f21d', 'check2': '050050790550450650150790201750650650201350001840890101201650790890101250750150250001890790840150790840750150201050940001'}) files.append({'path': 'lib\\wxmsw28uh_adv_vc.dll', 'path2': '801501890290911021901511911050650711401590790001811590811990640001801801', 'check': 'd0aac3f14afe9c0bedc9a906b4dd6981597a8685', 'check2': '001840790790990150201940250790201101750990840890101001990750790750840450890250001001450750650940350750550790650450650350'}) files.append({'path': 'tsengine.exe', 'path2': '611511101011301501011101640101021101', 'check': '1a77f3cf03b882514683af1d6d2f9f0480a4bf2e', 'check2': '940790550550201150990201840150890650650050350940250450650150790201940001450001050201750201840250650840790250890201050101'}) files.append({'path': 'tsengine_stream.exe', 'path2': '611511101011301501011101590511611411101790901640101021101', 'check': '0c28965c60bae004e0c8a0a79f070dce266f6e33', 'check2': '840990050650750450350990450840890790101840840250101840990650790840790550750201840550840001990101050450450201450101150150'}) return self.check_files(base, files) def check_files(self, base, files): for f in files: do_check = f.has_key('check') if not self.check_string(f['path'], f['path2']): if DEVELOPER_MODE: log('path failed:', f['path']) return False if do_check and not self.check_string(f['check'], f['check2']): if DEVELOPER_MODE: log('check failed:', f['check']) return False path = os.path.join(base, f['path']) if not self.file_exists(path): if DEVELOPER_MODE: log('not found:', path) return False if do_check: check = self.file_checksum(path) if check != f['check']: if DEVELOPER_MODE: log('checksum failed:', path, f['check'], check) return False return True def check_string(self, s, check): s1 = self.get_string(check) if s1 != s: if DEVELOPER_MODE: log('check string failed:', s, s1) return False return True def get_string(self, s, padding = 3): return ''.join([ chr(int(s[i:i + padding][::-1])) for i in xrange(0, len(s), padding) ]) def file_exists(self, path): if not os.path.isfile(path): return False try: f = open(path, 'rb') f.close() except: return False return True def file_checksum(self, path): f = None try: f = open(path, 'rb') h = hashlib.sha1() got_data = False while True: buf = f.read(4096) if not buf: break got_data = True h.update(buf) if not got_data: return '' return h.hexdigest() except: if DEBUG: print_exc() return '' finally: if f is not None: f.close()
48.625198
520
0.598059
[ "Apache-2.0" ]
C6SUMMER/allinclusive-kodi-pi
.kodi/userdata/addon_data/plugin.video.p2p-streams/acestream/ace/ACEStream/Player/BaseApp.py
153,607
Python
""" Support for Homekit number ranges. These are mostly used where a HomeKit accessory exposes additional non-standard characteristics that don't map to a Home Assistant feature. """ from aiohomekit.model.characteristics import Characteristic, CharacteristicsTypes from homeassistant.components.number import NumberEntity from homeassistant.core import callback from . import KNOWN_DEVICES, CharacteristicEntity NUMBER_ENTITIES = { CharacteristicsTypes.Vendor.VOCOLINC_HUMIDIFIER_SPRAY_LEVEL: { "name": "Spray Quantity", "icon": "mdi:water", }, CharacteristicsTypes.Vendor.EVE_DEGREE_ELEVATION: { "name": "Elevation", "icon": "mdi:elevation-rise", }, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Homekit numbers.""" hkid = config_entry.data["AccessoryPairingID"] conn = hass.data[KNOWN_DEVICES][hkid] @callback def async_add_characteristic(char: Characteristic): kwargs = NUMBER_ENTITIES.get(char.type) if not kwargs: return False info = {"aid": char.service.accessory.aid, "iid": char.service.iid} async_add_entities([HomeKitNumber(conn, info, char, **kwargs)], True) return True conn.add_char_factory(async_add_characteristic) class HomeKitNumber(CharacteristicEntity, NumberEntity): """Representation of a Number control on a homekit accessory.""" def __init__( self, conn, info, char, device_class=None, icon=None, name=None, **kwargs, ): """Initialise a HomeKit number control.""" self._device_class = device_class self._icon = icon self._name = name super().__init__(conn, info, char) def get_characteristic_types(self): """Define the homekit characteristics the entity is tracking.""" return [self._char.type] @property def device_class(self): """Return type of sensor.""" return self._device_class @property def icon(self): """Return the sensor icon.""" return self._icon @property def min_value(self) -> float: """Return the minimum value.""" return self._char.minValue @property def max_value(self) -> float: """Return the maximum value.""" return self._char.maxValue @property def step(self) -> float: """Return the increment/decrement step.""" return self._char.minStep @property def value(self) -> float: """Return the current characteristic value.""" return self._char.value async def async_set_value(self, value: float): """Set the characteristic to this value.""" await self.async_put_characteristics( { self._char.type: value, } )
27.653846
81
0.644645
[ "Apache-2.0" ]
0xFEEDC0DE64/homeassistant-core
homeassistant/components/homekit_controller/number.py
2,876
Python
# -*- coding: utf-8 -*- from django.conf.urls import url from django.views.generic import TemplateView from . import views app_name = 'services_communicator' urlpatterns = [ url( regex="^ServiceList/~create/$", view=views.ServiceListCreateView.as_view(), name='ServiceList_create', ), url( regex="^ServiceList/(?P<pk>\d+)/~delete/$", view=views.ServiceListDeleteView.as_view(), name='ServiceList_delete', ), url( regex="^ServiceList/(?P<pk>\d+)/$", view=views.ServiceListDetailView.as_view(), name='ServiceList_detail', ), url( regex="^ServiceList/(?P<pk>\d+)/~update/$", view=views.ServiceListUpdateView.as_view(), name='ServiceList_update', ), url( regex="^ServiceList/$", view=views.ServiceListListView.as_view(), name='ServiceList_list', ), ]
25.305556
51
0.601537
[ "MIT" ]
eshafik/services_communicator
services_communicator/urls.py
911
Python
# # Copyright 2018 EveryUP Srl # # 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 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 __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone from authosm.exceptions import OSMAuthException from lib.osm.osmclient.clientv2 import Client import utils class OsmUserManager(BaseUserManager): """Custom manager for OsmUser.""" def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): """Create and save a CustomUser with the given username and password. """ now = timezone.now() if not username: raise ValueError('The given username must be set') is_active = extra_fields.pop("is_active", True) user = self.model(username=username, is_staff=is_staff, is_active=is_active, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user """Create and save an OsmUser with the given username and password.""" def create_superuser(self, username, password, **extra_fields): return self._create_user(username, password, True, True, is_admin=True, **extra_fields) class AbstractOsmUser(AbstractBaseUser, PermissionsMixin): """Abstract User with the same behaviour as Django's default User. Inherits from both the AbstractBaseUser and PermissionMixin. The following attributes are inherited from the superclasses: * password * last_login * is_superuser """ username = models.CharField(_('username'), primary_key=True, max_length=255, unique=True, db_index=True) is_admin = models.BooleanField(_('admin status'), default=False) is_basic_user = models.BooleanField(_('basic_user status'), default=False) current_project = models.CharField(_('project_id'), max_length=255) psw = models.CharField(_('psw'), max_length=36) token = models.CharField(_('token'), max_length=36) project_id = models.CharField(_('project_id'), max_length=36) token_expires = models.FloatField(_('token_expires'), max_length=36) objects = OsmUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] @property def is_authenticated(self): """Checks for a valid authentication.""" if self.token is not None and utils.is_token_valid({'expires': self.token_expires}): return True else: return False def get_token(self): if self.is_authenticated: return {'id': self.token, 'expires': self.token_expires, 'project_id': self.project_id} return None def get_projects(self): client = Client() result = client.get_user_info(self.get_token(), self.username) if 'error' in result and result['error'] is True: return [] else: return result['data']['projects'] def switch_project(self, project_id): client = Client() result = client.switch_project({'project_id': project_id, 'username': self.username, 'password': self.psw}) if 'error' in result and result['error'] is True: raise OSMAuthException(result['data']) else: self.token = result['data']['id'] self.project_id = result['data']['project_id'] self.token_expires = result['data']['expires'] self.save() return True return False class Meta: verbose_name = _('custom user') verbose_name_plural = _('custom users') abstract = True class OsmUser(AbstractOsmUser): """ Concrete class of AbstractCustomUser. Use this if you don't need to extend CustomUser. """ class Meta(AbstractOsmUser.Meta): swappable = 'AUTH_USER_MODEL'
35.138462
115
0.669002
[ "Apache-2.0" ]
5g-media/OIDC_ON_OSMr5
LW-UI/authosm/models.py
4,568
Python
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ feedforward neural network """ import mindspore.nn as nn from mindelec.architecture import get_activation, LinearBlock class FFNN(nn.Cell): """ Full-connect networks. Args: input_dim (int): the input dimensions. output_dim (int): the output dimensions. hidden_layer (int): number of hidden layers. activation (str or Cell): activation functions. """ def __init__(self, input_dim, output_dim, hidden_layer=64, activation="sin"): super(FFNN, self).__init__() self.activation = get_activation(activation) self.fc1 = LinearBlock(input_dim, hidden_layer) self.fc2 = LinearBlock(hidden_layer, hidden_layer) self.fc3 = LinearBlock(hidden_layer, hidden_layer) self.fc4 = LinearBlock(hidden_layer, hidden_layer) self.fc5 = LinearBlock(hidden_layer, output_dim) def construct(self, *inputs): """fc network""" x = inputs[0] out = self.fc1(x) out = self.activation(out) out = self.fc2(out) out = self.activation(out) out = self.fc3(out) out = self.activation(out) out = self.fc4(out) out = self.activation(out) out = self.fc5(out) return out
33.946429
81
0.652814
[ "Apache-2.0" ]
mindspore-ai/mindscience
MindElec/examples/physics_driven/frequency_domain_maxwell/src/model.py
1,901
Python
# !/usr/bin/python3 # coding: utf_8 """ Config your app """ import os from hal.files.parsers import JSONParser from hal.files.save_as import write_dicts_to_json from .config import APP_FOLDER, API_FOLDER, DATA_FOLDER from .data.coins import CryptoCoin, CRYPTO_COINS class ConfigManager: """ Manages config files for app """ def __init__(self, config_file): create_workplace() self.config_file = config_file self.raw = None self.data = {} self._check() self._read_config() def _read_config(self): """ :return: {} Config data """ self.raw = JSONParser(self.config_file).get_content() for key, value in self.raw.items(): self.data[key] = value def _check(self): if not os.path.exists(self.config_file): raise ValueError( "Empty config file! Please write your settings " "and store at " + self.config_file ) def create_config(self): """ :return: void Creates config file """ if os.path.exists(self.config_file): raise ValueError("Creating new config will erase previous data!") write_dicts_to_json({}, self.config_file) # empty data def get(self, key): """ :param key: str What you want :return: {} Item you want """ return self.data[key] def save(self): """ :return: void Saves app data to local config file """ write_dicts_to_json(self.data, self.config_file) def create_workplace(): """ :return: void Creates folder """ for directory in [APP_FOLDER, API_FOLDER, DATA_FOLDER]: if not os.path.exists(directory): os.makedirs(directory) def get_coin(symbol): """ :param symbol: str Symbol of coin :return: CryptoCoin Coin if a crypto-coin exists with that name """ candidate = CryptoCoin(symbol, symbol) for coin in CRYPTO_COINS: if coin.symbol == candidate: return coin
22.163265
77
0.575967
[ "MIT" ]
sirfoga/pyhodl
pyhodl/app.py
2,172
Python
"""is_sqllab_view Revision ID: 130915240929 Revises: f231d82b9b26 Create Date: 2018-04-03 08:19:34.098789 """ import sqlalchemy as sa from alembic import op from sqlalchemy.ext.declarative import declarative_base from rabbitai import db # revision identifiers, used by Alembic. revision = "130915240929" down_revision = "f231d82b9b26" Base = declarative_base() class Table(Base): """Declarative class to do query in upgrade""" __tablename__ = "tables" id = sa.Column(sa.Integer, primary_key=True) sql = sa.Column(sa.Text) is_sqllab_view = sa.Column(sa.Boolean()) def upgrade(): bind = op.get_bind() op.add_column( "tables", sa.Column( "is_sqllab_view", sa.Boolean(), nullable=True, default=False, server_default=sa.false(), ), ) session = db.Session(bind=bind) # Use Slice class defined here instead of models.Slice for tbl in session.query(Table).all(): if tbl.sql: tbl.is_sqllab_view = True session.commit() db.session.close() def downgrade(): op.drop_column("tables", "is_sqllab_view")
20.785714
58
0.648625
[ "Apache-2.0" ]
psbsgic/rabbitai
rabbitai/migrations/versions/130915240929_is_sqllab_viz_flow.py
1,164
Python
from collections import OrderedDict from . import util from ..errors import ModelInfoLookupError class ModelInfo: def __init__(self, pairs=[], default_fields=None): """ Constructs a mapping of information about a model. :class:`~revscoring.scoring.ModelInfo` objects are usually nested within each other to provide a convenient tree structure for :func:`~revscoring.scoring.ModelInfo.lookup` and :func:`~revscoring.scoring.ModelInfo.format`. """ self._data = OrderedDict(pairs) self._default_fields = set(default_fields) \ if default_fields is not None else None def __len__(self): return len(self.keys()) def __getitem__(self, key): return self._data[key] def __setitem__(self, key, value): self._data[key] = value def __contains__(self, key): try: return (key in self._data or key in ('true', 'false') and key == 'true' in self._data or int(key) in self._data) except ValueError: return False def keys(self): return self._data.keys() def get(self, key, default=None): return self._data.get(key, default) def values(self): return self._data.values() def items(self): return self._data.items() def __iter__(self): return iter(self._data) def move_to_end(self, key, last=True): return self._data.move_to_end(key, last=last) def lookup(self, path=None): """ Looks up a specific information value based on either a string pattern or a path. For example, the pattern "stats.roc_auc.labels.true" is the same as the path ``['stats', 'roc_auc', 'labels', True]``. :Parameters: path : `str` | `list` The location of the information to lookup. """ if isinstance(path, str): path = util.parse_pattern(path) elif path is None: path = [] d = self remaining_path = list(path) # Make sure we don't overwrite the input while len(path) > 0: key = path.pop(0) d = try_key(key, d) if hasattr(d, "lookup"): return d.lookup(remaining_path) else: continue return d def format(self, paths=None, formatting="str", **kwargs): """ Format a representation of the model information in a useful way. :Parameters: paths : `iterable` ( `str` | [`str`] ) A set of paths to use when selecting which information should formatted. Everything beneath a provided path in the tree will be formatted. E.g. `statistics.roc_auc` and `statistics` will format redundantly because `roc_auc` is already within `statistics`. Alternatively `statistics.roc_auc` and `statistics.pr_auc` will format only those two specific bits of information. formatting : "json" or "str" Which output formatting do you want? "str" returns something nice to show on the command-line. "json" returns something that will pass through :func:`json.dump` without error. """ paths = paths or [] _paths = [ util.parse_pattern(path) if isinstance(path, str) else path for path in paths] path_tree = util.treeify(_paths) if formatting == "str": return self.format_str(path_tree, **kwargs) elif formatting == "json": return self.format_json(path_tree, **kwargs) else: raise ValueError("Formatting {0} is not available for {1}." .format(formatting, self.__class__.__name__)) def format_str(self, path_tree, **kwargs): formatted = "Model Information:\n" for key in self.normalize_fields(path_tree): key_val = try_key(key, self) if hasattr(key_val, "format_str"): sub_tree = path_tree.get(key, {}) formatted += util.tab_it_in( key_val.format_str(sub_tree, **kwargs)) else: formatted += util.tab_it_in(" - {0}: {1}" .format(key, key_val)) return formatted def format_json(self, path_tree, **kwargs): d = OrderedDict() for key in self.normalize_fields(path_tree): key_val = try_key(key, self) if hasattr(key_val, "format_json"): sub_tree = path_tree.get(key, {}) d[key] = key_val.format_json(sub_tree, **kwargs) else: d[key] = key_val return d def normalize_fields(self, path_tree): if len(path_tree) > 0: yield from path_tree.keys() else: for field in self.keys(): if self._default_fields is None or \ field in self._default_fields: yield field def try_key(key, d): try: return d[key] except KeyError: try: if key in ("true", "false"): return d[key == 'true'] else: try: return d[int(key)] except ValueError: raise ModelInfoLookupError(key) except KeyError: raise ModelInfoLookupError(key)
33.335329
79
0.553979
[ "MIT" ]
leojoubert/revscoring
revscoring/scoring/model_info.py
5,567
Python
# -*- coding: utf-8 -*- import cv2 import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt # Define a class to receive the characteristics of each line detection class Lane(): def __init__(self): # 当前的图像 self.current_warped_binary = None # 当前图片的尺寸 self.current_warped_binary_shape = [] # 检测到的车道线像素的横坐标 x values for detected line pixels self.allx = None # 检测到的车道线像素的纵坐标 y values for detected line pixels self.ally = None # 以纵坐标为自变量,取值空间 self.ploty = None # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 是否检测到车道线 was the line detected in the last iteration? self.detected = False # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 保存的数据量 self.n = 5 # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 最近n个帧的拟合曲线 x values of the last n fits of the line self.recent_fitted_xs = [] # 最近n个帧的平均拟合曲线 average x values of the fitted line over the last n iterations self.average_fitted_x = [] # 当前帧的拟合曲线 self.current_fitted_x = [] # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 最近n个帧的拟合函数 self.recent_fits = [] # 最近n个帧的拟合函数 polynomial coefficients averaged over the last n iterations self.average_fit = [] # 当前帧的拟合函数 polynomial coefficients for the most recent fit self.current_fit = [np.array([False])] # 拟合函数的误差 difference in fit coefficients between last and new fits self.diffs = np.array([0, 0, 0], dtype='float') # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # 半径 radius of curvature of the line in some units self.radius_of_curvature = [] # 车辆在车道线之间距离 distance in meters of vehicle center from the line self.line_base_pos = None # 对全新的帧进行车道线像素检测 def find_lane_pixels(self, binary_warped, location): self.current_warped_binary = binary_warped self.current_warped_binary_shape = binary_warped.shape self.ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) # Take a histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0) # Create an output image to draw on and visualize the result # out_img = np.dstack((binary_warped, binary_warped, binary_warped)) # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0] // 2) if location == "left": base = np.argmax(histogram[:midpoint]) elif location == "right": base = np.argmax(histogram[midpoint:]) + midpoint # HYPERPARAMETERS # Choose the number of sliding windows nwindows = 9 # Set the width of the windows +/- margin margin = 80 # Set minimum number of pixels found to recenter window minpix = 50 # Set height of windows - based on nwindows above and image shape window_height = np.int(binary_warped.shape[0] // nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() # 扁平化后非零值点的列表 nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated later for each window in nwindows current = base # Create empty lists to receive left and right lane pixel indices lane_inds = [] # right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window + 1) * window_height win_y_high = binary_warped.shape[0] - window * window_height win_x_low = current - margin win_x_high = current + margin # # Draw the windows on the visualization image # cv2.rectangle(out_img, (win_xleft_low, win_y_low), # (win_xleft_high, win_y_high), (0, 255, 0), 2) # cv2.rectangle(out_img, (win_xright_low, win_y_low), # (win_xright_high, win_y_high), (0, 255, 0), 2) # 形成对每个像素的bool值 # Identify the nonzero pixels in x and y within the window # good_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_x_low) & (nonzerox < win_x_high)).nonzero()[0] # Append these indices to the lists lane_inds.append(good_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_inds) > minpix: current = np.int(np.mean(nonzerox[good_inds])) # Concatenate the arrays of indices (previously was a list of lists of pixels) try: lane_inds = np.concatenate(lane_inds) except ValueError: # Avoids an error if the above is not implemented fully pass # Extract left and right line pixel positions x = nonzerox[lane_inds] y = nonzeroy[lane_inds] self.allx = x self.ally = y return x, y # 在之前的plot基础上找车道线 def search_pixel_around_poly(self, binary_warped): self.current_warped_binary = binary_warped self.current_warped_binary_shape = binary_warped.shape self.ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) # HYPERPARAMETER # Choose the width of the margin around the previous polynomial to search # The quiz grader expects 100 here, but feel free to tune on your own! margin = 80 # Grab activated pixels nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) fit = self.recent_fits[-1] ### TO-DO: Set the area of search based on activated x-values ### ### within the +/- margin of our polynomial function ### ### Hint: consider the window areas for the similarly named variables ### ### in the previous quiz, but change the windows to our new search area ### lane_inds = ((nonzerox > (fit[0] * (nonzeroy ** 2) + fit[1] * nonzeroy + fit[2] - margin)) & ( nonzerox < (fit[0] * (nonzeroy ** 2) + fit[1] * nonzeroy + fit[2] + margin))) # Again, extract left and right line pixel positions x = nonzerox[lane_inds] y = nonzeroy[lane_inds] self.allx = x self.ally = y return x, y def fit_polynomial(self): ploty = self.ploty # Fit a second order polynomial to each using `np.polyfit` fit = np.polyfit(self.ally, self.allx, 2) # 存储当前结果 self.current_fit = fit # 计算误差 if len(self.recent_fits) == 0: self.diffs = [0,0,0] else: new = np.array(self.current_fit) old = np.array(self.recent_fits[-1]) self.diffs = new - old # 存储为历史结果 if len(self.recent_fits) < self.n: self.recent_fits.append(self.current_fit) elif len(self.recent_fits) == self.n: self.recent_fits.pop(0) self.recent_fits.append(self.current_fit) else: self.recent_fits.append(self.current_fit) self.recent_fits = self.recent_fits[-self.n:] # 后面n个 # 计算当前平均 self.average_fit = np.array(self.recent_fits).mean(axis=0) try: x_fitted = self.average_fit[0] * ploty ** 2 + self.average_fit[1] * ploty + self.average_fit[2] except TypeError: # Avoids an error if `left` and `right_fit` are still none or incorrect print('The function failed to fit a line!') x_fitted = 1 * ploty ** 2 + 1 * ploty self.detected = False else: self.detected = True self.current_fitted_x = x_fitted # 存储为历史结果 if len(self.recent_fitted_xs) < self.n: self.recent_fitted_xs.append(self.current_fitted_x) elif len(self.recent_fitted_xs) == self.n: self.recent_fitted_xs.pop(0) self.recent_fitted_xs.append(self.current_fitted_x) else: self.recent_fitted_xs.append(self.current_fitted_x) self.recent_fitted_xs = self.recent_fitted_xs[-self.n:] # 后面n个 self.average_fitted_x = np.array(self.recent_fitted_xs).mean(axis=0) return self.average_fitted_x def fit(self, binary_warped,location,sequence=True): if sequence: if not self.detected: # 没有检测到,重新开始检测 self.find_lane_pixels(binary_warped,location) else: # 从上一次周围开始检测 self.search_pixel_around_poly(binary_warped) # TODO 如果两次检测的误差较大怎么办? # TODO 是否存在 self.fit_polynomial() # if np.abs(self.diffs).sum() > 20: # self.current_fit = np.array(self.recent_fits[:-1]).mean(axis=0) # self.recent_fits[-1] = self.current_fit # self.average_fit = np.array(self.recent_fits).mean(axis=0) # # self.current_fitted_x = np.array(self.recent_fitted_xs[:-1]).mean(axis=0) # self.recent_fitted_xs[-1] = self.current_fitted_x # self.average_fitted_x = np.array(self.recent_fitted_xs).mean(axis=0) else: self.find_lane_pixels(binary_warped, location) self.fit_polynomial() def measure_curvature_real(self,ploty, x, y): ''' Calculates the curvature of polynomial functions in meters. ''' # Define conversions in x and y from pixels space to meters ym_per_pix = 30 / 720 # meters per pixel in y dimension xm_per_pix = 3.7 / 700 # meters per pixel in x dimension fit_cr = np.polyfit(y * ym_per_pix, x * xm_per_pix, 2) # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image y_eval = np.max(ploty) # Calculation of R_curve (radius of curvature) curverad = ((1 + (2 * fit_cr[0] * y_eval * ym_per_pix + fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * fit_cr[0]) self.radius_of_curvature = curverad return curverad if __name__ == "__main__": from lane.perspective import perspective,src,dst from lane.gaussian_blur import gaussian_blur from lane.combined_threshold import combined_threshold from lane.measure_vehicle_pos import measure_vehicle_pos from lane.draw_lane import draw_lane image = mpimg.imread('../output_images/undistorted/straight_lines1-undistorted.jpg') image = gaussian_blur(image, 3) combined = combined_threshold(image, ksize=3, th=[[20, 100], [25, 254], [100, 250], [0.6, 1.2], [180, 254], [250, 0]]) combined = gaussian_blur(combined, 3) perspectived_img = perspective(combined,src,dst) # plt.imshow(perspectived_img,cmap="gray") # plt.show() left_lane = Lane() left_lane.fit(perspectived_img,"left") right_lane = Lane() right_lane.fit(perspectived_img, "right") result = left_lane.visual(perspectived_img,"left") plt.imshow(result) result = right_lane.visual(perspectived_img, "right") plt.imshow(result) plt.show() # # 计算曲率 # left_r = left_lane.measure_curvature_real(left_lane.ploty, left_lane.average_fitted_x, left_lane.ploty) # right_r = left_lane.measure_curvature_real(right_lane.ploty, right_lane.average_fitted_x, right_lane.ploty) # # # 计算偏移值 # v = measure_vehicle_pos(left_lane.average_fitted_x, right_lane.average_fitted_x,left_lane.current_warped_binary_shape[1]) # # # 绘制车道线 # img = draw_lane(image, combined, dst, src,left_lane.current_fitted_x, right_lane.current_fitted_x, right_lane.ploty) # plt.imshow(img) # # 打印文字 # plt.text(0,60,"Radius of Curvature = %d(m)"%int(r),fontdict={'size': 20, 'color': 'w'}) # plt.text(0,120, "Vehicle is %.2f(m) left of center" % v, fontdict={'size': 20, 'color': 'w'}) # plt.show()
36.617391
127
0.592654
[ "MIT" ]
jo-ny/CarND-Advanced-Lane-Lines
lane/Lane.py
13,189
Python
import ctypes as C import numpy as np from math import log,e import hankelmatrixcreator import sys import time import iohelpers import math import modelconversion from scipy.sparse.linalg import lsqr from scipy import sparse import copy DEBUG = False VERBOSE = True FAILURE_CONST = -100000.0 class TensorWFA: def __init__(self, n_symbols): self.n_symbols = n_symbols self.hankels_learnt = False def _estimate_hankels(self, data, prefixdict, suffixdict): self.h_pands,self.symbol_hankels,self.hp_pandsigma,self.hbar_pands,self.hbar_pandsigma,self.hbar_sigmaands = hankelmatrixcreator.construct_tensor_hankels(data, prefixdict, suffixdict, self.n_symbols, 100) if VERBOSE: print "Finished Hankel estimation" def compute_XY(self, hbar_pands, hbar_pandsigma, hbar_sigmaands, symbol_hankels, num_symbols, num_components): if VERBOSE: print "Constructing Q matrices.." self.qp,_,self.qs = sparse.linalg.svds(hbar_pands,num_components) self.qs_constructed = True qp = sparse.csr_matrix(np.mat((self.qp[:,0:num_components]).T)) qs = sparse.csr_matrix(np.mat((self.qs[0:num_components, :]))) qp.eliminate_zeros() qp.prune() qs.eliminate_zeros() qs.prune() if VERBOSE: print "Computing N.." hsquiggleps = qp*hbar_pands*qs.T hsquiggleps = sparse.csr_matrix(np.linalg.inv(hsquiggleps.A)) N = qs.T*(hsquiggleps)*qp N.eliminate_zeros() N.prune() if VERBOSE: print "Computing X.." Xs = hbar_sigmaands*N*hbar_pandsigma X = np.empty((num_symbols, num_symbols), order='F', dtype=np.float64) X[:,:] = Xs.A self.rank = np.linalg.matrix_rank(X) if self.rank < num_components: print "Rank Deficient!!" return [],[], False if VERBOSE: print "Computing Y..." leftside = hbar_sigmaands*N leftside.eliminate_zeros() leftside.prune() rightside = N*hbar_pandsigma rightside.eliminate_zeros() rightside.prune() Y = np.empty((num_symbols, num_symbols, num_symbols)) for sym in range(num_symbols): Y[:,sym,:] = (leftside*(symbol_hankels[sym])*rightside).A return X,Y, True def learn_tensor(self, data, prefixdict, suffixdict, num_components): starttime = time.clock() if not self.hankels_learnt: begintime = time.clock() self._estimate_hankels(data, prefixdict, suffixdict) self.inittime = time.clock()-begintime self.hankels_learnt = True #adding aliases with "self" prefix for readability. h_pands = self.h_pands symbol_hankels = self.symbol_hankels hp_pandsigma = self.hp_pandsigma hbar_pands = self.hbar_pands hbar_pandsigma = self.hbar_pandsigma hbar_sigmaands = self.hbar_sigmaands num_symbols = self.n_symbols X,Y, success = self.compute_XY(hbar_pands, hbar_pandsigma, hbar_sigmaands, symbol_hankels, num_symbols, num_components) if not success: return success if VERBOSE: print "Performing tensor decomposition.." lib = C.CDLL('./cpp/libTensor.so') f_learn_tensor = lib.learn_tensor f_learn_tensor.argtypes = [np.ctypeslib.ndpointer(dtype = np.float64), np.ctypeslib.ndpointer(dtype = np.float64), C.c_int, np.ctypeslib.ndpointer(dtype = np.float64), np.ctypeslib.ndpointer(dtype = np.float64), C.c_int, C.c_int] f_learn_tensor.restype = C.c_double Otilde = np.empty((num_symbols, num_components), order='F', dtype=np.float64) gamma = np.empty((num_components), order='F', dtype=np.float64) res = f_learn_tensor(X,Y,num_components,Otilde,gamma,num_symbols, 1) if res == FAILURE_CONST: return False if VERBOSE: print "Building unnormalized model.." Otilde = np.mat(Otilde) # hbar_pandsigma = np.mat(self.hbar_pandsigma.toarray()) # hbar_sigmaands = np.mat(self.hbar_sigmaands.toarray()) # hbar_pands = np.mat(self.hbar_pands.toarray()) Otildepinv = np.linalg.pinv(Otilde) spOtildepinv = sparse.csr_matrix(Otildepinv) spOtildepinv.eliminate_zeros() spOtildepinv.prune() Otildep = hbar_pandsigma*Otildepinv.T Otildes = Otildepinv*hbar_sigmaands alphatilde = np.mat(Otildep[0,:]).T stopvec = np.mat(Otildes[:,0]) spOtildeppinv = sparse.csr_matrix(np.linalg.pinv(Otildep)) spOtildeppinv.eliminate_zeros() spOtildeppinv.prune() Ttilde = self._compute_T(spOtildeppinv, num_components) Dgamma = np.mat(np.diag(gamma)) Dgamma = Dgamma*Dgamma Ds = spOtildeppinv*hp_pandsigma*spOtildepinv.T Dspinv = np.mat(Ds.A) Ds = np.linalg.pinv(np.mat(Ds.A)) Dsigma = np.eye(alphatilde.shape[0])-np.diag(stopvec) Dsigmapinv = np.linalg.pinv(Dsigma) Beta = Ds*(np.linalg.pinv(Ttilde))*Dgamma*stopvec for i in range(stopvec.shape[0]): stopvec[i] = Beta[i]/(1+Beta[i]) alpha = np.empty((num_components), order='F', dtype=np.float64) alpha[:] = (alphatilde.T*Dsigmapinv*Dspinv).A O = np.empty((num_components, num_symbols), order='F', dtype=np.float64) O[:,:] = (Otilde*Dsigma).A.T T = np.empty((num_components, num_components), order='F', dtype=np.float64) T[:] = (Ds*Ttilde*Dspinv*Dsigmapinv).A if DEBUG: print "O before PNFA projection: ", O print "T before PNFA projection: ", T print "ainf before simplex projection: ", stopvec print "a before simplex projection: ", alpha O,T,alpha, stopvec = self._project_to_probabilities(O,T,alpha, stopvec.T.A[0], num_components, num_symbols) stopvec = np.mat(stopvec).T alpha = np.mat(alpha).T O = O.T if DEBUG: print "O after PNFA projection: ", O print "T after PNFA projection: ", T print "ainf after simplex projection: ", stopvec print "a after simplex projection: ", alpha self.initvec, self.ainf, self.wordstopvec, self.As = self.convert_hmm_to_wfa(O, T, alpha, stopvec) self.a = self.initvec.copy() self.buildtime = time.clock() - starttime return True def _compute_sparse_pinv(self, sparsemat, rank): u,s,v = sparse.linalg.svds(sparsemat, rank) u = np.mat(u) s = np.mat(np.diag(s)) v = np.mat(v) pinv = v.T*np.linalg.inv(s)*u.T return np.mat(pinv) def _compute_T(self, Otildepinv, num_components): A = (Otildepinv*self.h_pands).T A.eliminate_zeros() A.prune() B = (Otildepinv*self.hbar_pands).T B.eliminate_zeros() B.prune() T = np.empty((num_components, num_components)) for i in range(num_components): T[i,:] = lsqr(A,B[:,i].A)[0] return T def _project_to_probabilities(self, O, T, alpha, ainf, num_components, num_symbols): lib = C.CDLL('../cpp/libTensor.so') f_simplex_proj = lib.do_simplex_projection f_simplex_proj.argtypes = [np.ctypeslib.ndpointer(dtype = np.float64), C.c_double, C.c_int] f_simplex_proj.restype = C.c_int f_probmat_proj = lib.do_probmat_projection f_probmat_proj.argtypes = [np.ctypeslib.ndpointer(dtype = np.float64), np.ctypeslib.ndpointer(dtype = np.float64), C.c_int, C.c_int] f_probmat_proj.restype = C.c_int f_simplex_proj(alpha, 1.0, num_components) zeros = np.zeros((num_components), order='F', dtype=np.float64) probO = np.zeros((num_components, num_symbols+1), order='F', dtype=np.float64) probO[:,0:num_symbols] = O probO[:,num_symbols:num_symbols+1] = np.mat(ainf).T f_probmat_proj(probO, zeros, num_components, num_symbols) O = probO[:,0:num_symbols] ainf = probO[:,num_symbols:num_symbols+1] ainf = ainf.T f_probmat_proj(T, zeros, num_components, num_components) return O, T, alpha, ainf def get_symbol_prediction(self): predictedsymbol = -1 maxscore = np.finfo(float).eps for symbol in range(self.n_symbols): symbolscore = self.get_obs_prob(symbol) if symbolscore > maxscore: predictedsymbol = symbol maxscore = symbolscore stopscore = float(self.a.T*self.wordstopvec) if stopscore > maxscore: predictedsymbol = self.n_symbols return predictedsymbol def get_WER(self, testdata): errors = 0 numpredictions = 0 for seq in testdata: for obs in seq: numpredictions += 1 predsymbol = self.get_symbol_prediction() self.update(obs) if predsymbol != obs: errors += 1 predsymbol = self.get_symbol_prediction() numpredictions += 1 if predsymbol != self.n_symbols: errors += 1 self.reset() return float(errors)/float(numpredictions) #provides average log-likelihood score def score(self, data): loglike = 0 for seq in data: seqloglike = 0 self.reset() for obs in seq: seqloglike = seqloglike + log(self.get_obs_prob(obs)) self.update(obs) loglike += seqloglike return loglike/(float(len(data))) #updates a/start/state vector after seeing symbol def update(self, obs): bomat = self.As[obs] numerator = self.a.T*bomat denom = numerator*self.ainf self.a = (numerator/denom).T #resets state vector def reset(self): self.a = self.initvec.copy() #returns the probablilty of a particular observation given current state def get_obs_prob(self, obs): prob = (self.a.T)*(self.As[obs])*self.ainf prob = min(prob,1) prob = max(prob,np.finfo(float).eps) return prob #returns the probability of an entire sequence, or "word" def get_word_prob(self,seq): seqprob = 0 for obs in seq: prob = self.get_obs_prob(obs) if prob <= np.finfo(float).eps: return np.finfo(float).eps seqprob += log(prob) self.update(obs) endprob = float(self.a.T*self.wordstopvec) if endprob <= np.finfo(float).eps: return np.finfo(float).eps seqprob += log(endprob) self.reset() if not math.isnan(seqprob): return e**seqprob else: return np.finfo(float).eps def scorepautomac(self, testdata, truprobs): modelprobs = np.zeros((len(truprobs))) probsum = 0 i = 0 for seq in testdata: prob = self.get_word_prob(seq) modelprobs[i] = prob probsum += prob i += 1 modelprobs /= float(probsum) i = 0 scoresum = 0 for truprob in truprobs: if modelprobs[i] < np.finfo(float).eps: modelprobs[i] = np.finfo(float).eps scoresum += truprob*log(modelprobs[i],2) i += 1 return 2.0**(-1.0*float(scoresum)) def get_perplexity(self, testdata): modelprobs = np.zeros((len(testdata))) probsum = 0 i = 0 for seq in testdata: prob = self.get_word_prob(seq) modelprobs[i] = prob probsum += prob i += 1 scoresum = 0 for i in range(len(modelprobs)): if modelprobs[i] < np.finfo(float).eps: modelprobs[i] = np.finfo(float).eps scoresum += log(modelprobs[i],2) scoresum /= float(len(testdata)) return 2.0**(-1.0*float(scoresum)) def convert_hmm_to_wfa(self, O, T, alpha, stopvec): As = {} for symbol in range(O.shape[0]): As[symbol] = np.mat(np.diag(O[symbol,:]))*T return alpha, np.mat(np.ones(T.shape[0])).T, stopvec, As if __name__ == '__main__': PAUTOMACPATH = "/home/williamleif/Dropbox/icml2014-experiments/datasets/PAutomaC-competition_sets/" RESULTS_DIR = "/home/williamleif/Dropbox/icml2014-experiments/results/tensor/" MODEL_DIR = "/home/williamleif/Dropbox/icml2014-experiments/models/" metric = sys.argv[1] problem = sys.argv[2] n_symbols = sys.argv[3] n_symbols = int(n_symbols) if problem != "tree" and problem != "timeseries": traindata = iohelpers.parse_file(PAUTOMACPATH+problem+".pautomac.train") testdata = iohelpers.parse_file(PAUTOMACPATH+problem+".pautomac.test") if metric == "KL": groundtruth = iohelpers.parse_groundtruth_file(PAUTOMACPATH+problem+".pautomac_solution.txt") else: validdata = traindata[15000:20000] traindata = traindata[0:15000] maxbasissize = int(sys.argv[4]) prefixdict, suffixdict = hankelmatrixcreator.top_k_string_bases(traindata,maxbasissize,n_symbols) basislength = len(prefixdict) bestsize = 0 avruntime = 0 nummodelsmade = 0 bestscore = 0 wfa = TensorWFA(n_symbols) begintime = time.clock() for i in range(3, 6): success = wfa.learn_tensor(traindata, prefixdict, suffixdict, i) if i == 3: inittime = wfa.inittime if not success: break if metric == "WER": score = wfa.get_WER(validdata) else: score = wfa.scorepautomac(testdata,groundtruth) if bestsize == 0: bestscore = score bestsize = i bestwfa = copy.deepcopy(wfa) elif score < bestscore and abs(score-1000) > 0.1: bestscore = score bestsize = i bestwfa = copy.deepcopy(wfa) print "Model size: ", i, " Score: ", score avruntime += wfa.buildtime nummodelsmade += 1 # if metric == "WER": # bestscore = bestwfa.get_WER(testdata) # iohelpers.write_results(RESULTS_DIR+"tensor-pautomac="+problem+"-"+metric+".txt", problem,"size= "+str(bestsize)+", basis size="+str(basislength), metric, bestscore, avruntime/float(nummodelsmade)) # iohelpers.write_pnfa_model(MODEL_DIR+"tensor-"+str(bestsize)+"-pautomac="+problem+"-"+metric+".fsm", bestwfa) runtime = time.clock()-begintime fp = open("/home/williamleif/Dropbox/icml2014-experiments/results/runtimes/tensor", "w") fp.write("Init time: "+str(inittime)+" Runtime: "+str(runtime)) else: RESULTS_DIR = "/home/williamleif/Dropbox/icml2014-experiments/results/real/" if problem == "tree": traindata = iohelpers.parse_file("/home/williamleif/Dropbox/icml2014-experiments/datasets/treebankdata.obs") validdata = traindata[0:5000] testdata = traindata[5000:10000] traindata = traindata[10000:len(traindata)] maxbasissize = int(sys.argv[4]) prefixdict, suffixdict = hankelmatrixcreator.top_k_string_bases(traindata,maxbasissize,n_symbols) basislength = len(prefixdict) bestsize = 0 avruntime = 0 nummodelsmade = 0 bestscore = 0 wfa = TensorWFA(n_symbols) for i in range(3, n_symbols+1): success = wfa.learn_tensor(traindata, prefixdict, suffixdict, i) if not success: break if metric == "WER": score = wfa.get_WER(validdata) else: score = wfa.get_perplexity(validdata) if bestsize == 0: bestscore = score bestsize = i bestwfa = copy.deepcopy(wfa) elif score < bestscore and abs(score-1000) > 0.1: bestscore = score bestsize = i bestwfa = copy.deepcopy(wfa) print "Model size: ", i, " Score: ", score avruntime += wfa.buildtime nummodelsmade += 1 if metric == "WER": bestscore = bestwfa.get_WER(testdata) else: bestscore = bestwfa.get_perplexity(testdata) iohelpers.write_results(RESULTS_DIR+"tensor-"+metric+".txt", problem,"size= "+str(bestsize)+", basis size="+str(basislength), metric, bestscore, 0) iohelpers.write_pnfa_model(MODEL_DIR+"tensor-"+str(bestsize)+"-pautomac="+problem+"-"+metric+".fsm", bestwfa)
33.281496
237
0.597741
[ "Apache-2.0" ]
ICML14MoMCompare/MoMs-for-StochasticLanguages
code/tensor/wfatensorlearn.py
16,907
Python
from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.db import transaction from rest_framework import exceptions, serializers from care.facility.models import Facility, FacilityUser, READ_ONLY_USER_TYPES from care.users.api.serializers.lsg import DistrictSerializer, LocalBodySerializer, StateSerializer, BlockSerializer from care.users.models import GENDER_CHOICES from care.utils.serializer.phonenumber_ispossible_field import PhoneNumberIsPossibleField from config.serializers import ChoiceField User = get_user_model() class SignUpSerializer(serializers.ModelSerializer): user_type = ChoiceField(choices=User.TYPE_CHOICES) gender = ChoiceField(choices=GENDER_CHOICES) password = serializers.CharField(write_only=True) phone_number = PhoneNumberIsPossibleField() alt_phone_number = PhoneNumberIsPossibleField(required=False, allow_blank=True) class Meta: model = User fields = ( "id", "username", "first_name", "last_name", "email", "password", "user_type", "ward", "local_body", "district", "state", "phone_number", "alt_phone_number", "gender", "age", ) def create(self, validated_data): validated_data["password"] = make_password(validated_data.get("password")) return super().create(validated_data) class UserCreateSerializer(SignUpSerializer): password = serializers.CharField(required=False) facilities = serializers.ListSerializer( child=serializers.UUIDField(), required=False, allow_empty=True, write_only=True ) class Meta: model = User include = ("facilities",) exclude = ( "is_superuser", "is_staff", "is_active", "last_login", "date_joined", "verified", "deleted", "groups", "user_permissions", ) def validate_facilities(self, facility_ids): if facility_ids: if len(facility_ids) != Facility.objects.filter(external_id__in=facility_ids).count(): available_facility_ids = Facility.objects.filter(external_id__in=facility_ids).values_list( "external_id", flat=True ) not_found_ids = list(set(facility_ids) - set(available_facility_ids)) raise serializers.ValidationError( f"Some facilities are not available - {', '.join([str(_id) for _id in not_found_ids])}" ) return facility_ids def validate_ward(self, value): if ( value is not None and value != self.context["created_by"].ward and not self.context["created_by"].is_superuser and not self.context["created_by"].user_type >= User.TYPE_VALUE_MAP["LocalBodyAdmin"] ): raise serializers.ValidationError("Cannot create for a different Ward") return value def validate_local_body(self, value): if ( value is not None and value != self.context["created_by"].local_body and not self.context["created_by"].is_superuser and not self.context["created_by"].user_type >= User.TYPE_VALUE_MAP["DistrictAdmin"] ): raise serializers.ValidationError("Cannot create for a different local body") return value def validate_district(self, value): if ( value is not None and value != self.context["created_by"].district and not self.context["created_by"].is_superuser and not self.context["created_by"].user_type >= User.TYPE_VALUE_MAP["StateAdmin"] ): raise serializers.ValidationError("Cannot create for a different state") return value def validate_state(self, value): if ( value is not None and value != self.context["created_by"].state and not self.context["created_by"].is_superuser ): raise serializers.ValidationError("Cannot create for a different state") return value def validate(self, attrs): validated = super(UserCreateSerializer, self).validate(attrs) if self.context["created_by"].user_type in READ_ONLY_USER_TYPES: if validated["user_type"] not in READ_ONLY_USER_TYPES: raise exceptions.ValidationError( {"user_type": ["Read only users can create other read only users only"]} ) if ( validated["user_type"] > self.context["created_by"].user_type and not self.context["created_by"].is_superuser ): raise exceptions.ValidationError( {"user_type": ["User cannot create another user with higher permissions"]} ) if ( not validated.get("ward") and not validated.get("local_body") and not validated.get("district") and not validated.get("state") ): raise exceptions.ValidationError({"__all__": ["One of ward, local body, district or state is required"]}) if validated.get("user_type") == User.TYPE_VALUE_MAP["BlockAdmin"]: local_body_object = validated.get("local_body") if local_body_object.block is None: raise exceptions.ValidationError({"__all__": ["The local_body doesn't have a Block associated with it"]}) return validated def facility_query(self, user): queryset = Facility.objects.all() if user.is_superuser: pass elif user.user_type >= User.TYPE_VALUE_MAP["StateLabAdmin"]: queryset = queryset.filter(state=user.state) elif user.user_type >= User.TYPE_VALUE_MAP["DistrictLabAdmin"]: queryset = queryset.filter(district=user.district) elif user.user_type >= User.TYPE_VALUE_MAP["BlockAdmin"]: queryset = queryset.filter(block=user.block) elif user.user_type >= User.TYPE_VALUE_MAP["LocalBodyAdmin"]: queryset = queryset.filter(local_body=user.local_body) else: queryset = queryset.filter(users__id__exact=user.id) return queryset def create(self, validated_data): with transaction.atomic(): facilities = validated_data.pop("facilities", []) user = User.objects.create_user(**{**validated_data, "verified": True}) user.set_password(validated_data["password"]) facility_query = self.facility_query(self.context["created_by"]) if facilities: facility_objs = facility_query.filter(external_id__in=facilities) facility_user_objs = [ FacilityUser(facility=facility, user=user, created_by=self.context["created_by"]) for facility in facility_objs ] FacilityUser.objects.bulk_create(facility_user_objs) return user class UserSerializer(SignUpSerializer): user_type = ChoiceField(choices=User.TYPE_CHOICES, read_only=True) is_superuser = serializers.BooleanField(read_only=True) local_body_object = LocalBodySerializer(source="local_body", read_only=True) block_object = BlockSerializer(source="local_body__block", read_only=True) district_object = DistrictSerializer(source="district", read_only=True) state_object = StateSerializer(source="state", read_only=True) alt_phone_number = PhoneNumberIsPossibleField(required=False, allow_blank=True) class Meta: model = User fields = ( "id", "username", "first_name", "last_name", "email", "user_type", "local_body", "block", "district", "state", "phone_number", "alt_phone_number", "gender", "age", "is_superuser", "verified", "local_body_object", "block_object", "district_object", "state_object", "pf_endpoint", "pf_p256dh", "pf_auth", ) read_only_fields = ( "is_superuser", "verified", "user_type", "ward", "local_body", "block", "district", "state", "pf_endpoint", "pf_p256dh", "pf_auth", ) extra_kwargs = {"url": {"lookup_field": "username"}} class UserBaseMinimumSerializer(serializers.ModelSerializer): user_type = ChoiceField(choices=User.TYPE_CHOICES, read_only=True) class Meta: model = User fields = ( "id", "first_name", "username", "email", "last_name", "user_type", "last_login", ) class UserListSerializer(serializers.ModelSerializer): local_body_object = LocalBodySerializer(source="local_body", read_only=True) block_object = BlockSerializer(source="local_body__block", read_only=True) district_object = DistrictSerializer(source="district", read_only=True) state_object = StateSerializer(source="state", read_only=True) user_type = ChoiceField(choices=User.TYPE_CHOICES, read_only=True) class Meta: model = User fields = ( "id", "first_name", "last_name", "username", "local_body_object", "block_object", "district_object", "state_object", "user_type", "last_login", )
36.316176
121
0.604778
[ "MIT" ]
CoronaSafeUP/care
care/users/api/serializers/user.py
9,878
Python
talks = [ "https://www.churchofjesuschrist.org/study/general-conference/2022/04/11nelson", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/12ballard", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/13aburto", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/14bednar", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/15andersen", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/16gavarret", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/17kacher", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/18eyring", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/23holland", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/24kearon", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/25aidukaitis", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/26gong", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/27ochoa", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/28hamilton", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/29cook", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/31oaks", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/32porter", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/33craven", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/34video", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/35bingham", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/36renlund", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/41christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/42wright", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/43stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/44ringwood", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/45rasband", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/46martinez", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/47nelson", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/51oaks", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/52ojediran", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/53klebingat", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/54pace", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/55soares", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/56funk", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/57uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2022/04/58nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/11nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/12holland", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/13cordon", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/14soares", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/15christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/16gilbert", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/17giuffra", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/18oaks", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/21eyring", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/22bednar", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/23schmeil", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/24porter", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/25kopischke", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/26rasband", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/27golden", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/28villanueva", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/29stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/31ballard", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/32eubank", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/33nielson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/34valenzuela", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/35wilcox", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/36kyungu", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/37nash", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/38eyring", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/41uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/42johnson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/43renlund", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/44sikahema", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/46cook", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/47nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/51gong", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/52budge", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/53perkins", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/54dunn", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/55douglas", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/56revillo", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/57meredith", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/58andersen", "https://www.churchofjesuschrist.org/study/general-conference/2021/10/59nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/11nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/12uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/13jones", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/14newman", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/15stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/16gong", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/17eyring", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/21oaks", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/22larson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/23holland", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/24becerra", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/25renlund", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/26andersen", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/27mutombo", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/28ballard", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/31cook", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/32corbitt", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/33nielsen", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/34eyring", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/35oaks", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/36nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/41soares", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/42aburto", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/43palmer", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/44dube", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/45teixeira", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/46wakolo", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/47wong", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/48teh", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/49nelson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/51oaks", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/52rasband", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/53dyches", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/54christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/55walker", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/56bednar", "https://www.churchofjesuschrist.org/study/general-conference/2021/04/57nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/11nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/12bednar", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/13whiting", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/14craig", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/15cook", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/16rasband", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/17oaks", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/21eyring", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/22christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/23lund", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/24gong", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/25waddell", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/26holland", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/27jackson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/28uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/31eubank", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/32craven", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/34franco", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/33video", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/35eyring", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/36oaks", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/37nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/41ballard", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/42harkness", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/43soares", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/44godoy", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/45andersen", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/46nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/51eyring", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/52jaggi", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/53stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/54camargo", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/55renlund", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/56johnson", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/57holland", "https://www.churchofjesuschrist.org/study/general-conference/2020/10/58nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/11nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/12ballard", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/13rasband", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/14jones", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/15andersen", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/16holmes", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/17eyring", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/21oaks", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/22jergensen", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/23soares", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/24mccune", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/25causse", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/26renlund", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/27tai", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/28stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/31gong", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/32alvarez", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/33petelo", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/34bingham", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/35eyring", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/36oaks", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/37nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/41rasband", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/42cordon", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/43holland", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/44bednar", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/45nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/46nelson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/51oaks", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/52cook", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/53gimenez", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/54uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/55clayton", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/56christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2020/04/57nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/57nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/56andersen", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/55soares", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/54johnson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/53ballard", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/52boom", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/51eyring", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/46nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/45stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/44gonzalez", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/43uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/42franco", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/41gong", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/36nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/35oaks", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/34eyring", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/33cordon", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/32harkness", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/31aburto", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/29rasband", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/28alvarado", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/27budge", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/26pace", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/25cook", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/24nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/23alliaud", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/22bednar", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/21eyring", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/17oaks", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/16renlund", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/15craig", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/14christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/13owen", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/12vinson", "https://www.churchofjesuschrist.org/study/general-conference/2019/10/11holland", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/57nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/56rasband", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/55mckay", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/54bednar", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/53gong", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/52villar", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/51oaks", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/46nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/45callister", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/44christofferson", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/43cook", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/42eubank", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/41renlund", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/36nelson", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/35oaks", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/34eyring", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/33clark", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/32cook", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/31stevenson", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/28holland", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/27homer", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/26wada", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/25andersen", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/24held", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/23ballard", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/22jergensen", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/21oaks", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/16eyring", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/15waddell", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/14uchtdorf", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/13hales", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/12craven", "https://www.churchofjesuschrist.org/study/general-conference/2019/04/11soares", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/wounded", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/women-and-gospel-learning-in-the-home", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/wilt-thou-be-made-whole", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/try-try-try", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/truth-and-the-plan", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-vision-of-the-redemption-of-the-dead", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-role-of-the-book-of-mormon-in-conversion", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-ministry-of-reconciliation", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-joy-of-unselfish-service", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-father", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/the-correct-name-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/taking-upon-ourselves-the-name-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/sisters-participation-in-the-gathering-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/shepherding-souls", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/parents-and-children", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/our-campfire-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/opening-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/one-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/now-is-the-time", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/lift-up-your-head-and-rejoice", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/laying-the-foundation-of-a-great-work", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/gather-together-in-one-all-things-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/for-him", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/firm-and-steadfast-in-the-faith-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/divine-discontent", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/deep-and-lasting-conversion-to-heavenly-father-and-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/come-listen-to-a-prophets-voice", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/choose-you-this-day", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/believe-love-do", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/becoming-exemplary-latter-day-saints", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/becoming-a-shepherd", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/be-not-troubled", "https://www.churchofjesuschrist.org/study/general-conference/2018/10/all-must-take-upon-them-the-name-given-of-the-father", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/young-women-in-the-work", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/with-one-accord", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/what-every-aaronic-priesthood-holder-needs-to-understand", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/until-seventy-times-seven", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/the-prophet-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/the-powers-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/the-heart-of-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/the-elders-quorum", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/teaching-in-the-home-a-joyful-and-sacred-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/take-the-holy-spirit-as-your-guide", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/solemn-assembly", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/small-and-simple-things", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/saving-ordinances-will-bring-us-marvelous-light", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/revelation-for-the-church-revelation-for-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/pure-love-the-true-sign-of-every-true-disciple-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/prophets-speak-by-the-power-of-the-holy-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/prepare-to-meet-god", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/precious-gifts-from-god", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/one-more-day", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/ministering-with-the-power-and-authority-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/ministering-as-the-savior-does", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/ministering", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/meek-and-lowly-of-heart", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/let-us-all-press-on", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/it-is-all-about-people", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/introductory-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/inspired-ministering", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/his-spirit-to-be-with-you", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/he-that-shall-endure-unto-the-end-the-same-shall-be-saved", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/family-history-and-temple-work-sealing-and-healing", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/even-as-christ-forgives-you-so-also-do-ye", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/christ-the-lord-is-risen-today", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/behold-the-man", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/behold-a-royal-army", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/be-with-and-strengthen-them", "https://www.churchofjesuschrist.org/study/general-conference/2018/04/am-i-a-child-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/value-beyond-measure", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/turn-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/turn-on-your-light", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/three-sisters", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-voice-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-truth-of-all-things", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-trek-continues", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-priesthood-and-the-saviors-atoning-power", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-plan-and-the-proclamation", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-needs-before-us", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-lord-leads-his-church", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-living-bread-which-came-down-from-heaven", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-heart-of-the-widow", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-eternal-everyday", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/the-book-of-mormon-what-would-your-life-be-like-without-it", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/that-your-joy-might-be-full", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/spiritual-eclipse", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/seek-ye-out-of-the-best-books", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/repentance-is-always-positive", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/love-one-another-as-he-has-loved-us", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/lord-wilt-thou-cause-that-my-eyes-may-be-opened", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/i-have-a-work-for-thee", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/has-the-day-of-miracles-ceased", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/gods-compelling-witness-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/fear-not-to-do-good", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/exceeding-great-and-precious-promises", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/essential-truths-our-need-to-act", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/earning-the-trust-of-the-lord-and-your-family", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/do-we-trust-him-hard-is-good", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/by-divine-design", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/bearers-of-heavenly-light", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/be-ye-therefore-perfect-eventually", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/apart-but-still-one", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/abiding-in-god-and-repairing-the-breach", "https://www.churchofjesuschrist.org/study/general-conference/2017/10/a-yearning-for-home", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/whatsoever-he-saith-unto-you-do-it", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/walk-with-me", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/trust-in-the-lord-and-lean-not", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/to-the-friends-and-investigators-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/then-jesus-beholding-him-loved-him", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-voice-of-warning", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-power-of-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-language-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-greatest-among-you", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-godhead-and-the-plan-of-salvation", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/the-beauty-of-holiness", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/that-our-light-may-be-a-standard-for-the-nations", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/stand-up-inside-and-be-all-in", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/songs-sung-and-unsung", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/return-and-receive", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/prepare-the-way", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/perfect-love-casteth-out-fear", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/overcoming-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/our-good-shepherd", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/our-fathers-glorious-plan", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/my-peace-i-leave-with-you", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/let-the-holy-spirit-guide", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/kindness-charity-and-love", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/how-does-the-holy-ghost-help-you", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/his-daily-guiding-hand", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/gathering-the-family-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/foundations-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/drawing-the-power-of-jesus-christ-into-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/dont-look-around-look-up", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/confide-in-god-unwaveringly", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/certain-women", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/called-to-the-work", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/brighter-and-brighter-until-the-perfect-day", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/becoming-a-disciple-of-our-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/and-this-is-life-eternal", "https://www.churchofjesuschrist.org/study/general-conference/2017/04/a-sin-resistant-generation", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/valiant-in-the-testimony-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/to-whom-shall-we-go", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/there-is-power-in-the-book", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-souls-sincere-desire", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-sacrament-can-help-us-become-holy", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-righteous-judge", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-perfect-path-to-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-master-healer", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-lord-jesus-christ-teaches-us-to-pray", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-great-plan-of-redemption", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-doctrine-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/the-blessings-of-worship", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/that-he-may-become-strong-also", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/sharing-the-restored-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/serve", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/rise-up-in-strength-sisters-in-zion", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/repentance-a-joyful-choice", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/principles-and-promises", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/o-how-great-the-plan-of-our-god", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/no-greater-joy-than-to-know-that-they-know", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/look-to-the-book-look-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/lest-thou-forget", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/learn-from-alma-and-amulek", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/joy-and-spiritual-survival", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/if-ye-had-known-me", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/i-will-bring-the-light-of-the-gospel-into-my-home", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/gratitude-on-the-sabbath-day", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/god-shall-wipe-away-all-tears", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/fourth-floor-last-door", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/for-our-spiritual-development-and-learning", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/emissaries-to-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/come-follow-me-by-practicing-christian-love-and-service", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/be-ambitious-for-christ", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/am-i-good-enough-will-i-make-it", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/abide-in-my-love", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/a-witness-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2016/10/a-choice-seer-will-i-raise-up", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/whoso-receiveth-them-receiveth-me", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/where-two-or-three-are-gathered", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/where-are-the-keys-and-authority-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/what-shall-we-do", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/trust-in-that-spirit-which-leadeth-to-do-good", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/tomorrow-the-lord-will-do-wonders-among-you", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/to-the-rescue-we-can-do-it", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-sacred-place-of-restoration", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-price-of-priesthood-power", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-power-of-godliness", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-healing-ointment-of-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/the-greatest-leaders-are-the-greatest-followers", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/that-i-might-draw-all-men-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/standing-with-the-leaders-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/see-yourself-in-the-temple", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/refuge-from-the-storm", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/opposition-in-all-things", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/in-praise-of-those-who-save", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/i-was-a-stranger", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/i-am-a-child-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/he-will-place-you-on-his-shoulders-and-carry-you-home", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/he-asks-us-to-be-his-hands", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/fathers", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/family-councils", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/eternal-families", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/do-i-believe", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/choices", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/be-thou-humble", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/and-there-shall-be-no-more-death", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/always-retain-a-remission-of-your-sins", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/always-remember-him", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/a-sacred-trust", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/a-pattern-for-peace", "https://www.churchofjesuschrist.org/study/general-conference/2016/04/a-childs-guiding-gift", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/your-next-step", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/you-are-not-alone-in-the-work", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/yielding-our-hearts-to-god", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/worthy-of-our-promised-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/why-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/what-lack-i-yet", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/turn-to-him-and-answers-will-come", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/through-gods-eyes", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/the-pleasing-word-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/the-joy-of-living-a-christ-centered-life", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/the-holy-ghost-as-your-companion", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/that-they-do-always-remember-him", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/tested-and-tempted-but-helped", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/strengthened-by-the-atonement-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/shipshape-and-bristol-fashion-be-temple-worthy-in-good-times-and-bad-times", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/remembering-in-whom-we-have-trusted", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/plain-and-precious-truths", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/my-heart-pondereth-them-continually", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/meeting-the-challenges-of-todays-world", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/let-the-clarion-trumpet-sound", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/keep-the-commandments", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/its-never-too-early-and-its-never-too-late", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/it-works-wonderfully", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/if-ye-love-me-keep-my-commandments", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/i-stand-all-amazed", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/hold-on-thy-way", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/here-to-serve-a-righteous-cause", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/god-is-at-the-helm", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/faith-is-not-by-chance-but-by-choice", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/eyes-to-see-and-ears-to-hear", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/discovering-the-divinity-within", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/chosen-to-bear-testimony-of-my-name", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/choose-the-light", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/blessed-and-happy-are-those-who-keep-the-commandments-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/behold-thy-mother", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/be-not-afraid-only-believe", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/be-an-example-and-a-light", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/a-summer-with-great-aunt-rose", "https://www.churchofjesuschrist.org/study/general-conference/2015/10/a-plea-to-my-sisters", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/yes-we-can-and-will-win", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/why-marriage-why-family", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/why-marriage-and-family-matter-everywhere-in-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/where-justice-love-and-mercy-meet", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/well-ascend-together", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/waiting-for-the-prodigal", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/truly-good-and-without-guile", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/thy-kingdom-come", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/therefore-they-hushed-their-fears", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-sabbath-is-a-delight", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-priesthood-a-sacred-gift", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-parable-of-the-sower", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-music-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-lord-is-my-light", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-greatest-generation-of-young-adults", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-gift-of-grace", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-family-is-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-eternal-perspective-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/the-comforter", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/stay-by-the-tree", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/seeking-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/returning-to-faith", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/priesthood-and-personal-prayer", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/preserving-agency-protecting-religious-freedom", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/on-being-genuine", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/latter-day-saints-keep-on-trying", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/is-not-this-the-fast-that-i-have-chosen", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/is-it-still-wonderful-to-you", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/if-you-will-be-responsible", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/filling-our-homes-with-light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/fatherhood-our-eternal-destiny", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/defenders-of-the-family-proclamation", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/choose-to-believe", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/blessings-of-the-temple", "https://www.churchofjesuschrist.org/study/general-conference/2015/04/be-fruitful-multiply-and-subdue-the-earth", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/yes-lord-i-will-follow-thee", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/which-way-do-you-face", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/trifle-not-with-sacred-things", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-sacrament-and-the-atonement", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-sacrament-a-renewal-for-the-soul", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-reason-for-our-hope", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-preparatory-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-lord-has-a-plan-for-us", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-law-of-the-fast-a-personal-responsibility-to-care-for-the-poor-and-needy", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/the-book", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/stay-in-the-boat-and-hold-on", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/sharing-your-light", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/rescue-in-unity", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/receiving-a-testimony-of-light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/prepared-in-a-manner-that-never-had-been-known", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/ponder-the-path-of-thy-feet", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/parents-the-prime-gospel-teachers-of-their-children", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/our-personal-ministries", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/make-the-exercise-of-faith-your-first-priority", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/loving-others-and-living-with-differences", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/lord-is-it-i", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/living-the-gospel-joyful", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/live-according-to-the-words-of-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/i-know-these-things-of-myself", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/guided-safely-home", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/free-forever-to-act-for-themselves", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/finding-lasting-peace-and-building-eternal-families", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/eternal-life-to-know-our-heavenly-father-and-his-son-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/covenant-daughters-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/continuing-revelation", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/come-and-see", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/choose-wisely", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/are-we-not-all-beggars", "https://www.churchofjesuschrist.org/study/general-conference/2014/10/approaching-the-throne-of-god-with-confidence", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/your-four-minutes", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/where-your-treasure-is", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/what-manner-of-men", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/what-are-you-thinking", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/wanted-hands-and-hearts-to-hasten-the-work", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-witness", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-resurrection-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-prophet-joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-priesthood-man", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-keys-and-authority-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-joyful-burden-of-discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-cost-and-blessings-of-discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/the-choice-generation", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/spiritual-whirlwinds", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/sisterhood-oh-how-we-need-each-other", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/roots-and-branches", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/protection-from-pornography-a-christ-focused-home", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/obedience-through-our-faithfulness", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/love-the-essence-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/live-true-to-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/lets-not-take-the-wrong-way", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/let-your-faith-show", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/keeping-covenants-protects-us-prepares-us-and-empowers-us", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/if-ye-love-me-keep-my-commandments", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/if-ye-lack-wisdom", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/i-have-given-you-an-example", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/grateful-in-any-circumstances", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/following-up", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/fear-not-i-am-with-thee", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/daughters-in-the-covenant", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/christ-the-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/bear-up-their-burdens-with-ease", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/be-strong-and-of-a-good-courage", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/are-you-sleeping-through-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/2014/04/a-priceless-heritage-of-hope", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/you-can-do-it-now", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/ye-are-no-more-strangers", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/wilt-thou-be-made-whole", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/we-never-walk-alone", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/we-have-great-reason-to-rejoice", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/true-shepherds", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/to-my-grandchildren", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/till-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-windows-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-strength-to-endure", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-power-joy-and-love-of-covenant-keeping", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-moral-force-of-women", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-key-to-spiritual-protection", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/the-doctrines-and-principles-contained-in-the-articles-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/teaching-with-the-power-and-authority-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/small-and-simple-things", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/put-your-trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/power-in-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/personal-strength-through-the-atonement-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/no-other-gods", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/look-up", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/look-ahead-and-believe", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/like-a-broken-vessel", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/lamentations-of-jeremiah-beware-of-bondage", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/i-will-not-fail-thee-nor-forsake-thee", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/hastening-the-lords-game-plan", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/general-conference-strengthening-faith-and-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/drawing-closer-to-god", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/do-we-know-what-we-have", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/decisions-for-eternity", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/continually-holding-fast", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/come-join-with-us", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/claim-the-blessings-of-your-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/called-of-him-to-declare-his-word", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/bind-up-their-wounds", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/be-ye-converted", "https://www.churchofjesuschrist.org/study/general-conference/2013/10/be-meek-and-lowly-of-heart", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/your-wonderful-journey-home", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/your-sacred-duty-to-minister", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/your-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/when-you-save-a-girl-you-save-generations", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/we-believe-in-being-chaste", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/we-are-one", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/we-are-daughters-of-our-heavenly-father", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/this-is-my-work-and-glory", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/these-things-i-know", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-words-we-speak", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-savior-wants-to-forgive", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-power-of-the-priesthood-in-the-boy", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-lords-way", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-hope-of-gods-light", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-home-the-school-of-life", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-gospel-to-all-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/the-father-and-the-son", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/stand-strong-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/redemption", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/personal-peace-the-reward-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/obedience-to-law-is-liberty", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/obedience-brings-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/marriage-watch-and-learn", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/lord-i-believe", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/its-a-miracle", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/four-titles", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/for-peace-at-home", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/followers-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/come-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/come-all-ye-sons-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/catch-the-wave", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/being-accepted-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/beautiful-mornings", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/be-not-moved", "https://www.churchofjesuschrist.org/study/general-conference/2013/04/a-sure-foundation", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/wide-awake-to-our-duties", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/where-is-the-pavilion", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/what-shall-a-man-give-in-exchange-for-his-soul", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/trial-of-your-faith", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-lord-has-not-forgotten-you", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-joy-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-joy-of-redeeming-the-dead", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-first-great-commandment", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-caregiver", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/the-atonement", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/temple-standard", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/see-others-as-they-may-become", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/protect-the-children", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/one-step-closer-to-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/of-regrets-and-resolutions", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/learning-with-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/is-faith-in-the-atonement-of-jesus-christ-written-in-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/i-know-it-i-live-it-i-love-it", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/help-them-aim-high", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/god-be-with-you-till-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/first-observe-then-serve", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/converted-unto-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/consider-the-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/come-unto-me-o-ye-house-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/can-ye-feel-so-now", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/by-faith-all-things-are-fulfilled", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/brethren-we-have-work-to-do", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/blessings-of-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/beware-concerning-yourselves", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/being-a-more-christian-christian", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/becoming-goodly-parents", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/becoming-a-true-disciple", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/because-i-live-ye-shall-live-also", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/be-valiant-in-courage-strength-and-activity", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/be-anxiously-engaged", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/ask-the-missionaries-they-can-help-you", "https://www.churchofjesuschrist.org/study/general-conference/2012/10/an-unspeakable-gift-from-god", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/willing-and-worthy-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/what-thinks-christ-of-me", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/was-it-worth-it", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/to-hold-sacred", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-why-of-priesthood-service", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-vision-of-prophets-regarding-relief-society-faith-family-relief", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-rescue-for-real-growth", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-race-of-life", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-powers-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-power-of-deliverance", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-merciful-obtain-mercy", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-laborers-in-the-vineyard", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/the-doctrine-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/that-the-lost-may-be-found", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/thanks-be-to-god", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/teaching-our-children-to-understand", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/special-lessons", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/seek-learning-you-have-a-work-to-do", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/sacrifice", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/only-upon-the-principles-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/now-is-the-time-to-arise-and-shine", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/mountains-to-climb", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/in-tune-with-the-music-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/how-to-obtain-revelation-and-inspiration-for-your-personal-life", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/he-truly-loves-us", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/having-the-vision-to-do", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/families-under-covenant", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/faith-fortitude-fulfillment-a-message-to-single-parents", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/converted-to-his-gospel-through-his-church", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/coming-to-ourselves-the-sacrament-the-temple-and-sacrifice-in-service", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/believe-obey-and-endure", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/as-we-gather-once-again", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/as-we-close-this-conference", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/arise-and-shine-forth", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/and-a-little-child-shall-lead-them", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/abide-in-the-lords-territory", "https://www.churchofjesuschrist.org/study/general-conference/2012/04/aaronic-priesthood-arise-and-use-the-power-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/you-matter-to-him", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/what-i-hope-my-granddaughters-and-grandsons-will-understand-about-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/we-are-all-enlisted", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/waiting-upon-the-lord-thy-will-be-done", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-time-shall-come", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-songs-they-could-not-sing", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-privilege-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-power-of-the-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-power-of-scripture", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-opportunity-of-a-lifetime", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-importance-of-a-name", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-hearts-of-the-children-shall-turn", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-divine-gift-of-repentance", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/the-book-of-mormon-a-book-from-god", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/teachings-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/teaching-after-the-manner-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/stand-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/redemption", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/providing-in-the-lords-way", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/preparation-in-the-priesthood-i-need-your-help", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/personal-revelation-and-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/perfect-love-casteth-out-fear", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/missionaries-are-a-treasure-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/love-her-mother", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/it-is-better-to-look-up", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/forget-me-not", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/doing-the-right-thing-at-the-right-time-without-delay", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/dare-to-stand-alone", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/covenants", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/counsel-to-youth", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/cleave-unto-the-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/choose-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/children", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/charity-never-faileth", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/as-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/a-witness", "https://www.churchofjesuschrist.org/study/general-conference/2011/10/a-time-to-prepare", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/your-potential-your-privilege", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/what-manner-of-men-and-women-ought-ye-to-be", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/waiting-on-the-road-to-damascus", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-spirit-of-revelation", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-sanctifying-work-of-welfare", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-sabbath-and-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-miracle-of-the-atonement", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-lords-richest-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-holy-temple-a-beacon-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-eternal-blessings-of-marriage", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-essence-of-discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/the-atonement-covers-all-pain", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/testimony", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/sacred-keys-of-the-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/remember-this-kindness-begins-with-me", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/priesthood-power", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/preparing-the-world-for-the-second-coming", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/opportunities-to-do-good", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/more-than-conquerors-through-him-that-loved-us", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/learning-in-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/lds-women-are-incredible", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/its-conference-once-again", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/i-believe-in-being-honest-and-true", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/hope", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/guided-by-the-holy-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/guardians-of-virtue", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/followers-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/finding-joy-through-loving-service", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/face-the-future-with-faith", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/establishing-a-christ-centered-home", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/desire", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/called-to-be-saints", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/become-as-a-little-child", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/at-parting", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/as-many-as-i-love-i-rebuke-and-chasten", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/an-ensign-to-the-nations", "https://www.churchofjesuschrist.org/study/general-conference/2011/04/a-living-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/what-have-you-done-with-my-name", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/two-lines-of-communication", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/trust-in-god-then-go-and-do", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/till-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/the-transforming-power-of-faith-and-character", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/the-three-rs-of-choice", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/the-priesthood-of-aaron", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/the-holy-ghost-and-revelation", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/the-divine-gift-of-gratitude", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/temple-mirrors-of-eternity-a-testimony-of-family", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/steadfast-and-immovable", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/stay-on-the-path", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/serve-with-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/rest-unto-your-souls", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/reflections-on-a-consecrated-life", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/receive-the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/pride-and-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/our-very-survival", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/of-things-that-matter-most", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/obedience-to-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/o-that-cunning-plan-of-the-evil-one", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/never-leave-him", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/let-there-be-light", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/he-teaches-us-to-put-off-the-natural-man", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/gospel-learning-and-teaching", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/faith-the-choice-is-yours", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/daughters-in-my-kingdom-the-history-and-work-of-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/courageous-parenting", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/come-unto-me-with-full-purpose-of-heart-and-i-shall-heal-you", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/cleansing-the-inner-vessel", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/charity-never-faileth", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/because-of-your-faith", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/be-thou-an-example-of-the-believers", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/be-an-example-of-the-believers", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/avoiding-the-trap-of-sin", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/as-we-meet-together-again", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/and-of-some-have-compassion-making-a-difference", "https://www.churchofjesuschrist.org/study/general-conference/2010/10/agency-essential-to-the-plan-of-life", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/your-happily-ever-after", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/you-are-my-hands", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/when-the-lord-commands", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/we-follow-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/watching-with-all-perseverance", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/turn-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/things-pertaining-to-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/the-rock-of-our-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/the-power-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/the-magnificent-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/the-divine-call-of-a-missionary", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/the-blessing-of-scripture", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/that-our-children-might-see-the-face-of-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/tell-me-the-stories-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/remember-who-you-are", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/preparation-brings-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/place-no-more-for-the-enemy-of-my-soul", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/our-path-of-duty", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/our-duty-to-god-the-mission-of-parents-and-leaders-to-the-rising-generation", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/never-never-never-give-up", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/mothers-teaching-children-in-the-home", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/mothers-and-daughters", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/mother-told-me", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/helping-hands-saving-hands", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/help-them-on-their-way-home", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/healing-the-sick", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/he-lives-all-glory-to-his-name", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/he-is-risen", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/generations-linked-in-love", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/developing-good-judgment-and-not-judging-others", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/continue-in-patience", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/be-of-a-good-courage", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/and-upon-the-handmaids-in-those-days-will-i-pour-out-my-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/all-things-work-together-for-good", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/act-in-all-diligence", "https://www.churchofjesuschrist.org/study/general-conference/2010/04/a-word-at-closing", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/what-have-i-done-for-someone-today", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/two-principles-for-any-economy", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/to-acquire-spiritual-guidance", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/the-past-way-of-facing-the-future", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/the-love-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/the-enduring-legacy-of-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/that-your-burdens-may-be-light", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/teaching-helps-save-lives", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/stewardship-a-sacred-trust", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/seeking-to-know-god-our-heavenly-father-and-his-son-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/school-thy-feelings-o-my-brother", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/safety-for-the-soul", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/repent-that-i-may-heal-you", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/relief-society-a-sacred-work", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/preserving-the-hearts-mighty-change", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/prayer-and-promptings", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/our-perfect-example", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/more-diligent-and-concerned-at-home", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/moral-discipline", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/mind-the-gap", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/love-and-law", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/let-virtue-garnish-your-thoughts", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/joseph-smith-prophet-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/i-love-loud-boys", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/hold-on", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/helping-others-recognize-the-whisperings-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/fathers-and-sons-a-remarkable-relationship", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/every-woman-needs-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/blessings-of-the-gospel-available-to-all", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/being-temperate-in-all-things", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/becoming-more-powerful-priesthood-holders", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/be-ready", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/attempting-the-impossible", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/ask-seek-knock", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/an-easiness-and-willingness-to-believe", "https://www.churchofjesuschrist.org/study/general-conference/2009/10/a-call-to-the-rising-generation", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/we-are-doing-a-great-work-and-cannot-come-down", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/unselfish-service", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/this-is-your-phone-call", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/the-way-of-the-disciple", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/the-power-of-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/temple-worship-the-source-of-strength-and-power-in-times-of-need", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/sacred-homes-sacred-temples", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/revealed-quorum-principles", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/respect-and-reverence", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/priesthood-responsibilities", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/our-fathers-plan-big-enough-for-all-his-children", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/none-were-with-him", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/may-you-have-courage", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/man-down", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/lessons-from-the-lords-prayers", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/learning-the-lessons-of-the-past", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/honorably-hold-a-name-and-standing", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/his-servants-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/his-arm-is-sufficient", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/gifts-to-help-us-navigate-our-life", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/get-on-with-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/finding-strength-in-challenging-times", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/faith-in-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/faith-in-adversity", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/counsel-to-young-men", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/come-unto-him", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/come-let-us-go-up-to-the-mountain-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/bring-souls-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/becoming-provident-providers-temporally-and-spiritually", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/be-your-best-self", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/be-thou-an-example-of-the-believers", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/be-of-good-cheer", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/adversity", "https://www.churchofjesuschrist.org/study/general-conference/2009/04/a-virtuous-life-step-by-step", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/you-know-enough", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/winning-the-war-against-evil", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/until-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/to-learn-to-do-to-be", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/the-way", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/the-truth-of-god-shall-go-forth", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/the-test", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/the-ministry-of-angels", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/the-infinite-power-of-hope", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/testimony-as-a-process", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/sacrament-meeting-and-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/returning-home", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/pray-always", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/our-hearts-knit-as-one", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/o-ye-that-embark", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/now-let-us-rejoice", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/lift-where-you-stand", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/let-him-do-it-with-simplicity", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/hope-ya-know-we-had-a-hard-time", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/honor-the-priesthood-and-use-it-well", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/holy-temples-sacred-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/happiness-your-heritage", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/gospel-teaching-our-most-important-calling", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/god-loves-and-helps-all-of-his-children", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/go-ye-therefore", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/fulfilling-the-purpose-of-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/finding-joy-in-the-journey", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/even-a-child-can-understand", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/come-what-may-and-love-it", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/come-to-zion", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/christian-courage-the-price-of-discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/celestial-marriage", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/because-my-father-read-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/arms-of-safety", "https://www.churchofjesuschrist.org/study/general-conference/2008/10/a-return-to-virtue", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/we-will-not-yield-we-cannot-yield", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/walk-in-the-light", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/today", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/to-heal-the-shattering-consequences-of-abuse", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/three-presiding-high-priests", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/the-twelve", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/the-true-and-living-church", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/the-power-of-light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/the-gospel-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/the-best-investment", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/testimony", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/stand-as-a-witness", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/special-experiences", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/service-a-divine-quality", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/salvation-and-exaltation", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/righteous-traditions", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/restoring-faith-in-the-family", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/opening-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/one-among-the-crowd", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/my-words-never-cease", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/my-soul-delighteth-in-the-things-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/looking-back-and-moving-forward", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/give-heed-unto-the-prophets-words", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/gaining-a-testimony-of-god-the-father-his-son-jesus-christ-and-the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/faith-of-our-father", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/faith-and-the-oath-and-covenant-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/examples-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/do-you-know-who-you-are", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/daughters-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/concern-for-the-one", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/born-again", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/at-all-times-in-all-things-and-in-all-places", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/ask-in-faith", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/and-who-is-my-neighbor", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/anchors-of-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/abundantly-blessed", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/a-matter-of-a-few-degrees", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/a-book-with-a-promise", "https://www.churchofjesuschrist.org/study/general-conference/2008/04/a-12-year-old-deacon", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/why-are-we-members-of-the-only-true-church", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/what-latter-day-saint-women-do-best-stand-strong-and-immovable", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/truth-the-foundation-of-correct-decisions", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/today-is-the-time", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/three-goals-to-guide-you", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/the-weak-and-the-simple-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/the-stone-cut-out-of-the-mountain", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/the-power-of-godliness-is-manifested-in-the-temples-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/the-only-true-god-and-jesus-christ-whom-he-hath-sent", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/the-great-commandment", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/strengthen-home-and-family", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/small-and-simple-things", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/slow-to-anger", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/service", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/scriptural-witnesses", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/raising-the-bar", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/quench-not-the-spirit-which-quickens-the-inner-man", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/preach-my-gospel-the-unifying-tool-between-members-and-missionaries", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/personal-revelation-the-teachings-and-examples-of-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/out-of-small-things", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/o-remember-remember", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/nourished-by-the-good-word-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/mrs-patton-the-story-continues", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/mothers-who-know", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/live-by-faith-and-not-by-fear", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/knowing-that-we-know", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/i-will-strengthen-thee-i-will-help-thee", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/have-we-not-reason-to-rejoice", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/good-better-best", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/god-helps-the-faithful-priesthood-holder", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/faith-family-facts-and-fruits", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/enduring-together", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/don-t-leave-for-tomorrow-what-you-can-do-today", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/do-it-now", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/clean-hands-and-a-pure-heart", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/claim-the-exceeding-great-and-precious-promises", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/blessed-are-all-the-pure-in-heart", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/after-all-we-can-do", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/a-royal-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2007/10/a-broken-heart-and-a-contrite-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/ye-must-be-born-again", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/will-a-man-rob-god", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/whos-on-the-lords-side", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/using-the-supernal-gift-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/to-the-aaronic-priesthood-preparing-for-the-decade-of-decision", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/this-day", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-tongue-of-angels", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-things-of-which-i-know", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-spirit-of-the-tabernacle", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-priesthood-a-sacred-gift", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-nourishing-power-of-hymns", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-miracle-of-the-holy-bible", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-message-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/the-healing-power-of-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/tabernacle-memories", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/stay-on-the-path", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/salt-lake-tabernacle-rededication", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/repentance-and-conversion", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/remembering-repenting-and-changing", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/remember-and-perish-not", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/prophets-pioneer-and-modern-day", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/point-of-safe-return", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/mom-are-we-christians", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/message-to-my-grandsons", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/lifes-lessons-learned", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/let-virtue-garnish-thy-thoughts-unceasingly", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/lay-up-in-store", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/its-true-isn-t-it-then-what-else-matters", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/if-these-old-walls-could-talk", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/i-know-that-my-redeemer-lives", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/i-am-clean", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/gratitude-a-path-to-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/do-you-know", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/divorce", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/daughters-of-heavenly-father", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/commitment-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/a-tabernacle-in-the-wilderness", "https://www.churchofjesuschrist.org/study/general-conference/2007/04/a-lesson-from-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/wherefore-settle-this-in-your-hearts", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/we-bear-testimony-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/true-to-our-priesthood-trust", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/to-look-reach-and-come-unto-christ", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/three-towels-and-a-25-cent-newspaper", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-temple-is-about-families", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-power-of-patience", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-power-of-a-personal-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-plan-of-salvation", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-law-of-tithing", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-great-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-great-and-wonderful-love", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-gathering-of-scattered-israel", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-first-generation", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-faith-to-move-mountains", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-atonement-can-secure-your-peace-and-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/the-atonement-can-clean-reclaim-and-sanctify-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/that-they-might-know-thee", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/sunday-will-come", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/spiritual-nutrients", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/rise-up-o-men-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/remembering-the-lords-love", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/receiving-by-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/prophets-in-the-land-again", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/o-be-wise", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/moving-closer-to-him", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/look-toward-eternity", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/let-us-be-men", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/in-the-arms-of-his-love", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/how-firm-a-foundation", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/holy-scriptures-the-power-of-god-unto-our-salvation", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/he-trusts-us", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/he-heals-the-heavy-laden", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/faith-service-constancy", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/eternally-encircled-in-his-love", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/behold-your-little-ones", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/becoming-instruments-in-the-hands-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/and-nothing-shall-offend-them", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/a-priesthood-quorum", "https://www.churchofjesuschrist.org/study/general-conference/2006/10/a-defense-and-a-refuge", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/zion-in-the-midst-of-babylon", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/your-mission-will-change-everything", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/your-light-a-standard-to-all-nations", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/you-have-a-noble-birthright", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/until-again-we-meet", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/true-to-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/to-grow-up-unto-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/to-act-for-ourselves-the-gift-and-blessings-of-agency", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/the-restoration-of-all-things", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/the-need-for-greater-kindness", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/the-great-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/the-gift-of-agency", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/the-abundant-life", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/that-we-may-always-have-his-spirit-to-be-with-us", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/tender-hearts-and-helping-hands", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/seek-ye-the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/see-the-end-from-the-beginning", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/repentance-a-blessing-of-membership", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/prayer-faith-and-family-stepping-stones-to-eternal-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/our-sacred-priesthood-trust", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/our-rising-generation", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/nurturing-marriage", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/now-is-the-time-to-serve-a-mission", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/it-shows-in-your-face", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/instruments-of-the-lords-peace", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/i-will-remember-your-sins-no-more", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/i-am-the-light-which-ye-shall-hold-up", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/creating-a-gospel-sharing-home", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/broken-things-to-mend", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/as-now-we-take-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/as-a-child", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/an-outpouring-of-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/all-men-everywhere", "https://www.churchofjesuschrist.org/study/general-conference/2006/04/a-royal-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/what-matters-most-is-what-lasts-longest", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/truth-restored", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/true-happiness-a-conscious-decision", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/to-young-women", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/the-sanctity-of-the-body", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/the-prophet-joseph-smith-teacher-by-example", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/the-light-in-their-eyes", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/the-book-of-mormon-the-instrument-to-gather-scattered-israel", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/the-blessings-of-general-conference", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/that-we-may-all-sit-down-in-heaven-together", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/sweet-moments", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/spiritual-preparedness-start-early-and-be-steady", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/sacrifice-is-a-joy-and-a-blessing", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/priesthood-authority-in-the-family-and-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/preparations-for-the-restoration-and-the-second-coming-my-hand-shall-be-over-thee", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/opening-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/on-zions-hill", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/my-soul-delighteth-in-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/mans-search-for-divine-truth", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/knowing-the-lords-will-for-you", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/journey-to-higher-ground", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/jesus-christ-the-master-healer", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/instruments-in-the-hands-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/if-ye-are-prepared-ye-shall-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/if-christ-had-my-opportunities", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/gospel-covenants-bring-promised-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/do-your-duty-that-is-best", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/compass-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/christlike-attributes-the-wind-beneath-our-wings", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/called-and-chosen", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/blessings-resulting-from-reading-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/benediction", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/becoming-a-missionary", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/be-prepared-be-ye-strong-from-henceforth", "https://www.churchofjesuschrist.org/study/general-conference/2005/10/a-pattern-for-all", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/whos-on-the-lords-side-who", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/what-seek-ye", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/what-greater-goodness-can-we-know-christlike-friends", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/tithing-a-commandment-even-for-the-destitute", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-worth-of-souls", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-virtue-of-kindness", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-tender-mercies-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-sacred-call-of-service", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-power-of-preach-my-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-great-things-which-god-has-revealed", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-fruits-of-the-first-vision", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/the-book-of-mormon-another-testament-of-jesus-christ-plain-and-precious-things", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/standing-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/pornography", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/perseverance", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/our-most-distinguishing-feature", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/opening-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/one-more", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/now-is-the-time-to-prepare", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/hearts-bound-together", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/he-knows-you-by-name", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/glad-tidings-from-cumorah", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/gambling", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/faith-is-the-answer", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/couple-missionaries-blessings-from-sacrifice-and-service", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/constant-truths-for-changing-times", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/beware-of-the-evil-behind-the-smiling-eyes", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/be-thou-an-example", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/be-of-good-cheer-and-faithful-in-adversity", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/appreciating-the-counsel-of-those-who-are-bowed-in-years", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/all-thy-children-shall-be-taught", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/a-work-for-me-to-do", "https://www.churchofjesuschrist.org/study/general-conference/2005/04/a-still-small-voice-and-a-throbbing-heart", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/where-do-i-make-my-stand", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/what-is-a-quorum", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/we-did-this-for-you", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/walking-towards-the-light-of-his-love", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-women-in-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-power-of-gods-love", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-opportunity-to-testify", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-least-of-these", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-key-of-the-knowledge-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/the-blessings-of-a-proper-fast", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/senior-missionaries-and-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/securing-our-testimonies", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/remember-the-teachings-of-your-father", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/pure-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/prophets-seers-and-revelators", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/press-on", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/perilous-times", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/peace-of-conscience-and-peace-of-mind", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/out-of-small-things", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/more-holiness-give-me", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/keeping-our-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/in-the-strength-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/if-ye-are-prepared-ye-shall-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/i-stand-at-the-door-and-knock", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/how-has-relief-society-blessed-your-life", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/finding-faith-in-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/faith-and-keys", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/condition-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/choose-you-this-day", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/bringing-peace-and-healing-to-your-soul", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/belonging-is-our-sacred-birthright", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/be-not-deceived", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/anxiously-engaged", "https://www.churchofjesuschrist.org/study/general-conference/2004/10/a-tragic-evil-among-us", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/your-personal-influence", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/with-all-the-feeling-of-a-tender-parent-a-message-of-hope-to-families", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/when-thou-art-converted", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-words-of-christ-our-spiritual-liahona", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-finished-story", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-dawning-of-a-brighter-day", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-church-grows-stronger", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-call-for-courage", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-atonement-and-the-value-of-one-soul", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/the-atonement-all-for-all", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/stay-on-the-high-road", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/standing-spotless-before-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/roots-and-branches", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/remember-how-merciful-the-lord-hath-been", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/preparation-for-the-second-coming", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/my-soul-delighteth-in-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/marriage-and-family-our-sacred-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/jesus-the-very-thought-of-thee", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/in-the-strength-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/i-was-an-hungred-and-ye-gave-me-meat", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/how-to-live-well-amid-increasing-evil", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/how-great-the-wisdom-and-the-love", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/for-the-strength-of-youth", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/fatherhood-an-eternal-calling", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/earthly-debts-heavenly-debts", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/do-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/did-you-get-the-right-message", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/concluding-remarks", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/choices", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/but-if-not", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/believe", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/applying-the-simple-and-plain-gospel-principles-in-the-family", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/all-things-shall-work-together-for-your-good", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/abide-in-me", "https://www.churchofjesuschrist.org/study/general-conference/2004/04/a-mother-heart", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/young-men-holders-of-keys", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/we-believe-all-that-god-has-revealed", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/to-the-women-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/three-choices", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-state-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-standard-of-truth-has-been-erected", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-shepherds-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-phenomenon-that-is-you", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-message-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-lord-thy-god-will-hold-thy-hand", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-grandeur-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-empowerment-of-humility", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-clarion-call-of-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-bridge-builder", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/the-atonement-repentance-and-dirty-linen", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/seeing-the-promises-afar-off", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/repentance-and-change", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/receiving-a-testimony-of-the-restored-gospel-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/realize-your-full-potential", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/priesthood-keys-and-the-power-to-bless", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/personal-priesthood-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/lord-i-believe-help-thou-mine-unbelief", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/let-us-live-the-gospel-more-fully", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/let-our-voices-be-heard", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/in-covenant-with-him", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/how-choice-a-seer", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/he-knows-us-he-loves-us", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/come-follow-me", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/choosing-charity-that-good-part", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/choose-ye-therefore-christ-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/bring-him-home", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/are-you-a-saint", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/an-ensign-to-the-nations-a-light-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/an-enduring-testimony-of-the-mission-of-the-prophet-joseph", "https://www.churchofjesuschrist.org/study/general-conference/2003/10/a-sure-foundation", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/you-are-a-child-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/words-to-live-by", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/war-and-peace", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/there-is-hope-smiling-brightly-before-us", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-virtues-of-righteous-daughters-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-unspeakable-gift", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-light-of-his-love", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-importance-of-the-family", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-golden-years", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-essential-role-of-member-missionary-work", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-devils-throat", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/the-condition-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/sweet-power-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/steadfast-in-our-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/stand-in-your-appointed-place", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/show-you-know", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/seek-and-ye-shall-find", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/press-forward-and-be-steadfast", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/preparing-for-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/overcoming-the-stench-of-sin", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/loyalty", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/in-search-of-treasure", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/i-can-pray-to-heavenly-father-anytime-anywhere", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/holy-place-sacred-space", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/growing-into-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/give-thanks-in-all-things", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/forgiveness-will-change-bitterness-to-love", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/follow-the-instructions", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/faith-through-tribulation-brings-peace-and-joy", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/eternal-marriage", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/did-i-tell-you", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/dear-are-the-sheep-that-have-wandered", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/church-auditing-department-report", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/care-for-the-life-of-the-soul", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/blessed-by-living-water", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/benediction", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/and-thats-the-way-it-is", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/a-prayer-for-the-children", "https://www.churchofjesuschrist.org/study/general-conference/2003/04/a-child-and-a-disciple", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/you-are-all-heaven-sent", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/yielding-to-the-enticings-of-the-holy-spirit", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/with-holiness-of-heart", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/whats-in-it-for-me", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/were-there-not-ten-cleansed", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/to-men-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/to-be-free-of-heavy-burdens", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/tithing-a-test-of-faith-with-eternal-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/the-stake-patriarch", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/the-marvelous-foundation-of-our-faith", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/the-greatest-generation-of-missionaries", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/the-global-church-blessed-by-the-voice-of-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/that-they-may-be-one-in-us", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/shall-he-find-faith-on-the-earth", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/sacrifice-brings-forth-the-blessings-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/rise-to-your-call", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/peace-be-still", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/o-that-i-were-an-angel-and-could-have-the-wish-of-mine-heart", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/models-to-follow", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/i-ll-go-where-you-want-me-to-go", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/i-believe-i-can-i-knew-i-could", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/fun-and-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/encircled-in-the-arms-of-his-love", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/each-a-better-person", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/dad-are-you-awake", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/come-to-zion-come-to-zion", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/charity-one-family-one-home-at-a-time", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/called-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/called-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/but-if-not", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/blessing-our-families-through-our-covenants", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/blessed-are-the-peacemakers", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/a-woman-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2002/10/a-voice-of-gladness-for-our-children", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/we-walk-by-faith", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/we-look-to-christ", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/true-friends", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/this-road-we-call-life", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/they-pray-and-they-go", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-peaceable-things-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-other-prodigal", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-opportunity-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-lifeline-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-law-of-tithing", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-language-of-love", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-gospel-in-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/the-church-goes-forward", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/strengthen-home-and-family", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/standing-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/some-basic-teachings-from-the-history-of-joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/personal-worthiness-to-exercise-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/pathways-to-perfection", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/out-of-darkness-into-his-marvelous-light", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/it-can-t-happen-to-me", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/i-ll-go-where-you-want-me-to-go", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/how-firm-our-foundation", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/hold-high-the-torch", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/hidden-wedges", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/full-conversion-brings-happiness", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/for-thy-good", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/follow-me", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/feel-the-love-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/faith-obedience", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/eternal-life-through-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/developing-inner-strength", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/consecrate-thy-performance", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/church-auditing-department-report", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/children", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/charity-perfect-and-everlasting-love", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/being-teachable", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/becoming-men-in-whom-the-spirit-of-god-is", "https://www.churchofjesuschrist.org/study/general-conference/2002/04/becoming-a-great-benefit-to-our-fellow-beings", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/writing-gospel-principles-in-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/till-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-times-in-which-we-live", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-seventh-commandment-a-shield", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-returned-missionary", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-power-of-a-strong-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-first-and-great-commandment", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-book-of-mormon-another-testament-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/the-atonement-our-greatest-hope", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/steadfast-and-immovable", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/standing-tall", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/stand-firm", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/some-great-thing", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/sharing-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/set-in-order-thy-house", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/reaching-down-to-lift-another", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/prayer", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/our-fathers-plan", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/our-duty-to-god", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/our-actions-determine-our-character", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/one-step-after-another", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/now-is-the-time", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/living-in-the-fulness-of-times", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/like-a-watered-garden", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/it-is-not-good-for-man-or-woman-to-be-alone", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/help-thou-mine-unbelief", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/fulfilling-our-duty-to-god", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/fear-not-for-they-that-be-with-us-are-more", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/faith-of-our-prophets", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/duty-calls", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/doctrine-of-inclusion", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/create-or-continue-priesthood-links", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/building-a-bridge-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/beware-of-murmuring", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/be-thou-an-example", "https://www.churchofjesuschrist.org/study/general-conference/2001/10/are-we-not-all-mothers", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/your-celestial-guide", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/you-can-t-pet-a-rattlesnake", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/witnesses-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/watch-with-me", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/united-in-love-and-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/to-walk-humbly-with-thy-god", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/to-the-rescue", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/to-bear-testimony-of-mine-only-begotten", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/them-that-honour-me-i-will-honour", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/the-work-goes-on", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/the-touch-of-the-masters-hand", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/the-perpetual-education-fund", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/the-miracle-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/the-law-of-the-fast", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/sacrifice-an-eternal-investment", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/priesthood-power", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/plow-in-hope", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/personal-preparation-for-temple-blessings", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/how-can-i-become-the-woman-of-whom-i-dream", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/his-word-ye-shall-receive", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/gratitude-and-service", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/good-bye-for-another-season", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/focus-and-priorities", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/first-things-first", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/enhancing-our-temple-experience", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/developing-our-talent-for-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/david-a-future-missionary", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/couple-missionaries-a-time-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/compassion", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/church-auditing-department-report", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/building-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/building-a-community-of-saints", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/born-again", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/an-invitation-with-promise", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/a-god-of-miracles", "https://www.churchofjesuschrist.org/study/general-conference/2001/04/a-comforter-a-guide-a-testifier", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/your-greatest-challenge-mother", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/ye-are-the-temple-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/write-upon-my-heart", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/we-are-instruments-in-the-hands-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/this-great-millennial-year", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-tugs-and-pulls-of-the-world", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-redemption-of-the-dead-and-the-testimony-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-path-to-peace-and-joy", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-joy-of-womanhood", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-enemy-within", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-covenant-of-baptism-to-be-in-the-kingdom-and-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-challenge-to-become", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-call-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/the-blessing-of-keeping-the-sabbath-day-holy", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/stand-tall-and-stand-together", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/sharing-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/seeking-the-spirit-of-god", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/satans-bag-of-snipes", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/sanctify-yourselves", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/ripples", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/retaining-a-remission-of-sin", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/pure-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/one-by-one", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/now-is-the-time", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/living-prophets-seers-and-revelators", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/living-by-scriptural-guidance", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/lead-kindly-light", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/great-shall-be-the-peace-of-thy-children", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/freedom-from-or-freedom-to", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/discipleship", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/dedication-day", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/cultivate-righteous-traditions", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/come-and-see", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/be-a-strong-link", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/an-humble-and-a-contrite-heart", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/a-growing-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/10/a-great-family-in-reverence-and-worship", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/your-own-personal-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/your-eternal-voyage", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/your-eternal-home", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/womanhood-the-highest-place-of-honor", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/we-are-creators", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/watch-over-and-strengthen", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/to-all-the-world-in-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/thou-shalt-give-heed-unto-all-his-words", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-widows-of-zion", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-stake-president", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-shield-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-sanctity-of-womanhood", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-power-of-self-mastery", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-creation", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-cloven-tongues-of-fire", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/standing-with-god", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/stand-as-a-witness", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/resurrection", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/my-testimony", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/living-happily-ever-after", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/keep-an-eternal-perspective", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/integrity", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/how-is-it-with-us", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/honoring-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/heavenly-father-has-a-special-plan", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/future-leaders", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/finding-a-safe-harbor", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/faith-devotion-and-gratitude", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/content-with-the-things-allotted-unto-us", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/because-my-father-sent-me", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/as-doves-to-our-windows", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/are-you-still-here", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/a-time-of-new-beginnings", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/a-temple-for-west-africa", "https://www.churchofjesuschrist.org/study/general-conference/2000/04/a-brief-introduction-to-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/why-we-do-some-of-the-things-we-do", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/what-it-means-to-be-a-daughter-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/we-are-women-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/the-tongue-of-angels", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/the-spirit-of-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/the-faith-of-a-sparrow-faith-and-trust-in-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/spiritual-hurricanes", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/serving-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/rejoice-daughters-of-zion", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/prophets-and-spiritual-mole-crickets", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/priesthood-power", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/peace-hope-and-direction", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/our-legacy", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/our-destiny", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/one-link-still-holds", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/of-seeds-and-soils", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/no-man-is-an-island", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/lessons-from-laman-and-lemuel", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/hope-an-anchor-of-the-soul", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/home-family-and-personal-enrichment", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/he-lives", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/growing-into-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/gospel-teaching", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/good-bye-to-this-wonderful-old-tabernacle", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/for-this-cause-came-i-into-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/do-not-delay", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/beware-of-false-prophets-and-false-teachers", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/behold-the-man", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/becoming-our-best-selves", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/at-the-summit-of-the-ages", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/an-high-priest-of-good-things-to-come", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/agency-a-blessing-and-a-burden", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/a-year-of-jubilee", "https://www.churchofjesuschrist.org/study/general-conference/1999/10/a-testimony-of-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/your-name-is-safe-in-our-home", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/your-light-in-the-wilderness", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/your-celestial-journey", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/welcome-home", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/true-followers", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/this-is-our-day", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-work-moves-forward", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-witness-martin-harris", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-shepherds-of-the-flock", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-priesthood-mighty-army-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-power-of-teaching-doctrine", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-hands-of-the-fathers", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/the-bishop-and-his-counselors", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/thanks-to-the-lord-for-his-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/teach-them-the-word-of-god-with-all-diligence", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/strengthening-families-our-sacred-duty", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/spiritual-power-of-our-baptism", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/receive-the-temple-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/priesthood-and-the-home", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/preparing-our-families-for-the-temple", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/out-of-small-things", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/our-sacred-duty-to-honor-women", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/our-only-chance", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/obedience-the-path-to-freedom", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/made-like-unto-the-son-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/love-and-service", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/like-a-flame-unquenchable", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/inspired-church-welfare", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/he-is-not-here-but-is-risen", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/greed-selfishness-and-overindulgence", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/friendship-a-gospel-principle", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/for-i-was-blind-but-now-i-see", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/follow-the-light", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/find-the-lambs-feed-the-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/fellowshipping", "https://www.churchofjesuschrist.org/study/general-conference/1999/04/bridges-and-eternal-keepsakes", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/youth-of-the-noble-birthright", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/ye-also-shall-bear-witness", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/what-are-people-asking-about-us", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/welcome-to-conference", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/we-are-not-alone", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/we-are-children-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/walking-in-the-light-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/today-determines-tomorrow", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/to-the-boys-and-to-the-men", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/think-to-thank", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/the-priesthood-quorum", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/the-power-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/the-living-prophet-our-source-of-pure-doctrine", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/the-aaronic-priesthood-and-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/small-temples-large-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/personal-purity", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/pearls-from-the-sand", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/parents-in-zion", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/overcoming-discouragement", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/opening-the-windows-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/obeying-the-law-serving-ones-neighbor", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/hope-through-the-atonement-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/healing-soul-and-body", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/establishing-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/cultivating-divine-attributes", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/come-to-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/come-listen-to-a-prophets-voice", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/come-let-us-walk-in-the-light-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/by-what-power-have-ye-done-this", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/benediction", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/bear-record-of-him", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/as-for-me-and-my-house-we-will-serve-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/are-we-keeping-pace", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/a-voice-of-warning", "https://www.churchofjesuschrist.org/study/general-conference/1998/10/a-season-of-opportunity", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/young-women-titles-of-liberty", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/we-seek-after-these-things", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/we-bear-witness-of-him", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/understanding-our-true-identity", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/turning-hearts-to-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/tithing-a-privilege", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-time-to-prepare", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-kingdoms-perfecting-pathway", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-heart-and-a-willing-mind", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/the-articles-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/that-we-may-be-one", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/testimony", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/teaching-our-children-to-love-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/search-me-o-god-and-know-my-heart", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/removing-barriers-to-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/put-your-shoulder-to-the-wheel", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/obedience-lifes-great-challenge", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/new-temples-to-provide-crowning-blessings-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/marvelous-are-the-revelations-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/look-to-god-and-live", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/living-worthy-of-the-girl-you-will-someday-marry", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/live-the-commandments", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/in-harms-way", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/how-near-to-the-angels", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/have-you-been-saved", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/come-unto-christ", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/christ-can-change-human-behavior", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/children-and-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/bridging-the-gap-between-uncertainty-and-certainty", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/behold-we-count-them-happy-which-endure", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/agency-and-anger", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/a-teacher-come-from-god", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/a-new-harvest-time", "https://www.churchofjesuschrist.org/study/general-conference/1998/04/a-disciple-a-friend", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/why-every-member-a-missionary", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/valued-companions", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/universal-application-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/the-weightier-matters-of-the-law-judgment-mercy-and-faith", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/the-plan-of-salvation-a-flight-plan-for-life", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/the-mighty-strength-of-the-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/the-lord-blesses-his-children-through-patriarchal-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/the-home-a-refuge-and-sanctuary", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/teachers-the-timeless-key", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/teach-the-children", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/standing-for-truth-and-right", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/spiritual-capacity", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/some-thoughts-on-temples-retention-of-converts-and-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/receive-truth", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/pioneers-of-the-future-be-not-afraid-only-believe", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/pioneer-shoes-through-the-ages", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/making-faith-a-reality", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/look-to-the-future", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/latter-day-saints-in-very-deed", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/in-remembrance-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/hymn-of-the-obedient-all-is-well", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/home-teaching-a-divine-service", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/he-hath-filled-the-hungry-with-good-things", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/four-absolute-truths-provide-an-unfailing-moral-compass", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/for-such-a-time-as-this", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/following-the-pioneers", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/feed-my-lambs", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/drawing-nearer-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/daughter-be-of-good-comfort", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/creating-places-of-security", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/care-for-new-converts", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/called-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/behold-the-man", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/are-you-the-woman-i-think-you-are", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/apply-the-atoning-blood-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1997/10/a-celestial-connection-to-your-teenage-years", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/you-have-nothing-to-fear-from-the-journey", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/when-thou-art-converted-strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/washed-clean", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/true-to-the-truth", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/true-to-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/they-will-come", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/they-showed-the-way", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/the-basics-have-not-changed", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/that-spirit-which-leadeth-to-do-good", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/pray-unto-the-father-in-my-name", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/power-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/pioneers-all", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/our-testimony-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/modern-pioneers", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/may-we-be-faithful-and-true", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/keep-walking-and-give-time-a-chance", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/jesus-christ-our-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/in-his-strength-i-can-do-all-things", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/his-peace", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/go-and-do-thou-likewise", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/from-whom-all-blessings-flow", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/friends-standing-together", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/finding-safety-in-counsel", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/finding-faith-in-every-footstep", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/eternity-lies-before-us", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/endure-and-be-lifted-up", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/draw-nearer-to-christ", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/converts-and-young-men", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/caring-for-the-souls-of-children", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/bishop-help", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/because-she-is-a-mother", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/as-good-as-our-bond", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/a-small-stone", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/a-righteous-choice", "https://www.churchofjesuschrist.org/study/general-conference/1997/04/a-holy-calling", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/women-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/woman-why-weepest-thou", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/witnesses-for-god", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/we-care-enough-to-send-our-very-best", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/this-thing-was-not-done-in-a-corner", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-twelve-apostles", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-spirit-of-prophecy", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-savior-is-counting-on-you", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-peaceable-things-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-ordinary-classroom-a-powerful-place-for-steady-and-continued-growth", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-joy-of-living-the-great-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-grand-key-words-for-the-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-eternal-family", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/the-atonement", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/strengthened-in-charity", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/run-and-not-be-weary", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/rejoice", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/reach-with-a-rescuing-hand", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/raised-in-hope", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/prophets-are-inspired", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/partakers-of-the-glories", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/listening-to-the-voice-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/listen-by-the-power-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/honesty-a-moral-compass", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/faith-in-every-footstep", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/covenant-marriage", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/confirmed-in-faith", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/christians-in-belief-and-action", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/christ-at-bethesdas-pool", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/behold-your-little-ones", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/be-thou-an-example", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/always-have-his-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1996/10/according-to-the-desire-of-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/ye-may-know", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/what-i-want-my-son-to-know-before-he-leaves-on-his-mission", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/thou-shalt-have-no-other-gods", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/this-work-is-true", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/this-glorious-easter-morn", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/the-word-of-wisdom-the-principle-and-the-promises", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/the-way-of-the-master", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/the-sabbath-day-and-sunday-shopping", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/the-prophetic-voice", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/temptation", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/stay-on-the-true-course", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/stand-true-and-faithful", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/spiritual-shepherds", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/sacrament-of-the-lords-supper", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/remember-thy-church-o-lord", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/remember-how-thou-hast-received-and-heard", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/my-prayers-were-answered", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/listening-with-new-ears", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/joseph-the-man-and-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/if-thou-wilt-enter-into-life-keep-the-commandments", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/he-has-given-me-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/finding-joy-in-life", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/feasting-at-the-lords-table", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/faith-of-our-fathers", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/facing-trials-with-optimism", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/duty-calls", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/conversion-and-commitment", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/commitment", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/becometh-as-a-child", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/be-ye-clean", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/baskets-and-bottles", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/an-anchor-for-eternity-and-today", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/a-legacy-of-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1996/04/a-handful-of-meal-and-a-little-oil", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/witnesses", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/windows-of-light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/who-honors-god-god-honors", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/what-is-relief-society-for", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/touch-the-hearts-of-the-children", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/to-touch-a-life-with-faith", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/this-do-in-remembrance-of-me", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/the-power-of-goodness", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/the-family-a-proclamation-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/the-fabric-of-faith-and-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/the-brilliant-morning-of-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/the-book-of-mormon-a-sacred-ancient-record", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/swallowed-up-in-the-will-of-the-father", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/stay-the-course-keep-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/stand-strong-against-the-wiles-of-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/spiritual-mountaintops", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/seek-first-the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/sacrifice-in-the-service", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/relief-society-a-balm-in-gilead", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/redeemer-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/priesthood-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/powerful-ideas", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/perfection-pending", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/patience-a-heavenly-virtue", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/our-message-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/of-missions-temples-and-stewardship", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/lord-to-whom-shall-we-go", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/if-ye-are-prepared-ye-shall-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/i-will-go", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/hyrum-smith-firm-as-the-pillars-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/eternal-laws-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/encircled-in-the-saviors-love", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/blessings-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/as-we-gather-together", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/acting-for-ourselves-and-not-being-acted-upon", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/a-strategy-for-war", "https://www.churchofjesuschrist.org/study/general-conference/1995/10/a-living-network", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/ye-shall-feast-upon-this-fruit", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/we-have-kept-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/we-have-a-work-to-do", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/watchmen-on-the-tower", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/trying-the-word-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/this-work-is-concerned-with-people", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/this-is-the-work-of-the-master", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-translation-miracle-of-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-temple-is-a-family-affair", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-shield-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-reward-is-worth-the-effort", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-power-to-heal-from-within", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-light-within-you", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/that-all-may-hear", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/search-for-identity", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/responsibilities-of-shepherds", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/our-priesthood-legacy", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/mercy-the-divine-gift", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/marriage-and-the-great-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/living-water-to-quench-spiritual-thirst", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/heirs-to-the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/hear-the-prophets-voice-and-obey", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/he-will-be-there-to-help", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/finding-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/fat-free-feasting", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/easter-reflections", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/deny-yourselves-of-all-ungodliness", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/covenant-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/children-of-the-covenant", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/celebrating-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/being-leaders-who-foster-growth", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/as-jesus-sees-us", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/apostasy-and-restoration", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/answers-to-lifes-questions", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/an-elect-lady", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/always-remember-him", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/a-time-to-choose", "https://www.churchofjesuschrist.org/study/general-conference/1995/04/a-table-encircled-with-love", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/worship-through-music", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-spirit-of-elijah", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-simple-things", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-revelations-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-only-true-and-valid-basis", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-kingdom-progresses-in-africa", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-keys-that-never-rust", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-importance-of-receiving-a-personal-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/the-fatherless-and-the-widows-beloved-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/that-thy-confidence-wax-strong", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/teach-the-children", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/stand-ye-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/stand-firm-in-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/solemn-assemblies", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/seek-and-ye-shall-find", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/save-the-children", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/rowing-your-boat", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/restored-truth", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/priceless-principles-for-success", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/personal-revelation-the-gift-the-test-and-the-promise", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/my-brothers-keeper", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/miracles-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/making-the-right-choices", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/make-thee-an-ark", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/let-us-build-fortresses", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/helping-children-know-truth-from-error", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/heed-the-prophets-voice", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/follow-the-son-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/exceeding-great-and-precious-promises", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/endure-to-the-end-in-charity", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/don-t-drop-the-ball", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/deep-roots", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/charity-and-learning", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/brightness-of-hope", "https://www.churchofjesuschrist.org/study/general-conference/1994/10/being-a-righteous-husband-and-father", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/what-shall-we-do", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/what-manner-of-men-ought-ye-to-be", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/what-he-would-have-us-do", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/we-all-have-a-father-in-whom-we-can-trust", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/walk-with-me", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/trying-to-be-like-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/to-be-healed", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/tithing", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/therefore-i-was-taught", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-unique-message-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-special-status-of-children", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-priesthood-a-sacred-trust", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-power-of-a-good-life", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-path-to-peace", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-greatest-miracle-in-human-history", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-father-and-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/teaching-children-to-walk-uprightly-before-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/teach-us-tolerance-and-love", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/take-especial-care-of-your-family", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/stretching-the-cords-of-the-tent", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/remember-your-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/live-in-obedience", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/jesus-of-nazareth", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/increase-in-faith", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/if-a-man-die-shall-he-live-again", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/growing-up-spiritually", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/god-is-at-the-helm", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/five-loaves-and-two-fishes", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/faith-is-the-answer", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/faith-in-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/decisions", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/courage-to-hearken", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/counseling-with-our-councils", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/a-divine-prescription-for-spiritual-healing", "https://www.churchofjesuschrist.org/study/general-conference/1994/04/a-childs-love-matured", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/your-personal-checklist-for-a-successful-eternal-flight", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/ward-and-branch-families-part-of-heavenly-fathers-plan-for-us", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/truth-is-the-issue", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/touch-not-the-evil-gift-nor-the-unclean-thing", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/the-upward-reach", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/the-search-for-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/the-modern-mighty-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/the-lords-wind", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/the-great-plan-of-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/take-time-for-your-children", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/strength-in-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/strength-in-counsel", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/service-and-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/relief-society-charity-the-guiding-principle", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/rearing-children-in-a-polluted-environment", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/ponder-the-path-of-thy-feet", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/our-lord-and-savior", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/my-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/missionary-work-our-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/meeting-lifes-challenges", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/look-to-god-and-live", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/keeping-covenants-and-honoring-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/how-will-our-children-remember-us", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/from-the-beginning", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/for-time-and-all-eternity", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/equality-through-diversity", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/divine-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/constancy-amid-change", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/combatting-spiritual-drift-our-global-pandemic", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/choose-the-right", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/bring-up-a-child-in-the-way-he-should-go", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/be-of-good-cheer", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/an-eternal-vision", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/acquiring-spiritual-knowledge", "https://www.churchofjesuschrist.org/study/general-conference/1993/10/a-mighty-change-of-heart", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/whom-the-lord-calls-the-lord-qualifies", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/this-peaceful-house-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-temple-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-temple-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-principle-of-work", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-power-of-correct-principles", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-lord-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-language-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/spiritually-strong-homes-and-families", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/some-lessons-i-learned-as-a-boy", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/search-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/search-and-rescue", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/receiving-divine-assistance-through-the-grace-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/prayer", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/power-of-the-church-rooted-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/personal-temple-worship", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/peace-through-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/keeping-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/keep-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/jesus-the-very-thought-of-thee", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/jesus-christ-the-son-of-the-living-god", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/i-know-in-whom-i-have-trusted", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/honoring-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/heroes", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/he-maketh-me-to-lie-down-in-green-pastures", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/gifts", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/father-come-home", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/faith-yields-priesthood-power", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/come-unto-christ", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/cats-cradle-of-kindness", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/back-to-gospel-basics", "https://www.churchofjesuschrist.org/study/general-conference/1993/04/a-prophets-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/where-is-wisdom", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/to-the-women-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/to-be-learned-is-good-if", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-priesthood-in-action", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-lord-will-prosper-the-righteous", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-joy-of-hope-fulfilled", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-golden-years", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-church-is-on-course", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/the-beacon-in-the-harbor-of-peace", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/successful-living-of-gospel-principles", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/spiritual-revival", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/spiritual-bonfires-of-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/sin-will-not-prevail", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/settle-this-in-your-hearts", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/remember-also-the-promises", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/nobody-said-that-it-would-be-easy", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/missionary-work-in-the-philippines", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/miracles-then-and-now", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/love-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/jesus-christ-is-at-the-center-of-the-restoration-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/honour-thy-father-and-thy-mother", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/healing-your-damaged-life", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/fear", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/confidence-through-conversion", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/coming-unto-christ-by-searching-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/by-the-power-of-his-word-did-they-cause-prisons-to-tumble", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/building-your-tabernacle", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/born-of-goodly-parents", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/bible-stories-and-personal-protection", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/behold-your-little-ones", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/behold-the-lord-hath-shown-unto-me-great-and-marvelous-things", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/becoming-wise-unto-salvation", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/at-parting", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/an-example-of-the-believers", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/a-yearning-for-home", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/a-priceless-heritage", "https://www.churchofjesuschrist.org/study/general-conference/1992/10/a-loving-communicating-god", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/you-are-not-alone", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/what-doest-ye-for-christ", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/unclutter-your-life", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/to-learn-to-do-to-be", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-tongue-can-be-a-sharp-sword", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-spirit-of-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-royal-law", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-relief-society-and-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-pure-love-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-mission-of-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/the-blessings-of-sacrifice", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/take-up-his-cross", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/spit-and-mud-and-kigatsuku", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/spiritual-healing", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/seeking-the-good", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/please-hear-the-call", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/patience-in-affliction", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/our-moral-environment", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/our-great-mission", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/nourish-the-flock-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/my-servant-joseph", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/memories-of-yesterday-counsel-for-today", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/look-up-and-press-on", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/healing-the-tragic-scars-of-abuse", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/gratitude-for-the-goodness-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/faith-and-good-works", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/doors-of-death", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/come-to-the-house-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/charity-never-faileth", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/but-the-labourers-are-few", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/believe-his-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/be-men", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/an-attitude-of-gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/a-prisoner-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/a-more-excellent-way", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/a-mighty-force-for-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/a-disciple-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1992/04/a-chosen-generation", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/today-a-day-of-eternity", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/to-a-missionary-son", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/these-were-our-examples", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/these-are-your-days", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-voice-is-still-small", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-ultimate-inheritance-an-allegory", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-lords-day", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-lord-bless-you", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-gospel-a-global-faith", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-family-of-the-prophet-joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-dual-aspects-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-conversion-process", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/the-call-an-eternal-miracle", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/testimony", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/strengthen-the-feeble-knees", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/reverence-invites-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/repentance", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/rejoice-in-every-good-thing", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/precious-children-a-gift-from-god", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/our-solemn-responsibilities", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/our-mission-of-saving", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/obtaining-help-from-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/light", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/joy-and-mercy", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/jesus-the-christ", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/fruits-of-the-restored-gospel-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/follow-christ-in-word-and-deed", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/daughters-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/covenants-and-ordinances", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/christ-is-the-light-to-all-mankind", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/charity-suffereth-long", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/called-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/bring-up-your-children-in-light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/becoming-self-reliant", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/be-thou-an-example", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/be-an-example-of-the-believers", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/and-now-you-will-know", "https://www.churchofjesuschrist.org/study/general-conference/1991/10/a-time-for-preparation", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/yagottawanna", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/what-god-hath-joined-together", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/to-honor-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/to-draw-closer-to-god", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/the-state-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/the-savior-and-joseph-smith-alike-yet-unlike", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/the-power-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/the-moving-of-the-water", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/teach-the-children", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/sunday-worship-service", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/repentance", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/redemption-of-the-dead", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/prophets", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/peace-within", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/peace", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/never-alone", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/making-the-right-decisions", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/listen-to-learn", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/linking-the-family-of-man", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/lest-ye-be-wearied-and-faint-in-your-minds", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/honour-thy-father-and-thy-mother", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/his-latter-day-kingdom-has-been-established", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/change", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/called-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/beware-lest-thou-forget-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/before-i-build-a-wall", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/a-voice-of-gladness", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/a-royal-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/a-pattern-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1991/04/a-crown-of-thorns-a-crown-of-glory", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/witnesses-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/what-is-truth", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/this-work-will-go-forward", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/these-things-are-manifested-unto-us-plainly", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-word-of-wisdom", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-value-of-a-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-straight-and-narrow-way", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-resurrection", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-many-witnesses-of-jesus-christ-and-his-work", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-lighthouse-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/the-greatest-challenge-in-the-world-good-parenting", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/that-we-may-touch-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/temples-and-work-therein", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/serve-god-acceptably-with-reverence-and-godly-fear", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/redemption-the-harvest-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/put-off-the-natural-man-and-come-off-conqueror", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/purity-precedes-power", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/no-more-strangers-and-foreigners", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/mormon-should-mean-more-good", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/kindness-a-part-of-gods-plan", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/in-counsellors-there-is-safety", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/in-all-things-give-thanks", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/hour-of-conversion", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/happiness-is-homemade", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/god-be-with-you-till-we-meet-again", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/follow-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/follow-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/draw-strength-from-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/days-never-to-be-forgotten", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/crickets-can-be-destroyed-through-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/covenants", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/come-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/choices", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/changing-channels", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/an-eternal-key", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/a-thousand-times", "https://www.churchofjesuschrist.org/study/general-conference/1990/10/a-pattern-in-all-things", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/ye-have-done-it-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/world-peace", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/who-is-a-true-friend", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/thus-shall-my-church-be-called", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-spirituality-of-service", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-resurrection", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-motorcycle-ride", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-lords-way", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-library-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-greatest-joy", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/the-aaronic-priesthood-return-with-honor", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/teachings-of-a-loving-father", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/teach-them-correct-principles", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/standing-as-witnesses-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/some-scriptural-lessons-on-leadership", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/small-and-simple-things", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/sacred-resolves", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/rise-to-a-larger-vision-of-the-work", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/preparing-the-heart", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/personal-integrity", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/one-small-step-for-a-man-one-giant-leap-for-mankind", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/neither-boast-of-faith-nor-of-mighty-works", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/my-brothers-keeper", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/keeping-the-temple-holy", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/instruments-to-accomplish-his-purposes", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/i-will-go-and-do", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/home-first", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/gratitude-as-a-saving-principle", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/finding-the-way-back", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/filling-the-whole-earth", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/family-traditions", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/endure-it-well", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/conference-is-here", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/choose-you-this-day", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/blessed-are-the-merciful", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/a-little-child-shall-lead-them", "https://www.churchofjesuschrist.org/study/general-conference/1990/04/a-latter-day-samaritan", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/woman-of-infinite-worth", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/windows", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/winding-up-our-spiritual-clocks", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/to-the-elderly-in-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-value-of-preparation", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-summer-of-the-lambs", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-service-that-counts", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-scourge-of-illicit-drugs", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-sacrament-and-the-sacrifice", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-peaceable-followers-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/the-golden-thread-of-choice", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/stalwart-and-brave-we-stand", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/running-your-marathon", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/rise-to-the-stature-of-the-divine-within-you", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/revelation-in-a-changing-world", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/remembrance-and-gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/remember-him", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/overcoming-adversity", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/murmur-not", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/modern-pioneers", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/love", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/look-to-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/learning-to-recognize-answers-to-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/keep-the-faith", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/identity-of-a-young-woman", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/he-loved-them-unto-the-end", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/good-memories-are-real-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/follow-him", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/duties-rewards-and-risks", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/continuous-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/chastity-the-source-of-true-manhood", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/an-eye-single-to-the-glory-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/an-ensign-to-the-nations", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/a-word-of-benediction", "https://www.churchofjesuschrist.org/study/general-conference/1989/10/a-lifetime-of-learning", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/university-for-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/to-young-women-and-men", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/to-the-children-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-way-to-perfection", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-god-that-doest-wonders", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-gift-of-the-holy-ghost-a-sure-compass", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-effects-of-television", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-canker-of-contention", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/the-beauty-and-importance-of-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/thanks-be-to-god", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/seeds-of-renewal", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/proclaim-my-gospel-from-land-to-land", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/our-kindred-family-expression-of-eternal-love", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/on-being-worthy", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/now-is-the-time", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/making-points-for-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/magnify-your-calling", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/lord-when-saw-we-thee-an-hungred", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/let-love-be-the-lodestar-of-your-life", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/irony-the-crust-on-the-bread-of-adversity", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/go-for-it", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/follow-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/beware-of-pride", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/alternate-voices", "https://www.churchofjesuschrist.org/study/general-conference/1989/04/adversity-and-the-divine-purpose-of-mortality", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/what-went-ye-out-to-see", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/what-think-ye-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/we-have-a-work-to-do", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/true-friends-that-lift", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/train-up-a-child", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/to-the-single-adult-sisters-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/to-the-bishops-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-supernal-gift-of-the-atonement", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-soil-and-roots-of-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-royal-law-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-quality-of-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-priesthood-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-measure-of-our-hearts", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-healing-power-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/the-hand-of-fellowship", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/stand-for-truth-and-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/making-righteous-choices-at-the-crossroads-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/inviting-others-to-come-unto-christ", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/i-will-follow-gods-plan-for-me", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/i-testify", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/hallmarks-of-a-happy-home", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/goal-beyond-victory", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/funerals-a-time-for-reverence", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/flooding-the-earth-with-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/christlike-communications", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/choose-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/children-at-peace", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/blessed-from-on-high", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/becoming-a-prepared-people", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/answer-me", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/addiction-or-freedom", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/a-willing-heart", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/a-more-excellent-way", "https://www.churchofjesuschrist.org/study/general-conference/1988/10/a-call-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/you-make-a-difference", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/without-guile", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/with-god-nothing-shall-be-impossible", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/while-they-are-waiting", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/what-think-ye-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/to-the-single-adult-brethren-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/to-help-a-loved-one-in-need", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/the-highest-place-of-honor", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/the-great-commandment-love-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/the-empty-tomb-bore-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/the-aaronic-priesthood-a-gift-from-god", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/teach-children-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/solutions-from-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/shepherds-of-israel", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/seek-the-blessings-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/our-lord-and-savior", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/in-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/he-is-risen", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/happiness-through-service", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/gods-love-for-his-children", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/for-i-will-lead-you-along", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/daughter-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/come-unto-christ-and-be-perfected-in-him", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/because-of-your-steadiness", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/because-i-pray-for-you", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/atonement-agency-accountability", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/assurance-that-comes-from-knowing", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/an-invitation-to-exaltation", "https://www.churchofjesuschrist.org/study/general-conference/1988/04/always-remember-him", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/yet-thou-art-there", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/to-the-fathers-in-israel", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/they-re-not-really-happy", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/there-are-many-gifts", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/the-opening-and-closing-of-doors", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/the-light-and-life-of-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/the-great-imitator", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/the-dawning-of-a-new-day-in-africa", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/take-not-the-name-of-god-in-vain", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/strengthening-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/selfless-service", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/sacrifice-and-self-sufficiency", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/overcoming-challenges-along-lifes-way", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/our-divine-constitution", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/opportunities-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/never-give-up", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/missionary-memories", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/lord-increase-our-faith", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/looking-beyond-the-mark", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/lessons-from-eve", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/keys-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/in-the-service-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/i-will-go-and-do", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/follow-the-brethren", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/finding-joy-in-life", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/ethics-and-honesty", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/come-unto-christ", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/called-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/balm-of-gilead", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/a-meaningful-celebration", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/a-doorway-called-love", "https://www.churchofjesuschrist.org/study/general-conference/1987/10/a-champion-of-youth", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/will-i-be-happy", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/what-it-means-to-be-a-saint", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/united-in-building-the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/to-the-home-teachers-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-will-within", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-saviors-visit-to-america", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-lengthened-shadow-of-the-hand-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-book-of-mormons-witness-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-book-of-mormon-and-the-doctrine-and-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/the-blessings-of-being-unified", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/tears-trials-trust-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/spiritual-security", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/some-have-compassion-making-a-difference", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/reverence-and-morality", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/priesthood-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/patience-a-key-to-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/overcome-even-as-i-also-overcame", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/no-shortcuts", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/my-neighbor-my-brother", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/looking-to-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/life-after-life", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/keeping-lifes-demands-in-balance", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/i-am-an-adult-now", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/covenants", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/by-faith-and-hope-all-things-are-fulfilled", "https://www.churchofjesuschrist.org/study/general-conference/1987/04/am-i-a-living-member", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/your-patriarchal-blessing-a-liahona-of-light", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/we-proclaim-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/unwanted-messages", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/touching-the-hearts-of-less-active-members", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/to-the-young-women-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-war-we-are-winning", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-spark-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-lords-touchstone", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-light-of-hope", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-joy-of-honest-labor", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-gift-of-modern-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-father-son-and-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/the-book-of-mormon-keystone-of-our-religion", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/spiritual-crevasses", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/shake-off-the-chains-with-which-ye-are-bound", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/pulling-in-the-gospel-net", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/presidents-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/my-son-and-yours-each-a-remarkable-one", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/missionary-work-is-the-lifeblood-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/little-children", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/joy-cometh-in-the-morning", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/i-will-look-unto-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/hope-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/happiness-and-joy-in-temple-work", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/godly-characteristics-of-the-master", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/god-will-yet-reveal", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/developing-faith", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/courage-counts", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/come-back-to-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/brothers-keeper", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/a-time-for-hope", "https://www.churchofjesuschrist.org/study/general-conference/1986/10/a-father-speaks", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/welfare-principles-to-guide-our-lives-an-eternal-plan-for-the-welfare-of-mens-souls", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/we-love-you-please-come-back", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/to-the-youth-of-the-noble-birthright", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/they-taught-and-did-minister-one-to-another", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-things-of-my-soul", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-responsibility-for-welfare-rests-with-me-and-my-family", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-question-of-a-mission", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-power-of-the-word", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-law-of-the-fast", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-kingdom-rolls-forth-in-south-america", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-greatest-news-of-all-times-is-that-jesus-lives", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/the-call-of-duty", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/sixteen-years-as-a-witness", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/reverent-and-clean", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/principles-and-programs", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/in-the-lords-own-way", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/happiness", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/come-and-partake", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/cleansing-the-inner-vessel", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/called-and-prepared-from-the-foundation-of-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/be-of-good-cheer", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/an-apostles-witness-of-the-resurrection", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/a-sacred-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/a-provident-plan-a-precious-promise", "https://www.churchofjesuschrist.org/study/general-conference/1986/04/a-prophet-chosen-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/worthy-fathers-worthy-sons", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/whats-the-difference", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/those-who-love-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-only-true-church", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-oath-and-covenant-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-holy-scriptures-letters-from-home", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-heavens-declare-the-glory-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-gospel-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-gospel-lifeline", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/the-abundant-life", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/ten-gifts-from-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/self-mastery", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/rejoice-in-this-great-era-of-temple-building", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/questions-and-answers", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/premortality-a-glorious-reality", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/peace-a-triumph-of-principles", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/let-us-move-this-work-forward", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/let-mercy-temper-justice", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/lessons-from-the-atonement-that-help-us-to-endure-to-the-end", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/joseph-smith-the-chosen-instrument", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/joined-together-in-love-and-faith", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/in-response-to-the-call", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/i-confer-the-priesthood-of-aaron", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/fast-day", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/draw-near-unto-me-through-obedience", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/draw-near-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/draw-near-to-him-in-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/can-there-any-good-thing-come-out-of-nazareth", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/by-their-fruits-ye-shall-know-them", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/born-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/as-i-have-loved-you", "https://www.churchofjesuschrist.org/study/general-conference/1985/10/adventures-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/willing-to-submit", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/to-please-our-heavenly-father", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/this-is-the-work-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-victory-over-death", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-spirit-of-the-gathering", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-spirit-giveth-life", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-resurrection", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-resurrected-christ", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-purifying-power-of-gethsemane", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-mantle-of-a-bishop", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-joy-of-service", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-invitation-of-the-master", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/the-answers-will-come", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/taking-upon-us-the-name-of-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/spencer-w-kimball-a-true-disciple-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/set-some-personal-goals", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/selflessness-a-pattern-for-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/reverence-for-life", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/pursuing-excellence", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/preparing-yourselves-for-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/prepare-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/our-responsibility-to-share-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/look-for-the-beautiful", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/hold-up-your-light", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/he-is-in-charge", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/god-has-a-work-for-us-to-do", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/from-such-turn-away", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/ears-to-hear", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/confidence-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/christ-our-passover", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/born-of-goodly-parents", "https://www.churchofjesuschrist.org/study/general-conference/1985/04/agency-and-accountability", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/young-women-striving-together", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/write-down-a-date", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/why-do-we-serve", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/when-i-was-called-as-a-scoutmaster", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-works-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-power-of-keeping-the-sabbath-day-holy", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-pattern-of-our-parentage", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-joy-of-the-penetrating-light", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-joy-of-service", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-gospel-and-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-good-and-faithful-servants", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-faith-of-our-people", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-cornerstones-of-our-faith", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-caravan-moves-on", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-banner-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/the-aaronic-priesthood-pathway", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/striving-together-transforming-our-beliefs-into-action", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/spiritual-power", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/service-in-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/protect-the-spiritual-power-line", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/prepare-for-a-mission", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/personal-morality", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/out-of-obscurity", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/master-the-tempest-is-raging", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/live-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/learning-our-fathers-will", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/keeping-the-covenants-we-make-at-baptism", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/if-thou-endure-it-well", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/if-thou-art-faithful", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/he-returned-speedily", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/eternal-marriage", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/coordination-and-cooperation", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/by-their-fruits-ye-shall-know-them", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/and-why-call-ye-me-lord-lord-and-do-not-the-things-which-i-say", "https://www.churchofjesuschrist.org/study/general-conference/1984/10/a-new-witness-for-christ", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/youth-of-the-noble-birthright", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/whos-on-the-lords-team", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/warmed-by-the-fires-of-their-lives", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/upheld-by-the-prayers-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-sure-sound-of-the-trumpet", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-simplicity-of-gospel-truths", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-practice-of-truth", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-pharisee-and-the-publican", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-miracle-made-possible-by-faith", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-magnificent-vision-near-palmyra", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-great-plan-of-the-eternal-god", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/the-church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/special-witnesses-for-christ", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/small-acts-lead-to-great-consequences", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/restoring-the-lost-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/patterns-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/our-commission-to-take-the-gospel-to-all-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/missions-only-you-can-decide", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/marriage-and-divorce", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/jesus-the-christ-the-words-and-their-meaning", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/i-love-the-sisters-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/home-and-family-a-divine-eternal-pattern", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/go-ye-therefore-and-teach-all-nations", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/covenants-ordinances-and-service", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/count-your-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/counsel-to-the-saints", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/coming-through-the-mists", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/choose-the-good-part", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/call-to-the-holy-apostleship", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/building-your-eternal-home", "https://www.churchofjesuschrist.org/study/general-conference/1984/04/a-generation-prepared-to-make-wise-choices", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/your-sorrow-shall-be-turned-to-joy", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/what-think-ye-of-the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/what-manner-of-men-ought-we-to-be", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-word-is-commitment", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-power-to-make-a-difference", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-mystery-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-keystone-of-our-religion", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-house-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-blessings-of-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/the-angel-moroni-came", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/removing-the-poison-of-an-unforgiving-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/prepare-to-teach-his-children", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/parents-concern-for-children", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/parent-child-interviews", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/our-responsibility-to-take-the-gospel-to-the-ends-of-the-earth", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/our-father-which-art-in-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/live-up-to-your-inheritance", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/let-us-go-forward", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/labels", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/joseph-the-seer", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/jesus-christ-our-savior-and-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/how-do-you-know", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/honour-thy-father-and-thy-mother", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/god-grant-us-faith", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/friend-or-foe", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/except-ye-are-one", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/called-as-if-he-heard-a-voice-from-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/become-a-star-thrower", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/be-not-deceived", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/be-a-peacemaker", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/agency-and-love", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/agency-and-accountability", "https://www.churchofjesuschrist.org/study/general-conference/1983/10/a-season-for-strength", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/within-the-clasp-of-your-arms", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/valiance-in-the-drama-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/unity", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/train-up-a-child", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/to-forgive-is-divine", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/the-keys-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/the-gospel-of-jesus-christ-and-basic-needs-of-people", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/that-ye-may-have-roots-and-branches", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/teaching-no-greater-call", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/straightway", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/shine-as-lights-in-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/repentance", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/receiving-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/profanity-and-swearing", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/overpowering-the-goliaths-in-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/muddy-feet-and-white-shirts", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/he-slumbers-not-nor-sleeps", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/finding-ones-identity", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/fear-not-to-do-good", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/evidences-of-the-resurrection", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/enriching-family-life", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/creator-and-savior", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/climbing-to-higher-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/anonymous", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/agency-and-control", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/a-royal-generation", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/a-principle-with-a-promise", "https://www.churchofjesuschrist.org/study/general-conference/1983/04/a-call-to-the-priesthood-feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/what-this-work-is-all-about", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-seven-christs", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-priesthood-of-aaron", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-power-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-pearl-of-great-price", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-meaning-of-maturity", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-lord-expects-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-celestial-nature-of-self-reliance", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-blessings-we-receive-as-we-meet-the-challenges-of-economic-stress", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/the-blessings-of-family-work-projects", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/run-boy-run", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/revitalizing-aaronic-priesthood-quorums", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/reach-out-in-love-and-kindness", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/pure-religion", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/prepare-the-heart-of-your-son", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/preparation-for-tomorrow", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/my-soul-delighteth-in-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/love-all", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/look-to-god", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/let-us-do-as-we-have-been-counseled", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/lds-hymns-worshiping-with-song", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/however-faint-the-light-may-glow", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/how-we-promote-activation", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/gratitude-and-thanksgiving", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/fundamentals-of-enduring-family-relationships", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/for-a-bishop-must-be-blameless", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/faith-the-force-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/commitment-to-god", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/believers-and-doers", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/behold-my-beloved-son-in-whom-i-am-well-pleased", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/be-of-good-cheer", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/be-a-friend-a-servant-a-son-of-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/application-of-welfare-principles-in-the-home-a-key-to-many-family-problems", "https://www.churchofjesuschrist.org/study/general-conference/1982/10/activating-young-men-of-the-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/work-and-welfare-a-historical-perspective", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/what-the-gospel-teaches", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/what-temples-are-for", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/we-believe-in-being-honest", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/valiant-in-the-testimony-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/true-greatness", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/tithing-an-opportunity-to-prove-our-faithfulness", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/this-is-no-harm", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-value-of-work", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-resurrection-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-power-of-family-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-lord-is-at-the-helm", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-gospel-the-foundation-for-our-career", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-future-history-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-first-and-the-last-words", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/the-doctrine-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/spiritual-guides-for-teachers-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/sailing-safely-the-seas-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/remember-the-mission-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/reach-for-joy", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/priesthood-activation", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/pondering-strengthens-the-spiritual-life", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/love-is-the-power-that-will-cure-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/let-us-improve-ourselves", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/let-us-go-up-to-the-house-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/jesus-is-our-savior", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/integrity-the-mother-of-many-virtues", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/her-children-arise-up-and-call-her-blessed", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/hearts-so-similar", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/gods-love-for-us-transcends-our-transgressions", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/five-million-members-a-milestone-and-not-a-summit", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/even-as-i-am", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/employment-challenges-in-the-1980s", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/beginning-again", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/an-invitation-to-grow", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/a-lasting-marriage", "https://www.churchofjesuschrist.org/study/general-conference/1982/04/a-brother-offended", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/who-hath-believed-our-report", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/when-ye-are-prepared-ye-shall-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/to-follow-or-not-that-is-the-question", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-strength-of-the-kingdom-is-within", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-plan-for-happiness-and-exaltation", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-perfect-law-of-liberty", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-ministry-of-the-aaronic-priesthood-holder", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-little-things-and-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-light-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-honored-place-of-woman", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-expanding-inheritance-from-joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/the-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/teach-the-why", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/sanctification-through-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/remember-who-you-are", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/relief-society-in-welfare", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/relief-society-in-times-of-transition", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/people-to-people", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/opposition-to-the-work-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/o-divine-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/my-specialty-is-mercy", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/my-sheep-hear-my-voice", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/love-extends-beyond-convenience", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/living-welfare-principles", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/joseph-smith-prophet-to-our-generation", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/he-is-risen", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/give-with-wisdom-that-they-may-receive-with-dignity", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/four-bs-for-boys", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/follow-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/finding-joy-by-serving-others", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/faith-the-essence-of-true-religion", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/except-a-man-be-born-again", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/examples-from-the-life-of-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/conference-time", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/charity-never-faileth", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/being-strengthened-through-service", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/be-ye-prepared", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/an-opportunity-for-continual-learning", "https://www.churchofjesuschrist.org/study/general-conference/1981/10/a-safe-place-for-marriages-and-families", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/we-serve-that-which-we-love", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/we-are-on-the-lords-errand", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/we-are-called-to-spread-the-light", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/upon-this-rock", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/turning-the-hearts", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-restoration-of-israel-to-the-lands-of-their-inheritance", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-responsibility-of-young-aaronic-priesthood-bearers", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-need-to-teach-personal-and-family-preparedness", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-long-line-of-the-lonely", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-joseph-smith-iii-document-and-the-keys-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-dignity-of-self", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/the-basic-principles-of-church-welfare", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/rendering-service-to-others", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/reach-out-to-our-fathers-children", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/reach-for-the-stars", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/providing-for-our-needs", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/our-responsibility-to-care-for-our-own", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/obedience-full-obedience", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/no-man-shall-add-to-or-take-away", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/moral-values-and-rewards", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/marriage", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/love-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/light-and-truth", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/life-a-great-proving-ground", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/in-saving-others-we-save-ourselves", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/he-is-there", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/great-things-required-of-their-fathers", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/gracias", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/gospel-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/follow-the-fundamentals", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/fast-offerings-fulfilling-our-responsibility-to-others", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/church-audit-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/call-of-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/building-bridges-to-faith", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/blessings-in-self-reliance", "https://www.churchofjesuschrist.org/study/general-conference/1981/04/a-report-of-my-stewardship", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/welfare-services-the-saviors-program", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/to-the-young-men-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/these-i-will-make-my-leaders", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-saviors-touch", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-oath-and-covenant-which-belongeth-to-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-net-gathers-of-every-kind", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-lord-god-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-law-of-tithing", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-keys-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-household-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-house-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-doctrines-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-circle-of-sisters", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-choice", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-bond-of-charity", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-blessing-of-a-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/the-bishop-center-stage-in-welfare", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/singleness-how-relief-society-can-help", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/seven-events-of-great-consequence", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/repentance", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/purify-our-minds-and-spirits", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/prepare-for-the-days-of-tribulation", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/prepare-every-needful-thing", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/our-thirtieth-anniversary-as-latter-day-saints", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/organize-yourselves", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/of-you-it-is-required-to-forgive", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/motherhood-and-the-family", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/miracles-among-the-lamanites", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/ministering-to-the-needs-of-members", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/let-every-man-learn-his-duty", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/learn-then-teach", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/know-the-shepherd", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/is-any-thing-too-hard-for-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/forgive-them-i-pray-thee", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/for-whatsoever-a-man-soweth-that-shall-he-also-reap", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/follow-joyously", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/families-can-be-eternal", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/do-not-weary-by-the-way", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/decide-to-decide", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/adversity-and-you", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/adam-the-archangel", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/acquaint-thyself-with-him-and-be-at-peace", "https://www.churchofjesuschrist.org/study/general-conference/1980/10/a-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/you-can-be-the-voice", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/writing-your-personal-and-family-history", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/willing-to-receive", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/where-do-we-stand", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/what-hath-god-wrought-through-his-servant-joseph", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/welfare-services-past-present-and-future", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/welfare-principles-in-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/time-out", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/the-scriptures-speak", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/the-prophet-and-the-prison", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/the-gospel-restored", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/the-coming-tests-and-trials-and-glory", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/teaching-by-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/self-accountability-and-human-progress", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/seek-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/salt-of-the-earth-savor-of-men-and-saviors-of-men", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/remarks-and-dedication-of-the-fayette-new-york-buildings", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/priesthood-councils-key-to-meeting-temporal-and-spiritual-needs", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/preparing-the-way", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/no-unhallowed-hand-can-stop-the-work", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/nauvoo-a-demonstration-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/let-us-not-weary-in-well-doing", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/introduction-to-the-proclamation", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/he-is-not-here-he-is-risen", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/god-will-have-a-tried-people", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/eternal-links-that-bind", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/do-we-all-believe-in-the-same-god", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/communion-with-the-holy-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/church-welfare-temporal-service-in-a-spiritual-setting", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/church-finance-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/celestial-marriages-and-eternal-families", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/an-example-of-what-welfare-services-can-do", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/a-tribute-to-the-rank-and-file-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/a-marvelous-work-and-a-wonder", "https://www.churchofjesuschrist.org/study/general-conference/1980/04/a-deep-commitment-to-the-principles-of-welfare-service", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/women-for-the-latter-day", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/we-will-go-with-our-young-and-with-our-old", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/we-need-a-listening-ear", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/therefore-i-was-taught", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-voice-of-the-lord-is-unto-all-people", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-role-of-righteous-women", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-role-of-a-bishop-in-the-church-welfare-program", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-relief-society-role-in-priesthood-councils", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-mystery-of-mormonism", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-governing-ones", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-gift-of-the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-contributions-of-the-prophet-joseph-smith", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/the-administration-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/teaching-our-little-women", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/send-missionaries-from-every-nation", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/reading-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/progress-through-change", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/priesthood-administration-of-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/prayers-and-answers", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/prayer-to-our-heavenly-father", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/pornography-the-deadly-carrier", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/our-sisters-in-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/our-mighty-errand", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/o-america-america", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/making-the-right-decisions", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/maintaining-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/language-a-divine-way-of-communicating", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/joseph-smith-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/happiness-now-and-forever", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/give-me-this-mountain", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/faith-in-the-lord-jesus-christ", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/establishing-the-church-welfare-services-missionaries-are-an-important-resource", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/constancy-amid-change", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/commandments-to-live-by", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/blessing-the-one", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/an-angel-from-on-high-the-long-long-silence-broke", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/after-much-tribulation-come-the-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1979/10/a-witness-and-a-warning", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/what-think-ye-of-christ-whom-say-ye-that-i-am", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/we-the-church-of-jesus-christ-of-latter-day-saints", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/to-those-searching-for-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/this-is-a-day-of-sacrifice", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-spirit-giveth-life", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-refiners-fire", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-need-for-love", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-home-as-an-educational-institution", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-heritage-of-royal-families", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/the-army-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/stand-independent-above-all-other-creatures", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/signs-of-the-true-church", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/roadblocks-to-progress", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/put-on-the-whole-armor-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/preparing-for-service-in-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/personal-and-family-financial-preparedness", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/new-emphasis-on-church-councils", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/let-us-move-forward-and-upward", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/judge-not-according-to-the-appearance", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/he-means-me", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/fundamental-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/fortify-your-homes-against-evil", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/following-christ-to-victory", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/feed-my-sheep", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/developing-temporal-plans-and-priorities", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/developing-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/church-government-through-councils", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/church-finance-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/because-i-have-a-father", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/applying-the-principles-of-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/and-peter-went-out-and-wept-bitterly", "https://www.churchofjesuschrist.org/study/general-conference/1979/04/a-personal-commitment", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/worthy-of-all-acceptation", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/womens-greatest-challenge", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/who-will-forfeit-the-harvest", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/what-are-the-blessings-of-a-mission-can-ye-tell", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/true-religion", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/thou-shalt-receive-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-worth-of-souls", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-stake-presidents-role-in-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-remarkable-example-of-the-bermejillo-mexico-branch", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-relief-society", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-last-words-of-moroni", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-joy-of-serving-a-mission", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-gospel-makes-people-happy", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-gift-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-fruit-of-our-welfare-services-labors", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-cs-of-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/the-blessing-of-church-interviews", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/successful-welfare-stewardship", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/spiritual-development", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/revelation-on-priesthood-accepted-church-officers-sustained", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/response-to-the-call", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/profiles-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/privileges-and-responsibilities-of-sisters", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/ours-is-a-shared-ancestry", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/never-be-weary-of-good-works", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/look-to-god-and-live", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/let-your-light-so-shine", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/let-there-be-no-misunderstanding", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/if-we-want-to-go-up-we-have-to-get-on", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/home-teaching-a-sacred-calling", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/hold-fast-to-the-iron-rod", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/he-hath-showed-thee-o-man-what-is-good", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/good-health-a-key-to-joyous-living", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/fundamental-principles-to-ponder-and-live", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/faith-courage-and-making-choices", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/come-listen-to-a-prophets-voice", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/come-home-felila", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/caring-for-the-poor-a-covenantal-obligation", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/behold-your-little-ones", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/be-one-with-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/attending-to-personal-and-family-preparedness", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/an-eternal-hope-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/a-disciple-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1978/10/a-basis-for-faith-in-the-living-god", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/ye-shall-know-the-truth", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/worthy-of-proper-recommendation", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/what-would-the-savior-have-me-do", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/what-is-truth", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/welfare-services-begins-with-you", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/we-are-his-stewards", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-women-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-true-way-of-life-and-salvation", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-storehouse-resource-system", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-second-coming-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-royal-law-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-primary-enriches-the-lives-of-children", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-prayer-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-poetry-of-success", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/the-morning-breaks-the-shadows-flee", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/strengthening-the-family-the-basic-unit-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/staying-unspotted-from-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/solving-emotional-problems-in-the-lords-own-way", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/seek-out-your-spiritual-leader", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/revelation", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/response-to-the-call", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/priesthood-responsibilities", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/prayer-and-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/not-my-will-but-thine", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/no-time-for-contention", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/may-the-kingdom-of-god-go-forth", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/making-your-marriage-successful", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/listen-to-the-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/in-the-time-of-old-age", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/i-did-not-reach-this-place-by-myself", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/grieve-not-the-holy-spirit-lest-we-lose-it", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/evidence-of-things-not-seen", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/everything-dear", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/decision", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/church-finance-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/bind-on-thy-sandals", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/being-anxiously-engaged", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/becoming-the-pure-in-heart", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/be-not-faithless", "https://www.churchofjesuschrist.org/study/general-conference/1978/04/a-haven-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/young-women-real-guardians", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/why-me-o-lord", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/welfare-services-the-gospel-in-action", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/welfare-responsibilities-of-the-priesthood-quorums", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/we-have-been-there-all-the-time", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/three-things-to-share", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/they-didn-t-give-up", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-way-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-tragic-cycle", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-things-of-god-and-man", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-ten-blessings-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-safety-of-the-gospel-law", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-role-of-bishops-in-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-power-of-forgiveness", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-light-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-foundations-of-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-fathers-duty-to-foster-the-welfare-of-his-family", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-enriching-of-marriage", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-blessings-of-righteous-obedience", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/the-balm-of-gilead", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/she-stretcheth-out-her-hand-to-the-poor", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/service-saves", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/seeing-the-five-a-s", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/sacrifice-missionary-style", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/rated-a", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/obeying-the-right-voice", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/letter-to-a-returned-missionary", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/latter-day-samaritans", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/jesus-the-christ", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/it-was-a-miracle", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/hallowed-be-thy-name", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/father-your-role-your-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/a-vision-of-the-law-of-the-fast", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/a-special-moment-in-church-history", "https://www.churchofjesuschrist.org/study/general-conference/1977/10/a-message-to-the-rising-generation", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/your-jericho-road", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/what-constitutes-the-true-church", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/we-beheld-his-glory", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/thoughts-on-the-sacrament", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-validity-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-role-of-the-stake-bishops-council-in-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-purpose-of-church-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-power-of-plainness", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-mediator", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-lord-expects-his-saints-to-follow-the-commandments", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-living-christ", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-light-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-greatest-brotherhood", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-daily-portion-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/the-beatitudes-and-our-perfection", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/revelation-the-word-of-the-lord-to-his-prophets", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/rendering-assistance-in-the-lords-way", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/presentation-of-scouting-award", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/prepare-now-for-your-mission", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/prayer", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/our-great-potential", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/neither-cryptic-nor-hidden", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/ministering-to-needs-through-the-lords-storehouse-system", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/ministering-to-needs-through-lds-social-services", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/lengthening-your-stride-as-a-missionary", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/joseph-the-seer", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/integrity", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/god-moves-in-a-mysterious-way-his-wonders-to-perform", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/follow-the-living-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/do-unto-others", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/did-not-our-heart-burn-within-us", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/come-let-israel-build-zion", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/come-know-the-lord-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/church-finance-committee-report", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/but-be-ye-doers-of-the-word", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/a-thousand-witnesses", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/a-silver-lining", "https://www.churchofjesuschrist.org/study/general-conference/1977/04/a-call-to-action", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/your-gift-from-god", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/you-never-know-who-you-may-save", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/which-road-will-you-travel", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/welfare-services-essentials-the-bishops-storehouse", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/we-believe-in-being-honest", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/we-are-a-covenant-making-people", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/to-die-well", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/there-is-the-light", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-temptations-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-spirit-of-missionary-work", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-simplicity-in-christ", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-savor-of-men", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-reconstitution-of-the-first-quorum-of-the-seventy", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-purpose-of-conferences", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-making-of-a-missionary", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-lords-support-system", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-lord-offers-everyone-a-way-back-from-sin", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-living-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-impact-teacher", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-greatest-thing-in-my-life", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/the-dead-who-die-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/teachings-of-the-apostle-paul", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/she-is-not-afraid-of-the-snow-for-her-household", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/search-the-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/ready-to-work-long-hours", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/proper-self-management", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/principles-of-welfare", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/perfecting-the-saints", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/parenthood", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/our-priceless-heritage", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/our-own-liahona", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/our-goal-is-perfection", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/notwithstanding-my-weakness", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/more-joy-and-rejoicing", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/loving-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/in-mine-own-way", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/i-will-never-be-the-same-again", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/i-have-gained", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/i-am-the-vine-ye-are-the-branches", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/go-and-do-the-work", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/follow-it", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/families-are-forever", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/extending-missionary-service", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/everything-to-gain-nothing-to-lose", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/dikes-versus-living-water", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/acquiring-and-managing-production-projects", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/a-report-on-the-churchs-participation-in-americas-bicentennial-celebration", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/a-report-and-a-challenge", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/a-program-for-man", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/a-personal-relationship-with-the-savior", "https://www.churchofjesuschrist.org/study/general-conference/1976/10/a-gospel-of-conversion", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/you-are-your-greatest-treasure", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/who-is-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/value-of-the-holy-scriptures", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/these-four-things", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/there-am-i-in-the-midst-of-them", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-word-of-wisdom", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-way-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-value-of-people", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-stone-cut-without-hands", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-still-small-voice", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-right-to-choose", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-message-of-elijah", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-matter-of-personal-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-leaves-are-commencing-to-show-on-the-fig-tree", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-lamanites-must-rise-in-majesty-and-power", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-constitution-a-glorious-standard", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-church-employment-system", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-church-and-the-family-in-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-book-of-mormon", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/the-blessing-of-building-a-temple", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/that-we-may-be-one", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/teach-lds-women-self-sufficiency", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/spiritual-crocodiles", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/shout-it-from-the-rooftops", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/seeking-eternal-riches", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/seek-not-for-riches-but-for-wisdom", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/relationships", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/priesthood-authority-and-power", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/on-accepting-the-call", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/learn-obedience-and-service", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/joseph-smith-the-mighty-prophet-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/jesus-of-nazareth-savior-and-king", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/if-they-will-but-serve-the-god-of-the-land", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/hopeless-dawn-joyful-morning", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/he-is-the-son-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/food-storage", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/family-preparedness", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/family-communications", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/easter-thoughts", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/church-welfare-services-basic-principles", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/but-they-were-in-one", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/boys-need-heroes-close-by", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/as-a-man-soweth", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/are-you-taking-your-priesthood-for-granted", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/are-you-a-member-missionary", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/are-we-following-christs-pattern", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/an-honest-man-gods-noblest-work", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/a-missionary-opportunity", "https://www.churchofjesuschrist.org/study/general-conference/1976/04/a-living-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/you-too-must-know", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/why-can-t-we", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/we-can-t-do-it-alone", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/we-are-sent-for-the-last-time", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/to-make-a-people-prepared-for-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/to-cleanse-our-souls", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/there-is-still-much-to-do", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-worlds-greatest-need", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-welfare-production-distribution-department", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-vision-of-the-aaronic-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-time-to-labor-is-now", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-tabernacle", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-redemption-of-the-dead", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-privilege-of-holding-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-power-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-laws-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-language-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-keys-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-importance-of-reputation", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-faith-of-a-child", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/the-developing-welfare-services-department", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/success-stories", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/spoken-from-their-hearts", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/relief-societys-role-in-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/prophets-and-prophecy", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/prepare-for-honorable-employment", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/opposing-evil", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/once-or-twice-in-a-thousand-years", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/oh-beautiful-for-patriot-dream", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/my-heritage-is-choice", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/my-gratitude", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/love-takes-time", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/let-all-thy-doings-be-unto-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/immanuel-god-with-us", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/hear-ye-him", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/for-they-loved-the-praise-of-men-more-than-the-praise-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/for-the-time-will-come-when-they-will-not-endure-sound-doctrine", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/family-research", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/family-home-evening", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/faith-and-works-in-the-far-east", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/do-it", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/covenants-and-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/but-watchman-what-of-the-night", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/an-overview-of-church-welfare-services", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/americas-destiny", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/according-to-the-covenants", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/a-prophets-faith", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/a-message-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1975/10/a-call-to-arms", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/why-do-we-continue-to-tolerate-sin", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/why-call-me-lord-lord-and-do-not-the-things-which-i-say", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/we-need-men-of-courage", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/using-our-free-agency", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/trust-in-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/today-millions-are-waiting", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/to-bear-the-priesthood-worthily", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-way-home", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-time-is-now", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-symbol-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-sanctity-of-life", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-sabbath-day", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-roots-of-mormonism", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-road-to-happiness", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-people-who-influence-us", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-message-of-easter", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-man-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-laws-of-god-are-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/the-book-of-mormon-is-the-word-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/testimony", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/success-is-gauged-by-self-mastery", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/scouters-lead-them-to-a-mission", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/salvation-for-the-dead-a-missionary-activity", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/one-lord-one-faith-one-baptism", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/obedience-consecration-and-sacrifice", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/my-mother-gained-a-better-son", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/make-haste-to-obey", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/help-for-parents", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/feed-the-flock", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/faithful-laborers", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/faith-the-first-step", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/easter-thoughts", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/come-drink-the-living-water", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/christ-in-america", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/birth", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/anchored-in-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/an-appeal-to-prospective-elders", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/a-tribute", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/a-time-to-prepare", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/a-time-for-every-purpose", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/a-self-inflicted-purging", "https://www.churchofjesuschrist.org/study/general-conference/1975/04/a-question-of-free-agency", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/your-mission-preparation", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/why-not-now", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/why-is-my-boy-wandering-tonight", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/whos-losing", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/where-much-is-given-much-is-required", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/when-thou-art-converted-strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/what-after-death", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/we-need-to-continue-in-righteousness", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/truth-will-emerge-victorious", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/transfusion", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/to-know-god", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-saviors-program-for-the-care-of-the-aged", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-most-vital-information", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-law-of-the-fast", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-divine-power-of-repentance", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-davids-and-the-goliaths", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-blessings-of-peace", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/the-beatitudes", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/power-over-satan", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/our-responsibility-to-the-transgressor", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/our-precious-families", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/ocean-currents-and-family-influences", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/my-personal-hall-of-fame", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/making-conferences-turning-points-in-our-lives", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/is-there-not-a-cause", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/integrity", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/how-men-are-saved", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/good-habits-develop-good-character", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/god-will-not-be-mocked", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/gifts-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/for-thy-servant-heareth", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/eternal-togetherness", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/do-not-procrastinate", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/do-not-despair", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/blessed-are-the-peacemakers", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/be-valiant-in-the-fight-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/as-a-beacon-on-a-hill", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/a-testimony-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/a-new-aristocracy", "https://www.churchofjesuschrist.org/study/general-conference/1974/10/a-city-set-upon-a-hill", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/what-does-jesus-mean-to-modern-man", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/what-do-we-hear", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/we-believe-all-that-god-has-revealed", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/touchstone-of-truth", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/three-important-questions", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/three-days-in-the-tomb", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-strength-of-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-solemn-assembly", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-saviors-ministry", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-power-of-elijah", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-people-say-amen", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-paths-jesus-walked", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-marriage-that-endures", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-importance-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-family-a-divine-blessing", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/the-cause-is-just-and-worthy", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/that-the-scriptures-might-be-fulfilled", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/testimony", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/strength-of-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/response-to-a-call", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/prophecy", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/planning-for-a-full-and-abundant-life", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/parents-teach-your-children", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/mother-catch-the-vision-of-your-call", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/missionary-work-a-major-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/justice-and-mercy", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/inertia", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/i-will-pour-you-out-a-blessing", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/his-final-hours", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/hearken-unto-the-voice-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/hanging-on", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/guidelines-to-carry-forth-the-work-of-god-in-cleanliness", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/god-foreordains-his-prophets-and-his-people", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/commitment-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/chosen-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/build-your-shield-of-faith", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/boys-need-men", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/be-ye-clean-that-bear-the-vessels-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/aaronic-priesthood-stewardship", "https://www.churchofjesuschrist.org/study/general-conference/1974/04/a-time-of-urgency", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/you-shall-receive-the-spirit", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/you-are-different", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/which-way-to-shore", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/what-will-a-man-give", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/we-thank-thee-o-god-for-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/understanding-who-we-are-brings-self-respect", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/to-be-in-the-world-but-not-of-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/thou-shalt-love-thy-wife-with-all-thy-heart", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/think-on-these-things", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/there-is-need-for-repentance", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-witnesses-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-role-of-fathers", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-rewards-the-blessings-the-promises", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-path-to-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-need-for-total-commitment", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/the-gospel-of-jesus-christ-is-the-golden-door", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/revealed-truths-of-the-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/president-harold-b-lees-general-priesthood-address", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/prepare-ye", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/our-youth-modern-sons-of-helaman", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/our-fundamental-obligation-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/opposition-in-order-to-strengthen-us", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/of-the-world-or-of-the-kingdom", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/obedience", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/no-greater-honor-the-womans-role", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/love-and-forgive-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/jesus-christ-our-redeemer", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/inspiring-music-worthy-thoughts", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/i-will-go-and-do-the-things-which-the-lord-hath-commanded", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/he-took-him-by-the-hand", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/happiness-is-having-a-father-who-cares", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/gods-way-to-eternal-life", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/forgiveness-the-ultimate-form-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/closing-remarks", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/church-welfare-some-fundamentals", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/behold-thy-mother", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/become-rich-toward-god", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/adversity-and-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1973/10/a-fortune-to-share", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/youths-opportunity-to-serve", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/yellow-canaries-with-gray-on-their-wings", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/when-i-read-i-am-there", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/what-manner-of-men-as-i-am", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/what-is-a-living-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/watchman-warn-the-wicked", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/upon-judeas-plains", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/thou-mayest-choose-for-thyself", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/this-is-my-gospel", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-worth-of-souls-is-great", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-true-strength-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-rock-of-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-path-to-eternal-glory", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-family-influence", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-continuing-power-of-the-holy-ghost", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-constant-exercise-of-our-faith", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-agency-of-man", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/the-aaronic-priesthood-mia", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/success-a-journey-or-a-destination", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/strengthen-the-stakes-of-zion", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/stand-ye-in-holy-places", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/share-the-unsearchable-riches-of-christ", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/salvation-comes-through-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/reaching-the-one", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/priesthood-responsibilities", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/power-of-evil", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/now-abideth-faith-hope-and-charity", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/man-a-child-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/magnifying-ones-calling-in-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/in-his-strength", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/hold-up-your-hands", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/he-has-sent-his-messenger-to-prepare-the-way", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/go-and-do-thou-likewise", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/follow-the-leadership-of-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/consider-your-ways", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/behold-your-little-ones", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/and-always-remember-him", "https://www.churchofjesuschrist.org/study/general-conference/1973/04/a-second-witness-for-christ", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/why-the-church-of-jesus-christ-of-latter-day-saints", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/why-do-latter-day-saints-build-temples", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/what-is-a-friend", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/we-thank-thee-o-god-for-a-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/we-have-made-covenants-with-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/watch-the-switches-in-your-life", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/warnings-from-outer-space", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/to-serve-the-master", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/to-become-one-of-the-fishers", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/thy-will-be-done-o-lord", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/three-pledges", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/the-sure-word-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/the-saints-securely-dwell", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/the-priesthood-and-its-presidency", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/teach-the-gospel-of-salvation", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/strange-creeds-of-christendom", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/spiritual-famine", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/pollution-of-the-mind", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/planting-gospel-seeds-of-spirituality", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/may-the-kingdom-of-god-go-forth", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/live-above-the-law-to-be-free", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/listen-to-a-prophets-voice", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/light-and-knowledge-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/keep-the-commandments", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/i-know-that-my-redeemer-lives", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/how-to-gain-a-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/home-teachers-watchmen-over-the-church", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/having-been-born-of-goodly-parents", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/harmony-in-the-home", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/hands", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/genealogy-a-personal-responsibility", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/every-man-in-his-own-place", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/entrance-into-the-kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/caring-for-the-poor-and-needy", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/by-love-serve-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/becoming-a-somebody", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/another-prophet-now-has-come", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/an-instrument-in-the-hands-of-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/altar-tent-well", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/admonitions-for-the-priesthood-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1972/10/a-blessing-for-the-saints", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/why-stay-morally-clean", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/whence-cometh-our-peace", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/what-will-the-church-do-for-you-a-man", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/what-is-your-destination", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/we-are-called-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-true-church", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-testimony-of-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-strength-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-priesthood-a-royal-army", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-miracle-of-missionary-work", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-last-dispensation", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-importance-of-prayer", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-importance-of-a-personal-testimony", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-fullness-of-the-gospel-in-each-mans-language", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-covenant-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/the-aaronic-priesthood-a-sure-foundation", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/successful-parenthood-a-noteworthy-accomplishment", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/setting-the-example-in-the-home", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/salvation-and-exaltation", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/priesthood-its-power-and-vitality", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/peace", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/our-witness-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/missionary-training-begins-early", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/medicine-for-the-soul", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/mans-eternal-horizon", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/knowing-god", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/know-thyself-control-thyself-give-thyself", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/keep-the-lines-of-communication-strong", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/judge-not-that-ye-be-not-judged", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/joy-through-christ", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/finishers-wanted", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/eternal-keys-and-the-right-to-preside", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/courts-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/counsel-to-the-saints-and-to-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/civic-standards-for-the-faithful-saints", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/be-a-missionary-always-everywhere-you-go", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/am-i-my-brothers-keeper", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-time-of-decision", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-teacher", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-prophets-blessing", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-people-of-sound-judgment", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-missionary-and-his-message", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-foundation-whereon-men-cannot-fall", "https://www.churchofjesuschrist.org/study/general-conference/1972/04/a-challenge-to-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/you-can-get-there-from-here", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/with-hand-and-heart", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/where-art-thou", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/what-is-a-teacher", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/watch-that-ye-may-be-ready", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/turn-heavenward-our-eyes", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/thus-saith-the-lord", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/thou-shalt-not", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/this-same-jesus", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/this-is-my-beloved-son", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-vitality-of-love", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-things-that-matter-most", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-ten-commandments", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-sifting", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-purpose-of-life-to-be-proved", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-only-true-and-living-church", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-nobility-of-man-in-choosing-good-over-evil", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-living-christ", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/the-light-shineth", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/strive-for-excellence", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/strengthen-thy-brethren", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/should-the-commandments-be-rewritten", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/satans-thrust-youth", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/sacrifice-still-brings-forth-blessings", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/responsibilities-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/our-responsibility-to-save-the-world", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/love-unconditional", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/let-the-spirit-of-oneness-prevail", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/laying-a-foundation-for-the-millennium", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/if-ye-be-willing-and-obedient", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/i-was-in-prison-and-ye-came-unto-me", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/i-know-that-my-redeemer-liveth", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/how-to-worship", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/honesty-a-principle-of-salvation", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/glimpses-of-heaven", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/elijah-the-prophet", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/decisions", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/continuity-of-service", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/confession-and-forsaking-elements-of-genuine-repentance", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/by-love-serve-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/blessings-of-the-priesthood", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/a-time-of-testing", "https://www.churchofjesuschrist.org/study/general-conference/1971/10/a-new-health-missionary-program", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/young-people-learn-wisdom-in-thy-youth", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/ye-shall-not-fear", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/where-are-you-really-going", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/when-thou-art-converted", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/warnings-from-the-past", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/voices-of-the-past-of-the-present-of-the-future", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/unchanging-principles-of-leadership", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/todays-young-people", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/thou-shalt-not-commit-adultery", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-spirit-beareth-record", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-message-of-the-restoration", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-meaning-of-morality", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-lords-people-receive-revelation", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-law-of-abundance", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/the-iron-rod", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/teach-one-another", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/search-for-the-wanderers", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/satan-the-great-deceiver", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/prepare-every-needful-thing", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/practicing-what-we-preach", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/out-of-the-darkness", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/our-responsibilities-as-priesthood-holders", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/my-brothers-keeper", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/marriage-is-intended-to-be-forever", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/man-cannot-endure-on-borrowed-light", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/love-of-the-right", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/love-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/lost-battalions", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/life-is-eternal", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/kingdom-of-god", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/in-the-mountain-of-the-lords-house", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/ignorance-is-expensive", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/honesty-and-integrity", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/help-needed-in-the-shaded-areas", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/great-experiences", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/except-the-lord-build-the-house", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/eternal-joy-is-eternal-growth", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/drink-of-the-pure-water", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/choose-you-this-day", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/be-slow-to-anger", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/all-may-share-in-adams-blessing", "https://www.churchofjesuschrist.org/study/general-conference/1971/04/a-witness-and-a-blessing" ] for talk in talks: split = talk.split('/') year = split[-3] month = split[-2] print(year + '\t' + month)
102.074423
159
0.779159
[ "MIT" ]
thetaylors/pyConferenceTalkRandomizer
playground.py
389,516
Python
"""\ Perl code generator @copyright: 2002-2004 D.H. aka crazyinsomniac on sourceforge.net @copyright: 2012-2016 Carsten Grohmann @copyright: 2017-2020 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import os, os.path, re from codegen import BaseLangCodeWriter, BaseSourceFileContent import wcodegen, compat import logging class SourceFileContent(BaseSourceFileContent): rec_block_start = re.compile( r'^(?P<spaces>\s*)' # leading spaces r'#\s*' # comment sign r'begin\s+wxGlade:\s*' # "begin wxGlade:" statement and tailing spaces r'(?P<classname>[a-zA-Z_]+[\w:]*?)??' # class or function name (non-greedy) r'(?::{2}|\s*)' # separator between class and function / block (non-greedy) r'(?P<block>\w+)' # function / block name r'\s*$' # tailing spaces ) rec_block_end = re.compile( r'^\s*' # leading spaces r'#\s*' # comment sign r'end\s+wxGlade' # "end exGlade" statement r'\s*$' # tailing spaces ) # Less precise regex, but working :-P # Should match: package Foo; or package Foo::bar::baz ; rec_class_decl = re.compile( r'^\s*' # leading spaces r'package\s+([a-zA-Z_][\w:]*)\s*;' # "package <name>" statement r'.*$' # any character till eol ) rec_event_handler = re.compile( r'^\s*' # leading spaces r'#\s*wxGlade:\s*(?P<class>[\w:]+)::(?P<handler>\w+) <event_handler>' # wxGlade event handler # statement with class and # event handler name r'\s*$' # tailing spaces ) # Regexp to match Perl's Plain Old Documentation format; see: manpage perlpod rec_pod = re.compile( r'^\s*' # leading spaces r'=[A-Za-z_]+\w*' # match POD statement r'.*$' # any character till eol ) def build_untouched_content(self): """\ Builds a string with the contents of the file that must be left as is, and replaces the wxGlade blocks with tags that in turn will be replaced by the new wxGlade blocks WARNING: NOT YET COMPLETE -- crazyinsomniac alb - almost done :) WARNING: There is *NO* support for here documents: if you put wxGlade blocks inside a here document, you're likely going into troubles... """ BaseSourceFileContent.build_untouched_content(self) inside_block = False inside_pod = False tmp_in = self._load_file(self.name) out_lines = [] check_old_methods = [] # list of indices with set_properties or do_layout for line in tmp_in: result = self.rec_pod.match(line) if result: inside_pod = True if inside_pod: out_lines.append(line) if line.startswith('=cut'): inside_pod = False continue result = self.rec_class_decl.match(line) if result: if not self.class_name: # this is the first class declared in the file: insert the new ones before this out_lines.append( '<%swxGlade insert new_classes>' % self.nonce ) self.new_classes_inserted = True self.class_name = result.group(1) self.class_name = self.format_classname(self.class_name) self.classes.add( self.class_name ) # add the found class to the list of classes of this module out_lines.append(line) elif not inside_block: result = self.rec_block_start.match(line) if result: # replace the lines inside a wxGlade block with a tag that will be used later by add_class spaces = result.group('spaces') which_class = result.group('classname') which_block = result.group('block') if not which_class: which_class = self.class_name else: which_class = self.format_classname(which_class) self.spaces[which_class] = spaces inside_block = True if not self.class_name: out_lines.append( '<%swxGlade replace %s>' % (self.nonce, which_block) ) else: if which_block in ("__do_layout","__set_properties"): # probably to be removed check_old_methods.append( len(out_lines) ) out_lines.append( '<%swxGlade replace %s %s>' % (self.nonce, which_class, which_block) ) else: result = self.rec_event_handler.match(line) if result: which_handler = result.group('handler') which_class = self.format_classname(result.group('class')) self.event_handlers.setdefault( which_class, set() ).add( which_handler ) if self.class_name and self.is_end_of_class(line): # add extra event handlers here... out_lines.append( '<%swxGlade event_handlers %s>' % (self.nonce, self.class_name) ) out_lines.append(line) else: # ignore all the lines inside a wxGlade block if self.rec_block_end.match(line): inside_block = False if not self.new_classes_inserted: # if we are here, the previous ``version'' of the file did not contain any class, so we must add the # new_classes tag at the end of the file out_lines.append( '<%swxGlade insert new_classes>' % self.nonce ) # when moving from 0.9 to 1.0: remove empty methods "do_layout" and "set_properties" while check_old_methods: i = check_old_methods.pop(-1) if out_lines[i+1].strip()=='}': # just end of block -> remove incl. trailing empty lines self._remove_method(out_lines, i-2, i+1) # set the ``persistent'' content of the file self.content = out_lines class PerlCodeWriter(BaseLangCodeWriter, wcodegen.PerlMixin): "Code writer class for writing Perl code out of the designed GUI elements; see: BaseLangCodeWriter" _code_statements = { 'backgroundcolour': "%(objname)s->SetBackgroundColour(%(value)s);\n", 'disabled': "%(objname)s->Enable(0);\n", 'extraproperties': "%(objname)s->Set%(propname_cap)s(%(value)s);\n", 'focused': "%(objname)s->SetFocus();\n", 'foregroundcolour': "%(objname)s->SetForegroundColour(%(value)s);\n", 'hidden': "%(objname)s->Show(0);\n", 'setfont': "%(objname)s->SetFont(Wx::Font->new(%(size)s, %(family)s, " "%(style)s, %(weight)s, %(underlined)s, %(face)s));\n", 'tooltip': "%(objname)s->SetToolTipString(%(tooltip)s);\n", 'tooltip_3': "%(objname)s->SetToolTip(%(tooltip)s);\n", 'wxcolour': "Wx::Colour->new(%(value)s)", 'wxnullcolour': "Wx::NullColour", 'wxsystemcolour': "Wx::SystemSettings::GetColour(%(value)s)", } class_separator = '::' classattr_always = ['wxBoxSizer', 'wxStaticBoxSizer', 'wxGridSizer', 'wxFlexGridSizer'] indent_amount = 1 indent_symbol = '\t' indent_level_func_body = 1 language_note = '# To get wxPerl visit http://www.wxperl.it\n' \ '#\n' name_ctor = 'new' new_defaults = [] # Default class members, will be initialised during new_project() shebang = '#!/usr/bin/perl -w -- \n#\n' SourceFileContent = SourceFileContent tmpl_cfunc_end = '%(tab)sreturn $self;\n' \ '\n' \ '}\n' \ '\n' tmpl_class_end = '\n%(comment)s end of class %(klass)s\n\n1;\n\n' tmpl_class_end_nomarker = '\n\n1;\n\n' tmpl_func_event_stub = """\ sub %(handler)s { %(tab)smy ($self, $event) = @_; %(tab)s# wxGlade: %(klass)s::%(handler)s <event_handler> %(tab)swarn "Event handler (%(handler)s) not implemented"; %(tab)s$event->Skip; %(tab)s# end wxGlade } """ tmpl_func_empty = '%(tab)sreturn;\n' tmpl_sizeritem = '%s->Add(%s, %s, %s, %s);\n' tmpl_gridbagsizeritem = '%s->Add(%s, %s, %s, %s, %s);\n' tmpl_gridbagsizerspacer = '%s->Add(%s, %s, %s, %s, %s, %s);\n' tmpl_spacersize = '%s, %s' tmpl_style = \ '%(tab)s$style = %(style)s\n' \ '%(tab)s%(tab)sunless defined $style;\n' \ '\n' tmpl_toplevel_style = tmpl_style tmpl_appfile = """%(overwrite)s%(header_lines)s""" def _get_app_template(self, app, top_win): 'build template string for application' if not self.app_name: return None # XXX use Show() for frames/panels and ShowModal()/Destroy for dialogs klass = app.klass if self._use_gettext: gettext1 = ['%(tab)smy $local = Wx::Locale->new("English", "en", "en"); # replace with ??', '%(tab)s$local->AddCatalog("%(textdomain)s"); # replace with the appropriate catalog name\n'] else: gettext1 = [] if klass: ret = [ 'package %(klass)s;', '', 'use base qw(Wx::App);', 'use strict;', '%(pl_import)s', 'sub OnInit {', '%(tab)smy( $self ) = shift;', '', '%(tab)sWx::InitAllImageHandlers();', '', '%(tab)smy $%(top_win)s = %(top_win_class)s->new();', '', '%(tab)s$self->SetTopWindow($%(top_win)s);', '%(tab)s$%(top_win)s->Show(1);', '', '%(tab)sreturn 1;', '}'] if self._mark_blocks: ret.append('# end of class %(klass)s') ret += ['', 'package main;', '', 'unless(caller){'] + gettext1 + [ '%(tab)smy $%(name)s = %(klass)s->new();', '%(tab)s$%(name)s->MainLoop();', '}', ''] else: ret = ['1;', '', 'package main;', '%(pl_import)s', 'unless(caller){'] + gettext1 + [ '%(tab)slocal *Wx::App::OnInit = sub{1};', '%(tab)smy $%(name)s = Wx::App->new();', '%(tab)sWx::InitAllImageHandlers();', '', '%(tab)smy $%(top_win)s = %(top_win_class)s->new();', '', '%(tab)s$%(name)s->SetTopWindow($%(top_win)s);', '%(tab)s$%(top_win)s->Show(1);', '%(tab)s$%(name)s->MainLoop();', '}', ''] return '\n'.join(ret) def init_lang(self, app_attrs): # initial new defaults late to use the proper indent characters tab = self.tabs(1) self.new_defaults = { '$parent' : '%s$parent = undef unless defined $parent;\n' % tab, '$id' : '%s$id = -1 unless defined $id;\n' % tab, '$title' : '%s$title = "" unless defined $title;\n' % tab, '$pos' : '%s$pos = wxDefaultPosition unless defined $pos;\n' % tab, '$size' : '%s$size = wxDefaultSize unless defined $size;\n' % tab, '$name' : '%s$name = "" unless defined $name;\n\n' % tab, #'$style' is a special case } self.header_lines = [ 'use Wx qw[:allclasses];\n', 'use strict;\n' ] def add_app(self, app_attrs, top_win): # add language specific mappings if self.multiple_files: self.lang_mapping['pl_import'] = "\nuse %s;\n" % top_win.klass else: self.lang_mapping['pl_import'] = '' BaseLangCodeWriter.add_app(self, app_attrs, top_win) def generate_code_ctor(self, code_obj, is_new, tab): code_lines = [] write = code_lines.append builder = self.obj_builders[code_obj.WX_CLASS] mycn = getattr(builder, 'cn', self.cn) mycn_f = getattr(builder, 'cn_f', self.cn_f) # custom base classes support custom_base = code_obj.check_prop_nodefault('custom_base') and code_obj.custom_base.strip() or None new_signature = getattr(builder, 'new_signature', []) # generate constructor code if is_new: write('package %s;\n\n' % code_obj.klass) write('use Wx qw[:everything];\nuse base qw(%s);\nuse strict;\n\n' % code_obj.WX_CLASS.replace('wx', 'Wx::', 1)) if self._use_gettext: if self.multiple_files: self.classes[code_obj].dependencies.add( "use Wx::Locale gettext => '_T';\n" ) else: write("use Wx::Locale gettext => '_T';\n") # The dependencies have to add to the package block too because global imports are not visible inside the # package block # TODO: Don't add dependencies twice with Perl # write the module dependencies for this class (package) dep_list = sorted( self.classes[code_obj].dependencies ) if dep_list: code = self._tagcontent('dependencies', dep_list, True) write(code) write('sub new {\n') write(tab + "my( $self, %s ) = @_;\n" % ", ".join(new_signature)) if new_signature: for k in new_signature: if k in self.new_defaults: write(self.new_defaults[k]) else: new_signature = ['@_[1 .. $#_]'] # shift(@_)->SUPER::new(@_); logging.info( "%s did not declare self.new_defaults ", code_obj.klass ) elif custom_base: # custom base classes set, but "overwrite existing sources" not set. Issue a warning about this self.warning( '%s has custom base classes, but you are not overwriting existing sources: ' 'please check that the resulting code is correct!' % code_obj.name ) if self._mark_blocks: # __init__ begin tag write(self.tmpl_block_begin % {'class_separator':self.class_separator, 'comment_sign':self.comment_sign, 'function':self.name_ctor, 'klass':self.cn_class(code_obj.klass), 'tab':tab} ) # the optional initial code from the code properties if not self.preview and code_obj.check_prop("extracode_pre"): for l in code_obj.properties["extracode_pre"].get_lines(): write(tab + l) style_p = code_obj.properties.get("style") if style_p and style_p.value_set != style_p.default_value: style = style_p.get_string_value() m_style = mycn_f( style ) if m_style: stmt_style = self._format_style(style, code_obj) write( stmt_style % {'style':m_style, 'tab':tab} ) # class parent constructor write(tab + '$self = $self->SUPER::new( %s );\n' % ", ".join(new_signature)) # set size here to avoid problems with splitter windows if code_obj.check_prop('size'): write( tab + self.generate_code_size(code_obj) ) for l in builder.get_properties_code(code_obj): write(tab + l) if code_obj.check_prop_truth('extraproperties'): for l in builder.generate_code_extraproperties(code_obj): write(tab + l) # the initial and final code for the contained elements for l in self.classes[code_obj].init: write(tab + l) if self.classes[code_obj].final: write(tab + "\n") for l in self.classes[code_obj].final: write(tab + l) # now check if there is initial and final code for the element itself for l in builder.get_init_code(code_obj): write(tab+l) for l in builder.get_layout_code(code_obj): write(tab + l) # the optional final code from the code properties if not self.preview and code_obj.check_prop("extracode_post"): for l in code_obj.properties["extracode_post"].get_lines(): write(tab + l) return code_lines def generate_code_event_bind(self, code_obj, tab, event_handlers): code_lines = [] for obj, event, handler, unused in event_handlers: if obj.name: obj_id = '%s->GetId'%self.format_generic_access(obj) # e.g. '$self->{button_1}->GetId' or '$self->GetId' else: obj_id = self.generate_code_id(None, obj.id)[1] or '-1' # but this is wrong anyway... if 'EVT_NAVIGATION_KEY' in event: tmpl = '''%(tab)s%(event)s($self, $self->can('%(handler)s'));\n''' else: tmpl = '''%(tab)s%(event)s($self, %(obj_id)s, $self->can('%(handler)s'));\n''' code_lines.append( tmpl % {'tab': tab, 'event': self.cn(event), 'handler': handler, 'obj_id': obj_id} ) if event_handlers: code_lines.append('\n') return code_lines def generate_code_id(self, obj, id=None): if id is None: id = obj.window_id if not id: if obj is not None and obj.check_prop_truth("stockitem"): return '', self.cn("wxID_" + obj.stockitem) return '', self.cn('wxID_ANY') id = str(id) tokens = id.split('=', 1) if len(tokens) != 2: return '', self.cn(tokens[0]) # we assume name is declared elsewhere name, val = tokens if not name: return '', self.cn(val) name = name.strip() val = val.strip() if val == '?': val = self.cn('wxNewId()') else: val = self.cn(val) # check to see if we have to make the var global or not... return 'use constant %s => %s;\n' % (name, val), name def generate_code_size(self, obj): objname = self.format_generic_access(obj) size = obj.properties["size"].get_string_value() use_dialog_units = (size[-1] == 'd') method = 'SetMinSize' if obj.parent_window else 'SetSize' if use_dialog_units: return '%s->%s(%s->ConvertDialogSizeToPixels(Wx::Size->new(%s)));\n' % (objname, method, objname, size[:-1]) return '%s->%s(Wx::Size->new(%s));\n' % (objname, method, size) def _quote_str(self, s): """Escape all unicode characters to there unicode code points in form of \\uxxxx. The returned string is a pure ascii string. Normal ascii characters like \\n or \\t won't be escaped. note: wxGlade don't handles file encoding well currently. Thereby we escape all unicode characters. note: The string 's' is encoded with self.app_encoding already. see: BaseLangCodeWriter._quote_str for additional details see: _recode_x80_xff()""" s = s.replace('$', r'\$') s = s.replace('@', r'\@') # convert all strings to unicode first if not isinstance(s, compat.unicode): s = s.decode(self.app_encoding) # check if it's pure ascii try: dummy = s.encode('ascii') if self._use_gettext: return '_T("%s")' % s else: return '"%s"' % s except UnicodeError: pass # convert unicode strings to pure ascii # use "raw-unicode-escape" just escaped unicode characters and not default escape sequences s = s.encode('raw-unicode-escape') s = self._recode_x80_xff(s) if compat.PYTHON3: # convert back to str (unicode) s = s.decode("ASCII") # convert Python style to Perl style s = re.sub(r'\\u([0-9a-f]{4})', r'\\N{U+\1}', s) if self._use_gettext: return '_T("%s")' % s else: return '"%s"' % s def add_object_format_name(self, name): return '#$self->%s' % name def _format_classattr(self, obj): res = BaseLangCodeWriter._format_classattr(self, obj) if not res: return res elif obj.name.startswith('$self->'): return obj.name elif obj.name.startswith('$'): return obj.name # spacer.name is "<width>, <height>" already elif obj.WX_CLASS == 'spacer': return obj.name # Perl stores sizers always in class attributes elif self.store_as_attr(obj) or obj.IS_SIZER: return '$self->{%s}' % obj.name return '$%s' % obj.name def _format_import(self, klass): return 'use %s;\n' % klass def _get_class_filename(self, klass): "Returns the name for a Perl module (.pm) to store a single class in multi file projects" return os.path.join( self.out_dir, klass.replace('::', os.sep) + '.pm' ) def format_generic_access(self, obj): if obj.IS_CLASS: return '$self' return self._format_classattr(obj) writer = PerlCodeWriter() # the code writer instance language = writer.language # Language generated by this code generator
41.484288
124
0.524841
[ "MIT" ]
ardovm/wxGlade
codegen/perl_codegen.py
22,443
Python
test = { 'name': 'rle', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (rle '()) () scm> (stream-to-list (rle (list-to-stream '(1 2 3)))) ((1 1) (2 1) (3 1)) scm> (stream-to-list (rle (list-to-stream '(1 1 2 2 3 3)))) ((1 2) (2 2) (3 2)) scm> (define s (rle (list-to-stream '(1 1 1 1 1 6 6 6 6 2 5 5 5)))) s scm> (stream-to-list s) ((1 5) (6 4) (2 1) (5 3)) """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': r""" scm> (load 'lab13_extra) """, 'teardown': '', 'type': 'scheme' } ] }
22.151515
77
0.352941
[ "MIT" ]
MassimoWu88/MassimoWu88
labs/lab13/tests/rle.py
731
Python
# Auto generated from meta.yaml by namespacegen.py version: 0.4.0 # Generation date: 2020-08-25 16:45 # Schema: metamodel # # id: https://w3id.org/biolink/biolinkml/meta # description: A metamodel for defining biolink related schemas # license: https://creativecommons.org/publicdomain/zero/1.0/ from collections import defaultdict from typing import Iterable, Dict, Tuple from biolinkml.utils.curienamespace import CurieNamespace GENE = 'gene' DISEASE = 'disease' CHEMICAL_SUBSTANCE = 'chemical substance' SYMBOL = 'Approved_Symbol' class IdentifierResolverException(RuntimeError): pass class BiolinkNameSpace: """ Map of BioLink Model registered URI Namespaces """ _namespaces = [ CurieNamespace('OIO', 'http://www.geneontology.org/formats/oboInOwl#'), CurieNamespace('bibo', 'http://purl.org/ontology/bibo/'), CurieNamespace('biolinkml', 'https://w3id.org/biolink/biolinkml/'), CurieNamespace('dcterms', 'http://purl.org/dc/terms/'), CurieNamespace('meta', 'https://w3id.org/biolink/biolinkml/meta/'), CurieNamespace('oslc', 'http://open-services.net/ns/core#'), CurieNamespace('owl', 'http://www.w3.org/2002/07/owl#'), CurieNamespace('pav', 'http://purl.org/pav/'), CurieNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'), CurieNamespace('rdfs', 'http://www.w3.org/2000/01/rdf-schema#'), CurieNamespace('schema', 'http://schema.org/'), CurieNamespace('skos', 'http://www.w3.org/2004/02/skos/core#'), CurieNamespace('xsd', 'http://www.w3.org/2001/XMLSchema#'), ] # class level dictionaries _prefix_map: Dict[str, CurieNamespace] = {} @classmethod def _get_prefix_map(cls): if not cls._prefix_map: for ns in cls._namespaces: # index by upper case for uniformity of search cls._prefix_map[ns.prefix.upper()] = ns return cls._prefix_map @classmethod def parse_curie(cls, curie: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate CURIE :param curie: candidate curie string :return: CURIE namespace and object_id """ found = CurieNamespace("", ""), curie # default value if not a CURIE or unknown XMLNS prefix if ':' in curie: part = curie.split(":") # Normalize retrieval with upper case of prefix for lookup prefix = part[0].upper() if prefix in cls._get_prefix_map(): found = cls._prefix_map[prefix], part[1] return found @classmethod def parse_uri(cls, uri: str) -> Tuple[CurieNamespace, str]: """ Parse a candidate URI :param uri: candidate URI string :return: namespace and object_id """ found = CurieNamespace("", ""), uri # default value returned if unknown URI namespace # TODO: is there a more efficient lookup scheme here than a linear search of namespaces? for ns in cls._namespaces: base_uri = str(ns) if uri.startswith(base_uri): # simple minded deletion of base_uri to give the object_id object_id = uri.replace(base_uri, "") found = ns, object_id break return found @classmethod def parse_identifier(cls, identifier: str) -> Tuple[CurieNamespace, str]: # trivial case of a null identifier? if not identifier: return CurieNamespace("", ""), "" # check if this is a candidate URI... if identifier.lower().startswith("http"): # guess that perhaps it is, so try to parse it return cls.parse_uri(identifier) else: # attempt to parse as a CURIE return cls.parse_curie(identifier) def object_id(identifier, keep_version=False) -> str: """ Returns the core object_id of a CURIE, with or without the version suffix. Note: not designed to be used with a URI (will give an invalid outcome) :param identifier: candidate CURIE identifier for processing :param keep_version: True if the version string suffix is to be retained in the identifier :return: """ # trivial case: null input value? if not identifier: return identifier if ':' in identifier: identifier = identifier.split(":")[1] if not keep_version and '.' in identifier: identifier = identifier.split(".")[0] return identifier def fix_curies(identifiers, prefix=''): """ Applies the specified XMLNS prefix to (an) identifier(s) known to be "raw" IDs as keys in a dictionary or elements in a list (or a simple string) :param identifiers: :param prefix: :return: """ if not prefix: # return identifiers without modification # Caller may already consider them in curie format return identifiers if isinstance(identifiers, dict): curie_dict = defaultdict(dict) for key in identifiers.keys(): curie_dict[prefix + ':' + object_id(key, keep_version=True)] = identifiers[key] return curie_dict # identifiers assumed to be just a single object identifier elif isinstance(identifiers, str): # single string to convert return prefix + ':' + object_id(identifiers, keep_version=True) elif isinstance(identifiers, Iterable): return [prefix + ':' + object_id(x, keep_version=True) for x in identifiers] else: raise RuntimeError("fix_curie() is not sure how to fix an instance of data type '", type(identifiers)) def curie(identifier) -> str: # Ignore enpty strings if not identifier: return "" else: namespace: CurieNamespace identifier_object_id: str namespace, identifier_object_id = BiolinkNameSpace.parse_identifier(identifier) return namespace.curie(identifier_object_id)
34.836257
110
0.642605
[ "CC0-1.0" ]
hsolbrig/biolinkml
tests/test_scripts/output/gennamespace/meta_namespaces.py
5,957
Python
from typing import Sequence, Dict, List, Optional from abc import ABC, abstractmethod # from nltk.corpus import wordnet from pymagnitude import Magnitude from .utils import ( UPPERCASE_RE, LOWERCASE_RE, DIGIT_RE, PUNC_REPEAT_RE, ) class FeatureExtractor(ABC): @abstractmethod def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: raise NotImplementedError class BiasFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: features["bias"] = 1.0 class TokenFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: features["tok[%d]=%s" % (relative_idx, token)] = 1.0 class UppercaseFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if str.isupper(token): features["uppercase[%d]" % (relative_idx)] = 1.0 class TitlecaseFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if str.istitle(token): features["titlecase[%d]" % (relative_idx)] = 1.0 class InitialTitlecaseFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if str.istitle(token) and current_idx + relative_idx == 0: features["initialtitlecase[%d]" % (relative_idx)] = 1.0 class PunctuationFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if PUNC_REPEAT_RE.fullmatch(token): features["punc[%d]" % (relative_idx)] = 1.0 class DigitFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if DIGIT_RE.search(token): features["digit[%d]" % (relative_idx)] = 1.0 class WordShapeFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: shape_str = token shape_str = UPPERCASE_RE.sub("X", shape_str) shape_str = LOWERCASE_RE.sub("x", shape_str) shape_str = DIGIT_RE.sub("0", shape_str) features["shape[%d]=%s" % (relative_idx, shape_str)] = 1.0 """ class LikelyAdjectiveFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: for synset in wordnet.synsets(token): if synset.name().split('.')[0] == token: if synset.pos() == 's': features["adj[%d]" % (relative_idx)] = 1.0 class AfterVerbFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if relative_idx != -1: return for synset in wordnet.synsets(token): if synset.name().split('.')[0] == token: if synset.pos() == 'v': features["afterverb[%d]" % (relative_idx)] = 1.0 class PosFeature(FeatureExtractor): def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: for synset in wordnet.synsets(token): if synset.name().split('.')[0] == token: features[f"adj[{relative_idx}]={synset.pos()}"] = 1.0 """ class WordVectorFeature(FeatureExtractor): def __init__(self, vectors_path: str, scaling: float = 1.0) -> None: self.vectors = Magnitude(vectors_path, normalized=False) self.scaling = scaling def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: vector = self.vectors.query(token) keys = ["v" + str(i) for i in range(len(vector))] values = vector * self.scaling features.update(zip(keys, values)) class BrownClusterFeature(FeatureExtractor): def __init__( self, clusters_path: str, *, use_full_paths: bool = False, use_prefixes: bool = False, prefixes: Optional[Sequence[int]] = None, ): if not use_full_paths and not use_prefixes: raise ValueError self.prefix_dict = {} self.full_path_dict = {} self.use_full_paths = use_full_paths with open(clusters_path, "r", encoding='utf-8') as cluster_file: for line in cluster_file: cluster, word, _frequency = line.split("\t") if use_full_paths: self.full_path_dict[word] = cluster elif use_prefixes: if prefixes is not None: self.prefix_dict[word] = [ cluster[:prefix] for prefix in prefixes if prefix <= len(cluster) ] else: self.prefix_dict[word] = [ cluster[:prefix] for prefix in range(1, len(cluster) + 1) ] def extract( self, token: str, current_idx: int, relative_idx: int, tokens: Sequence[str], features: Dict[str, float], ) -> None: if relative_idx != 0: return if self.use_full_paths and token in self.full_path_dict: features[f"cpath={self.full_path_dict[token]}"] = 1.0 elif token in self.prefix_dict: for prefix in self.prefix_dict[token]: features[f"cprefix{len(prefix)}={prefix}"] = 1.0 class WindowedTokenFeatureExtractor: def __init__(self, feature_extractors: Sequence[FeatureExtractor], window_size: int): self.feature_extractors = feature_extractors self.window_size = window_size def extract(self, tokens: Sequence[str]) -> List[Dict[str, float]]: features = [] for i, _ in enumerate(tokens): current_feature = {} start = max(0, i - self.window_size) end = min(len(tokens) - 1, i + self.window_size) + 1 for j in range(start, end): relative_idx = j - i for feature_extractor in self.feature_extractors: feature_extractor.extract( tokens[j], i, relative_idx, tokens, current_feature ) features.append(current_feature) return features
30.137255
89
0.554066
[ "MIT" ]
YifanLeng/Esports_NER
CRF/feature_extractors.py
7,685
Python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing from functools import partial import tensorflow as tf import tensorflow.contrib.eager as tfe from general.utilTF1.utils import session from general.kneeOsteoarthritisDataset.KneeOsteoarthritsDataset import KneeOsteoarthritsDataset _N_CPU = multiprocessing.cpu_count() def batch_dataset(dataset, batch_size, prefetch_batch=_N_CPU + 1, drop_remainder=True, filter=None, map_func=None, num_threads=_N_CPU, shuffle=True, buffer_size=4096, repeat=-1): if filter: dataset = dataset.filter(filter) if map_func: dataset = dataset.map(map_func, num_parallel_calls=num_threads) if shuffle: dataset = dataset.shuffle(buffer_size) if drop_remainder: dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size)) else: dataset = dataset.batch(batch_size) dataset = dataset.repeat(repeat).prefetch(prefetch_batch) return dataset class Dataset(object): def __init__(self): self._dataset = None self._iterator = None self._batch_op = None self._sess = None self._is_eager = tf.executing_eagerly() self._eager_iterator = None def __del__(self): if self._sess: self._sess.close() def __iter__(self): return self def __next__(self): try: b = self.get_next() except: raise StopIteration else: return b next = __next__ def get_next(self): if self._is_eager: return self._eager_iterator.get_next() else: return self._sess.run(self._batch_op) def reset(self, feed_dict={}): if self._is_eager: self._eager_iterator = tfe.Iterator(self._dataset) else: self._sess.run(self._iterator.initializer, feed_dict=feed_dict) def _bulid(self, dataset, sess=None): self._dataset = dataset if self._is_eager: self._eager_iterator = tfe.Iterator(dataset) else: self._iterator = dataset.make_initializable_iterator() self._batch_op = self._iterator.get_next() if sess: self._sess = sess else: self._sess = session() try: self.reset() except: pass @property def dataset(self): return self._dataset @property def iterator(self): return self._iterator @property def batch_op(self): return self._batch_op def get_dataset(data_set_path,shuffle=True): # shape img_shape = [256,256, 1] # dataset def _map_func(img,label): img = tf.image.resize_images(img, [img_shape[0], img_shape[1]], method=tf.image.ResizeMethod.BICUBIC) img = tf.clip_by_value(tf.cast(img, tf.float32), 0, 255) / 255 # / 127.5 - 1 return img,label # get image pathes # kneeosteo_train = KneeOsteoarthritsDataset(data_path=data_set_path) labels = list(kneeosteo_train.dict_url_class.values()) paths = list(kneeosteo_train.dict_url_class.keys()) assert (len(paths) == len(labels)) print('The dataset %s has %f elements. ' % (data_set_path, len(labels))) Dataset = partial(DiskImageData, img_paths=paths,labels=labels, repeat=1, map_func=_map_func,shuffle=shuffle) # index func def get_imgs(batch): return batch return Dataset, img_shape, get_imgs def disk_image_batch_dataset(img_paths, batch_size, labels=None, prefetch_batch=_N_CPU + 1, drop_remainder=True, filter=None, map_func=None, num_threads=_N_CPU, shuffle=True, buffer_size=4096, repeat=-1): """Disk image batch dataset. This function is suitable for jpg and png files Arguments: img_paths : String list or 1-D tensor, each of which is an iamge path labels : Label list/tuple_of_list or tensor/tuple_of_tensor, each of which is a corresponding label """ if labels is None: dataset = tf.data.Dataset.from_tensor_slices(img_paths) elif isinstance(labels, tuple): dataset = tf.data.Dataset.from_tensor_slices((img_paths,) + tuple(labels)) else: dataset = tf.data.Dataset.from_tensor_slices((img_paths, labels)) def parse_func(path, *label): img = tf.read_file(path) img = tf.image.decode_png(img, 1) return (img,) + label if map_func: def map_func_(*args): return map_func(*parse_func(*args)) else: map_func_ = parse_func # dataset = dataset.map(parse_func, num_parallel_calls=num_threads) is slower dataset = batch_dataset(dataset, batch_size, prefetch_batch, drop_remainder, filter, map_func_, num_threads, shuffle, buffer_size, repeat) return dataset class DiskImageData(Dataset): """DiskImageData. This class is suitable for jpg and png files Arguments: img_paths : String list or 1-D tensor, each of which is an iamge path labels : Label list or tensor, each of which is a corresponding label """ def __init__(self, img_paths, batch_size, labels=None, prefetch_batch=_N_CPU + 1, drop_remainder=True, filter=None, map_func=None, num_threads=_N_CPU, shuffle=True, buffer_size=4096, repeat=-1, sess=None): super(DiskImageData, self).__init__() dataset = disk_image_batch_dataset(img_paths, batch_size, labels, prefetch_batch, drop_remainder, filter, map_func, num_threads, shuffle, buffer_size, repeat) self._bulid(dataset, sess) self._n_data = len(img_paths) def __len__(self): return self._n_data
30.489583
125
0.65562
[ "BSD-3-Clause" ]
duennbart/masterthesis_VAE
general/utilTF1/dataset.py
5,854
Python
#!/usr/bin/env python from django.contrib.auth import get_user_model import django import configparser import sys import os django_project_name = os.environ.get('DJANGO_PROJECT_NAME') sys.path.append('/app') os.environ.setdefault("DJANGO_SETTINGS_MODULE", django_project_name+'.settings') django.setup() def django_superuser_creation(**kwargs): User = get_user_model() if User.objects.filter(username=kwargs['username']).count()==0: User.objects.create_superuser(**kwargs) print('[django] Superuser created.') else: print('[django] Superuser creation skipped.') config = configparser.ConfigParser() config.read('/run/secrets/djangodb.cnf') try: user_detail = dict(config['superuser']) except KeyError as e: print('[django] Config file for django does not has superuser detail.') sys.exit(1) else: django_superuser_creation(**user_detail)
27.151515
80
0.736607
[ "MIT" ]
narendra-cs/DjangoApp
scripts/create_django_superuser.py
896
Python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from flask import Flask from flask import request from flask import jsonify from line_sdk import Linebot LINE_ACCESS_TOKEN = "" LINE_CHANNEL_SECRET = "" app = Flask(__name__) @app.route("/", methods=["GET", "POST"]) def webhook(): # GET if request.method == "GET": return "Line Webhook Success." # POST elif request.method == "POST": body = request.get_data(as_text=True) signature = request.headers["X-Line-Signature"] # Line linebot = Linebot(LINE_ACCESS_TOKEN, LINE_CHANNEL_SECRET) # dataLIST = [{status, type, message, userID, replyToken, timestamp}] # replyToken = 回覆需要的ID , message = 使用者輸入的內容 dataLIST = linebot.parse(body, signature) for dataDICT in dataLIST: if dataDICT["status"]: if dataDICT["type"] == "message": try: # 這裡輸入客製化內容 # dataDICT["message"] => 使用者輸入的內容 msgSTR = "[MSG] {}".format(dataDICT["message"]) except Exception as e: msgSTR = "[ERROR] {}".format(str(e)) # respText(聊天室ID, 要回覆的內容) linebot.respText(dataDICT["replyToken"], msgSTR) return jsonify({"status": True, "msg": "Line Webhook Success."}) # OTHER else: return "HTTP_405_METHOD_NOT_ALLOWED" if __name__ == "__main__": app.run()
28.132075
77
0.560027
[ "MIT" ]
RobinJLin/LokiHub
Heroku/Heroku-Linebot-Github/line_app.py
1,569
Python
# All paths are relative to train_val.py file config = { 'images_path': 'train_val_data/Flicker8k_Dataset/', #Make sure you put that last slash(/) 'train_data_path': 'train_val_data/Flickr8k_text/Flickr_8k.trainImages.txt', 'val_data_path': 'train_val_data/Flickr8k_text/Flickr_8k.devImages.txt', 'captions_path': 'train_val_data/Flickr8k_text/Flickr8k.token.txt', 'tokenizer_path': 'model_data/tokenizer.pkl', 'model_data_path': 'model_data/', #Make sure you put that last slash(/) 'model_load_path': 'model_data/model_vgg16_epoch-17_train_loss-2.2955_val_loss-3.1448.hdf5', 'num_of_epochs': 18, 'max_length': 40, #This is set manually after training of model and required for test.py 'batch_size': 64, 'beam_search_k':3, 'test_data_tuple': [ "https://images.unsplash.com/photo-1502673530728-f79b4cab31b1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80", # Photo by John Price (https://unsplash.com/@johnprice?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on Unsplash (https://unsplash.com/s/photos/dog?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) "https://images.unsplash.com/photo-1576941089067-2de3c901e126?ixlib=rb-1.2.1&auto=format&fit=crop&w=1443&q=80", # Photo by Jacques Bopp (https://unsplash.com/@jacquesbopp?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on Unsplash (https://unsplash.com/s/photos/house?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) "https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" # Photo by Dan (https://unsplash.com/@dann?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on Unsplash (https://unsplash.com/s/photos/person?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) ], #sample images 'test_data_path': 'test_data/', #Make sure you put that last slash(/) 'model_type': 'vgg16', # inceptionv3 or vgg16 'random_seed': 1035 } rnnConfig = { 'embedding_size': 300, 'LSTM_units': 256, 'dense_units': 256, 'dropout': 0.3 }
71.466667
378
0.772854
[ "MIT" ]
saharshxyz/altML
ml/config.py
2,144
Python
""" --- title: Train Feedback Transformer summary: This is training code with notes for a feedback transformer. --- # Train Feedback Transformer This trains a [feedback transformer](index.html) model for auto-regression. You can pick the original feedback transformer or the new version where the keys and values are precalculated. Here's a Colab notebook for training a feedback transformer on Tiny Shakespeare dataset. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lab-ml/nn/blob/master/labml_nn/transformers/feedback/experiment.ipynb) [![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://web.lab-ml.com/run?uuid=d8eb9416530a11eb8fb50242ac1c0002) """ import torch from torch import nn from labml import experiment from labml.configs import option from labml.utils.pytorch import get_modules from labml_helpers.module import Module from labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs from labml_nn.transformers import Encoder, Generator, TransformerConfigs from labml_nn.transformers.utils import subsequent_mask class AutoregressiveModel(Module): """ ## Auto regressive model """ def __init__(self, n_vocab: int, d_model: int, transformer: Module): super().__init__() # Token embedding module self.src_embed = nn.Embedding(n_vocab, d_model) self.transformer = transformer self.generator = nn.Linear(d_model, n_vocab) def __call__(self, x: torch.Tensor): # Embed the tokens x = self.src_embed(x) # Run it through the the transformer res = self.transformer(x) # Generate logits of the next token return self.generator(res), None class Configs(NLPAutoRegressionConfigs): """ ## Configurations The default configs can and will be over-ridden when we start the experiment """ model: AutoregressiveModel d_model: int = 512 heads: int = 8 dropout: float = 0.0 d_ff: int = 2048 n_layers: int = 6 @option(Configs.model) def feedback_transformer(c: Configs): """ Create [original feedback transformer](index.html). """ from labml_nn.transformers.feedback import FeedbackTransformer, FeedbackTransformerLayer, \ FeedbackAttention, FeedForward return AutoregressiveModel( c.n_tokens, c.d_model, FeedbackTransformer( FeedbackTransformerLayer(d_model=c.d_model, attn=FeedbackAttention(c.heads, c.d_model, c.dropout), feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout), dropout_prob=c.dropout), c.n_layers)).to(c.device) @option(Configs.model) def feedback_transformer_kv(c: Configs): """ Create [updated feedback transformer](index.html#kv_shared), with precalculated keys and values. """ from labml_nn.transformers.feedback import FeedbackTransformerKV, FeedbackTransformerLayer, \ FeedbackAttention, FeedForward return AutoregressiveModel( c.n_tokens, c.d_model, FeedbackTransformerKV( FeedbackTransformerLayer(d_model=c.d_model, attn=FeedbackAttention(c.heads, c.d_model, c.dropout, is_kv_precomputed=True), feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout), dropout_prob=c.dropout), c.n_layers, c.d_model, c.heads)).to(c.device) def main(): # Create experiment experiment.create(name="feedback_transformer") # Create configs conf = Configs() # Load configurations experiment.configs(conf, # A dictionary of configurations to override {'tokenizer': 'character', 'text': 'tiny_shakespeare', 'optimizer.learning_rate': 1.0, 'optimizer.optimizer': 'Noam', 'prompt': 'It is', 'prompt_separator': '', # Use `feedback_transformer` for original feedback transformer 'model': 'feedback_transformer_kv', 'train_loader': 'shuffled_train_loader', 'valid_loader': 'shuffled_valid_loader', 'seq_len': 128, 'epochs': 128, 'batch_size': 64, 'inner_iterations': 25}) # Set models for saving and loading experiment.add_pytorch_models(get_modules(conf)) # Start the experiment with experiment.start(): # Run the training loop conf.run() if __name__ == '__main__': main()
34.216783
188
0.628858
[ "MIT" ]
drpraneshkrishnan/nn
labml_nn/transformers/feedback/experiment.py
4,893
Python
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys from pathlib import Path from typing import cast import toml sys.path.insert(0, os.path.abspath("../../")) # -- Project information ----------------------------------------------------- project = "dataprep" copyright = "2020, SFU Database System Lab" author = "SFU Database System Lab" # The full version, including alpha/beta/rc tags def get_version() -> str: """ Get the library version from pyproject.toml """ path = Path(__file__).resolve().parents[2] / "pyproject.toml" pyproject = toml.loads(open(str(path)).read()) return cast(str, pyproject["tool"]["poetry"]["version"]) release = get_version() # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.todo", "sphinx.ext.viewcode", "sphinx.ext.autodoc", "sphinx.ext.napoleon", "nbsphinx", "sphinx_autodoc_typehints", ] autodoc_typehints = "description" # Napoleon settings napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections = None # autodoc_default_options = { # "members": True, # "member-order": "bysource", # "special-members": "__init__", # } # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] master_doc = "index" # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "nature" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"]
31.27551
79
0.6969
[ "MIT" ]
Sanjana12111994/dataprep
docs/source/conf.py
3,065
Python
import os from os import path import stat import mmap import directio from setting import ( LONGHORN_SOCKET_DIR, LONGHORN_DEV_DIR, PAGE_SIZE, ) def readat_direct(dev, offset, length): pg = offset / PAGE_SIZE in_page_offset = offset % PAGE_SIZE # either read less than a page, or whole pages if in_page_offset != 0: assert pg == (offset + length) / PAGE_SIZE to_read = PAGE_SIZE else: assert length % PAGE_SIZE == 0 to_read = length pg_offset = pg * PAGE_SIZE f = os.open(dev, os.O_DIRECT | os.O_RDONLY) try: os.lseek(f, pg_offset, os.SEEK_SET) ret = directio.read(f, to_read) finally: os.close(f) return ret[in_page_offset: in_page_offset + length] def writeat_direct(dev, offset, data): pg = offset / PAGE_SIZE # don't support across page write assert pg == (offset + len(data)) / PAGE_SIZE pg_offset = pg * PAGE_SIZE f = os.open(dev, os.O_DIRECT | os.O_RDWR) m = mmap.mmap(-1, PAGE_SIZE) try: os.lseek(f, pg_offset, os.SEEK_SET) pg_data = readat_direct(dev, pg_offset, PAGE_SIZE) m.write(pg_data) m.seek(offset % PAGE_SIZE) m.write(data) ret = directio.write(f, m) finally: m.close() os.close(f) return ret def get_socket_path(volume): return path.join(LONGHORN_SOCKET_DIR, "longhorn-" + volume + ".sock") class blockdev: def __init__(self, volume): self.dev = path.join(LONGHORN_DEV_DIR, volume) def readat(self, offset, length): with open(self.dev, 'r') as f: f.seek(offset) ret = f.read(length) return ret # return readat_direct(self.dev, offset, length) def writeat(self, offset, data): return writeat_direct(self.dev, offset, data) def ready(self): if not os.path.exists(self.dev): return False mode = os.stat(self.dev).st_mode if not stat.S_ISBLK(mode): return False return True
25.525
73
0.617042
[ "Apache-2.0" ]
MalibuKoKo/longhorn-engine
integration/data/frontend.py
2,042
Python
import datetime import string from collections import namedtuple from distutils.version import LooseVersion from random import choices from typing import Optional, Type import numpy as np import pandas as pd import pyarrow as pa import pytest from pandas.tests.extension.base import ( BaseArithmeticOpsTests, BaseBooleanReduceTests, BaseCastingTests, BaseComparisonOpsTests, BaseConstructorsTests, BaseDtypeTests, BaseGetitemTests, BaseGroupbyTests, BaseInterfaceTests, BaseMethodsTests, BaseMissingTests, BaseNoReduceTests, BaseNumericReduceTests, BaseParsingTests, BasePrintingTests, BaseReshapingTests, BaseSetitemTests, ) from fletcher import FletcherBaseDtype if LooseVersion(pd.__version__) >= "0.25.0": # imports of pytest fixtures needed for derived unittest classes from pandas.tests.extension.conftest import ( # noqa: F401 as_array, # noqa: F401 use_numpy, # noqa: F401 groupby_apply_op, # noqa: F401 as_frame, # noqa: F401 as_series, # noqa: F401 ) PANDAS_GE_1_1_0 = LooseVersion(pd.__version__) >= "1.1.0" FletcherTestType = namedtuple( "FletcherTestType", [ "dtype", "data", "data_missing", "data_for_grouping", "data_for_sorting", "data_missing_for_sorting", "data_repeated", ], ) def is_arithmetic_type(arrow_dtype: pa.DataType) -> bool: """Check whether this is a type that support arithmetics.""" return ( pa.types.is_integer(arrow_dtype) or pa.types.is_floating(arrow_dtype) or pa.types.is_decimal(arrow_dtype) ) skip_non_artithmetic_type = pytest.mark.skip_by_type_filter( [lambda x: not is_arithmetic_type(x)] ) xfail_list_scalar_constuctor_not_implemented = pytest.mark.xfail_by_type_filter( [pa.types.is_list], "constructor from scalars is not implemented for lists" ) xfail_list_equals_not_implemented = pytest.mark.xfail_by_type_filter( [pa.types.is_list], "== is not implemented for lists" ) xfail_list_setitem_not_implemented = pytest.mark.xfail_by_type_filter( [pa.types.is_list], "__setitem__ is not implemented for lists" ) xfail_missing_list_dict_encode = pytest.mark.xfail_by_type_filter( [pa.types.is_list], "ArrowNotImplementedError: dictionary-encode not implemented for list<item: string>", ) xfail_bool_too_few_uniques = pytest.mark.xfail_by_type_filter( [pa.types.is_boolean], "Test requires at least 3 unique values" ) test_types = [ FletcherTestType( pa.string(), ["🙈", "Ö", "Č", "a", "B"] * 20, [None, "A"], ["B", "B", None, None, "A", "A", "B", "C"], ["B", "C", "A"], ["B", None, "A"], lambda: choices(list(string.ascii_letters), k=10), ), FletcherTestType( pa.bool_(), [True, False, True, True, False] * 20, [None, False], [True, True, None, None, False, False, True, False], [True, False, False], [True, None, False], lambda: choices([True, False], k=10), ), FletcherTestType( pa.int8(), # Use small values here so that np.prod stays in int32 [2, 1, 1, 2, 1] * 20, [None, 1], [2, 2, None, None, -100, -100, 2, 100], [2, 100, -10], [2, None, -10], lambda: choices(list(range(100)), k=10), ), FletcherTestType( pa.int16(), # Use small values here so that np.prod stays in int32 [2, 1, 3, 2, 1] * 20, [None, 1], [2, 2, None, None, -100, -100, 2, 100], [2, 100, -10], [2, None, -10], lambda: choices(list(range(100)), k=10), ), FletcherTestType( pa.int32(), # Use small values here so that np.prod stays in int32 [2, 1, 3, 2, 1] * 20, [None, 1], [2, 2, None, None, -100, -100, 2, 100], [2, 100, -10], [2, None, -10], lambda: choices(list(range(100)), k=10), ), FletcherTestType( pa.int64(), # Use small values here so that np.prod stays in int64 [2, 1, 3, 2, 1] * 20, [None, 1], [2, 2, None, None, -100, -100, 2, 100], [2, 100, -10], [2, None, -10], lambda: choices(list(range(100)), k=10), ), FletcherTestType( pa.float64(), [2, 1.0, 1.0, 5.5, 6.6] * 20, [None, 1.1], [2.5, 2.5, None, None, -100.1, -100.1, 2.5, 100.1], [2.5, 100.99, -10.1], [2.5, None, -10.1], lambda: choices([2.5, 1.0, -1.0, 0, 66.6], k=10), ), # Most of the tests fail as assert_extension_array_equal casts to numpy object # arrays and on them equality is not defined. pytest.param( FletcherTestType( pa.list_(pa.string()), [["B", "C"], ["A"], [None], ["A", "A"], []] * 20, [None, ["A"]], [["B"], ["B"], None, None, ["A"], ["A"], ["B"], ["C"]], [["B"], ["C"], ["A"]], [["B"], None, ["A"]], lambda: choices([["B", "C"], ["A"], [None], ["A", "A"]], k=10), ) ), FletcherTestType( pa.date64(), [ datetime.date(2015, 1, 1), datetime.date(2010, 12, 31), datetime.date(1970, 1, 1), datetime.date(1900, 3, 31), datetime.date(1999, 12, 31), ] * 20, [None, datetime.date(2015, 1, 1)], [ datetime.date(2015, 2, 2), datetime.date(2015, 2, 2), None, None, datetime.date(2015, 1, 1), datetime.date(2015, 1, 1), datetime.date(2015, 2, 2), datetime.date(2015, 3, 3), ], [ datetime.date(2015, 2, 2), datetime.date(2015, 3, 3), datetime.date(2015, 1, 1), ], [datetime.date(2015, 2, 2), None, datetime.date(2015, 1, 1)], lambda: choices(list(pd.date_range("2010-1-1", "2011-1-1").date), k=10), ), ] @pytest.fixture(params=[True, False]) def box_in_series(request): """Whether to box the data in a Series.""" return request.param @pytest.fixture(params=test_types) def fletcher_type(request): return request.param @pytest.fixture(autouse=True) def skip_by_type_filter(request, fletcher_type): if request.node.get_closest_marker("skip_by_type_filter"): for marker in request.node.iter_markers("skip_by_type_filter"): for func in marker.args[0]: if func(fletcher_type.dtype): pytest.skip(f"skipped for type: {fletcher_type}") @pytest.fixture(autouse=True) def xfail_by_type_filter(request, fletcher_type): if request.node.get_closest_marker("xfail_by_type_filter"): for marker in request.node.iter_markers("xfail_by_type_filter"): for func in marker.args[0]: if func(fletcher_type.dtype): pytest.xfail(f"XFAIL for type: {fletcher_type}") @pytest.fixture def dtype(fletcher_type, fletcher_dtype): return fletcher_dtype(fletcher_type.dtype) @pytest.fixture def data(fletcher_type, fletcher_array): return fletcher_array(fletcher_type.data, dtype=fletcher_type.dtype) @pytest.fixture def data_for_twos(dtype, fletcher_type, fletcher_array): if dtype._is_numeric: return fletcher_array([2] * 100, dtype=fletcher_type.dtype) else: return None @pytest.fixture def data_missing(fletcher_type, fletcher_array): return fletcher_array(fletcher_type.data_missing, dtype=fletcher_type.dtype) @pytest.fixture def data_repeated(fletcher_type, fletcher_array): """Return different versions of data for count times.""" pass # noqa def gen(count): for _ in range(count): yield fletcher_array( fletcher_type.data_repeated(), dtype=fletcher_type.dtype ) yield gen @pytest.fixture def data_for_grouping(fletcher_type, fletcher_array): """Fixture with data for factorization, grouping, and unique tests. Expected to be like [B, B, NA, NA, A, A, B, C] Where A < B < C and NA is missing """ return fletcher_array(fletcher_type.data_for_grouping, dtype=fletcher_type.dtype) @pytest.fixture def data_for_sorting(fletcher_type, fletcher_array): """Length-3 array with a known sort order. This should be three items [B, C, A] with A < B < C """ return fletcher_array(fletcher_type.data_for_sorting, dtype=fletcher_type.dtype) @pytest.fixture def data_missing_for_sorting(fletcher_type, fletcher_array): """Length-3 array with a known sort order. This should be three items [B, NA, A] with A < B and NA missing. """ return fletcher_array( fletcher_type.data_missing_for_sorting, dtype=fletcher_type.dtype ) @pytest.fixture(params=[None, lambda x: x]) def sort_by_key(request): """ Return a simple fixture for festing keys in sorting methods. Tests None (no key) and the identity key. """ return request.param class TestBaseCasting(BaseCastingTests): pass class TestBaseConstructors(BaseConstructorsTests): def test_from_dtype(self, data): if pa.types.is_string(data.dtype.arrow_dtype): pytest.xfail( "String construction is failing as Pandas wants to pass the FletcherChunkedDtype to NumPy" ) BaseConstructorsTests.test_from_dtype(self, data) @xfail_list_scalar_constuctor_not_implemented def test_series_constructor_scalar_with_index(self, data, dtype): if PANDAS_GE_1_1_0: BaseConstructorsTests.test_series_constructor_scalar_with_index( self, data, dtype ) class TestBaseDtype(BaseDtypeTests): pass class TestBaseGetitemTests(BaseGetitemTests): def test_loc_iloc_frame_single_dtype(self, data): if pa.types.is_string(data.dtype.arrow_dtype): pytest.mark.xfail( reason="https://github.com/pandas-dev/pandas/issues/27673" ) else: BaseGetitemTests.test_loc_iloc_frame_single_dtype(self, data) class TestBaseGroupbyTests(BaseGroupbyTests): @xfail_bool_too_few_uniques @xfail_missing_list_dict_encode @pytest.mark.parametrize("as_index", [True, False]) def test_groupby_extension_agg(self, as_index, data_for_grouping): BaseGroupbyTests.test_groupby_extension_agg(self, as_index, data_for_grouping) @xfail_bool_too_few_uniques @xfail_missing_list_dict_encode def test_groupby_extension_no_sort(self, data_for_grouping): BaseGroupbyTests.test_groupby_extension_no_sort(self, data_for_grouping) @xfail_missing_list_dict_encode def test_groupby_extension_transform(self, data_for_grouping): if pa.types.is_boolean(data_for_grouping.dtype.arrow_dtype): valid = data_for_grouping[~data_for_grouping.isna()] df = pd.DataFrame({"A": [1, 1, 3, 3, 1, 4], "B": valid}) result = df.groupby("B").A.transform(len) # Expected grouping is different as we only have two non-null values expected = pd.Series([3, 3, 3, 3, 3, 3], name="A") self.assert_series_equal(result, expected) else: BaseGroupbyTests.test_groupby_extension_transform(self, data_for_grouping) @xfail_missing_list_dict_encode def test_groupby_extension_apply( self, data_for_grouping, groupby_apply_op # noqa: F811 ): BaseGroupbyTests.test_groupby_extension_apply( self, data_for_grouping, groupby_apply_op ) class TestBaseInterfaceTests(BaseInterfaceTests): @pytest.mark.xfail( reason="view or self[:] returns a shallow copy in-place edits are not backpropagated" ) def test_view(self, data): BaseInterfaceTests.test_view(self, data) def test_array_interface(self, data): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("Not sure whether this test really holds for list") else: BaseInterfaceTests.test_array_interface(self, data) @xfail_list_setitem_not_implemented def test_copy(self, data): BaseInterfaceTests.test_array_interface(self, data) class TestBaseMethodsTests(BaseMethodsTests): # https://github.com/pandas-dev/pandas/issues/22843 @pytest.mark.skip(reason="Incorrect expected") @pytest.mark.parametrize("dropna", [True, False]) def test_value_counts(self, all_data, dropna, dtype): pass @xfail_list_equals_not_implemented @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame]) def test_equals(self, data, na_value, as_series, box): # noqa: F811 if PANDAS_GE_1_1_0: BaseMethodsTests.test_equals(self, data, na_value, as_series, box) @xfail_missing_list_dict_encode def test_value_counts_with_normalize(self, data): if PANDAS_GE_1_1_0: BaseMethodsTests.test_value_counts_with_normalize(self, data) def test_combine_le(self, data_repeated): # GH 20825 # Test that combine works when doing a <= (le) comparison # Fletcher returns 'fletcher_chunked[bool]' instead of np.bool as dtype orig_data1, orig_data2 = data_repeated(2) if pa.types.is_list(orig_data1.dtype.arrow_dtype): return pytest.skip("__le__ not implemented for list scalars with None") s1 = pd.Series(orig_data1) s2 = pd.Series(orig_data2) result = s1.combine(s2, lambda x1, x2: x1 <= x2) expected = pd.Series( orig_data1._from_sequence( [a <= b for (a, b) in zip(list(orig_data1), list(orig_data2))] ) ) self.assert_series_equal(result, expected) val = s1.iloc[0] result = s1.combine(val, lambda x1, x2: x1 <= x2) expected = pd.Series( orig_data1._from_sequence([a <= val for a in list(orig_data1)]) ) self.assert_series_equal(result, expected) def test_combine_add(self, data_repeated, dtype): if dtype.name in [ "fletcher_chunked[date64[ms]]", "fletcher_continuous[date64[ms]]", ]: pytest.skip( "unsupported operand type(s) for +: 'datetime.date' and 'datetime.date" ) else: BaseMethodsTests.test_combine_add(self, data_repeated) @xfail_bool_too_few_uniques def test_argsort(self, data_for_sorting): BaseMethodsTests.test_argsort(self, data_for_sorting) @xfail_bool_too_few_uniques def test_argmin_argmax(self, data_for_sorting, data_missing_for_sorting, na_value): if PANDAS_GE_1_1_0: BaseMethodsTests.test_argmin_argmax( self, data_for_sorting, data_missing_for_sorting, na_value ) else: pass @pytest.mark.parametrize("ascending", [True, False]) @xfail_bool_too_few_uniques @xfail_missing_list_dict_encode def test_sort_values(self, data_for_sorting, ascending, sort_by_key): if PANDAS_GE_1_1_0: BaseMethodsTests.test_sort_values( self, data_for_sorting, ascending, sort_by_key ) else: BaseMethodsTests.test_sort_values(self, data_for_sorting, ascending) @pytest.mark.parametrize("na_sentinel", [-1, -2]) @xfail_bool_too_few_uniques @xfail_missing_list_dict_encode def test_factorize(self, data_for_grouping, na_sentinel): BaseMethodsTests.test_factorize(self, data_for_grouping, na_sentinel) @pytest.mark.parametrize("na_sentinel", [-1, -2]) @xfail_bool_too_few_uniques @xfail_missing_list_dict_encode def test_factorize_equivalence(self, data_for_grouping, na_sentinel): BaseMethodsTests.test_factorize_equivalence( self, data_for_grouping, na_sentinel ) @pytest.mark.parametrize("ascending", [True, False]) @xfail_missing_list_dict_encode def test_sort_values_frame(self, data_for_sorting, ascending): BaseMethodsTests.test_sort_values_frame(self, data_for_sorting, ascending) @xfail_bool_too_few_uniques def test_searchsorted(self, data_for_sorting, as_series): # noqa: F811 BaseMethodsTests.test_searchsorted(self, data_for_sorting, as_series) @pytest.mark.parametrize("box", [pd.Series, lambda x: x]) @pytest.mark.parametrize("method", [lambda x: x.unique(), pd.unique]) @xfail_missing_list_dict_encode def test_unique(self, data, box, method): BaseMethodsTests.test_unique(self, data, box, method) @xfail_missing_list_dict_encode def test_factorize_empty(self, data): BaseMethodsTests.test_factorize_empty(self, data) def test_fillna_copy_frame(self, data_missing): if pa.types.is_list(data_missing.dtype.arrow_dtype): pytest.xfail("pandas' fillna cannot cope with lists as a scalar") else: BaseMethodsTests.test_fillna_copy_frame(self, data_missing) def test_fillna_copy_series(self, data_missing): if pa.types.is_list(data_missing.dtype.arrow_dtype): pytest.xfail("pandas' fillna cannot cope with lists as a scalar") else: BaseMethodsTests.test_fillna_copy_series(self, data_missing) @xfail_list_setitem_not_implemented def test_combine_first(self, data): BaseMethodsTests.test_combine_first(self, data) @xfail_list_setitem_not_implemented def test_shift_0_periods(self, data): if PANDAS_GE_1_1_0: BaseMethodsTests.test_shift_0_periods(self, data) def test_shift_fill_value(self, data): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("pandas' isna cannot cope with lists") else: BaseMethodsTests.test_shift_fill_value(self, data) def test_hash_pandas_object_works(self, data, as_frame): # noqa: F811 if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("Fails on hashing ndarrays") else: BaseMethodsTests.test_hash_pandas_object_works(self, data, as_frame) @xfail_list_setitem_not_implemented def test_where_series(self, data, na_value, as_frame): # noqa: F811 BaseMethodsTests.test_where_series(self, data, na_value, as_frame) class TestBaseMissingTests(BaseMissingTests): @pytest.mark.parametrize("method", ["ffill", "bfill"]) def test_fillna_series_method(self, data_missing, method): BaseMissingTests.test_fillna_series_method(self, data_missing, method) def test_fillna_frame(self, data_missing): if pa.types.is_list(data_missing.dtype.arrow_dtype): pytest.xfail("pandas' fillna cannot cope with lists as a scalar") else: BaseMissingTests.test_fillna_frame(self, data_missing) def test_fillna_scalar(self, data_missing): if pa.types.is_list(data_missing.dtype.arrow_dtype): pytest.xfail("pandas' fillna cannot cope with lists as a scalar") else: BaseMissingTests.test_fillna_scalar(self, data_missing) def test_fillna_series(self, data_missing): if pa.types.is_list(data_missing.dtype.arrow_dtype): pytest.xfail("pandas' fillna cannot cope with lists as a scalar") else: BaseMissingTests.test_fillna_series(self, data_missing) class TestBaseReshapingTests(BaseReshapingTests): def test_concat_mixed_dtypes(self, data, dtype): arrow_dtype = data.dtype.arrow_dtype if ( pa.types.is_integer(arrow_dtype) or pa.types.is_floating(arrow_dtype) or pa.types.is_boolean(arrow_dtype) ): # https://github.com/pandas-dev/pandas/issues/21792 pytest.skip("pd.concat(int64, fletcher_chunked[int64] yields int64") elif pa.types.is_temporal(arrow_dtype): # https://github.com/pandas-dev/pandas/issues/33331 pytest.xfail("pd.concat(temporal, categorical) mangles dates") else: BaseReshapingTests.test_concat_mixed_dtypes(self, data) def test_merge_on_extension_array(self, data): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("pandas tries to hash scalar lists") else: BaseReshapingTests.test_merge_on_extension_array(self, data) def test_merge_on_extension_array_duplicates(self, data): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("pandas tries to hash scalar lists") else: BaseReshapingTests.test_merge_on_extension_array_duplicates(self, data) @xfail_list_setitem_not_implemented def test_ravel(self, data): BaseReshapingTests.test_ravel(self, data) @xfail_list_setitem_not_implemented @pytest.mark.xfail(reason="Views don't update their parent #96") def test_transpose(self, data): if hasattr(BaseReshapingTests, "test_transpose"): BaseReshapingTests.test_transpose(self, data) class TestBaseSetitemTests(BaseSetitemTests): @xfail_list_setitem_not_implemented def test_setitem_scalar_series(self, data, box_in_series): BaseSetitemTests.test_setitem_scalar_series(self, data, box_in_series) @xfail_list_setitem_not_implemented def test_setitem_sequence(self, data, box_in_series): BaseSetitemTests.test_setitem_sequence(self, data, box_in_series) @xfail_list_setitem_not_implemented def test_setitem_empty_indxer(self, data, box_in_series): BaseSetitemTests.test_setitem_empty_indxer(self, data, box_in_series) @xfail_list_setitem_not_implemented def test_setitem_sequence_broadcasts(self, data, box_in_series): BaseSetitemTests.test_setitem_sequence_broadcasts(self, data, box_in_series) @pytest.mark.parametrize("setter", ["loc", "iloc"]) @xfail_list_setitem_not_implemented def test_setitem_scalar(self, data, setter): BaseSetitemTests.test_setitem_scalar(self, data, setter) @xfail_list_setitem_not_implemented def test_setitem_loc_scalar_mixed(self, data): BaseSetitemTests.test_setitem_loc_scalar_mixed(self, data) @xfail_list_setitem_not_implemented def test_setitem_loc_scalar_single(self, data): BaseSetitemTests.test_setitem_loc_scalar_single(self, data) @xfail_list_setitem_not_implemented def test_setitem_loc_scalar_multiple_homogoneous(self, data): BaseSetitemTests.test_setitem_loc_scalar_multiple_homogoneous(self, data) @xfail_list_setitem_not_implemented def test_setitem_iloc_scalar_mixed(self, data): BaseSetitemTests.test_setitem_iloc_scalar_mixed(self, data) @xfail_list_setitem_not_implemented def test_setitem_iloc_scalar_single(self, data): BaseSetitemTests.test_setitem_iloc_scalar_single(self, data) @xfail_list_setitem_not_implemented def test_setitem_iloc_scalar_multiple_homogoneous(self, data): BaseSetitemTests.test_setitem_iloc_scalar_multiple_homogoneous(self, data) @xfail_list_setitem_not_implemented def test_setitem_nullable_mask(self, data): if not PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_nullable_mask(self, data) @pytest.mark.parametrize("as_callable", [True, False]) @pytest.mark.parametrize("setter", ["loc", None]) @xfail_list_setitem_not_implemented def test_setitem_mask_aligned(self, data, as_callable, setter): BaseSetitemTests.test_setitem_mask_aligned(self, data, as_callable, setter) @pytest.mark.parametrize("setter", ["loc", None]) @xfail_list_setitem_not_implemented def test_setitem_mask_broadcast(self, data, setter): BaseSetitemTests.test_setitem_mask_broadcast(self, data, setter) @xfail_list_setitem_not_implemented def test_setitem_slice(self, data, box_in_series): if PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_slice(self, data, box_in_series) @xfail_list_setitem_not_implemented def test_setitem_loc_iloc_slice(self, data): if PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_loc_iloc_slice(self, data) @xfail_list_setitem_not_implemented def test_setitem_slice_array(self, data): BaseSetitemTests.test_setitem_slice_array(self, data) @xfail_list_setitem_not_implemented @pytest.mark.parametrize( "mask", [ np.array([True, True, True, False, False]), pd.array([True, True, True, False, False], dtype="boolean"), pd.array([True, True, True, pd.NA, pd.NA], dtype="boolean"), ], ids=["numpy-array", "boolean-array", "boolean-array-na"], ) def test_setitem_mask(self, data, mask, box_in_series): if PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_mask(self, data, mask, box_in_series) @pytest.mark.xfail(reason="Views don't update their parent #96") def test_setitem_preserves_views(self, data): pass @xfail_list_setitem_not_implemented def test_setitem_mask_boolean_array_with_na(self, data, box_in_series): if PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_mask_boolean_array_with_na( self, data, box_in_series ) @pytest.mark.parametrize( "idx", [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])], ids=["list", "integer-array", "numpy-array"], ) @pytest.mark.xfail(reason="https://github.com/xhochy/fletcher/issues/110") def test_setitem_integer_array(self, data, idx, box_in_series): if PANDAS_GE_1_1_0: BaseSetitemTests.test_setitem_integer_array(self, data, idx, box_in_series) class TestBaseParsingTests(BaseParsingTests): @pytest.mark.parametrize("engine", ["c", "python"]) def test_EA_types(self, engine, data): pytest.mark.xfail( "pandas doesn't yet support registering ExtentionDtypes via a pattern" ) class TestBasePrintingTests(BasePrintingTests): pass class TestBaseBooleanReduceTests(BaseBooleanReduceTests): @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series(self, data, all_boolean_reductions, skipna): if pa.types.is_boolean(data.dtype.arrow_dtype): BaseBooleanReduceTests.test_reduce_series( self, data, all_boolean_reductions, skipna ) else: pytest.skip("Boolean reductions are only tested with boolean types") class TestBaseNoReduceTests(BaseNoReduceTests): @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna): arrow_dtype = data.dtype.arrow_dtype if ( pa.types.is_integer(arrow_dtype) or pa.types.is_floating(arrow_dtype) or pa.types.is_decimal(arrow_dtype) ): pytest.skip("Numeric arrays implement reductions, so don't raise") else: BaseNoReduceTests.test_reduce_series_numeric( self, data, all_numeric_reductions, skipna ) @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): if pa.types.is_boolean(data.dtype.arrow_dtype): pytest.skip("BooleanArray does define boolean reductions, so don't raise") else: BaseNoReduceTests.test_reduce_series_boolean( self, data, all_boolean_reductions, skipna ) class TestBaseNumericReduceTests(BaseNumericReduceTests): @pytest.mark.parametrize("skipna", [True, False]) def test_reduce_series(self, data, all_numeric_reductions, skipna): if all_numeric_reductions == "prod": # Shorten in the case of prod to avoid overflows data = data[:2] arrow_dtype = data.dtype.arrow_dtype if ( pa.types.is_integer(arrow_dtype) or pa.types.is_floating(arrow_dtype) or pa.types.is_decimal(arrow_dtype) ): BaseNumericReduceTests.test_reduce_series( self, data, all_numeric_reductions, skipna ) else: pytest.skip("Reduce not implemented on non-numeric types") class TestBaseComparisonOpsTests(BaseComparisonOpsTests): def check_opname(self, s, op_name, other, exc=None): super().check_opname(s, op_name, other, exc=None) def _compare_other(self, s, data, op_name, other): self.check_opname(s, op_name, other) def test_compare_scalar(self, data, all_compare_operators): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("pandas cannot cope with lists as scalar") else: # FIXME: Upstream always compares againt 0 op_name = all_compare_operators s = pd.Series(data) self._compare_other(s, data, op_name, data[0]) def test_compare_array(self, data, all_compare_operators): if pa.types.is_list(data.dtype.arrow_dtype): pytest.xfail("Comparision of list not implemented yet") else: BaseComparisonOpsTests.test_compare_array(self, data, all_compare_operators) def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: result = op(s, other) # We return fletcher booleans to support nulls expected = s.combine(other, op) if not isinstance(expected.dtype, FletcherBaseDtype): expected = pd.Series(type(s.values)(expected.values)) self.assert_series_equal(result, expected) else: with pytest.raises(exc): op(s, other) class TestBaseArithmeticOpsTests(BaseArithmeticOpsTests): # TODO: Instead of skipping other types, we should set the correct exceptions here series_scalar_exc: Optional[Type[TypeError]] = None frame_scalar_exc: Optional[Type[TypeError]] = None series_array_exc: Optional[Type[TypeError]] = None divmod_exc: Optional[Type[TypeError]] = None def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: result = op(s, other) expected = s.combine(other, op) # Combine always returns an int64 for integral arrays but for # operations on smaller integer types, we expect also smaller int types # in the result of the non-combine operations. if hasattr(expected.dtype, "arrow_dtype"): arrow_dtype = expected.dtype.arrow_dtype if pa.types.is_integer(arrow_dtype): # In the case of an operand with a higher bytesize, we also expect the # output to be int64. other_is_np_int64 = ( isinstance(other, pd.Series) and isinstance(other.values, np.ndarray) and other.dtype.char in ("q", "l") ) if ( pa.types.is_integer(arrow_dtype) and pa.types.is_integer(s.dtype.arrow_dtype) and not other_is_np_int64 ): expected = expected.astype(s.dtype) self.assert_series_equal(result, expected) else: with pytest.raises(exc): op(s, other) @skip_non_artithmetic_type def test_arith_series_with_scalar(self, data, all_arithmetic_operators): BaseArithmeticOpsTests.test_arith_series_with_scalar( self, data, all_arithmetic_operators ) @skip_non_artithmetic_type def test_arith_series_with_array(self, data, all_arithmetic_operators): BaseArithmeticOpsTests.test_arith_series_with_array( self, data, all_arithmetic_operators ) @skip_non_artithmetic_type def test_divmod(self, data): BaseArithmeticOpsTests.test_divmod(self, data) @skip_non_artithmetic_type def test_divmod_series_array(self, data, data_for_twos): BaseArithmeticOpsTests.test_divmod(self, data) @skip_non_artithmetic_type def test_add_series_with_extension_array(self, data): BaseArithmeticOpsTests.test_add_series_with_extension_array(self, data) def test_error(self, data, all_arithmetic_operators): arrow_dtype = data.dtype.arrow_dtype if ( pa.types.is_integer(arrow_dtype) or pa.types.is_floating(arrow_dtype) or pa.types.is_decimal(arrow_dtype) ): pytest.skip("Numeric does not error on ops") else: pytest.xfail("Should error here") def _check_divmod_op(self, s, op, other, exc=None): super()._check_divmod_op(s, op, other, None)
36.478357
106
0.664953
[ "MIT" ]
artemru/fletcher
tests/test_pandas_extension.py
32,872
Python
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-09 13:02 from __future__ import unicode_literals from django.db import migrations def load_continents(apps, schema_editor): continent = apps.get_model("country_name_tool", "Continent") newcontinents = [['NA', 'North America'], ['AS', 'Asia'], ['AF', 'Africa'], ['EU', 'Europe'], ['SA', 'South America'], ['OC', 'Oceania'], ['AN', 'Antarctica']] for each in newcontinents: toinsert = continent(continent_code=each[0], continent_name=each[1]) toinsert.save() class Migration(migrations.Migration): dependencies = [ ('country_name_tool', '0002_auto_20170523_1825'), ] operations = [ migrations.RunPython(load_continents) ]
29.96
163
0.658211
[ "MIT" ]
owid/owid-importer
country_name_tool/migrations/0003_auto_20170609_1302.py
749
Python
import os,sys,json,cv2 from nima.inference.inference_model import InferenceModel import opt4 as opt from PIL import Image # write to result file def write_json(args,score): try: outfile =open(args[3],'w') #print('saving test json at '+args[3]) except IndexError: print('output_location not found') print('saving test json at "./test_data/data.json"') outfile = open('./test_data/data.json','w+') finally: #print(score) json.dump(score,outfile) outfile.close #get score by testing def test(model,image): score = {'results':[]} for i in image: #''' img = cv2.imread(image.get(i)) img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)) r = model.predict_from_pil_image(img) ''' r = model.predict_from_file(image.get(i)) ''' score['results'].append({'name':i, 'score':r['mean_score'], 'b':0, 'c':0}) #print(r['mean_score'],type(r['mean_score'])) score['results'] = sorted(score['results'], key= lambda x : x['score'], reverse= True) return score #switch mode and execute test def start(mode,model,image): if mode == 'test': score = test(model,image) ''' print(str(len(image))+' pictures found!') print('=======================') print('test_json') print(score) print('=======================') ''' elif mode == 'adjust': #print(image) if len(image) > 1: print('error adjust more than 1 image') sys.exit(0) score = test(model,image) ''' print('=======================') print('test_json') print(score) print('=======================') ''' for i in image: results = opt.starts(image.get(i)) #print(i,results) filepath, ext = os.path.splitext(image.get(i)) img_dir = filepath+'_'+ext results[2].save(img_dir) score['results'].append({'name':i.split('.')[-2]+'_.'+i.split('.')[-1], 'score':results[1], 'b':results[0][0], 'c':results[0][1], 'img_dir':img_dir}) ''' print('adjsut_json') print(score) print('=======================') ''' else: print('error select mode') sys.exit(0) return score #get image from a folder def handle_folder(pth): image = {} for i in os.listdir(pth): if i.endswith('.jpeg') or i.endswith('.jpg'): image[i] = pth + i return image # detect test or adjust def detect_mode(args): target = args[1] if target == 'test': return 'test' elif target == 'adjust': return 'adjust' else: print('error mode in args[1]') sys.exit(0) # detect folder or a picture def detect_pth(args): target = args[2] if target.endswith('.jpeg') or target.endswith('.jpg'): try: _=open(target) except: print('error pic') sys.exit(0) else: return 'pic',target else: try: #print(target) os.stat(target) except: print('error folder') sys.exit(0) else: if not target.endswith('/'): target += '/' try: os.stat(target) except: print('error detecting the path') sys.exit(0) return 'folder',target # main def mynima(args): model_pth = './tmp3/emd_loss_epoch_49_train_0.05391903784470127_0.12613263790013726.pth' #model_pth = './tmp/emd_loss_epoch_49_train_0.03547421253612805_0.08993149643023331.pth' #model_pth = './tmp0710/emd_loss_epoch_49_train_0.06696929275146844_0.1384279955681362.pth' model = InferenceModel(path_to_model=model_pth) mode = detect_mode(args) method,pth = detect_pth(args) #print(method) if method == 'pic': name = os.path.basename(pth) #print('name '+name) #get pic name image = {name:pth} #make image dict. elif method == 'folder': image = handle_folder(pth) #get image dict. score = start(mode,model,image) write_json(args,score) return #arg[1]: (adjust/test) arg[2]: (folder_path/img_pth) arg[3]: (output_file) mynima(sys.argv)
28.025641
161
0.539341
[ "MIT" ]
jjmao-cs/nima.pytorch
nima/nima_new.py
4,372
Python
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from functorch import grad, nnc_jit, make_fx, make_nnc import torch import time def f(x): return torch.sin(x).sum() inp = torch.randn(100) grad_pt = grad(f) grad_fx = make_fx(grad_pt)(inp) grad_nnc = nnc_jit(grad_pt, skip_specialization=True) loopnest = make_nnc(grad_pt)(inp) print(loopnest) def bench(name, f, iters=10000, warmup=3): for _ in range(warmup): f() begin = time.time() for _ in range(iters): f() print(f"{name}: ", time.time() - begin) bench("Pytorch: ", lambda: grad_pt(inp)) bench("FX: ", lambda: grad_fx(inp)) bench("NNC: ", lambda: grad_nnc(inp))
22.694444
71
0.682987
[ "BSD-3-Clause" ]
ConnollyLeon/functorch
examples/compilation/simple_function.py
817
Python
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2021 Florent Kermarrec <[email protected]> # Copyright (c) 2021 Greg Davill <[email protected]> # SPDX-License-Identifier: BSD-2-Clause # Build/Use: # ./gsd_butterstick.py --uart-name=crossover --with-etherbone --csr-csv=csr.csv --build --load # litex_server --udp # litex_term bridge import os import sys import argparse from migen import * from migen.genlib.resetsync import AsyncResetSynchronizer from litex_boards.platforms import butterstick from litex.build.lattice.trellis import trellis_args, trellis_argdict from litex.soc.cores.clock import * from litex.soc.integration.soc_core import * from litex.soc.integration.builder import * from litex.soc.cores.led import LedChaser from litedram.modules import MT41K64M16,MT41K128M16,MT41K256M16,MT41K512M16 from litedram.phy import ECP5DDRPHY from liteeth.phy.ecp5rgmii import LiteEthPHYRGMII # CRG --------------------------------------------------------------------------------------------- class _CRG(Module): def __init__(self, platform, sys_clk_freq): self.rst = Signal() self.clock_domains.cd_init = ClockDomain() self.clock_domains.cd_por = ClockDomain(reset_less=True) self.clock_domains.cd_sys = ClockDomain() self.clock_domains.cd_sys2x = ClockDomain() self.clock_domains.cd_sys2x_i = ClockDomain(reset_less=True) # # # self.stop = Signal() self.reset = Signal() # Clk / Rst clk30 = platform.request("clk30") rst_n = platform.request("user_btn", 0) # Power on reset por_count = Signal(16, reset=2**16-1) por_done = Signal() self.comb += self.cd_por.clk.eq(clk30) self.comb += por_done.eq(por_count == 0) self.sync.por += If(~por_done, por_count.eq(por_count - 1)) # PLL self.submodules.pll = pll = ECP5PLL() self.comb += pll.reset.eq(~por_done | ~rst_n | self.rst) pll.register_clkin(clk30, 30e6) pll.create_clkout(self.cd_sys2x_i, 2*sys_clk_freq) pll.create_clkout(self.cd_init, 25e6) self.specials += [ Instance("ECLKSYNCB", i_ECLKI = self.cd_sys2x_i.clk, i_STOP = self.stop, o_ECLKO = self.cd_sys2x.clk), Instance("CLKDIVF", p_DIV = "2.0", i_ALIGNWD = 0, i_CLKI = self.cd_sys2x.clk, i_RST = self.reset, o_CDIVX = self.cd_sys.clk), AsyncResetSynchronizer(self.cd_sys, ~pll.locked | self.reset), AsyncResetSynchronizer(self.cd_sys2x, ~pll.locked | self.reset), ] # BaseSoC ------------------------------------------------------------------------------------------ class BaseSoC(SoCCore): def __init__(self, revision="1.0", device="85F", sdram_device="MT41K64M16", sys_clk_freq=int(60e6), toolchain="trellis", with_ethernet=False, with_etherbone=False, eth_ip="192.168.1.50", eth_dynamic_ip=False, with_spi_flash=False, with_led_chaser=True, **kwargs) : platform = butterstick.Platform(revision=revision, device=device ,toolchain=toolchain) # SoCCore ---------------------------------------------------------------------------------- if kwargs["uart_name"] == "serial": kwargs["uart_name"] = "crossover" SoCCore.__init__(self, platform, sys_clk_freq, ident = "LiteX SoC on ButterStick", ident_version = True, **kwargs) # CRG -------------------------------------------------------------------------------------- self.submodules.crg = _CRG(platform, sys_clk_freq) # DDR3 SDRAM ------------------------------------------------------------------------------- if not self.integrated_main_ram_size: available_sdram_modules = { "MT41K64M16": MT41K64M16, "MT41K128M16": MT41K128M16, "MT41K256M16": MT41K256M16, "MT41K512M16": MT41K512M16, } sdram_module = available_sdram_modules.get(sdram_device) self.submodules.ddrphy = ECP5DDRPHY( platform.request("ddram"), sys_clk_freq=sys_clk_freq) self.comb += self.crg.stop.eq(self.ddrphy.init.stop) self.comb += self.crg.reset.eq(self.ddrphy.init.reset) self.add_sdram("sdram", phy = self.ddrphy, module = sdram_module(sys_clk_freq, "1:2"), l2_cache_size = kwargs.get("l2_size", 8192) ) # Ethernet / Etherbone --------------------------------------------------------------------- if with_ethernet or with_etherbone: self.submodules.ethphy = LiteEthPHYRGMII( clock_pads = self.platform.request("eth_clocks"), pads = self.platform.request("eth")) if with_ethernet: self.add_ethernet(phy=self.ethphy, dynamic_ip=eth_dynamic_ip) if with_etherbone: self.add_etherbone(phy=self.ethphy, ip_address=eth_ip) # SPI Flash -------------------------------------------------------------------------------- if with_spi_flash: from litespi.modules import W25Q128JV from litespi.opcodes import SpiNorFlashOpCodes as Codes self.add_spi_flash(mode="4x", module=W25Q128JV(Codes.READ_1_1_4), with_master=False) # Leds ------------------------------------------------------------------------------------- if with_led_chaser: self.comb += platform.request("user_led_color").eq(0b010) # Blue. self.submodules.leds = LedChaser( pads = platform.request_all("user_led"), sys_clk_freq = sys_clk_freq) # Build -------------------------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="LiteX SoC on ButterStick") parser.add_argument("--build", action="store_true", help="Build bitstream.") parser.add_argument("--load", action="store_true", help="Load bitstream.") parser.add_argument("--toolchain", default="trellis", help="FPGA toolchain (trellis or diamond).") parser.add_argument("--sys-clk-freq", default=75e6, help="System clock frequency.") parser.add_argument("--revision", default="1.0", help="Board Revision (1.0).") parser.add_argument("--device", default="85F", help="ECP5 device (25F, 45F, 85F).") parser.add_argument("--sdram-device", default="MT41K64M16", help="SDRAM device (MT41K64M16, MT41K128M16, MT41K256M16 or MT41K512M16).") ethopts = parser.add_mutually_exclusive_group() ethopts.add_argument("--with-ethernet", action="store_true", help="Add Ethernet.") ethopts.add_argument("--with-etherbone", action="store_true", help="Add EtherBone.") parser.add_argument("--eth-ip", default="192.168.1.50", help="Ethernet/Etherbone IP address.") parser.add_argument("--eth-dynamic-ip", action="store_true", help="Enable dynamic Ethernet IP addresses setting.") parser.add_argument("--with-spi-flash", action="store_true", help="Enable SPI Flash (MMAPed).") sdopts = parser.add_mutually_exclusive_group() sdopts.add_argument("--with-spi-sdcard", action="store_true", help="Enable SPI-mode SDCard support.") sdopts.add_argument("--with-sdcard", action="store_true", help="Enable SDCard support.") builder_args(parser) soc_core_args(parser) trellis_args(parser) args = parser.parse_args() assert not (args.with_etherbone and args.eth_dynamic_ip) soc = BaseSoC( toolchain = args.toolchain, revision = args.revision, device = args.device, sdram_device = args.sdram_device, sys_clk_freq = int(float(args.sys_clk_freq)), with_ethernet = args.with_ethernet, with_etherbone = args.with_etherbone, eth_ip = args.eth_ip, eth_dynamic_ip = args.eth_dynamic_ip, with_spi_flash = args.with_spi_flash, **soc_core_argdict(args)) if args.with_spi_sdcard: soc.add_spi_sdcard() if args.with_sdcard: soc.add_sdcard() builder = Builder(soc, **builder_argdict(args)) builder_kargs = trellis_argdict(args) if args.toolchain == "trellis" else {} builder.build(**builder_kargs, run=args.build) if args.load: prog = soc.platform.create_programmer() prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".bit")) if __name__ == "__main__": main()
43.916256
144
0.573864
[ "BSD-2-Clause" ]
Logicwax/litex-boards
litex_boards/targets/gsd_butterstick.py
8,915
Python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Provides standard metric evaluations for dialog. Uses locking and shared memory when ``numthreads`` is set to >1 to share metrics between processes. """ import re from abc import ABC, abstractmethod from collections import Counter import queue import functools import datetime from typing import Union, List, Optional, Tuple, Set, Any, Dict import torch from parlai.core.message import Message from parlai.utils.misc import warn_once from parlai.utils.typing import TScalar, TVector try: import torch.multiprocessing as multiprocessing except ImportError: import multiprocessing # type: ignore DEFAULT_METRICS = {'bleu-4', 'accuracy', 'f1'} ROUGE_METRICS = {'rouge-1', 'rouge-2', 'rouge-L'} BLEU_METRICS = {'bleu-1', 'bleu-2', 'bleu-3', 'bleu-4'} ALL_METRICS = DEFAULT_METRICS | ROUGE_METRICS | BLEU_METRICS try: from nltk.translate import bleu_score as nltkbleu except ImportError: # User doesn't have nltk installed, so we can't use it for bleu # We'll just turn off things, but we might want to warn the user nltkbleu = None try: from fairseq import bleu as fairseqbleu except ImportError: fairseqbleu = None try: import rouge except ImportError: # User doesn't have py-rouge installed, so we can't use it. # We'll just turn off rouge computations rouge = None re_art = re.compile(r'\b(a|an|the)\b') re_punc = re.compile(r'[!"#$%&()*+,-./:;<=>?@\[\]\\^`{|}~_\']') @functools.total_ordering class Metric(ABC): """ Base class for storing metrics. Subclasses should define .value(). Examples are provided for each subclass. """ @property def is_global(self) -> bool: """ Indicates whether this metric should be reported globally or per-task. """ return False @property def macro_average(self) -> bool: """ Indicates whether this metric should be macro-averaged when globally reported. """ return False @abstractmethod def value(self) -> float: """ Return the value of the metric as a float. """ pass @abstractmethod def __add__(self, other: Any) -> 'Metric': raise NotImplementedError def __iadd__(self, other): return self.__radd__(other) def __radd__(self, other: Any): if other is None: return self return self.__add__(other) def __str__(self) -> str: return f'{self.value():.4g}' def __repr__(self) -> str: return f'{self.__class__.__name__}({self.value():.4g})' def __float__(self) -> float: return float(self.value()) def __int__(self) -> int: return int(self.value()) def __eq__(self, other: Any) -> bool: if isinstance(other, Metric): return self.value() == other.value() else: return self.value() == other def __lt__(self, other: Any) -> bool: if isinstance(other, Metric): return self.value() < other.value() else: return self.value() < other def __sub__(self, other: Any) -> float: """ Used heavily for assertAlmostEqual. """ if not isinstance(other, float): raise TypeError('Metrics.__sub__ is intentionally limited to floats.') return self.value() - other def __rsub__(self, other: Any) -> float: """ Used heavily for assertAlmostEqual. NOTE: This is not necessary in python 3.7+. """ if not isinstance(other, float): raise TypeError('Metrics.__rsub__ is intentionally limited to floats.') return other - self.value() @classmethod def as_number(cls, obj: TScalar) -> Union[int, float]: if isinstance(obj, torch.Tensor): obj_as_number: Union[int, float] = obj.item() else: obj_as_number = obj # type: ignore assert isinstance(obj_as_number, int) or isinstance(obj_as_number, float) return obj_as_number @classmethod def as_float(cls, obj: TScalar) -> float: return float(cls.as_number(obj)) @classmethod def as_int(cls, obj: TScalar) -> int: return int(cls.as_number(obj)) @classmethod def many(cls, *objs: List[TVector]) -> List['Metric']: """ Construct many of a Metric from the base parts. Useful if you separately compute numerators and denomenators, etc. """ lengths = [len(o) for o in objs] if len(set(lengths)) != 1: raise IndexError(f'Uneven {cls.__name__} constructions: {lengths}') return [cls(*items) for items in zip(*objs)] class FixedMetric(Metric): """ Fixed metrics are verified to be the same when combined, or throw an error. FixedMetric is used for things like total_train_updates, which should not be combined across different multitasks or different workers. """ __slots__ = ('_value',) def __init__(self, value: TScalar): self._value = self.as_number(value) def __add__(self, other: Optional['FixedMetric']) -> 'FixedMetric': if other is None: return self if self != other: raise ValueError(f"FixedMetrics not the same: {self} and {other}") return self def value(self) -> float: return self._value class SumMetric(Metric): """ Class that keeps a running sum of some metric. Examples of SumMetric include things like "exs", the number of examples seen since the last report, which depends exactly on a teacher. """ __slots__ = ('_sum',) def __init__(self, sum_: TScalar = 0): if isinstance(sum_, torch.Tensor): self._sum = sum_.item() else: assert isinstance(sum_, (int, float)) self._sum = sum_ def __add__(self, other: Optional['SumMetric']) -> 'SumMetric': # NOTE: hinting can be cleaned up with "from __future__ import annotations" when # we drop Python 3.6 if other is None: return self full_sum = self._sum + other._sum # always keep the same return type return type(self)(sum_=full_sum) def value(self) -> float: return self._sum class AverageMetric(Metric): """ Class that keeps a running average of some metric. Examples of AverageMetrics include hits@1, F1, accuracy, etc. These metrics all have per-example values that can be directly mapped back to a teacher. """ __slots__ = ('_numer', '_denom') @property def macro_average(self) -> bool: """ Indicates whether this metric should be macro-averaged when globally reported. """ return True def __init__(self, numer: TScalar, denom: TScalar = 1): self._numer = self.as_number(numer) self._denom = self.as_number(denom) def __add__(self, other: Optional['AverageMetric']) -> 'AverageMetric': # NOTE: hinting can be cleaned up with "from __future__ import annotations" when # we drop Python 3.6 if other is None: return self full_numer: TScalar = self._numer + other._numer full_denom: TScalar = self._denom + other._denom # always keep the same return type return type(self)(numer=full_numer, denom=full_denom) def value(self) -> float: if self._numer == 0 and self._denom == 0: # don't nan out if we haven't counted anything return 0.0 if self._denom == 0: return float('nan') return self._numer / self._denom class MacroAverageMetric(Metric): """ Class that represents the macro average of several numbers. Used for aggregating task level metrics. It is only used for things that are AverageMetrics already. """ __slots__ = '_values' def __init__(self, metrics: Dict[str, Metric]) -> None: self._values = metrics def __add__(self, other: Optional['MacroAverageMetric']) -> 'MacroAverageMetric': if other is None: return self output = dict(**self._values) for k, v in other._values.items(): output[k] = output.get(k, None) + v return MacroAverageMetric(output) def value(self) -> float: sum_ = sum(v.value() for v in self._values.values()) n = len(self._values) return sum_ / n class TimerMetric(Metric): """ A timer metric keep tracks of the first/last times it was used. """ __slots__ = ('_value', '_start', '_end') @classmethod def _now(cls) -> int: return datetime.datetime.utcnow().timestamp() def __init__( self, value: TScalar, start_time: Optional[int] = None, end_time: Optional[int] = None, ): self._value = self.as_number(value) if start_time is None: start_time = self._now() if end_time is None: end_time = self._now() self._start = start_time self._end = end_time def __add__(self, other: Optional['TimerMetric']) -> 'TimerMetric': # NOTE: hinting can be cleaned up with "from __future__ import annotations" when # we drop Python 3.6 if other is None: return self total: TScalar = self._value + other._value start: int = min(self._start, other._start) end: int = max(self._start, other._end) return type(self)(total, start, end) def value(self) -> float: if self._value == 0 or self._end == self._start: return 0 return self._value / (self._end - self._start) class GlobalMetric: """ A global metric is one that should not be aggregated across different tasks. Examples of global metric include things like learning rate and updates. These need to be accumulated or averaged over multiple parleys, but cannot be correlated with a single task. Key to it is the notion that any one worker or any one task already has a global view of the value, and so no combinations should be done. Note this is different then a FixedMetric, in that a GlobalMetric can be still averaged across multiple parleys(), but a FixedMetric is always fixed. """ @property def is_global(self) -> bool: return True class GlobalFixedMetric(GlobalMetric, FixedMetric): """ Global fixed metric. Used for things like total_train_updates. """ pass class GlobalSumMetric(GlobalMetric, SumMetric): """ Global sum metric. Used for 'exs' and 'updates'. """ pass class GlobalAverageMetric(GlobalMetric, AverageMetric): """ Global Average metric. Used for things like learning rate, and many agent-specific metrics. """ pass class LegacyMetric(GlobalAverageMetric): """ Legacy Metrics are reported by agent as float. """ pass class GlobalTimerMetric(GlobalMetric, TimerMetric): pass class F1Metric(AverageMetric): """ Helper class which computes token-level F1. """ @staticmethod def _prec_recall_f1_score(pred_items, gold_items): """ Compute precision, recall and f1 given a set of gold and prediction items. :param pred_items: iterable of predicted values :param gold_items: iterable of gold values :return: tuple (p, r, f1) for precision, recall, f1 """ common = Counter(gold_items) & Counter(pred_items) num_same = sum(common.values()) if num_same == 0: return 0, 0, 0 precision = 1.0 * num_same / len(pred_items) recall = 1.0 * num_same / len(gold_items) f1 = (2 * precision * recall) / (precision + recall) return precision, recall, f1 @staticmethod def compute(guess: str, answers: List[str]) -> 'F1Metric': if guess is None or answers is None: return AverageMetric(0, 0) g_tokens = normalize_answer(guess).split() scores = [ F1Metric._prec_recall_f1_score(g_tokens, normalize_answer(a).split()) for a in answers ] return F1Metric(max(f1 for p, r, f1 in scores), 1) class ExactMatchMetric(AverageMetric): @staticmethod def compute(guess: str, answers: List[str]) -> 'ExactMatchMetric': if guess is None or answers is None: return None guess = normalize_answer(guess) for a in answers: if guess == normalize_answer(a): return ExactMatchMetric(1) return ExactMatchMetric(0) class BleuMetric(AverageMetric): @staticmethod def compute(guess: str, answers: List[str], k: int = 4) -> Optional['BleuMetric']: """ Compute approximate BLEU score between guess and a set of answers. """ if nltkbleu is None: # bleu library not installed, just return a default value return None # Warning: BLEU calculation *should* include proper tokenization and # punctuation etc. We're using the normalize_answer for everything though, # so we're over-estimating our BLEU scores. Also note that NLTK's bleu is # going to be slower than fairseq's (which is written in C), but fairseq's # requires that everything be in arrays of ints (i.e. as tensors). NLTK's # works with strings, which is better suited for this module. weights = [1 / k for _ in range(k)] score = nltkbleu.sentence_bleu( [normalize_answer(a).split(" ") for a in answers], normalize_answer(guess).split(" "), smoothing_function=nltkbleu.SmoothingFunction(epsilon=1e-12).method1, weights=weights, ) return BleuMetric(score) class FairseqBleuMetric(AverageMetric): @staticmethod def compute_many( guess: torch.Tensor, answers: torch.Tensor, pad_idx, end_idx, unk_idx ): """ Return BLEU-1..4 using fairseq and tokens. """ if fairseqbleu is None: return None scorer = fairseqbleu.Scorer(pad_idx, end_idx, unk_idx) answers = answers.cpu().int() guess = guess.cpu().int() scorer.add(answers, guess) return [FairseqBleuMetric(scorer.score(i) / 100.0) for i in range(1, 5)] class RougeMetric(AverageMetric): _evaluator = None @staticmethod def compute_many( guess: str, answers: List[str] ) -> Tuple[ Optional['RougeMetric'], Optional['RougeMetric'], Optional['RougeMetric'] ]: """ Compute ROUGE score between guess and *any* answer. Done with compute_many due to increased efficiency. :return: (rouge-1, rouge-2, rouge-L) """ # possible global initialization global rouge if rouge is None: return None, None, None if RougeMetric._evaluator is None: RougeMetric._evaluator = rouge.Rouge( metrics=['rouge-n', 'rouge-l'], max_n=2 ) try: scores = [ RougeMetric._evaluator.get_scores( normalize_answer(guess), normalize_answer(a) ) for a in answers ] except LookupError: warn_once( 'ROUGE requires nltk punkt tokenizer. Please run ' '`python -c "import nltk; nltk.download(\'punkt\')`' ) return None, None, None scores_rouge1 = max(score['rouge-1']['r'] for score in scores) scores_rouge2 = max(score['rouge-2']['r'] for score in scores) scores_rougeL = max(score['rouge-l']['r'] for score in scores) return ( RougeMetric(scores_rouge1), RougeMetric(scores_rouge2), RougeMetric(scores_rougeL), ) def normalize_answer(s): """ Lower text and remove punctuation, articles and extra whitespace. """ s = s.lower() s = re_punc.sub(' ', s) s = re_art.sub(' ', s) # TODO: this could almost certainly be faster with a regex \s+ -> ' ' s = ' '.join(s.split()) return s def aggregate_named_reports( named_reports: Dict[str, Dict[str, Metric]], micro_average: bool = False ) -> Dict[str, Metric]: """ Aggregate metrics from multiple reports. :param reports: Dict of tasks -> metrics. :param micro_average: If true, top level metrics will be the micro average. By default, we use macro average. :return: The aggregated report """ if len(named_reports) == 0: raise ValueError("Cannot aggregate empty reports.") if len(named_reports) == 1: # no real aggregation to be done return next(iter(named_reports.values())) # reporters is a list of teachers or worlds m: Dict[str, Metric] = {} macro_averages: Dict[str, Dict[str, Metric]] = {} for task_id, task_report in named_reports.items(): for each_metric, value in task_report.items(): if value.is_global: # just take the first one we saw if each_metric not in m: m[each_metric] = value else: task_metric = f'{task_id}/{each_metric}' m[task_metric] = m.get(task_metric) + value if micro_average or not value.macro_average: # none + a => a from implementation of Metric.__add__ m[each_metric] = m.get(each_metric) + value else: # macro average if each_metric not in macro_averages: macro_averages[each_metric] = {} macro_averages[each_metric][task_id] = value for key, values in macro_averages.items(): m[key] = MacroAverageMetric(values) return m def aggregate_unnamed_reports(reports: List[Dict[str, Metric]]) -> Dict[str, Metric]: """ Combines metrics without regard for tracking provenence. """ m: Dict[str, Metric] = {} for task_report in reports: for each_metric, value in task_report.items(): m[each_metric] = m.get(each_metric) + value return m class Metrics(object): """ Threadsafe metrics container focused on aggregation. """ def __init__(self, threadsafe=False, shared=None): self._threadsafe = threadsafe if self._threadsafe and shared is None: # Threadsafe metrics tracking works by keeping a queue that workers can # push updates to. the main worker works through the queue at report # time. We could add some buffering to improve performance, but we # are deprioritizing hogwild performance at this time. self._buffer = None self._queue = multiprocessing.SimpleQueue() self._worker = False self._data = {} elif shared and 'queue' in shared: # This is a clone, in threadsafe mode self._buffer = {} self._queue = shared['queue'] self._worker = True self._data = None elif shared and 'data' in shared: # This is a clone, in non-threadsafe mode self._buffer = None self._queue = None self._worker = False self._data = shared['data'] else: # The original in non-threadsafe mode self._buffer = None self._queue = None self._worker = False self._data = {} def __str__(self): return str(self._data) def __repr__(self): return f'Metrics({repr(self._data)})' def add(self, key: str, value: Optional[Metric]) -> None: """ Record an accumulation to a metric. """ if self._threadsafe and self._worker: self._buffer[key] = self._buffer.get(key) + value else: self._data[key] = self._data.get(key) + value def flush(self): """ Clear the local buffer and push it on. """ if self._threadsafe and self._buffer: self._queue.put(self._buffer) self._buffer.clear() def report(self): """ Report the metrics over all data seen so far. """ self.sync() return {k: v for k, v in self._data.items()} def sync(self): """ Process all items on the queue to ensure it is up to date. """ if self._worker: self.flush() elif self._threadsafe and not self._worker: for buffer_ in self._drain_queue(): for key, value in buffer_.items(): self._data[key] = self._data.get(key) + value def _drain_queue(self): """ Drain the queue, yielding all items in it. """ while not self._queue.empty(): try: yield self._queue.get() except queue.Empty: break def clear(self): """ Clear all the metrics. """ if self._worker: self._buffer.clear() elif self._threadsafe and not self._worker: for _ in self._drain_queue(): pass if self._data: self._data.clear() def share(self): if self._threadsafe: return {'queue': self._queue} else: return {'data': self._data} class TeacherMetrics(Metrics): """ Helper container which encapsulates standard metrics (F1, BLEU, ...). """ def __init__( self, threadsafe: bool = False, metrics_list: str = "default", shared: Dict[str, Any] = None, ) -> None: super().__init__(threadsafe=threadsafe, shared=shared) self._metrics_list = self._infer_metrics(metrics_list) self.eval_pr = [1, 5, 10, 100] @staticmethod def _infer_metrics(cli_arg: str) -> Set[str]: """ Parse the CLI metric into a list of metrics we wish to compute. """ col: Set[str] = set() names = cli_arg.split(",") for n in names: if n == 'default': col |= DEFAULT_METRICS elif n == 'rouge': col |= ROUGE_METRICS elif n == 'bleu': col |= BLEU_METRICS elif n == 'all': col |= ALL_METRICS else: col.add(n) return col def _update_ranking_metrics(self, observation, labels): text_cands = observation.get('text_candidates', None) if text_cands is None: return # Now loop through text candidates, assuming they are sorted. # If any of them is a label then score a point. # maintain hits@1, 5, 10, 50, 100, etc. label_set = set(normalize_answer(l) for l in labels) cnts = {k: 0 for k in self.eval_pr} cnt = 0 for c in text_cands: cnt += 1 if normalize_answer(c) in label_set: for k in self.eval_pr: if cnt <= k: cnts[k] += 1 # hits metric is 1 if cnts[k] > 0. # (other metrics such as p@k and r@k take # the value of cnt into account.) for k in self.eval_pr: self.add(f'hits@{k}', AverageMetric(cnts[k] > 0)) def evaluate_response(self, observation: Message, labels: List[str]) -> None: """ Compute all required text-based metrics based on an observation and labels. """ prediction = observation.get('text', None) self.add('exs', SumMetric(1)) if prediction is not None: self.add('accuracy', ExactMatchMetric.compute(prediction, labels)) self.add('f1', F1Metric.compute(prediction, labels)) for k in range(1, 5): # 1..4 if f'bleu-{k}' in self._metrics_list: self.add(f'bleu-{k}', BleuMetric.compute(prediction, labels, k)) # if any of the rouges are in the list if self._metrics_list & ROUGE_METRICS: r1, r2, rL = RougeMetric.compute_many(prediction, labels) if 'rouge-1' in self._metrics_list: self.add('rouge_1', r1) if 'rouge-2' in self._metrics_list: self.add('rouge_2', r2) if 'rouge-L' in self._metrics_list: self.add('rouge_L', rL) # Ranking metrics. self._update_ranking_metrics(observation, labels) # User-reported metrics if 'metrics' in observation: for uk, v in observation['metrics'].items(): if uk in ALL_METRICS: # don't let the user override our metrics uk = f'USER_{uk}' assert isinstance(uk, str), type(k) if not isinstance(v, Metric): warn_once(f'Metric {uk} is assumed to be averaged per example.') v = AverageMetric(v) assert isinstance(v, Metric) self.add(uk, v) # always flush at the end of processing this response self.flush()
31.426634
88
0.59395
[ "MIT" ]
Totoola-Kehinde/ParlAI
parlai/core/metrics.py
25,487
Python
from abcunits import ConversionUnit KFACTOR = 273.15 #Difference Kelvin, C (how precise is this known?) class TempUnit(ConversionUnit): """ Temperature units. ALl conversions go through Kelvin. """ #http://www.metric-conversions.org/temperature/fahrenheit-to-kelvin.htm class Kelvin(TempUnit): short = 'K' full = 'Kelvin' #Proper names, keep this way? symbol = 'r$^{\deg}K$' #Isn't degree Kelvin technially wrong? _canonical = True @staticmethod def to_canonical(x): return x @staticmethod def from_canonical(x): return x class Celsius(TempUnit): short = 'C' full = 'Celsius' symbol = 'r$^{\deg}C$' @staticmethod def to_canonical(x): return x + KFACTOR @staticmethod def from_canonical(x): return x - KFACTOR class Farenheiht(TempUnit): short = 'F' full = 'Farenheiht' symbol = 'r$^{\deg}F$' @staticmethod def to_canonical(x): return ((x - 32.00)/1.80) + 273.15 @staticmethod def from_canonical(x): return ((x - KFACTOR) * 1.80) + 32.00 _tempunits = (Kelvin(), Celsius(), Farenheiht(), ConversionUnit() #For null case ) TEMPUNITS = dict((obj.short, obj) for obj in _tempunits)
22.137931
71
0.610592
[ "BSD-3-Clause" ]
hugadams/scikit-spectra
skspec/units/tempunits.py
1,284
Python
## ## # File auto-generated against equivalent DynamicSerialize Java class class DeleteRequest(object): def __init__(self): self.datasets = None self.groups = None self.filename = None def getDatasets(self): return self.datasets def setDatasets(self, datasets): self.datasets = datasets def getGroups(self): return self.groups def setGroups(self, groups): self.groups = groups def getFilename(self): return self.filename def setFilename(self, filename): self.filename = filename
19
68
0.641766
[ "BSD-3-Clause" ]
mjames-upc/python-awips
dynamicserialize/dstypes/com/raytheon/uf/common/pypies/request/DeleteRequest.py
589
Python
# -*- coding: utf-8 -*- { "name": """Preview Media Files""", "summary": """Open attached images in popup""", "category": "Web", "images": ["images/screenshot-1.png"], "vesion": "10.0.1.0.0", "application": False, "author": "IT-Projects LLC, Dinar Gabbasov", "support": "[email protected]", "website": "https://twitter.com/gabbasov_dinar", "license": "OPL-1", "price": 19.00, "currency": "EUR", "depends": ["ir_attachment_url"], "external_dependencies": {"python": [], "bin": []}, "data": ["views/web_preview_template.xml"], "qweb": ["static/src/xml/media_tree_view_widget.xml"], "demo": [], "post_load": None, "pre_init_hook": None, "post_init_hook": None, "auto_install": False, "installable": True, }
30.269231
58
0.579416
[ "MIT" ]
ShaheenHossain/itpp-labs-misc-addons13
web_preview/__manifest__.py
787
Python
"""Conftests """
5.666667
12
0.529412
[ "MIT" ]
Azure-Samples/azure-intelligent-edge-patterns
factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/streams/tests/conftest.py
17
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # convert / import osm xml .osm file into a Shapefile import subprocess import os import shutil # specify output format output_format = "ESRI Shapefile" # complete path to input OSM xml file .osm input_osm = '../geodata/OSM_san_francisco_westbluff.osm' # Windows users can uncomment these two lines if needed # ogr2ogr = r"c:/OSGeo4W/bin/ogr2ogr.exe" # ogr_info = r"c:/OSGeo4W/bin/ogrinfo.exe" # view what geometry types are available in our OSM file subprocess.call([ogr_info, input_osm]) destination_dir = os.path.realpath('../geodata/temp') if os.path.isdir(destination_dir): # remove output folder if it exists shutil.rmtree(destination_dir) print("removing existing directory : " + destination_dir) # create new output folder os.mkdir(destination_dir) print("creating new directory : " + destination_dir) # list of geometry types to convert to Shapefile geom_types = ["lines", "points", "multilinestrings", "multipolygons"] # create a new Shapefile for each geometry type for g_type in geom_types: subprocess.call([ogr2ogr, "-skipfailures", "-f", output_format, destination_dir, input_osm, "layer", g_type, "--config","OSM_USE_CUSTOM_INDEXING", "NO"]) print("done creating " + g_type) # if you like to export to SPATIALITE from .osm # subprocess.call([ogr2ogr, "-skipfailures", "-f", # "SQLITE", "-dsco", "SPATIALITE=YES", # "my2.sqlite", input_osm])
30.45098
73
0.676111
[ "MIT" ]
MatthiasWunsch/python-geospatial-analysis-cookbook
ch03/code/ch03-04_osm2shp.py
1,553
Python
from flask_wtf import FlaskForm from flask_wtf.file import FileRequired from wtforms import ( StringField, SubmitField, PasswordField, FileField, SelectField, TextAreaField, BooleanField, ) from wtforms.validators import DataRequired, Length, ValidationError from models import RoomBGMTypes """ Reference: movie_id = form.movie_id.data place = form.place.data imageid = form.imageid.data title = form.title.data """ class RoomMovieForm(FlaskForm): movie_id = StringField("Movie ID") place = StringField("Place in Room") imageid = StringField("Image ID") title = StringField("Movie Title") submit = SubmitField("Done!") class LoginForm(FlaskForm): username = StringField("Username") password = PasswordField("Password") submit = SubmitField("Enter the underground") class NewsForm(FlaskForm): news = TextAreaField("News Contents", validators=[DataRequired()]) create = SubmitField("Create!") class MiiUploadForm(FlaskForm): mii = FileField("Mii Selection", validators=[FileRequired()]) name = StringField("Mii Name", validators=[DataRequired()]) color1 = StringField("Shirt Color (Hex)", validators=[DataRequired()]) color2 = StringField("Pants Color (Hex)", validators=[DataRequired()]) upload = SubmitField("Add Mii") class NewUserForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) password1 = PasswordField("Password", validators=[DataRequired()]) password2 = PasswordField("Confirm Password", validators=[DataRequired()]) upload = SubmitField("Complete") def validate_password1(self, _): if self.password1.data != self.password2.data: return ValidationError("New passwords must be the same") class ChangePasswordForm(FlaskForm): current_password = PasswordField("Password", validators=[DataRequired()]) new_password = PasswordField("New Password", validators=[DataRequired()]) new_password_confirmation = PasswordField( "Confirm New Password", validators=[DataRequired()] ) complete = SubmitField("Complete") def validate_current_password(self, _): if self.current_password.data == self.new_password.data: return ValidationError("New password cannot be the same as current!") def validate_new_password(self, _): if self.new_password.data != self.new_password_confirmation.data: return ValidationError("New passwords must be the same") class MovieUploadForm(FlaskForm): movie = FileField("Movie", validators=[FileRequired()]) title = StringField("Movie title", validators=[DataRequired(), Length(max=48)]) thumbnail = FileField("Movie thumbnail", validators=[FileRequired()]) # Choices for the select field are only evaluated once, so we must set it when necessary. category = SelectField("Movie category", validators=[DataRequired()]) upload = SubmitField("Add Movie") class CategoryAddForm(FlaskForm): category_name = StringField("Category Name", validators=[DataRequired()]) thumbnail = FileField("Movie thumbnail", validators=[FileRequired()]) submit = SubmitField("Add") class CategoryEditForm(FlaskForm): category_name = StringField("Category Name", validators=[DataRequired()]) thumbnail = FileField("Movie thumbnail") submit = SubmitField("Edit") class ParadeForm(FlaskForm): news = StringField("News", validators=[DataRequired()]) company = StringField("Company", validators=[DataRequired()]) image = FileField("Parade Banner", validators=[FileRequired()]) submit = SubmitField("Create") class RoomForm(FlaskForm): bgm = SelectField( "Background Music", choices=RoomBGMTypes.choices(), coerce=RoomBGMTypes.coerce, ) room_logo = FileField("Room Logo", validators=[FileRequired()]) has_mascot = BooleanField("Mascot Enabled") has_contact = BooleanField("Show Contact Information") intro_msg = StringField("Intro Message", validators=[DataRequired()]) mii_msg = StringField("Mii Message", validators=[DataRequired()]) submit = SubmitField("Create") class KillMii(FlaskForm): given_id = StringField("Item ID", validators=[DataRequired()]) submit = SubmitField("Delete!") class ConciergeForm(FlaskForm): prof = StringField("Profession", validators=[DataRequired()]) message1 = StringField("Message 1", validators=[DataRequired()]) message2 = StringField("Message 2", validators=[DataRequired()]) message3 = StringField("Message 3", validators=[DataRequired()]) message4 = StringField("Message 4", validators=[DataRequired()]) message5 = StringField("Message 5", validators=[DataRequired()]) message6 = StringField("Message 6", validators=[DataRequired()]) message7 = StringField("Message 7", validators=[DataRequired()]) movieid = StringField("Movie ID", validators=[DataRequired()]) submit = SubmitField("Create!") class PosterForm(FlaskForm): file = FileField("Poster Image", validators=[FileRequired()]) title = StringField("Title", validators=[DataRequired()]) msg = StringField("Message", validators=[DataRequired()]) upload = SubmitField("Create Poster!")
36.213793
93
0.708246
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dhtdht020/room-server
theunderground/forms.py
5,251
Python
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2020 The UFO Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """UFO test framework primitive and message structures CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....: data structures that should map to corresponding structures in UFO/primitives msg_block, msg_tx, msg_headers, etc.: data structures that represent network messages ser_*, deser_*: functions that handle serialization/deserialization. Classes use __slots__ to ensure extraneous attributes aren't accidentally added by tests, compromising their intended effect. """ from codecs import encode import copy import hashlib from io import BytesIO import math import random import socket import struct import time from test_framework.siphash import siphash256 from test_framework.util import hex_str_to_bytes, assert_equal MAX_LOCATOR_SZ = 101 MAX_BLOCK_BASE_SIZE = 1000000 MAX_BLOOM_FILTER_SIZE = 36000 MAX_BLOOM_HASH_FUNCS = 50 COIN = 100000000 # 1 btc in satoshis MAX_MONEY = 21000000 * COIN BIP125_SEQUENCE_NUMBER = 0xfffffffd # Sequence number that is BIP 125 opt-in and BIP 68-opt-out MAX_PROTOCOL_MESSAGE_LENGTH = 4000000 # Maximum length of incoming protocol messages MAX_HEADERS_RESULTS = 2000 # Number of headers sent in one getheaders result MAX_INV_SIZE = 50000 # Maximum number of entries in an 'inv' protocol message NODE_NETWORK = (1 << 0) NODE_BLOOM = (1 << 2) NODE_WITNESS = (1 << 3) NODE_COMPACT_FILTERS = (1 << 6) NODE_NETWORK_LIMITED = (1 << 10) MSG_TX = 1 MSG_BLOCK = 2 MSG_FILTERED_BLOCK = 3 MSG_CMPCT_BLOCK = 4 MSG_WTX = 5 MSG_WITNESS_FLAG = 1 << 30 MSG_TYPE_MASK = 0xffffffff >> 2 MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG FILTER_TYPE_BASIC = 0 WITNESS_SCALE_FACTOR = 4 # Serialization/deserialization tools def sha256(s): return hashlib.new('sha256', s).digest() def hash256(s): return sha256(sha256(s)) def ser_compact_size(l): r = b"" if l < 253: r = struct.pack("B", l) elif l < 0x10000: r = struct.pack("<BH", 253, l) elif l < 0x100000000: r = struct.pack("<BI", 254, l) else: r = struct.pack("<BQ", 255, l) return r def deser_compact_size(f): nit = struct.unpack("<B", f.read(1))[0] if nit == 253: nit = struct.unpack("<H", f.read(2))[0] elif nit == 254: nit = struct.unpack("<I", f.read(4))[0] elif nit == 255: nit = struct.unpack("<Q", f.read(8))[0] return nit def deser_string(f): nit = deser_compact_size(f) return f.read(nit) def ser_string(s): return ser_compact_size(len(s)) + s def deser_uint256(f): r = 0 for i in range(8): t = struct.unpack("<I", f.read(4))[0] r += t << (i * 32) return r def ser_uint256(u): rs = b"" for _ in range(8): rs += struct.pack("<I", u & 0xFFFFFFFF) u >>= 32 return rs def uint256_from_str(s): r = 0 t = struct.unpack("<IIIIIIII", s[:32]) for i in range(8): r += t[i] << (i * 32) return r def uint256_from_compact(c): nbytes = (c >> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v # deser_function_name: Allow for an alternate deserialization function on the # entries in the vector. def deser_vector(f, c, deser_function_name=None): nit = deser_compact_size(f) r = [] for _ in range(nit): t = c() if deser_function_name: getattr(t, deser_function_name)(f) else: t.deserialize(f) r.append(t) return r # ser_function_name: Allow for an alternate serialization function on the # entries in the vector (we use this for serializing the vector of transactions # for a witness block). def ser_vector(l, ser_function_name=None): r = ser_compact_size(len(l)) for i in l: if ser_function_name: r += getattr(i, ser_function_name)() else: r += i.serialize() return r def deser_uint256_vector(f): nit = deser_compact_size(f) r = [] for _ in range(nit): t = deser_uint256(f) r.append(t) return r def ser_uint256_vector(l): r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r def deser_string_vector(f): nit = deser_compact_size(f) r = [] for _ in range(nit): t = deser_string(f) r.append(t) return r def ser_string_vector(l): r = ser_compact_size(len(l)) for sv in l: r += ser_string(sv) return r # Deserialize from a hex string representation (eg from RPC) def FromHex(obj, hex_string): obj.deserialize(BytesIO(hex_str_to_bytes(hex_string))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): return obj.serialize().hex() # Objects that map to UFOd objects, which can be serialized/deserialized class CAddress: __slots__ = ("net", "ip", "nServices", "port", "time") # see https://github.com/UFO/bips/blob/master/bip-0155.mediawiki NET_IPV4 = 1 ADDRV2_NET_NAME = { NET_IPV4: "IPv4" } ADDRV2_ADDRESS_LENGTH = { NET_IPV4: 4 } def __init__(self): self.time = 0 self.nServices = 1 self.net = self.NET_IPV4 self.ip = "0.0.0.0" self.port = 0 def deserialize(self, f, *, with_time=True): """Deserialize from addrv1 format (pre-BIP155)""" if with_time: # VERSION messages serialize CAddress objects without time self.time = struct.unpack("<I", f.read(4))[0] self.nServices = struct.unpack("<Q", f.read(8))[0] # We only support IPv4 which means skip 12 bytes and read the next 4 as IPv4 address. f.read(12) self.net = self.NET_IPV4 self.ip = socket.inet_ntoa(f.read(4)) self.port = struct.unpack(">H", f.read(2))[0] def serialize(self, *, with_time=True): """Serialize in addrv1 format (pre-BIP155)""" assert self.net == self.NET_IPV4 r = b"" if with_time: # VERSION messages serialize CAddress objects without time r += struct.pack("<I", self.time) r += struct.pack("<Q", self.nServices) r += b"\x00" * 10 + b"\xff" * 2 r += socket.inet_aton(self.ip) r += struct.pack(">H", self.port) return r def deserialize_v2(self, f): """Deserialize from addrv2 format (BIP155)""" self.time = struct.unpack("<I", f.read(4))[0] self.nServices = deser_compact_size(f) self.net = struct.unpack("B", f.read(1))[0] assert self.net == self.NET_IPV4 address_length = deser_compact_size(f) assert address_length == self.ADDRV2_ADDRESS_LENGTH[self.net] self.ip = socket.inet_ntoa(f.read(4)) self.port = struct.unpack(">H", f.read(2))[0] def serialize_v2(self): """Serialize in addrv2 format (BIP155)""" assert self.net == self.NET_IPV4 r = b"" r += struct.pack("<I", self.time) r += ser_compact_size(self.nServices) r += struct.pack("B", self.net) r += ser_compact_size(self.ADDRV2_ADDRESS_LENGTH[self.net]) r += socket.inet_aton(self.ip) r += struct.pack(">H", self.port) return r def __repr__(self): return ("CAddress(nServices=%i net=%s addr=%s port=%i)" % (self.nServices, self.ADDRV2_NET_NAME[self.net], self.ip, self.port)) class CInv: __slots__ = ("hash", "type") typemap = { 0: "Error", MSG_TX: "TX", MSG_BLOCK: "Block", MSG_TX | MSG_WITNESS_FLAG: "WitnessTx", MSG_BLOCK | MSG_WITNESS_FLAG: "WitnessBlock", MSG_FILTERED_BLOCK: "filtered Block", MSG_CMPCT_BLOCK: "CompactBlock", MSG_WTX: "WTX", } def __init__(self, t=0, h=0): self.type = t self.hash = h def deserialize(self, f): self.type = struct.unpack("<I", f.read(4))[0] self.hash = deser_uint256(f) def serialize(self): r = b"" r += struct.pack("<I", self.type) r += ser_uint256(self.hash) return r def __repr__(self): return "CInv(type=%s hash=%064x)" \ % (self.typemap[self.type], self.hash) def __eq__(self, other): return isinstance(other, CInv) and self.hash == other.hash and self.type == other.type class CBlockLocator: __slots__ = ("nVersion", "vHave") def __init__(self): self.vHave = [] def deserialize(self, f): struct.unpack("<i", f.read(4))[0] # Ignore version field. self.vHave = deser_uint256_vector(f) def serialize(self): r = b"" r += struct.pack("<i", 0) # UFO Core ignores version field. Set it to 0. r += ser_uint256_vector(self.vHave) return r def __repr__(self): return "CBlockLocator(vHave=%s)" % (repr(self.vHave)) class COutPoint: __slots__ = ("hash", "n") def __init__(self, hash=0, n=0): self.hash = hash self.n = n def deserialize(self, f): self.hash = deser_uint256(f) self.n = struct.unpack("<I", f.read(4))[0] def serialize(self): r = b"" r += ser_uint256(self.hash) r += struct.pack("<I", self.n) return r def __repr__(self): return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n) class CTxIn: __slots__ = ("nSequence", "prevout", "scriptSig") def __init__(self, outpoint=None, scriptSig=b"", nSequence=0): if outpoint is None: self.prevout = COutPoint() else: self.prevout = outpoint self.scriptSig = scriptSig self.nSequence = nSequence def deserialize(self, f): self.prevout = COutPoint() self.prevout.deserialize(f) self.scriptSig = deser_string(f) self.nSequence = struct.unpack("<I", f.read(4))[0] def serialize(self): r = b"" r += self.prevout.serialize() r += ser_string(self.scriptSig) r += struct.pack("<I", self.nSequence) return r def __repr__(self): return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \ % (repr(self.prevout), self.scriptSig.hex(), self.nSequence) class CTxOut: __slots__ = ("nValue", "scriptPubKey") def __init__(self, nValue=0, scriptPubKey=b""): self.nValue = nValue self.scriptPubKey = scriptPubKey def deserialize(self, f): self.nValue = struct.unpack("<q", f.read(8))[0] self.scriptPubKey = deser_string(f) def serialize(self): r = b"" r += struct.pack("<q", self.nValue) r += ser_string(self.scriptPubKey) return r def __repr__(self): return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \ % (self.nValue // COIN, self.nValue % COIN, self.scriptPubKey.hex()) class CScriptWitness: __slots__ = ("stack",) def __init__(self): # stack is a vector of strings self.stack = [] def __repr__(self): return "CScriptWitness(%s)" % \ (",".join([x.hex() for x in self.stack])) def is_null(self): if self.stack: return False return True class CTxInWitness: __slots__ = ("scriptWitness",) def __init__(self): self.scriptWitness = CScriptWitness() def deserialize(self, f): self.scriptWitness.stack = deser_string_vector(f) def serialize(self): return ser_string_vector(self.scriptWitness.stack) def __repr__(self): return repr(self.scriptWitness) def is_null(self): return self.scriptWitness.is_null() class CTxWitness: __slots__ = ("vtxinwit",) def __init__(self): self.vtxinwit = [] def deserialize(self, f): for i in range(len(self.vtxinwit)): self.vtxinwit[i].deserialize(f) def serialize(self): r = b"" # This is different than the usual vector serialization -- # we omit the length of the vector, which is required to be # the same length as the transaction's vin vector. for x in self.vtxinwit: r += x.serialize() return r def __repr__(self): return "CTxWitness(%s)" % \ (';'.join([repr(x) for x in self.vtxinwit])) def is_null(self): for x in self.vtxinwit: if not x.is_null(): return False return True class CTransaction: __slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout", "wit") def __init__(self, tx=None): if tx is None: self.nVersion = 1 self.vin = [] self.vout = [] self.wit = CTxWitness() self.nLockTime = 0 self.sha256 = None self.hash = None else: self.nVersion = tx.nVersion self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime self.sha256 = tx.sha256 self.hash = tx.hash self.wit = copy.deepcopy(tx.wit) def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.vin = deser_vector(f, CTxIn) flags = 0 if len(self.vin) == 0: flags = struct.unpack("<B", f.read(1))[0] # Not sure why flags can't be zero, but this # matches the implementation in UFOd if (flags != 0): self.vin = deser_vector(f, CTxIn) self.vout = deser_vector(f, CTxOut) else: self.vout = deser_vector(f, CTxOut) if flags != 0: self.wit.vtxinwit = [CTxInWitness() for _ in range(len(self.vin))] self.wit.deserialize(f) else: self.wit = CTxWitness() self.nLockTime = struct.unpack("<I", f.read(4))[0] self.sha256 = None self.hash = None def serialize_without_witness(self): r = b"" r += struct.pack("<i", self.nVersion) r += ser_vector(self.vin) r += ser_vector(self.vout) r += struct.pack("<I", self.nLockTime) return r # Only serialize with witness when explicitly called for def serialize_with_witness(self): flags = 0 if not self.wit.is_null(): flags |= 1 r = b"" r += struct.pack("<i", self.nVersion) if flags: dummy = [] r += ser_vector(dummy) r += struct.pack("<B", flags) r += ser_vector(self.vin) r += ser_vector(self.vout) if flags & 1: if (len(self.wit.vtxinwit) != len(self.vin)): # vtxinwit must have the same length as vin self.wit.vtxinwit = self.wit.vtxinwit[:len(self.vin)] for _ in range(len(self.wit.vtxinwit), len(self.vin)): self.wit.vtxinwit.append(CTxInWitness()) r += self.wit.serialize() r += struct.pack("<I", self.nLockTime) return r # Regular serialization is with witness -- must explicitly # call serialize_without_witness to exclude witness data. def serialize(self): return self.serialize_with_witness() def getwtxid(self): return hash256(self.serialize())[::-1].hex() # Recalculate the txid (transaction hash without witness) def rehash(self): self.sha256 = None self.calc_sha256() return self.hash # We will only cache the serialization without witness in # self.sha256 and self.hash -- those are expected to be the txid. def calc_sha256(self, with_witness=False): if with_witness: # Don't cache the result, just return it return uint256_from_str(hash256(self.serialize_with_witness())) if self.sha256 is None: self.sha256 = uint256_from_str(hash256(self.serialize_without_witness())) self.hash = hash256(self.serialize_without_witness())[::-1].hex() def is_valid(self): self.calc_sha256() for tout in self.vout: if tout.nValue < 0 or tout.nValue > 21000000 * COIN: return False return True # Calculate the virtual transaction size using witness and non-witness # serialization size (does NOT use sigops). def get_vsize(self): with_witness_size = len(self.serialize_with_witness()) without_witness_size = len(self.serialize_without_witness()) return math.ceil(((WITNESS_SCALE_FACTOR - 1) * without_witness_size + with_witness_size) / WITNESS_SCALE_FACTOR) def __repr__(self): return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \ % (self.nVersion, repr(self.vin), repr(self.vout), repr(self.wit), self.nLockTime) class CBlockHeader: __slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nufos", "nNonce", "nTime", "nVersion", "sha256") def __init__(self, header=None): if header is None: self.set_null() else: self.nVersion = header.nVersion self.hashPrevBlock = header.hashPrevBlock self.hashMerkleRoot = header.hashMerkleRoot self.nTime = header.nTime self.nufos = header.nufos self.nNonce = header.nNonce self.sha256 = header.sha256 self.hash = header.hash self.calc_sha256() def set_null(self): self.nVersion = 1 self.hashPrevBlock = 0 self.hashMerkleRoot = 0 self.nTime = 0 self.nufos = 0 self.nNonce = 0 self.sha256 = None self.hash = None def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.hashPrevBlock = deser_uint256(f) self.hashMerkleRoot = deser_uint256(f) self.nTime = struct.unpack("<I", f.read(4))[0] self.nufos = struct.unpack("<I", f.read(4))[0] self.nNonce = struct.unpack("<I", f.read(4))[0] self.sha256 = None self.hash = None def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256(self.hashPrevBlock) r += ser_uint256(self.hashMerkleRoot) r += struct.pack("<I", self.nTime) r += struct.pack("<I", self.nufos) r += struct.pack("<I", self.nNonce) return r def calc_sha256(self): if self.sha256 is None: r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256(self.hashPrevBlock) r += ser_uint256(self.hashMerkleRoot) r += struct.pack("<I", self.nTime) r += struct.pack("<I", self.nufos) r += struct.pack("<I", self.nNonce) self.sha256 = uint256_from_str(hash256(r)) self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii') def rehash(self): self.sha256 = None self.calc_sha256() return self.sha256 def __repr__(self): return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nufos=%08x nNonce=%08x)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nufos, self.nNonce) BLOCK_HEADER_SIZE = len(CBlockHeader().serialize()) assert_equal(BLOCK_HEADER_SIZE, 80) class CBlock(CBlockHeader): __slots__ = ("vtx",) def __init__(self, header=None): super().__init__(header) self.vtx = [] def deserialize(self, f): super().deserialize(f) self.vtx = deser_vector(f, CTransaction) def serialize(self, with_witness=True): r = b"" r += super().serialize() if with_witness: r += ser_vector(self.vtx, "serialize_with_witness") else: r += ser_vector(self.vtx, "serialize_without_witness") return r # Calculate the merkle root given a vector of transaction hashes @classmethod def get_merkle_root(cls, hashes): while len(hashes) > 1: newhashes = [] for i in range(0, len(hashes), 2): i2 = min(i+1, len(hashes)-1) newhashes.append(hash256(hashes[i] + hashes[i2])) hashes = newhashes return uint256_from_str(hashes[0]) def calc_merkle_root(self): hashes = [] for tx in self.vtx: tx.calc_sha256() hashes.append(ser_uint256(tx.sha256)) return self.get_merkle_root(hashes) def calc_witness_merkle_root(self): # For witness root purposes, the hash of the # coinbase, with witness, is defined to be 0...0 hashes = [ser_uint256(0)] for tx in self.vtx[1:]: # Calculate the hashes with witness data hashes.append(ser_uint256(tx.calc_sha256(True))) return self.get_merkle_root(hashes) def is_valid(self): self.calc_sha256() target = uint256_from_compact(self.nufos) if self.sha256 > target: return False for tx in self.vtx: if not tx.is_valid(): return False if self.calc_merkle_root() != self.hashMerkleRoot: return False return True def solve(self): self.rehash() target = uint256_from_compact(self.nufos) while self.sha256 > target: self.nNonce += 1 self.rehash() def __repr__(self): return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nufos=%08x nNonce=%08x vtx=%s)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nufos, self.nNonce, repr(self.vtx)) class PrefilledTransaction: __slots__ = ("index", "tx") def __init__(self, index=0, tx = None): self.index = index self.tx = tx def deserialize(self, f): self.index = deser_compact_size(f) self.tx = CTransaction() self.tx.deserialize(f) def serialize(self, with_witness=True): r = b"" r += ser_compact_size(self.index) if with_witness: r += self.tx.serialize_with_witness() else: r += self.tx.serialize_without_witness() return r def serialize_without_witness(self): return self.serialize(with_witness=False) def serialize_with_witness(self): return self.serialize(with_witness=True) def __repr__(self): return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx)) # This is what we send on the wire, in a cmpctblock message. class P2PHeaderAndShortIDs: __slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length", "shortids", "shortids_length") def __init__(self): self.header = CBlockHeader() self.nonce = 0 self.shortids_length = 0 self.shortids = [] self.prefilled_txn_length = 0 self.prefilled_txn = [] def deserialize(self, f): self.header.deserialize(f) self.nonce = struct.unpack("<Q", f.read(8))[0] self.shortids_length = deser_compact_size(f) for _ in range(self.shortids_length): # shortids are defined to be 6 bytes in the spec, so append # two zero bytes and read it in as an 8-byte number self.shortids.append(struct.unpack("<Q", f.read(6) + b'\x00\x00')[0]) self.prefilled_txn = deser_vector(f, PrefilledTransaction) self.prefilled_txn_length = len(self.prefilled_txn) # When using version 2 compact blocks, we must serialize with_witness. def serialize(self, with_witness=False): r = b"" r += self.header.serialize() r += struct.pack("<Q", self.nonce) r += ser_compact_size(self.shortids_length) for x in self.shortids: # We only want the first 6 bytes r += struct.pack("<Q", x)[0:6] if with_witness: r += ser_vector(self.prefilled_txn, "serialize_with_witness") else: r += ser_vector(self.prefilled_txn, "serialize_without_witness") return r def __repr__(self): return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn)) # P2P version of the above that will use witness serialization (for compact # block version 2) class P2PHeaderAndShortWitnessIDs(P2PHeaderAndShortIDs): __slots__ = () def serialize(self): return super().serialize(with_witness=True) # Calculate the BIP 152-compact blocks shortid for a given transaction hash def calculate_shortid(k0, k1, tx_hash): expected_shortid = siphash256(k0, k1, tx_hash) expected_shortid &= 0x0000ffffffffffff return expected_shortid # This version gets rid of the array lengths, and reinterprets the differential # encoding into indices that can be used for lookup. class HeaderAndShortIDs: __slots__ = ("header", "nonce", "prefilled_txn", "shortids", "use_witness") def __init__(self, p2pheaders_and_shortids = None): self.header = CBlockHeader() self.nonce = 0 self.shortids = [] self.prefilled_txn = [] self.use_witness = False if p2pheaders_and_shortids is not None: self.header = p2pheaders_and_shortids.header self.nonce = p2pheaders_and_shortids.nonce self.shortids = p2pheaders_and_shortids.shortids last_index = -1 for x in p2pheaders_and_shortids.prefilled_txn: self.prefilled_txn.append(PrefilledTransaction(x.index + last_index + 1, x.tx)) last_index = self.prefilled_txn[-1].index def to_p2p(self): if self.use_witness: ret = P2PHeaderAndShortWitnessIDs() else: ret = P2PHeaderAndShortIDs() ret.header = self.header ret.nonce = self.nonce ret.shortids_length = len(self.shortids) ret.shortids = self.shortids ret.prefilled_txn_length = len(self.prefilled_txn) ret.prefilled_txn = [] last_index = -1 for x in self.prefilled_txn: ret.prefilled_txn.append(PrefilledTransaction(x.index - last_index - 1, x.tx)) last_index = x.index return ret def get_siphash_keys(self): header_nonce = self.header.serialize() header_nonce += struct.pack("<Q", self.nonce) hash_header_nonce_as_str = sha256(header_nonce) key0 = struct.unpack("<Q", hash_header_nonce_as_str[0:8])[0] key1 = struct.unpack("<Q", hash_header_nonce_as_str[8:16])[0] return [ key0, key1 ] # Version 2 compact blocks use wtxid in shortids (rather than txid) def initialize_from_block(self, block, nonce=0, prefill_list=None, use_witness=False): if prefill_list is None: prefill_list = [0] self.header = CBlockHeader(block) self.nonce = nonce self.prefilled_txn = [ PrefilledTransaction(i, block.vtx[i]) for i in prefill_list ] self.shortids = [] self.use_witness = use_witness [k0, k1] = self.get_siphash_keys() for i in range(len(block.vtx)): if i not in prefill_list: tx_hash = block.vtx[i].sha256 if use_witness: tx_hash = block.vtx[i].calc_sha256(with_witness=True) self.shortids.append(calculate_shortid(k0, k1, tx_hash)) def __repr__(self): return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn)) class BlockTransactionsRequest: __slots__ = ("blockhash", "indexes") def __init__(self, blockhash=0, indexes = None): self.blockhash = blockhash self.indexes = indexes if indexes is not None else [] def deserialize(self, f): self.blockhash = deser_uint256(f) indexes_length = deser_compact_size(f) for _ in range(indexes_length): self.indexes.append(deser_compact_size(f)) def serialize(self): r = b"" r += ser_uint256(self.blockhash) r += ser_compact_size(len(self.indexes)) for x in self.indexes: r += ser_compact_size(x) return r # helper to set the differentially encoded indexes from absolute ones def from_absolute(self, absolute_indexes): self.indexes = [] last_index = -1 for x in absolute_indexes: self.indexes.append(x-last_index-1) last_index = x def to_absolute(self): absolute_indexes = [] last_index = -1 for x in self.indexes: absolute_indexes.append(x+last_index+1) last_index = absolute_indexes[-1] return absolute_indexes def __repr__(self): return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes)) class BlockTransactions: __slots__ = ("blockhash", "transactions") def __init__(self, blockhash=0, transactions = None): self.blockhash = blockhash self.transactions = transactions if transactions is not None else [] def deserialize(self, f): self.blockhash = deser_uint256(f) self.transactions = deser_vector(f, CTransaction) def serialize(self, with_witness=True): r = b"" r += ser_uint256(self.blockhash) if with_witness: r += ser_vector(self.transactions, "serialize_with_witness") else: r += ser_vector(self.transactions, "serialize_without_witness") return r def __repr__(self): return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions)) class CPartialMerkleTree: __slots__ = ("nTransactions", "vufos", "vHash") def __init__(self): self.nTransactions = 0 self.vHash = [] self.vufos = [] def deserialize(self, f): self.nTransactions = struct.unpack("<i", f.read(4))[0] self.vHash = deser_uint256_vector(f) vBytes = deser_string(f) self.vufos = [] for i in range(len(vBytes) * 8): self.vufos.append(vBytes[i//8] & (1 << (i % 8)) != 0) def serialize(self): r = b"" r += struct.pack("<i", self.nTransactions) r += ser_uint256_vector(self.vHash) vBytesArray = bytearray([0x00] * ((len(self.vufos) + 7)//8)) for i in range(len(self.vufos)): vBytesArray[i // 8] |= self.vufos[i] << (i % 8) r += ser_string(bytes(vBytesArray)) return r def __repr__(self): return "CPartialMerkleTree(nTransactions=%d, vHash=%s, vufos=%s)" % (self.nTransactions, repr(self.vHash), repr(self.vufos)) class CMerkleBlock: __slots__ = ("header", "txn") def __init__(self): self.header = CBlockHeader() self.txn = CPartialMerkleTree() def deserialize(self, f): self.header.deserialize(f) self.txn.deserialize(f) def serialize(self): r = b"" r += self.header.serialize() r += self.txn.serialize() return r def __repr__(self): return "CMerkleBlock(header=%s, txn=%s)" % (repr(self.header), repr(self.txn)) # Objects that correspond to messages on the wire class msg_version: __slots__ = ("addrFrom", "addrTo", "nNonce", "relay", "nServices", "nStartingHeight", "nTime", "nVersion", "strSubVer") msgtype = b"version" def __init__(self): self.nVersion = 0 self.nServices = 0 self.nTime = int(time.time()) self.addrTo = CAddress() self.addrFrom = CAddress() self.nNonce = random.getrandufos(64) self.strSubVer = '' self.nStartingHeight = -1 self.relay = 0 def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.nServices = struct.unpack("<Q", f.read(8))[0] self.nTime = struct.unpack("<q", f.read(8))[0] self.addrTo = CAddress() self.addrTo.deserialize(f, with_time=False) self.addrFrom = CAddress() self.addrFrom.deserialize(f, with_time=False) self.nNonce = struct.unpack("<Q", f.read(8))[0] self.strSubVer = deser_string(f).decode('utf-8') self.nStartingHeight = struct.unpack("<i", f.read(4))[0] if self.nVersion >= 70001: # Relay field is optional for version 70001 onwards try: self.relay = struct.unpack("<b", f.read(1))[0] except: self.relay = 0 else: self.relay = 0 def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += struct.pack("<Q", self.nServices) r += struct.pack("<q", self.nTime) r += self.addrTo.serialize(with_time=False) r += self.addrFrom.serialize(with_time=False) r += struct.pack("<Q", self.nNonce) r += ser_string(self.strSubVer.encode('utf-8')) r += struct.pack("<i", self.nStartingHeight) r += struct.pack("<b", self.relay) return r def __repr__(self): return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i relay=%i)' \ % (self.nVersion, self.nServices, time.ctime(self.nTime), repr(self.addrTo), repr(self.addrFrom), self.nNonce, self.strSubVer, self.nStartingHeight, self.relay) class msg_verack: __slots__ = () msgtype = b"verack" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_verack()" class msg_addr: __slots__ = ("addrs",) msgtype = b"addr" def __init__(self): self.addrs = [] def deserialize(self, f): self.addrs = deser_vector(f, CAddress) def serialize(self): return ser_vector(self.addrs) def __repr__(self): return "msg_addr(addrs=%s)" % (repr(self.addrs)) class msg_addrv2: __slots__ = ("addrs",) msgtype = b"addrv2" def __init__(self): self.addrs = [] def deserialize(self, f): self.addrs = deser_vector(f, CAddress, "deserialize_v2") def serialize(self): return ser_vector(self.addrs, "serialize_v2") def __repr__(self): return "msg_addrv2(addrs=%s)" % (repr(self.addrs)) class msg_sendaddrv2: __slots__ = () msgtype = b"sendaddrv2" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_sendaddrv2()" class msg_inv: __slots__ = ("inv",) msgtype = b"inv" def __init__(self, inv=None): if inv is None: self.inv = [] else: self.inv = inv def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_inv(inv=%s)" % (repr(self.inv)) class msg_getdata: __slots__ = ("inv",) msgtype = b"getdata" def __init__(self, inv=None): self.inv = inv if inv is not None else [] def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_getdata(inv=%s)" % (repr(self.inv)) class msg_getblocks: __slots__ = ("locator", "hashstop") msgtype = b"getblocks" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uint256(f) def serialize(self): r = b"" r += self.locator.serialize() r += ser_uint256(self.hashstop) return r def __repr__(self): return "msg_getblocks(locator=%s hashstop=%064x)" \ % (repr(self.locator), self.hashstop) class msg_tx: __slots__ = ("tx",) msgtype = b"tx" def __init__(self, tx=CTransaction()): self.tx = tx def deserialize(self, f): self.tx.deserialize(f) def serialize(self): return self.tx.serialize_with_witness() def __repr__(self): return "msg_tx(tx=%s)" % (repr(self.tx)) class msg_wtxidrelay: __slots__ = () msgtype = b"wtxidrelay" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_wtxidrelay()" class msg_no_witness_tx(msg_tx): __slots__ = () def serialize(self): return self.tx.serialize_without_witness() class msg_block: __slots__ = ("block",) msgtype = b"block" def __init__(self, block=None): if block is None: self.block = CBlock() else: self.block = block def deserialize(self, f): self.block.deserialize(f) def serialize(self): return self.block.serialize() def __repr__(self): return "msg_block(block=%s)" % (repr(self.block)) # for cases where a user needs tighter control over what is sent over the wire # note that the user must supply the name of the msgtype, and the data class msg_generic: __slots__ = ("data") def __init__(self, msgtype, data=None): self.msgtype = msgtype self.data = data def serialize(self): return self.data def __repr__(self): return "msg_generic()" class msg_no_witness_block(msg_block): __slots__ = () def serialize(self): return self.block.serialize(with_witness=False) class msg_getaddr: __slots__ = () msgtype = b"getaddr" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_getaddr()" class msg_ping: __slots__ = ("nonce",) msgtype = b"ping" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self): return "msg_ping(nonce=%08x)" % self.nonce class msg_pong: __slots__ = ("nonce",) msgtype = b"pong" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self): return "msg_pong(nonce=%08x)" % self.nonce class msg_mempool: __slots__ = () msgtype = b"mempool" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_mempool()" class msg_notfound: __slots__ = ("vec", ) msgtype = b"notfound" def __init__(self, vec=None): self.vec = vec or [] def deserialize(self, f): self.vec = deser_vector(f, CInv) def serialize(self): return ser_vector(self.vec) def __repr__(self): return "msg_notfound(vec=%s)" % (repr(self.vec)) class msg_sendheaders: __slots__ = () msgtype = b"sendheaders" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_sendheaders()" # getheaders message has # number of entries # vector of hashes # hash_stop (hash of last desired block header, 0 to get as many as possible) class msg_getheaders: __slots__ = ("hashstop", "locator",) msgtype = b"getheaders" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uint256(f) def serialize(self): r = b"" r += self.locator.serialize() r += ser_uint256(self.hashstop) return r def __repr__(self): return "msg_getheaders(locator=%s, stop=%064x)" \ % (repr(self.locator), self.hashstop) # headers message has # <count> <vector of block headers> class msg_headers: __slots__ = ("headers",) msgtype = b"headers" def __init__(self, headers=None): self.headers = headers if headers is not None else [] def deserialize(self, f): # comment in UFOd indicates these should be deserialized as blocks blocks = deser_vector(f, CBlock) for x in blocks: self.headers.append(CBlockHeader(x)) def serialize(self): blocks = [CBlock(x) for x in self.headers] return ser_vector(blocks) def __repr__(self): return "msg_headers(headers=%s)" % repr(self.headers) class msg_merkleblock: __slots__ = ("merkleblock",) msgtype = b"merkleblock" def __init__(self, merkleblock=None): if merkleblock is None: self.merkleblock = CMerkleBlock() else: self.merkleblock = merkleblock def deserialize(self, f): self.merkleblock.deserialize(f) def serialize(self): return self.merkleblock.serialize() def __repr__(self): return "msg_merkleblock(merkleblock=%s)" % (repr(self.merkleblock)) class msg_filterload: __slots__ = ("data", "nHashFuncs", "nTweak", "nFlags") msgtype = b"filterload" def __init__(self, data=b'00', nHashFuncs=0, nTweak=0, nFlags=0): self.data = data self.nHashFuncs = nHashFuncs self.nTweak = nTweak self.nFlags = nFlags def deserialize(self, f): self.data = deser_string(f) self.nHashFuncs = struct.unpack("<I", f.read(4))[0] self.nTweak = struct.unpack("<I", f.read(4))[0] self.nFlags = struct.unpack("<B", f.read(1))[0] def serialize(self): r = b"" r += ser_string(self.data) r += struct.pack("<I", self.nHashFuncs) r += struct.pack("<I", self.nTweak) r += struct.pack("<B", self.nFlags) return r def __repr__(self): return "msg_filterload(data={}, nHashFuncs={}, nTweak={}, nFlags={})".format( self.data, self.nHashFuncs, self.nTweak, self.nFlags) class msg_filteradd: __slots__ = ("data") msgtype = b"filteradd" def __init__(self, data): self.data = data def deserialize(self, f): self.data = deser_string(f) def serialize(self): r = b"" r += ser_string(self.data) return r def __repr__(self): return "msg_filteradd(data={})".format(self.data) class msg_filterclear: __slots__ = () msgtype = b"filterclear" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_filterclear()" class msg_feefilter: __slots__ = ("feerate",) msgtype = b"feefilter" def __init__(self, feerate=0): self.feerate = feerate def deserialize(self, f): self.feerate = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.feerate) return r def __repr__(self): return "msg_feefilter(feerate=%08x)" % self.feerate class msg_sendcmpct: __slots__ = ("announce", "version") msgtype = b"sendcmpct" def __init__(self, announce=False, version=1): self.announce = announce self.version = version def deserialize(self, f): self.announce = struct.unpack("<?", f.read(1))[0] self.version = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<?", self.announce) r += struct.pack("<Q", self.version) return r def __repr__(self): return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version) class msg_cmpctblock: __slots__ = ("header_and_shortids",) msgtype = b"cmpctblock" def __init__(self, header_and_shortids = None): self.header_and_shortids = header_and_shortids def deserialize(self, f): self.header_and_shortids = P2PHeaderAndShortIDs() self.header_and_shortids.deserialize(f) def serialize(self): r = b"" r += self.header_and_shortids.serialize() return r def __repr__(self): return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids) class msg_getblocktxn: __slots__ = ("block_txn_request",) msgtype = b"getblocktxn" def __init__(self): self.block_txn_request = None def deserialize(self, f): self.block_txn_request = BlockTransactionsRequest() self.block_txn_request.deserialize(f) def serialize(self): r = b"" r += self.block_txn_request.serialize() return r def __repr__(self): return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request)) class msg_blocktxn: __slots__ = ("block_transactions",) msgtype = b"blocktxn" def __init__(self): self.block_transactions = BlockTransactions() def deserialize(self, f): self.block_transactions.deserialize(f) def serialize(self): r = b"" r += self.block_transactions.serialize() return r def __repr__(self): return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions)) class msg_no_witness_blocktxn(msg_blocktxn): __slots__ = () def serialize(self): return self.block_transactions.serialize(with_witness=False) class msg_getcfilters: __slots__ = ("filter_type", "start_height", "stop_hash") msgtype = b"getcfilters" def __init__(self, filter_type, start_height, stop_hash): self.filter_type = filter_type self.start_height = start_height self.stop_hash = stop_hash def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.start_height = struct.unpack("<I", f.read(4))[0] self.stop_hash = deser_uint256(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += struct.pack("<I", self.start_height) r += ser_uint256(self.stop_hash) return r def __repr__(self): return "msg_getcfilters(filter_type={:#x}, start_height={}, stop_hash={:x})".format( self.filter_type, self.start_height, self.stop_hash) class msg_cfilter: __slots__ = ("filter_type", "block_hash", "filter_data") msgtype = b"cfilter" def __init__(self, filter_type=None, block_hash=None, filter_data=None): self.filter_type = filter_type self.block_hash = block_hash self.filter_data = filter_data def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.block_hash = deser_uint256(f) self.filter_data = deser_string(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += ser_uint256(self.block_hash) r += ser_string(self.filter_data) return r def __repr__(self): return "msg_cfilter(filter_type={:#x}, block_hash={:x})".format( self.filter_type, self.block_hash) class msg_getcfheaders: __slots__ = ("filter_type", "start_height", "stop_hash") msgtype = b"getcfheaders" def __init__(self, filter_type, start_height, stop_hash): self.filter_type = filter_type self.start_height = start_height self.stop_hash = stop_hash def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.start_height = struct.unpack("<I", f.read(4))[0] self.stop_hash = deser_uint256(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += struct.pack("<I", self.start_height) r += ser_uint256(self.stop_hash) return r def __repr__(self): return "msg_getcfheaders(filter_type={:#x}, start_height={}, stop_hash={:x})".format( self.filter_type, self.start_height, self.stop_hash) class msg_cfheaders: __slots__ = ("filter_type", "stop_hash", "prev_header", "hashes") msgtype = b"cfheaders" def __init__(self, filter_type=None, stop_hash=None, prev_header=None, hashes=None): self.filter_type = filter_type self.stop_hash = stop_hash self.prev_header = prev_header self.hashes = hashes def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.stop_hash = deser_uint256(f) self.prev_header = deser_uint256(f) self.hashes = deser_uint256_vector(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += ser_uint256(self.stop_hash) r += ser_uint256(self.prev_header) r += ser_uint256_vector(self.hashes) return r def __repr__(self): return "msg_cfheaders(filter_type={:#x}, stop_hash={:x})".format( self.filter_type, self.stop_hash) class msg_getcfcheckpt: __slots__ = ("filter_type", "stop_hash") msgtype = b"getcfcheckpt" def __init__(self, filter_type, stop_hash): self.filter_type = filter_type self.stop_hash = stop_hash def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.stop_hash = deser_uint256(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += ser_uint256(self.stop_hash) return r def __repr__(self): return "msg_getcfcheckpt(filter_type={:#x}, stop_hash={:x})".format( self.filter_type, self.stop_hash) class msg_cfcheckpt: __slots__ = ("filter_type", "stop_hash", "headers") msgtype = b"cfcheckpt" def __init__(self, filter_type=None, stop_hash=None, headers=None): self.filter_type = filter_type self.stop_hash = stop_hash self.headers = headers def deserialize(self, f): self.filter_type = struct.unpack("<B", f.read(1))[0] self.stop_hash = deser_uint256(f) self.headers = deser_uint256_vector(f) def serialize(self): r = b"" r += struct.pack("<B", self.filter_type) r += ser_uint256(self.stop_hash) r += ser_uint256_vector(self.headers) return r def __repr__(self): return "msg_cfcheckpt(filter_type={:#x}, stop_hash={:x})".format( self.filter_type, self.stop_hash)
28.754199
262
0.604537
[ "MIT" ]
UFO-ETL/ufo
test/functional/test_framework/messages.py
51,355
Python
def main(): def Problem1(): def Problem2(): def Problem3(): def Problem4(): def Problem1(): def countFunction for .count(0 <= NUMBER) def Problem2(): userInput = "" while(userInput != 'q'): userInput = input("Enter something") def Problem3(): def addFunction def subtractFunction def multiplyFunction def divideFunction userInput = input("Enter two numbers") .run(addFunction) .run(subtractFunction) .run(multiplyFunction) .run(divideFunction) def Problem4(): userInput = input("Give me a number") def twoNumbersFunction userInput2 = input("Do you want to add, subtract, multiply, or divide the two numbers?") return str print(userInput) print(userInput2) print(result)
20.171429
88
0.719547
[ "Apache-2.0" ]
cs-fullstack-2019-spring/python-functions-cw-rdunavant
CW.py
706
Python
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = u'Messages' copyright = u'2018, Tim Phillips' author = u'Tim Phillips, Tasha Chin' # The short X.Y version version = u'' # The full version, including alpha/beta/rc tags release = u'' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'Messagesdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Messages.tex', u'Messages Documentation', u'Tasha Chin', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'messages', u'Messages Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Messages', u'Messages Documentation', author, 'Messages', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html']
29.809249
79
0.653481
[ "MIT" ]
Ipv6Python/messages
docs/conf.py
5,157
Python
from unittest import TestCase, mock from bulksms.sms import send_single, send_bulk class BulkSMSTestCase(TestCase): def test_send_single_sms(self): # Mock send single sms function. mock_send_single = mock.create_autospec(send_single, return_value='results') mock_send_single('0831234567', 'Message.') mock_send_single.assert_called_once_with('0831234567', 'Message.') self.assertEqual(mock_send_single.call_count, 1) def test_send_bulk_sms(self): # Mock send bulk sms function. mock_send_bulk = mock.create_autospec(send_bulk, return_value='results') mock_send_bulk('test.txt') mock_send_bulk.assert_called_once_with('test.txt') self.assertEqual(mock_send_bulk.call_count, 1)
38.4
84
0.729167
[ "MIT" ]
tsotetsi/django-bulksms
tests/unit/test_bulksms.py
768
Python
import os from options.train_options import TrainOptions from models import create_model from util.visualizer import save_images from util import html from PIL import Image import string import torch import torchvision import torchvision.transforms as transforms import coremltools as ct from util import util import numpy as np opt = TrainOptions().gather_options() opt.isTrain = True opt.name = "siggraph_caffemodel" opt.mask_cent = 0 # opt.name = "siggraph_retrained" opt.gpu_ids = [] opt.load_model = True opt.num_threads = 1 # test code only supports num_threads = 1 opt.batch_size = 1 # test code only supports batch_size = 1 opt.display_id = -1 # no visdom display opt.phase = 'val' opt.dataroot = './dataset/ilsvrc2012/%s/' % opt.phase opt.serial_batches = True opt.aspect_ratio = 1. # process opt.suffix if opt.suffix: suffix = ('_' + opt.suffix.format(**vars(opt)) ) if opt.suffix != '' else '' opt.name = opt.name + suffix opt.A = 2 * opt.ab_max / opt.ab_quant + 1 opt.B = opt.A class Colorization(torch.nn.Module): def __init__(self): super(Colorization, self).__init__() model = create_model(opt) model.setup(opt) model.eval() self.model = model def forward(self, image, hint): data = { "A": image[:, 0:1, :, :], "B": image[:, 1:3, :, :], "hint_B": hint[:, 0:2, :, :], "mask_B": hint[:, 2:3, :, :] } # with torch.no_grad(): self.model.set_input(data) self.model.forward() fake_reg = torch.cat((self.model.real_A, self.model.fake_B_reg), dim=1) return fake_reg image_path = "./large.JPG" image = Image.open(image_path) image = transforms.Compose([ transforms.Resize(512), transforms.ToTensor(), ])(image) image = image.view(1, *image.shape) image = util.crop_mult(image, mult=8, HWmax=[4032, 4032]) transforms.ToPILImage()(image[0]).show(command='fim') data = util.get_colorization_data( [image], opt, ab_thresh=0., p=0.125) img = torch.cat((data["A"], data["B"]), dim=1) hint = torch.cat((data["hint_B"], data["mask_B"]), dim=1) # print(data["mask_B"], data["hint_B"]) # data["hint_B"] = torch.zeros_like(data["hint_B"]) # data["mask_B"] = torch.zeros_like(data["mask_B"]) # model = Colorization() with torch.no_grad(): model = Colorization() model.eval() for param in model.parameters(): param.requires_grad = False model.model.set_requires_grad(model.model.netG) # model(data) # transforms.ToPILImage()(image[0]).show(command='fim') # to_visualize = ['gray', 'hint', 'hint_ab', 'fake_entr', # 'real', 'fake_reg', 'real_ab', 'fake_ab_reg', ] # visuals = util.get_subset_dict( # model.model.get_current_visuals(), to_visualize) # for key, value in visuals.items(): # print(key) # transforms.ToPILImage()(value[0]).show(command='fim') output = model(img, hint) output = util.lab2rgb(output, opt=opt) transforms.ToPILImage()(output[0]).show(command='fim') traced_model = torch.jit.trace( model, (img, hint), check_trace=False) mlmodel = ct.convert(model=traced_model, inputs=[ ct.TensorType(name="image", shape=ct.Shape( shape=(1, 3, ct.RangeDim(1, 4096), ct.RangeDim(1, 4096)))), ct.TensorType(name="hint", shape=ct.Shape( shape=(1, 3, ct.RangeDim(1, 4096), ct.RangeDim(1, 4096)))), ]) mlmodel.save("~/color.mlmodel")
29.222222
79
0.65253
[ "MIT" ]
zengxinzhy/colorization-pytorch
imtest.py
3,419
Python
from __future__ import division from itertools import combinations_with_replacement import numpy as np import math import sys def shuffle_data(X, y, seed=None): if seed: np.random.seed(seed) n_samples = X.shape[0] idx = np.arange(n_samples) np.random.shuffle(idx) X = X[idx] y = y[idx] return X, y # Divide dataset based on if sample value on feature index is larger than # the given threshold def divide_on_feature(X, feature_i, threshold): split_func = None if isinstance(threshold, int) or isinstance(threshold, float): split_func = lambda sample: sample[feature_i] >= threshold else: split_func = lambda sample: sample[feature_i] == threshold X_1 = np.array([sample for sample in X if split_func(sample)]) X_2 = np.array([sample for sample in X if not split_func(sample)]) return np.array([X_1, X_2]) def polynomial_features(X, degree): n_samples, n_features = np.shape(X) def index_combinations(): combs = [combinations_with_replacement(range(n_features), i) for i in range(0, degree + 1)] flat_combs = [item for sublist in combs for item in sublist] return flat_combs combinations = index_combinations() n_output_features = len(combinations) X_new = np.empty((n_samples, n_output_features)) for i, index_combs in enumerate(combinations): X_new[:, i] = np.prod(X[:, index_combs], axis=1) return X_new # Return random subsets (with replacements) of the data def get_random_subsets(X, y, n_subsets, replacements=True): n_samples = np.shape(X)[0] # Concatenate x and y and do a random shuffle X_y = np.concatenate((X, y.reshape((1, len(y))).T), axis=1) np.random.shuffle(X_y) subsets = [] # Uses 50% of training samples without replacements subsample_size = n_samples // 2 if replacements: subsample_size = n_samples # 100% with replacements for _ in range(n_subsets): idx = np.random.choice( range(n_samples), size=np.shape(range(subsample_size)), replace=replacements) X = X_y[idx][:, :-1] y = X_y[idx][:, -1] subsets.append([X, y]) return subsets # Normalize the dataset X def normalize(X, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(X, order, axis)) l2[l2 == 0] = 1 return X / np.expand_dims(l2, axis) # Standardize the dataset X def standardize(X): X_std = X mean = X.mean(axis=0) std = X.std(axis=0) for col in range(np.shape(X)[1]): if std[col]: X_std[:, col] = (X_std[:, col] - mean[col]) / std[col] # X_std = (X - X.mean(axis=0)) / X.std(axis=0) return X_std # Split the data into train and test sets def train_test_split(X, y, test_size=0.5, shuffle=True, seed=None): if shuffle: X, y = shuffle_data(X, y, seed) # Split the training data from test data in the ratio specified in # test_size split_i = len(y) - int(len(y) // (1 / test_size)) x_train, x_test = X[:split_i], X[split_i:] y_train, y_test = y[:split_i], y[split_i:] return x_train, x_test, y_train, y_test # Split the data into k sets of training / test data def k_fold_cross_validation_sets(X, y, k, shuffle=True): if shuffle: X, y = shuffle_data(X, y) n_samples = len(y) left_overs = {} n_left_overs = (n_samples % k) if n_left_overs != 0: left_overs["X"] = X[-n_left_overs:] left_overs["y"] = y[-n_left_overs:] X = X[:-n_left_overs] y = y[:-n_left_overs] X_split = np.split(X, k) y_split = np.split(y, k) sets = [] for i in range(k): X_test, y_test = X_split[i], y_split[i] X_train = np.concatenate(X_split[:i] + X_split[i + 1:], axis=0) y_train = np.concatenate(y_split[:i] + y_split[i + 1:], axis=0) sets.append([X_train, X_test, y_train, y_test]) # Add left over samples to last set as training samples if n_left_overs != 0: np.append(sets[-1][0], left_overs["X"], axis=0) np.append(sets[-1][2], left_overs["y"], axis=0) return np.array(sets) # Making an array of nominal values into a binarized matrix def categorical_to_binary(x): n_col = np.amax(x) + 1 binarized = np.zeros((len(x), n_col)) for i in range(len(x)): binarized[i, x[i]] = 1 return binarized # Converting from binary vectors to nominal values def binary_to_categorical(x): categorical = [] for i in range(len(x)): if not 1 in x[i]: categorical.append(0) else: i_where_one = np.where(x[i] == 1)[0][0] categorical.append(i_where_one) return categorical # Converts a vector into an diagonal matrix def make_diagonal(x): m = np.zeros((len(x), len(x))) for i in range(len(m[0])): m[i, i] = x[i] return m
29.125
99
0.626405
[ "MIT" ]
MachineLearningCommunity/ML-From-Scratch
mlfromscratch/utils/data_manipulation.py
4,893
Python
''' This file is a part of Test Mile Arjuna Copyright 2018 Test Mile Software Testing Pvt Ltd Website: www.TestMile.com Email: support [at] testmile.com Creator: Rahul Verma 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 arjuna.core.exceptions import * class DataSourceFinished(StopIteration): def __init__(self, msg=None): super().__init__(msg is None and "Done" or msg) class EmptyListDataRecordLookupException(Exception): def __init__(self, index): super().__init__("Invalid index [%s] used for list data record lookup. It is empty.".format(index)) class ListDataRecordLookupException(Exception): def __init__(self, index, max_index): super().__init__( "Invalid index [%s] used for list data record lookup. Use indices between 0 and %d".format(index, max_index)) class MapDataRecordLookupException(Exception): def __init__(self, key): super().__init__("Invalid Key/header [%s] used for map data record lookup.".format(key)) class DataSourceConstructionError(Exception): def __init__(self, message, name, exc): super().__init__(message) self.name = name self.exc = exc def get_Exception(self): return self.exc def get_Name(self): return self.name class InvalidTestObjectException(Exception): pass class SessionNodesFinishedException(Exception): def __init__(self): super().__init__("Done") class SubTestsFinished(Exception): def __init__(self): super().__init__("Done") class TestGroupsFinishedException(Exception): def __init__(self): super().__init__("Done") class PickerMisConfigurationException(Exception): def __init__(self): super().__init__("Picker is misconfigured.") # Test Result Related class StepResultEvent(ArjunaException): def __init__(self, step): super().__init__(step.assert_message) self.step = step class Pass(StepResultEvent): def __init__(self, check): super().__init__(check) class Error(StepResultEvent): def __init__(self, step): super().__init__(step) class Failure(StepResultEvent): def __init__(self, step): super().__init__(step) class DependencyNotMet(Exception): def __init__(self, iid): self.iid = iid
27.485714
114
0.688496
[ "Apache-2.0" ]
test-mile/arjuna
arjuna/engine/unitee/exceptions.py
2,886
Python
# Copyright The PyTorch Lightning team. # # 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. """General utilities.""" import numpy from pytorch_lightning.utilities.apply_func import move_data_to_device # noqa: F401 from pytorch_lightning.utilities.distributed import AllGatherGrad # noqa: F401 from pytorch_lightning.utilities.enums import ( # noqa: F401 _AcceleratorType, _StrategyType, AMPType, DistributedType, GradClipAlgorithmType, LightningEnum, ModelSummaryMode, ) from pytorch_lightning.utilities.grads import grad_norm # noqa: F401 from pytorch_lightning.utilities.imports import ( # noqa: F401 _APEX_AVAILABLE, _BAGUA_AVAILABLE, _DEEPSPEED_AVAILABLE, _FAIRSCALE_AVAILABLE, _FAIRSCALE_FULLY_SHARDED_AVAILABLE, _FAIRSCALE_OSS_FP16_BROADCAST_AVAILABLE, _GROUP_AVAILABLE, _HIVEMIND_AVAILABLE, _HOROVOD_AVAILABLE, _HPU_AVAILABLE, _HYDRA_AVAILABLE, _HYDRA_EXPERIMENTAL_AVAILABLE, _IPU_AVAILABLE, _IS_INTERACTIVE, _IS_WINDOWS, _module_available, _OMEGACONF_AVAILABLE, _POPTORCH_AVAILABLE, _RICH_AVAILABLE, _TORCH_GREATER_EQUAL_1_9, _TORCH_GREATER_EQUAL_1_10, _TORCH_GREATER_EQUAL_1_11, _TORCH_QUANTIZE_AVAILABLE, _TORCHTEXT_AVAILABLE, _TORCHVISION_AVAILABLE, _TPU_AVAILABLE, _XLA_AVAILABLE, ) from pytorch_lightning.utilities.parameter_tying import find_shared_parameters, set_shared_parameters # noqa: F401 from pytorch_lightning.utilities.parsing import AttributeDict, flatten_dict, is_picklable # noqa: F401 from pytorch_lightning.utilities.rank_zero import ( # noqa: F401 rank_zero_deprecation, rank_zero_info, rank_zero_only, rank_zero_warn, ) FLOAT16_EPSILON = numpy.finfo(numpy.float16).eps FLOAT32_EPSILON = numpy.finfo(numpy.float32).eps FLOAT64_EPSILON = numpy.finfo(numpy.float64).eps
33.169014
115
0.780042
[ "Apache-2.0" ]
jerome-habana/pytorch-lightning
pytorch_lightning/utilities/__init__.py
2,355
Python
""" WSGI config for poker project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'poker.settings') application = get_wsgi_application()
22.764706
78
0.782946
[ "MIT" ]
yuriymironov96/python-poker
poker/wsgi.py
387
Python
#!/usr/bin/env python # Import required modules from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str import os import argparse import subprocess import ICA_AROMA_functions as aromafunc import shutil import classification_plots # Change to script directory cwd = os.path.realpath(os.path.curdir) scriptDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(scriptDir) #-------------------------------------------- PARSER --------------------------------------------# parser = argparse.ArgumentParser( description= 'Script to run ICA-AROMA v0.3 beta (\'ICA-based Automatic Removal Of Motion Artifacts\') on fMRI data. See the companion manual for further information.' ) # Required options reqoptions = parser.add_argument_group('Required arguments') reqoptions.add_argument( '-o', '-out', dest="outDir", required=True, help='Output directory name') # Required options in non-Feat mode nonfeatoptions = parser.add_argument_group('Required arguments - generic mode') nonfeatoptions.add_argument( '-i', '-in', dest="inFile", required=False, help='Input file name of fMRI data (.nii.gz)') nonfeatoptions.add_argument( '-mc', dest="mc", required=False, help= 'File name of the motion parameters obtained after motion realingment (e.g., FSL mcflirt). Note that the order of parameters does not matter, should your file not originate from FSL mcflirt. (e.g., /home/user/PROJECT/SUBJECT.feat/mc/prefiltered_func_data_mcf.par' ) nonfeatoptions.add_argument( '-a', '-affmat', dest="affmat", default="", help= 'File name of the mat-file describing the affine registration (e.g., FSL FLIRT) of the functional data to structural space (.mat file). (e.g., /home/user/PROJECT/SUBJECT.feat/reg/example_func2highres.mat' ) nonfeatoptions.add_argument( '-w', '-warp', dest="warp", default="", help= 'File name of the warp-file describing the non-linear registration (e.g., FSL FNIRT) of the structural data to MNI152 space (.nii.gz). (e.g., /home/user/PROJECT/SUBJECT.feat/reg/highres2standard_warp.nii.gz' ) nonfeatoptions.add_argument( '-m', '-mask', dest="mask", default="", help= 'File name of the mask to be used for MELODIC (denoising will be performed on the original/non-masked input data)' ) # Required options in Feat mode featoptions = parser.add_argument_group('Required arguments - FEAT mode') featoptions.add_argument( '-f', '-feat', dest="inFeat", required=False, help= 'Feat directory name (Feat should have been run without temporal filtering and including registration to MNI152)' ) # Optional options optoptions = parser.add_argument_group('Optional arguments') optoptions.add_argument('-tr', dest="TR", help='TR in seconds', type=float) optoptions.add_argument( '-den', dest="denType", default="nonaggr", help= 'Type of denoising strategy: \'no\': only classification, no denoising; \'nonaggr\': non-aggresssive denoising (default); \'aggr\': aggressive denoising; \'both\': both aggressive and non-aggressive denoising (seperately)' ) optoptions.add_argument( '-md', '-meldir', dest="melDir", default="", help='MELODIC directory name, in case MELODIC has been run previously.') optoptions.add_argument( '-dim', dest="dim", default=0, help= 'Dimensionality reduction into #num dimensions when running MELODIC (default: automatic estimation; i.e. -dim 0)', type=int) optoptions.add_argument( '-ow', '-overwrite', dest="overwrite", action='store_true', help='Overwrite existing output', default=False) print( '\n------------------------------- RUNNING ICA-AROMA ------------------------------- ' ) print( '--------------- \'ICA-based Automatic Removal Of Motion Artifacts\' --------------- \n' ) #--------------------------------------- PARSE ARGUMENTS ---------------------------------------# args = parser.parse_args() # Define variables based on the type of input (i.e. Feat directory or specific input arguments), and check whether the specified files exist. cancel = False if args.inFeat: inFeat = args.inFeat # Check whether the Feat directory exists if not os.path.isdir(inFeat): print('The specified Feat directory does not exist.') print( '\n----------------------------- ICA-AROMA IS CANCELED -----------------------------\n' ) exit() # Define the variables which should be located in the Feat directory inFile = os.path.join(args.inFeat, 'filtered_func_data.nii.gz') mc = os.path.join(args.inFeat, 'mc', 'prefiltered_func_data_mcf.par') affmat = os.path.join(args.inFeat, 'reg', 'example_func2highres.mat') warp = os.path.join(args.inFeat, 'reg', 'highres2standard_warp.nii.gz') # Check whether these files actually exist if not os.path.isfile(inFile): print('Missing filtered_func_data.nii.gz in Feat directory.') cancel = True if not os.path.isfile(mc): print('Missing mc/prefiltered_func_data_mcf.mat in Feat directory.') cancel = True if not os.path.isfile(affmat): print('Missing reg/example_func2highres.mat in Feat directory.') cancel = True if not os.path.isfile(warp): print('Missing reg/highres2standard_warp.nii.gz in Feat directory.') cancel = True # Check whether a melodic.ica directory exists if os.path.isdir(os.path.join(args.inFeat, 'filtered_func_data.ica')): melDir = os.path.join(args.inFeat, 'filtered_func_data.ica') else: melDir = args.melDir else: inFile = args.inFile mc = args.mc affmat = args.affmat warp = args.warp melDir = args.melDir # Check whether the files exist if not inFile: print('No input file specified.') else: if not os.path.isfile(inFile): print('The specified input file does not exist.') cancel = True if not mc: print('No mc file specified.') else: if not os.path.isfile(mc): print('The specified mc file does does not exist.') cancel = True if affmat: if not os.path.isfile(affmat): print('The specified affmat file does not exist.') cancel = True if warp: if not os.path.isfile(warp): print('The specified warp file does not exist.') cancel = True # Parse the arguments which do not depend on whether a Feat directory has been specified outDir = args.outDir dim = args.dim denType = args.denType # Check if the mask exists, when specified. if args.mask: if not os.path.isfile(args.mask): print('The specified mask does not exist.') cancel = True # Check if the type of denoising is correctly specified, when specified if not (denType == 'nonaggr') and not (denType == 'aggr') and not ( denType == 'both') and not (denType == 'no'): print( 'Type of denoising was not correctly specified. Non-aggressive denoising will be run.' ) denType = 'nonaggr' # If the criteria for file/directory specifications have not been met. Cancel ICA-AROMA. if cancel: print( '\n----------------------------- ICA-AROMA IS CANCELED -----------------------------\n' ) exit() #------------------------------------------- PREPARE -------------------------------------------# # Define the FSL-bin directory fslDir = os.path.join(os.environ["FSLDIR"], 'bin', '') # Create output directory if needed if os.path.isdir(outDir) and args.overwrite is False: print( 'Output directory', outDir, """already exists. AROMA will not continue. Rerun with the -overwrite option to explicitly overwrite existing output.""" ) exit() elif os.path.isdir(outDir) and args.overwrite is True: print('Warning! Output directory', outDir, 'exists and will be overwritten.\n') shutil.rmtree(outDir) os.makedirs(outDir) else: os.makedirs(outDir) # Get TR of the fMRI data, if not specified if args.TR: TR = args.TR else: cmd = ' '.join([ os.path.join(fslDir, 'fslinfo'), inFile, '| grep pixdim4 | awk \'{print $2}\'' ]) TR = float(subprocess.getoutput(cmd)) # Check TR if TR == 1: print('Warning! Please check whether the determined TR (of ' + str(TR) + 's) is correct!\n') elif TR == 0: print( 'TR is zero. ICA-AROMA requires a valid TR and will therefore exit. Please check the header, or define the TR as an additional argument.\n----------------------------- ICA-AROMA IS CANCELED -----------------------------\n' ) exit() # Define/create mask. Either by making a copy of the specified mask, or by creating a new one. mask = os.path.join(outDir, 'mask.nii.gz') if args.mask: shutil.copyfile(args.mask, mask) else: # If a Feat directory is specified, and an example_func is present use example_func to create a mask if args.inFeat and os.path.isfile( os.path.join(inFeat, 'example_func.nii.gz')): os.system(' '.join([ os.path.join(fslDir, 'bet'), os.path.join(inFeat, 'example_func.nii.gz'), os.path.join(outDir, 'bet'), '-f 0.3 -n -m -R' ])) os.system(' '.join( ['mv', os.path.join(outDir, 'bet_mask.nii.gz'), mask])) if os.path.isfile(os.path.join(outDir, 'bet.nii.gz')): os.remove(os.path.join(outDir, 'bet.nii.gz')) else: if args.inFeat: print( ' - No example_func was found in the Feat directory. A mask will be created including all voxels with varying intensity over time in the fMRI data. Please check!\n' ) os.system(' '.join( [os.path.join(fslDir, 'fslmaths'), inFile, '-Tstd -bin', mask])) #---------------------------------------- Run ICA-AROMA ----------------------------------------# print('Step 1) MELODIC') aromafunc.runICA(fslDir, inFile, outDir, melDir, mask, dim, TR) print('Step 2) Automatic classification of the components') print(' - registering the spatial maps to MNI') melIC = os.path.join(outDir, 'melodic_IC_thr.nii.gz') melIC_MNI = os.path.join(outDir, 'melodic_IC_thr_MNI2mm.nii.gz') aromafunc.register2MNI(fslDir, melIC, melIC_MNI, affmat, warp) print(' - extracting the CSF & Edge fraction features') edgeFract, csfFract = aromafunc.feature_spatial(fslDir, outDir, scriptDir, melIC_MNI) print(' - extracting the Maximum RP correlation feature') melmix = os.path.join(outDir, 'melodic.ica', 'melodic_mix') maxRPcorr = aromafunc.feature_time_series(melmix, mc) print(' - extracting the High-frequency content feature') melFTmix = os.path.join(outDir, 'melodic.ica', 'melodic_FTmix') HFC = aromafunc.feature_frequency(melFTmix, TR) print(' - classification') motionICs = aromafunc.classification(outDir, maxRPcorr, edgeFract, HFC, csfFract) # classification_plots.classification_plot(os.path.join(outDir, 'classification_overview.txt'), # outDir) if (denType != 'no'): print('Step 3) Data denoising') aromafunc.denoising(fslDir, inFile, outDir, melmix, denType, motionICs) # Remove thresholded melodic_IC file os.remove(melIC) # Revert to old directory os.chdir(cwd) print( '\n----------------------------------- Finished -----------------------------------\n' )
35.521472
267
0.629102
[ "MIT" ]
spunt/bspm
thirdparty/ICA_AROMA_79x95x69/ICA_AROMA.py
11,580
Python
#!/usr/bin/env python from markovLatex.markov import TextGenerator import argparse, sys def main(args): parser = argparse.ArgumentParser(description="Generate pseudorandom text from input text files.") parser.add_argument('files', type=str, nargs='+', help='one or more input text files') parser.add_argument('-p','--paragraphs', type=int, default=1, help='The number of paragraphs in the output text') args = parser.parse_args(args) corpus = [] for arg in args.files: try: corpus.append(open(arg, 'r')) except Exception as e: print(e) if corpus: try: text_generator = TextGenerator(corpus) for i in range(0, args.paragraphs): print(text_generator.paragraph()) except Exception as e: print(e) return 1 return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
27.617647
117
0.614483
[ "MIT" ]
SeanMcGrath/MarkovLatex
markovgen.py
939
Python
# -*- coding: utf-8 -*- # Copyright Hannah von Reth <[email protected]> # # 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. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. ### fetch functions from CraftCore import CraftCore from CraftDebug import deprecated import utils import io import os import urllib import subprocess import sys import re def getFile(url, destdir, filename='', quiet=None) -> bool: """download file from 'url' into 'destdir'""" if quiet is None: quiet = CraftCore.settings.getboolean("ContinuousIntegration", "Enabled", False) CraftCore.log.debug("getFile called. url: %s" % url) if url == "": CraftCore.log.error("fetch: no url given") return False pUrl = urllib.parse.urlparse(url) if not filename: filename = os.path.basename(pUrl.path) utils.createDir(destdir) if pUrl.scheme == "s3": return s3File(url, destdir, filename) elif pUrl.scheme == "minio": return minioGet(pUrl.netloc + pUrl.path, destdir, filename) # curl and wget basically only work when we have a cert store on windows if not CraftCore.compiler.isWindows or os.path.exists(os.path.join(CraftCore.standardDirs.etcDir(), "cacert.pem")): if not CraftCore.settings.getboolean("General", "NoWget"): if CraftCore.cache.findApplication("wget"): return wgetFile(url, destdir, filename, quiet) if CraftCore.cache.findApplication("curl"): return curlFile(url, destdir, filename, quiet) if os.path.exists(os.path.join(destdir, filename)): return True powershell = CraftCore.cache.findApplication("powershell") if powershell: filename = os.path.join(destdir, filename) return utils.system([powershell, "-NoProfile", "-ExecutionPolicy", "ByPass", "-Command", f"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; (new-object net.webclient).DownloadFile(\"{url}\", \"{filename}\")"]) else: def dlProgress(count, blockSize, totalSize): if totalSize != -1: percent = int(count * blockSize * 100 / totalSize) utils.printProgress(percent) else: sys.stdout.write(("\r%s bytes downloaded" % (count * blockSize))) sys.stdout.flush() try: urllib.request.urlretrieve(url, filename=os.path.join(destdir, filename), reporthook=dlProgress if CraftCore.debug.verbose() >= 0 else None) except Exception as e: CraftCore.log.warning(e) return False if CraftCore.debug.verbose() >= 0: sys.stdout.write("\n") sys.stdout.flush() return True def curlFile(url, destdir, filename, quiet): """download file with curl from 'url' into 'destdir', if filename is given to the file specified""" curl = CraftCore.cache.findApplication("curl") command = [curl, "-C", "-", "--retry", "10", "-L", "--ftp-ssl", "--fail"] cert = os.path.join(CraftCore.standardDirs.etcDir(), "cacert.pem") if os.path.exists(cert): command += ["--cacert", cert] # the default of 20 might not be enough for sourceforge ... command += ["--max-redirs", "50"] command += ["-o", os.path.join(destdir, filename)] command += [url] CraftCore.log.debug("curlfile called") if CraftCore.debug.verbose() < 1: if quiet: with io.StringIO() as tmp: ciMode = CraftCore.settings.getboolean("ContinuousIntegration", "Enabled", False) if ciMode: command += ["-v"] if not utils.system(command, logCommand=ciMode, stdout=tmp, stderr=subprocess.STDOUT): CraftCore.log.warning(tmp.getvalue()) return False if ciMode: loc = re.findall(r"Host: ([^\s]+)", tmp.getvalue()) if loc: CraftCore.log.info(f"Downloaded from: {loc[-1]}") return True elif CraftCore.cache.checkCommandOutputFor(curl, "--progress-bar"): command += ["--progress-bar"] CraftCore.log.info(f"curl {url}") return utils.system(command, displayProgress=True, logCommand=False, stderr=subprocess.STDOUT) command += ["-v"] return utils.system(command) def wgetFile(url, destdir, filename, quiet): """download file with wget from 'url' into 'destdir', if filename is given to the file specified""" wget = CraftCore.cache.findApplication("wget") command = [wget, "-c", "-t", "10"] cert = os.path.join(CraftCore.standardDirs.etcDir(), "cacert.pem") if os.path.exists(cert): command += ["--ca-certificate", cert] # the default of 20 might not be enough for sourceforge ... command += ["--max-redirect", "50"] if CraftCore.settings.getboolean("General", "EMERGE_NO_PASSIVE_FTP", False): command += ["--no-passive-ftp"] if not filename: command += ["-P", destdir] else: command += ["-O", os.path.join(destdir, filename)] command += [url] if CraftCore.debug.verbose() < 1: if quiet: with io.StringIO() as tmp: ciMode = CraftCore.settings.getboolean("ContinuousIntegration", "Enabled", False) if not utils.system(command, logCommand=ciMode, stdout=tmp, stderr=subprocess.STDOUT): CraftCore.log.warning(tmp.getvalue()) return False if ciMode: loc = re.findall(r"Location: ([^\s]+)", tmp.getvalue()) if loc: CraftCore.log.info(f"Downloaded from: {loc[-1]}") return True elif CraftCore.cache.checkCommandOutputFor(wget, "--show-progress"): command += ["-q", "--show-progress"] CraftCore.log.info(f"wget {url}") return utils.system(command, displayProgress=True, logCommand=False, stderr=subprocess.STDOUT) return utils.system(command) def s3File(url : str, destdir : str, filename : str) ->bool: aws = CraftCore.cache.findApplication("aws") if not aws: CraftCore.log.critical("aws not found, please install awscli. \"pip install awscli\" ") return False return utils.system([aws, "s3", "cp", url, os.path.join(destdir, filename)]) def minioGet(url : str, destdir : str, filename : str) ->bool: minio = None if CraftCore.compiler.isWindows: minio = CraftCore.cache.findApplication("minio") if not minio: minio = CraftCore.cache.findApplication("mc") if not minio: CraftCore.log.critical("minio client not found, please install minio") return False return utils.system([minio, "cp", url, os.path.join(destdir, filename)])
43.448649
175
0.635357
[ "BSD-2-Clause" ]
C-EO/craft
bin/Utils/GetFiles.py
8,038
Python
#!/usr/bin/env python import unittest import Cheetah import Cheetah.Parser import Cheetah.Template class Chep_2_Conditionalized_Import_Behavior(unittest.TestCase): def test_ModuleLevelImport(self): ''' Verify module level (traditional) import behavior ''' pass def test_InlineImport(self): ''' Verify (new) inline import behavior works ''' template = ''' #def funky($s) #try #import urllib #except ImportError #pass #end try #return urllib.quote($s) #end def ''' try: template = Cheetah.Template.Template.compile(template) except Cheetah.Parser.ParseError, ex: self.fail('Failed to properly generate code %s' % ex) template = template() rc = tepmlate.funky('abc def') assert rc == 'abc+def' def test_LegacyMode(self): ''' Verify disabling of CHEP #2 works ''' pass if __name__ == '__main__': unittest.main()
26.95
66
0.565863
[ "MIT" ]
analurandis/Tur
backend/venv/Lib/site-packages/Cheetah/Tests/Cheps.py
1,078
Python
import requests from requests.auth import HTTPBasicAuth r = requests.get('http://localhost:5000', auth=HTTPBasicAuth('username', 'password')) print(r.status_code)
32.6
85
0.785276
[ "Apache-2.0" ]
silianpan/seal-spider-demo
requests/demo27.py
163
Python
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zhekudblog.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.636364
74
0.684127
[ "MIT" ]
ZhekuD/ZhekuDBlog
src/zhekudblog/manage.py
630
Python
import discord from discord.ext import commands from core import checks from core.models import PermissionLevel class Suggest(commands.Cog): """ Let's you send a suggestion to a designated channel. """ def __init__(self, bot): self.bot = bot self.coll = bot.plugin_db.get_partition(self) @commands.command(aliases = ['ssc']) @checks.has_permissions(PermissionLevel.ADMIN) async def setsuggestchannel(self, ctx, channel: discord.TextChannel): """ Set the channel where suggestions go. """ await self.coll.find_one_and_update( {"_id": "config"}, {"$set": {"suggestion-channel": {"channel": str(channel.id)}}}, upsert=True, ) embed=discord.Embed(title=f'Set suggestion channel to {channel}.', color=0x4dff73) embed.set_author(name="Success!") embed.set_footer(text="Task succeeded successfully.") await ctx.send(embed=embed) @commands.command() async def suggest(self, ctx, *, suggestion): """ Suggest something! """ async with ctx.channel.typing(): config = await self.coll.find_one({"_id": "config"}) if config is None: embed=discord.Embed(title="Suggestion channel not set.", color=self.bot.error_colour) embed.set_author(name="Error.") embed.set_footer("Task failed successfully.") await ctx.send(embed=embed) else: suggestion_channel = self.bot.get_channel(int(config["suggestion-channel"]["channel"])) embed=discord.Embed(title=suggestion, color=self.bot.main_color) embed.set_author(name=f"Suggestion by {ctx.author}:", icon_url=ctx.author.avatar_url) await suggestion_channel.send(embed=embed) suggestion_channel.send(embed).then(embedMessage = { embedMessage.add_reaction('👍'); embedMessage.add_reaction('👎'); }); await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') def setup(bot): bot.add_cog(Suggest(bot))
38.836364
103
0.617041
[ "MIT" ]
AlertShamrock/modmail-plugins-2
suggest/suggest.py
2,142
Python
import numpy as np import tempfile import os import pytest import torch from anndata import AnnData from scvi.dataset import ( AnnDatasetFromAnnData, CortexDataset, SyntheticDataset, GeneExpressionDataset, Dataset10X, ) from scvi.inference import ( JointSemiSupervisedTrainer, AlternateSemiSupervisedTrainer, ClassifierTrainer, UnsupervisedTrainer, AdapterTrainer, TotalTrainer, TotalPosterior, ) from scvi.inference.posterior import unsupervised_clustering_accuracy from scvi.inference.posterior_utils import load_posterior from scvi.inference.annotation import compute_accuracy_rf, compute_accuracy_svc from scvi.models import VAE, SCANVI, VAEC, LDVAE, TOTALVI, AutoZIVAE from scvi.models.distributions import ZeroInflatedNegativeBinomial, NegativeBinomial from scvi.models.classifier import Classifier from scvi.models.log_likelihood import log_zinb_positive, log_nb_positive from scvi import set_seed set_seed(0) use_cuda = True def test_cortex(save_path): cortex_dataset = CortexDataset(save_path=save_path) vae = VAE(cortex_dataset.nb_genes, cortex_dataset.n_batches) trainer_cortex_vae = UnsupervisedTrainer( vae, cortex_dataset, train_size=0.5, use_cuda=use_cuda ) trainer_cortex_vae.train(n_epochs=1) trainer_cortex_vae.train_set.reconstruction_error() trainer_cortex_vae.train_set.differential_expression_stats() trainer_cortex_vae.train_set.generate_feature_correlation_matrix( n_samples=2, correlation_type="pearson" ) trainer_cortex_vae.train_set.generate_feature_correlation_matrix( n_samples=2, correlation_type="spearman" ) trainer_cortex_vae.train_set.imputation(n_samples=1) trainer_cortex_vae.test_set.imputation(n_samples=5) trainer_cortex_vae.corrupt_posteriors(corruption="binomial") trainer_cortex_vae.corrupt_posteriors() trainer_cortex_vae.train(n_epochs=1) trainer_cortex_vae.uncorrupt_posteriors() trainer_cortex_vae.train_set.imputation_benchmark( n_samples=1, show_plot=False, title_plot="imputation", save_path=save_path ) trainer_cortex_vae.train_set.generate_parameters() n_cells, n_genes = ( len(trainer_cortex_vae.train_set.indices), cortex_dataset.nb_genes, ) n_samples = 3 (dropout, means, dispersions) = trainer_cortex_vae.train_set.generate_parameters() assert dropout.shape == (n_cells, n_genes) and means.shape == (n_cells, n_genes) assert dispersions.shape == (n_cells, n_genes) (dropout, means, dispersions) = trainer_cortex_vae.train_set.generate_parameters( n_samples=n_samples ) assert dropout.shape == (n_samples, n_cells, n_genes) assert means.shape == (n_samples, n_cells, n_genes) (dropout, means, dispersions) = trainer_cortex_vae.train_set.generate_parameters( n_samples=n_samples, give_mean=True ) assert dropout.shape == (n_cells, n_genes) and means.shape == (n_cells, n_genes) full = trainer_cortex_vae.create_posterior( vae, cortex_dataset, indices=np.arange(len(cortex_dataset)) ) x_new, x_old = full.generate(n_samples=10) assert x_new.shape == (cortex_dataset.nb_cells, cortex_dataset.nb_genes, 10) assert x_old.shape == (cortex_dataset.nb_cells, cortex_dataset.nb_genes) trainer_cortex_vae.train_set.imputation_benchmark( n_samples=1, show_plot=False, title_plot="imputation", save_path=save_path ) svaec = SCANVI( cortex_dataset.nb_genes, cortex_dataset.n_batches, cortex_dataset.n_labels ) trainer_cortex_svaec = JointSemiSupervisedTrainer( svaec, cortex_dataset, n_labelled_samples_per_class=3, use_cuda=use_cuda ) trainer_cortex_svaec.train(n_epochs=1) trainer_cortex_svaec.labelled_set.accuracy() trainer_cortex_svaec.full_dataset.reconstruction_error() svaec = SCANVI( cortex_dataset.nb_genes, cortex_dataset.n_batches, cortex_dataset.n_labels ) trainer_cortex_svaec = AlternateSemiSupervisedTrainer( svaec, cortex_dataset, n_labelled_samples_per_class=3, use_cuda=use_cuda ) trainer_cortex_svaec.train(n_epochs=1, lr=1e-2) trainer_cortex_svaec.unlabelled_set.accuracy() data_train, labels_train = trainer_cortex_svaec.labelled_set.raw_data() data_test, labels_test = trainer_cortex_svaec.unlabelled_set.raw_data() compute_accuracy_svc( data_train, labels_train, data_test, labels_test, param_grid=[{"C": [1], "kernel": ["linear"]}], ) compute_accuracy_rf( data_train, labels_train, data_test, labels_test, param_grid=[{"max_depth": [3], "n_estimators": [10]}], ) cls = Classifier(cortex_dataset.nb_genes, n_labels=cortex_dataset.n_labels) cls_trainer = ClassifierTrainer(cls, cortex_dataset) cls_trainer.train(n_epochs=1) cls_trainer.train_set.accuracy() def test_synthetic_1(): synthetic_dataset = SyntheticDataset() synthetic_dataset.cell_types = np.array(["A", "B", "C"]) svaec = SCANVI( synthetic_dataset.nb_genes, synthetic_dataset.n_batches, synthetic_dataset.n_labels, ) trainer_synthetic_svaec = JointSemiSupervisedTrainer( svaec, synthetic_dataset, use_cuda=use_cuda ) trainer_synthetic_svaec.train(n_epochs=1) trainer_synthetic_svaec.labelled_set.entropy_batch_mixing() with tempfile.TemporaryDirectory() as temp_dir: posterior_save_path = os.path.join(temp_dir, "posterior_data") original_post = trainer_synthetic_svaec.labelled_set.sequential() original_post.save_posterior(posterior_save_path) new_svaec = SCANVI( synthetic_dataset.nb_genes, synthetic_dataset.n_batches, synthetic_dataset.n_labels, ) new_post = load_posterior(posterior_save_path, model=new_svaec, use_cuda=False) assert np.array_equal(new_post.indices, original_post.indices) assert np.array_equal(new_post.gene_dataset.X, original_post.gene_dataset.X) assert np.array_equal( new_post.gene_dataset.labels, original_post.gene_dataset.labels ) trainer_synthetic_svaec.full_dataset.knn_purity() trainer_synthetic_svaec.labelled_set.show_t_sne(n_samples=5) trainer_synthetic_svaec.unlabelled_set.show_t_sne(n_samples=5, color_by="labels") trainer_synthetic_svaec.labelled_set.show_t_sne( n_samples=5, color_by="batches and labels" ) trainer_synthetic_svaec.labelled_set.clustering_scores() trainer_synthetic_svaec.labelled_set.clustering_scores(prediction_algorithm="gmm") trainer_synthetic_svaec.unlabelled_set.unsupervised_classification_accuracy() trainer_synthetic_svaec.unlabelled_set.differential_expression_score( synthetic_dataset.labels.ravel() == 1, synthetic_dataset.labels.ravel() == 2, n_samples=2, M_permutation=10, ) trainer_synthetic_svaec.unlabelled_set.one_vs_all_degenes( n_samples=2, M_permutation=10 ) def test_synthetic_2(): synthetic_dataset = SyntheticDataset() vaec = VAEC( synthetic_dataset.nb_genes, synthetic_dataset.n_batches, synthetic_dataset.n_labels, ) trainer_synthetic_vaec = JointSemiSupervisedTrainer( vaec, synthetic_dataset, use_cuda=use_cuda, frequency=1, early_stopping_kwargs={ "early_stopping_metric": "reconstruction_error", "on": "labelled_set", "save_best_state_metric": "reconstruction_error", }, ) trainer_synthetic_vaec.train(n_epochs=2) def base_benchmark(gene_dataset): vae = VAE(gene_dataset.nb_genes, gene_dataset.n_batches, gene_dataset.n_labels) trainer = UnsupervisedTrainer(vae, gene_dataset, train_size=0.5, use_cuda=use_cuda) trainer.train(n_epochs=1) return trainer def ldvae_benchmark(dataset, n_epochs, use_cuda=True): ldvae = LDVAE( dataset.nb_genes, n_batch=dataset.n_batches, latent_distribution="normal" ) trainer = UnsupervisedTrainer(ldvae, dataset, use_cuda=use_cuda) trainer.train(n_epochs=n_epochs) trainer.test_set.reconstruction_error() trainer.test_set.marginal_ll() ldvae = LDVAE(dataset.nb_genes, n_batch=dataset.n_batches, latent_distribution="ln") trainer = UnsupervisedTrainer(ldvae, dataset, use_cuda=use_cuda) trainer.train(n_epochs=n_epochs) trainer.test_set.reconstruction_error() ldvae.get_loadings() return trainer def totalvi_benchmark(dataset, n_epochs, use_cuda=True): totalvae = TOTALVI( dataset.nb_genes, len(dataset.protein_names), n_batch=dataset.n_batches ) trainer = TotalTrainer( totalvae, dataset, train_size=0.5, use_cuda=use_cuda, early_stopping_kwargs=None ) trainer.train(n_epochs=n_epochs) trainer.test_set.reconstruction_error() trainer.test_set.marginal_ll() trainer.test_set.get_protein_background_mean() trainer.test_set.get_latent() trainer.test_set.generate() trainer.test_set.get_sample_dropout() trainer.test_set.get_normalized_denoised_expression(transform_batch=0) trainer.test_set.get_normalized_denoised_expression(transform_batch=0) trainer.test_set.imputation() trainer.test_set.get_protein_mean() trainer.test_set.one_vs_all_degenes(n_samples=2, M_permutation=10) trainer.test_set.generate_feature_correlation_matrix(n_samples=2) trainer.test_set.generate_feature_correlation_matrix(n_samples=2, transform_batch=0) return trainer def test_synthetic_3(): gene_dataset = SyntheticDataset() trainer = base_benchmark(gene_dataset) adapter_trainer = AdapterTrainer( trainer.model, gene_dataset, trainer.train_set, frequency=1 ) adapter_trainer.train(n_path=1, n_epochs=1) def test_nb_not_zinb(): synthetic_dataset = SyntheticDataset() svaec = SCANVI( synthetic_dataset.nb_genes, synthetic_dataset.n_batches, synthetic_dataset.n_labels, labels_groups=[0, 0, 1], reconstruction_loss="nb", ) trainer_synthetic_svaec = JointSemiSupervisedTrainer( svaec, synthetic_dataset, use_cuda=use_cuda ) trainer_synthetic_svaec.train(n_epochs=1) def test_poisson_not_zinb(): synthetic_dataset = SyntheticDataset() svaec = SCANVI( synthetic_dataset.nb_genes, synthetic_dataset.n_batches, synthetic_dataset.n_labels, labels_groups=[0, 0, 1], reconstruction_loss="poisson", ) trainer_synthetic_svaec = JointSemiSupervisedTrainer( svaec, synthetic_dataset, use_cuda=use_cuda ) trainer_synthetic_svaec.train(n_epochs=1) def test_classifier_accuracy(save_path): cortex_dataset = CortexDataset(save_path=save_path) cls = Classifier(cortex_dataset.nb_genes, n_labels=cortex_dataset.n_labels) cls_trainer = ClassifierTrainer( cls, cortex_dataset, metrics_to_monitor=["accuracy"], frequency=1, early_stopping_kwargs={ "early_stopping_metric": "accuracy", "save_best_state_metric": "accuracy", }, ) cls_trainer.train(n_epochs=2) cls_trainer.train_set.accuracy() def test_LDVAE(save_path): synthetic_datset_one_batch = SyntheticDataset(n_batches=1) ldvae_benchmark(synthetic_datset_one_batch, n_epochs=1, use_cuda=False) synthetic_datset_two_batches = SyntheticDataset(n_batches=2) ldvae_benchmark(synthetic_datset_two_batches, n_epochs=1, use_cuda=False) def test_sampling_zl(save_path): cortex_dataset = CortexDataset(save_path=save_path) cortex_vae = VAE(cortex_dataset.nb_genes, cortex_dataset.n_batches) trainer_cortex_vae = UnsupervisedTrainer( cortex_vae, cortex_dataset, train_size=0.5, use_cuda=use_cuda ) trainer_cortex_vae.train(n_epochs=2) cortex_cls = Classifier((cortex_vae.n_latent + 1), n_labels=cortex_dataset.n_labels) trainer_cortex_cls = ClassifierTrainer( cortex_cls, cortex_dataset, sampling_model=cortex_vae, sampling_zl=True ) trainer_cortex_cls.train(n_epochs=2) trainer_cortex_cls.test_set.accuracy() def test_annealing_procedures(save_path): cortex_dataset = CortexDataset(save_path=save_path) cortex_vae = VAE(cortex_dataset.nb_genes, cortex_dataset.n_batches) trainer_cortex_vae = UnsupervisedTrainer( cortex_vae, cortex_dataset, train_size=0.5, use_cuda=use_cuda, n_epochs_kl_warmup=1, ) trainer_cortex_vae.train(n_epochs=2) assert trainer_cortex_vae.kl_weight >= 0.99, "Annealing should be over" trainer_cortex_vae = UnsupervisedTrainer( cortex_vae, cortex_dataset, train_size=0.5, use_cuda=use_cuda, n_epochs_kl_warmup=5, ) trainer_cortex_vae.train(n_epochs=2) assert trainer_cortex_vae.kl_weight <= 0.99, "Annealing should be proceeding" # iter trainer_cortex_vae = UnsupervisedTrainer( cortex_vae, cortex_dataset, train_size=0.5, use_cuda=use_cuda, n_iter_kl_warmup=1, n_epochs_kl_warmup=None, ) trainer_cortex_vae.train(n_epochs=2) assert trainer_cortex_vae.kl_weight >= 0.99, "Annealing should be over" def test_differential_expression(save_path): dataset = CortexDataset(save_path=save_path) n_cells = len(dataset) all_indices = np.arange(n_cells) vae = VAE(dataset.nb_genes, dataset.n_batches) trainer = UnsupervisedTrainer(vae, dataset, train_size=0.5, use_cuda=use_cuda) trainer.train(n_epochs=2) post = trainer.create_posterior(vae, dataset, shuffle=False, indices=all_indices) with tempfile.TemporaryDirectory() as temp_dir: posterior_save_path = os.path.join(temp_dir, "posterior_data") post = post.sequential(batch_size=3) post.save_posterior(posterior_save_path) new_vae = VAE(dataset.nb_genes, dataset.n_batches) new_post = load_posterior(posterior_save_path, model=new_vae, use_cuda=False) assert new_post.data_loader.batch_size == 3 assert np.array_equal(new_post.indices, post.indices) assert np.array_equal(new_post.gene_dataset.X, post.gene_dataset.X) # Sample scale example px_scales = post.scale_sampler( n_samples_per_cell=4, n_samples=None, selection=all_indices )["scale"] assert ( px_scales.shape[1] == dataset.nb_genes ), "posterior scales should have shape (n_samples, n_genes)" # Differential expression different models idx_1 = [1, 2, 3] idx_2 = [4, 5, 6, 7] de_dataframe = post.differential_expression_score( idx1=idx_1, idx2=idx_2, n_samples=10, mode="vanilla", use_permutation=True, M_permutation=100, ) de_dataframe = post.differential_expression_score( idx1=idx_1, idx2=idx_2, n_samples=10, mode="change", use_permutation=True, M_permutation=100, cred_interval_lvls=[0.5, 0.95], ) print(de_dataframe.keys()) assert ( de_dataframe["lfc_confidence_interval_0.5_min"] <= de_dataframe["lfc_confidence_interval_0.5_max"] ).all() assert ( de_dataframe["lfc_confidence_interval_0.95_min"] <= de_dataframe["lfc_confidence_interval_0.95_max"] ).all() # DE estimation example de_probabilities = de_dataframe.loc[:, "proba_de"] assert ((0.0 <= de_probabilities) & (de_probabilities <= 1.0)).all() # Test totalVI DE sp = os.path.join(save_path, "10X") dataset = Dataset10X(dataset_name="pbmc_10k_protein_v3", save_path=sp) n_cells = len(dataset) all_indices = np.arange(n_cells) vae = TOTALVI( dataset.nb_genes, len(dataset.protein_names), n_batch=dataset.n_batches ) trainer = TotalTrainer( vae, dataset, train_size=0.5, use_cuda=use_cuda, early_stopping_kwargs=None ) trainer.train(n_epochs=2) post = trainer.create_posterior( vae, dataset, shuffle=False, indices=all_indices, type_class=TotalPosterior ) # Differential expression different models idx_1 = [1, 2, 3] idx_2 = [4, 5, 6, 7] de_dataframe = post.differential_expression_score( idx1=idx_1, idx2=idx_2, n_samples=10, mode="vanilla", use_permutation=True, M_permutation=100, ) de_dataframe = post.differential_expression_score( idx1=idx_1, idx2=idx_2, n_samples=10, mode="change", use_permutation=True, M_permutation=100, ) def test_totalvi(save_path): synthetic_dataset_one_batch = SyntheticDataset(n_batches=1) totalvi_benchmark(synthetic_dataset_one_batch, n_epochs=1, use_cuda=use_cuda) synthetic_dataset_two_batches = SyntheticDataset(n_batches=2) totalvi_benchmark(synthetic_dataset_two_batches, n_epochs=1, use_cuda=use_cuda) # adversarial testing dataset = synthetic_dataset_two_batches totalvae = TOTALVI( dataset.nb_genes, len(dataset.protein_names), n_batch=dataset.n_batches ) trainer = TotalTrainer( totalvae, dataset, train_size=0.5, use_cuda=use_cuda, early_stopping_kwargs=None, use_adversarial_loss=True, ) trainer.train(n_epochs=1) with tempfile.TemporaryDirectory() as temp_dir: posterior_save_path = os.path.join(temp_dir, "posterior_data") original_post = trainer.create_posterior( totalvae, dataset, indices=np.arange(len(dataset)), type_class=TotalPosterior, ) original_post.save_posterior(posterior_save_path) new_totalvae = TOTALVI( dataset.nb_genes, len(dataset.protein_names), n_batch=dataset.n_batches ) new_post = load_posterior( posterior_save_path, model=new_totalvae, use_cuda=False ) assert new_post.posterior_type == "TotalPosterior" assert np.array_equal( new_post.gene_dataset.protein_expression, dataset.protein_expression ) def test_autozi(save_path): data = SyntheticDataset(n_batches=1) for disp_zi in ["gene", "gene-label"]: autozivae = AutoZIVAE( n_input=data.nb_genes, dispersion=disp_zi, zero_inflation=disp_zi, n_labels=data.n_labels, ) trainer_autozivae = UnsupervisedTrainer( model=autozivae, gene_dataset=data, train_size=0.5 ) trainer_autozivae.train(n_epochs=2, lr=1e-2) trainer_autozivae.test_set.elbo() trainer_autozivae.test_set.reconstruction_error() trainer_autozivae.test_set.marginal_ll() def test_multibatches_features(): data = [ np.random.randint(1, 5, size=(20, 10)), np.random.randint(1, 10, size=(20, 10)), np.random.randint(1, 10, size=(20, 10)), np.random.randint(1, 10, size=(30, 10)), ] dataset = GeneExpressionDataset() dataset.populate_from_per_batch_list(data) vae = VAE(dataset.nb_genes, dataset.n_batches) trainer = UnsupervisedTrainer(vae, dataset, train_size=0.5, use_cuda=use_cuda) trainer.train(n_epochs=2) trainer.test_set.imputation(n_samples=2, transform_batch=0) trainer.train_set.imputation(n_samples=2, transform_batch=[0, 1, 2]) def test_deprecated_munkres(): y = np.array([0, 1, 0, 1, 0, 1, 1, 1]) y_pred = np.array([0, 0, 0, 0, 1, 1, 1, 1]) reward, assignment = unsupervised_clustering_accuracy(y, y_pred) assert reward == 0.625 assert (assignment == np.array([[0, 0], [1, 1]])).all() y = np.array([1, 1, 2, 2, 0, 0, 3, 3]) y_pred = np.array([1, 1, 2, 2, 3, 3, 0, 0]) reward, assignment = unsupervised_clustering_accuracy(y, y_pred) assert reward == 1.0 assert (assignment == np.array([[0, 3], [1, 1], [2, 2], [3, 0]])).all() def test_zinb_distribution(): theta = 100.0 + torch.rand(size=(2,)) mu = 15.0 * torch.ones_like(theta) pi = torch.randn_like(theta) x = torch.randint_like(mu, high=20) log_p_ref = log_zinb_positive(x, mu, theta, pi) dist = ZeroInflatedNegativeBinomial(mu=mu, theta=theta, zi_logits=pi) log_p_zinb = dist.log_prob(x) assert (log_p_ref - log_p_zinb).abs().max().item() <= 1e-8 torch.manual_seed(0) s1 = dist.sample((100,)) assert s1.shape == (100, 2) s2 = dist.sample(sample_shape=(4, 3)) assert s2.shape == (4, 3, 2) log_p_ref = log_nb_positive(x, mu, theta) dist = NegativeBinomial(mu=mu, theta=theta) log_p_nb = dist.log_prob(x) assert (log_p_ref - log_p_nb).abs().max().item() <= 1e-8 s1 = dist.sample((1000,)) assert s1.shape == (1000, 2) assert (s1.mean(0) - mu).abs().mean() <= 1e0 assert (s1.std(0) - (mu + mu * mu / theta) ** 0.5).abs().mean() <= 1e0 size = (50, 3) theta = 100.0 + torch.rand(size=size) mu = 15.0 * torch.ones_like(theta) pi = torch.randn_like(theta) x = torch.randint_like(mu, high=20) dist1 = ZeroInflatedNegativeBinomial(mu=mu, theta=theta, zi_logits=pi) dist2 = NegativeBinomial(mu=mu, theta=theta) assert dist1.log_prob(x).shape == size assert dist2.log_prob(x).shape == size with pytest.raises(ValueError): ZeroInflatedNegativeBinomial(mu=-mu, theta=theta, zi_logits=pi) with pytest.warns(UserWarning): dist1.log_prob(-x) # ensures neg values raise warning with pytest.warns(UserWarning): dist2.log_prob(0.5 * x) # ensures float values raise warning def test_anndata_loader(): x = np.random.randint(low=0, high=100, size=(15, 4)) batch_ids = np.random.randint(low=0, high=2, size=(15,)) n_batches = 2 adata = AnnData(X=x, obs=dict(batch=batch_ids)) _ = AnnDatasetFromAnnData(adata, batch_label="batch") dataset = AnnDatasetFromAnnData(adata, batch_label="batch") assert ( dataset.n_batches == n_batches ), "AnnDatasetFromAnnData should not modify the anndata object"
35.495974
88
0.70857
[ "MIT" ]
shaoxin0801/scVI
tests/test_scvi.py
22,043
Python
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class JianshuSpiderSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class JianshuSpiderDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
34.701923
78
0.667221
[ "Apache-2.0" ]
2904574716qq/spider_python
scrapy/jianshu_spider/jianshu_spider/middlewares.py
3,611
Python
#!/usr/bin/env python # Copyright 2016 Medical Research Council Harwell. # # 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. # # # @author Neil Horner <[email protected]> from setuptools.command import easy_install dependencies = ["pyqtgraph", "appdirs", "SimpleITK", "numpy"] for dep in dependencies: try: mod = __import__(dep) # try to import module print("{0} already installed.".format(dep)) except ImportError: # If it fails, try to easy install it easy_install.main(["--user", dep])
29.617647
74
0.735849
[ "Apache-2.0" ]
Dorky-Lever/vpv
setup.py
1,007
Python
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Philippe Biondi <[email protected]> # This program is published under a GPLv2 license ############################################################################# # # # hsrp.py --- HSRP protocol support for Scapy # # # # Copyright (C) 2010 Mathieu RENARD mathieu.renard(at)gmail.com # # # # This program is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License version 2 as # # published by the Free Software Foundation; version 2. # # # # 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. # # # ############################################################################# # HSRP Version 1 # Ref. RFC 2281 # HSRP Version 2 # Ref. http://www.smartnetworks.jp/2006/02/hsrp_8_hsrp_version_2.html ## # $Log: hsrp.py,v $ # Revision 0.2 2011/05/01 15:23:34 mrenard # Cleanup code """ HSRP (Hot Standby Router Protocol): proprietary redundancy protocol for Cisco routers. # noqa: E501 """ from scapy.fields import ByteEnumField, ByteField, IPField, SourceIPField, \ StrFixedLenField, XIntField, XShortField from scapy.packet import Packet, bind_layers, bind_bottom_up from scapy.layers.inet import DestIPField, UDP from scapy.layers.inet6 import DestIP6Field class HSRP(Packet): name = "HSRP" fields_desc = [ ByteField("version", 0), ByteEnumField("opcode", 0, {0: "Hello", 1: "Coup", 2: "Resign", 3: "Advertise"}), # noqa: E501 ByteEnumField("state", 16, {0: "Initial", 1: "Learn", 2: "Listen", 4: "Speak", 8: "Standby", 16: "Active"}), # noqa: E501 ByteField("hellotime", 3), ByteField("holdtime", 10), ByteField("priority", 120), ByteField("group", 1), ByteField("reserved", 0), StrFixedLenField("auth", b"cisco" + b"\00" * 3, 8), IPField("virtualIP", "192.168.1.1")] def guess_payload_class(self, payload): if self.underlayer.len > 28: return HSRPmd5 else: return Packet.guess_payload_class(self, payload) class HSRPmd5(Packet): name = "HSRP MD5 Authentication" fields_desc = [ ByteEnumField("type", 4, {4: "MD5 authentication"}), ByteField("len", None), ByteEnumField("algo", 0, {1: "MD5"}), ByteField("padding", 0x00), XShortField("flags", 0x00), SourceIPField("sourceip", None), XIntField("keyid", 0x00), StrFixedLenField("authdigest", b"\00" * 16, 16)] def post_build(self, p, pay): if self.len is None and pay: tmp_len = len(pay) p = p[:1] + hex(tmp_len)[30:] + p[30:] return p bind_bottom_up(UDP, HSRP, dport=1985) bind_bottom_up(UDP, HSRP, sport=1985) bind_bottom_up(UDP, HSRP, dport=2029) bind_bottom_up(UDP, HSRP, sport=2029) bind_layers(UDP, HSRP, dport=1985, sport=1985) bind_layers(UDP, HSRP, dport=2029, sport=2029) DestIPField.bind_addr(UDP, "224.0.0.2", dport=1985) DestIP6Field.bind_addr(UDP, "ff02::66", dport=2029)
41.844444
130
0.545672
[ "MIT" ]
4shadoww/hakkuframework
lib/scapy/layers/hsrp.py
3,766
Python
# model settings model = dict( type='FasterRCNN', pretrained='open-mmlab://resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='GARPNHead', in_channels=256, feat_channels=256, octave_base_scale=8, scales_per_octave=3, octave_ratios=[0.5, 1.0, 2.0], anchor_strides=[4, 8, 16, 32, 64], anchor_base_sizes=None, anchoring_means=[.0, .0, .0, .0], anchoring_stds=[0.07, 0.07, 0.14, 0.14], target_means=(.0, .0, .0, .0), target_stds=[0.07, 0.07, 0.11, 0.11], loc_filter_thr=0.01, loss_loc=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_shape=dict(type='BoundedIoULoss', beta=0.2, loss_weight=1.0), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', out_size=7, sample_num=2), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='SharedFCBBoxHead', num_fcs=2, in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=81, target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1], reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))) # model training and testing settings train_cfg = dict( rpn=dict( ga_assigner=dict( type='ApproxMaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), ga_sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, center_ratio=0.2, ignore_ratio=0.5, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_num=300, nms_thr=0.7, min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), pos_weight=-1, debug=False)) test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_num=300, nms_thr=0.7, min_bbox_size=0), rcnn=dict( score_thr=1e-3, nms=dict(type='nms', iou_thr=0.5), max_per_img=100)) # dataset settings dataset_type = 'CocoDataset' data_root = 'data/coco/' img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( imgs_per_gpu=2, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline)) # optimizer optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[8, 11]) checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=50, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable # runtime settings total_epochs = 12 dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = './work_dirs/ga_faster_rcnn_r50_caffe_fpn_1x' load_from = None resume_from = None workflow = [('train', 1)]
30.665
76
0.581608
[ "Apache-2.0" ]
1243France/SCB_Loss
configs/guided_anchoring/ga_faster_r50_caffe_fpn_1x.py
6,133
Python
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ### from pprint import pprint from config_loader import try_load_from_file from hpOneView.exceptions import HPOneViewException from hpOneView.oneview_client import OneViewClient config = { "ip": "<oneview_ip>", "credentials": { "userName": "<oneview_administrator_name>", "password": "<oneview_administrator_password>", } } # Try load config from a file (if there is a config file) config = try_load_from_file(config) oneview_client = OneViewClient(config) # To run this sample you must define a server hardware type uri and an enclosure group uri enclosure_group_uri = None server_hardware_type_uri = None # To run the example 'get a specific storage system' you must define a storage system ID storage_system_id = None # To run the example 'get port model associated with a server hardware' you must define a server hardware uri server_hardware_uri = None try: # Create a server profile template to associate with the server profile basic_server_template = oneview_client.server_profile_templates.create(dict( name="ProfileTemplate101", serverHardwareTypeUri=server_hardware_type_uri, enclosureGroupUri=enclosure_group_uri )) server_template_uri = basic_server_template['uri'] # Create a server profile print("\nCreate a basic connection-less assigned server profile") basic_profile_options = dict( name="Profile101", serverProfileTemplateUri=server_template_uri, serverHardwareTypeUri=server_hardware_type_uri, enclosureGroupUri=enclosure_group_uri ) basic_profile = oneview_client.server_profiles.create(basic_profile_options) profile_uri = basic_profile["uri"] pprint(basic_profile) except HPOneViewException as e: print(e.msg) # Update bootMode from recently created profile print("\nUpdate bootMode from recently created profile") profile_to_update = basic_profile.copy() profile_to_update["bootMode"] = dict(manageMode=True, mode="BIOS") profile_updated = oneview_client.server_profiles.update(resource=profile_to_update, id_or_uri=profile_to_update["uri"]) pprint(profile_updated) # Patch print("\nUpdate the profile configuration from server profile template") profile_updated = oneview_client.server_profiles.patch(id_or_uri=profile_uri, operation="replace", path="/templateCompliance", value="Compliant") pprint(profile_updated) # Get all print("\nGet list of all server profiles") all_profiles = oneview_client.server_profiles.get_all() for profile in all_profiles: print(' %s' % profile['name']) # Get by property print("\nGet a list of server profiles that matches the specified macType") profile_mac_type = all_profiles[1]["macType"] profiles = oneview_client.server_profiles.get_by('macType', profile_mac_type) for profile in profiles: print(' %s' % profile['name']) # Get by name print("\nGet a server profile by name") profile = oneview_client.server_profiles.get_by_name("Profile101") pprint(profile) # Get by uri print("\nGet a server profile by uri") profile = oneview_client.server_profiles.get(profile_uri) pprint(profile) if oneview_client.api_version <= 500: # Retrieve ServerProfile schema # This method available only for API version <= 500 print("\nRetrieve the generated ServerProfile schema") schema = oneview_client.server_profiles.get_schema() pprint(schema) try: # Server profile compliance preview print("\nGets the preview of manual and automatic updates required to make the server profile consistent " "with its template.") schema = oneview_client.server_profiles.get_compliance_preview(profile_uri) pprint(schema) except HPOneViewException as e: print(e.msg) # Get profile ports print("\nRetrieve the port model associated with a server hardware type and enclosure group") profile_ports = oneview_client.server_profiles.get_profile_ports(enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri) pprint(profile_ports) try: # Get profile ports if server_hardware_uri: print("\nRetrieve the port model associated with a server hardware") profile_ports = oneview_client.server_profiles.get_profile_ports(serverHardwareUri=server_hardware_uri) pprint(profile_ports) except HPOneViewException as e: print(e.msg) try: # Retrieve the error or status messages associated with the specified profile print("\nList profile status messages associated with a profile") messages = oneview_client.server_profiles.get_messages(profile_uri) pprint(messages) except HPOneViewException as e: print(e.msg) try: # Transform an server profile print("\nTransform an existing profile by supplying a new server hardware type and/or enclosure group.") server_transformed = oneview_client.server_profiles.get_transformation( basic_profile['uri'], enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri) print("Transformation complete. Updating server profile with the new configuration.") profile_updated = oneview_client.server_profiles.update(server_transformed, server_transformed["uri"]) pprint(profile_updated) except HPOneViewException as e: print(e.msg) try: # Get the list of networks and network sets that are available to a server profile along with their respective ports print("\nList all Ethernet networks associated with a server hardware type and enclosure group") available_networks = oneview_client.server_profiles.get_available_networks( enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri, view='Ethernet') pprint(available_networks) except HPOneViewException as e: print(e.msg) try: # Get the all Ethernet networks associated with a server hardware type, enclosure group and scopeuris if oneview_client.api_version >= 600: enclosure_group_uri = "/rest/enclosure-groups/8cf8fd62-ad9f-4946-abf7-6dac9cb59253" server_hardware_type_uri = "/rest/server-hardware-types/B342B5D4-387D-4DEB-ADBB-9D7256DF2A47" available_networks = oneview_client.server_profiles.get_available_networks(enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri, view='Ethernet', scope_uris="\"'/rest/scopes/3bb0c754-fd38-45af-be8a-4d4419de06e9'\"") if len(available_networks) > 0: pprint(available_networks) else: print("No Server Profiles Group found.") except HPOneViewException as e: print(e.msg) try: # Get the list of available servers print("\nList all available servers associated with a server hardware type and enclosure group") available_servers = oneview_client.server_profiles.get_available_servers( enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri) pprint(available_servers) except HPOneViewException as e: print(e.msg) try: # List available storage systems print("\nList available storage systems associated with the given enclosure group URI and server hardware type URI") available_storage_systems = oneview_client.server_profiles.get_available_storage_systems( count=25, start=0, enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri) pprint(available_storage_systems) except HPOneViewException as e: print(e.msg) try: # Get a specific storage system if storage_system_id: print("\nRetrieve a specific storage system associated with the given enclosure group URI, a server hardware" " type URI and a storage system ID") available_storage_system = oneview_client.server_profiles.get_available_storage_system( storageSystemId=storage_system_id, enclosureGroupUri=enclosure_group_uri, serverHardwareTypeUri=server_hardware_type_uri) pprint(available_storage_system) except HPOneViewException as e: print(e.msg) try: # List available targets print("\nList all available servers and bays for a given enclosure group.") available_targets = oneview_client.server_profiles.get_available_targets(enclosureGroupUri=enclosure_group_uri) pprint(available_targets) except HPOneViewException as e: print(e.msg) # Generate a new Server Profile Template based on an existing Server Profile new_spt = oneview_client.server_profiles.get_new_profile_template(basic_profile['uri']) print('\nNew SPT generated:') pprint(new_spt) new_spt['name'] = 'spt_generated_from_sp' new_spt = oneview_client.server_profile_templates.create(new_spt) print('\nNew SPT created successfully.') oneview_client.server_profile_templates.delete(new_spt) print('\nDropped recently created SPT.') # Delete the created server profile print("\nDelete the created server profile") oneview_client.server_profiles.delete(basic_profile) print("The server profile was successfully deleted.") # Delete the created server profile template oneview_client.server_profile_templates.delete(basic_server_template) # Delete all server profile (filtering) print("\nRemove all profiles that match the name 'Profile fake'") # Create a new profile to delete oneview_client.server_profiles.create(dict( name="Profile fake", serverHardwareTypeUri=server_hardware_type_uri, enclosureGroupUri=enclosure_group_uri )) oneview_client.server_profiles.delete_all(filter="name='Profile fake'") print("The server profiles were successfully deleted.")
42.325581
152
0.758608
[ "MIT" ]
HewlettPackard/python-hpOneView
examples/server_profiles.py
10,920
Python
import sqlite3 import pandas as pd import numpy as np import csv import gzip from collections import defaultdict if __name__ == '__main__': conn = sqlite3.connect('data/instacart.db') c = conn.cursor() # Get the orders properly sorted, so we can directly # group by user_id, order_id and then compute the weights. q = """ SELECT user_id, order_id, days_since_prior_order FROM orders ORDER BY order_number """ orders = pd.read_sql(q, conn) # First day is 0 orders.ix[orders.days_since_prior_order == '', 'days_since_prior_order'] = 0 # Cumsum to obtain total days since *first* order orders_g = orders.groupby(['user_id'])['days_since_prior_order'].cumsum() orders['cumulative_days'] = orders_g.astype(int) # But I need to subtract cumulative_days from the actual day of the # order we want to compute... which will be the maximum max_cum_days = orders.groupby(['user_id'])['cumulative_days'].max() max_cum_days = max_cum_days.reset_index() max_cum_days.columns = ['user_id', 'max_order_day'] orders = pd.merge(orders, max_cum_days, on = "user_id", how = 'left') # Compute weights orders['w_periodic'] = (np.cos(2 * (orders['max_order_day'] - orders['cumulative_days']) / 365.0 * 3.14) + 1) / 2 orders['w_decay'] = 1.0 / ((365 - orders['cumulative_days']) / 365.0 + 1.0) # Remove unwanted columns (for DB storage, let's try not do duplicate) res = orders res = res.drop(['days_since_prior_order', 'cumulative_days', 'max_order_day'], axis = 1) # Insert weights into the DB res.to_sql('order_weights', conn, if_exists = 'replace') c.execute("CREATE INDEX IF NOT EXISTS idx_tmp1 ON order_weights(user_id)") c.execute("CREATE INDEX IF NOT EXISTS idx_tmp2 ON order_weights(order_id)")
37.68
118
0.662951
[ "MIT" ]
Keesiu/meta-kaggle
data/external/repositories_2to3/164369/kaggle-public-master/instacart/compute_weights_2.py
1,884
Python
from rolepermissions.roles import AbstractUserRole class Admin(AbstractUserRole): available_permissions = { 'deactivate_user': True, 'activate_user': True, 'change_user_permissions': True, 'create_client_record': True, 'delete_client_recods': True, 'update_client_recods': True, } class Manager(AbstractUserRole): available_permissions = { 'create_client_record': True, 'delete_client_recods': True, 'update_client_recods': True, }
24.952381
50
0.666031
[ "MIT" ]
lunyamwis/appraisal-system
app/api/roles/roles.py
524
Python
import cv2 import numpy as np import math from vcam import vcam,meshGen def nothing(x): pass WINDOW_NAME = "output" cv2.namedWindow(WINDOW_NAME,cv2.WINDOW_NORMAL) cv2.resizeWindow(WINDOW_NAME,700,700) # Creating the tracker bar for all the features cv2.createTrackbar("X",WINDOW_NAME,500,1000,nothing) cv2.createTrackbar("Y",WINDOW_NAME,500,1000,nothing) cv2.createTrackbar("Z",WINDOW_NAME,0,1000,nothing) cv2.createTrackbar("alpha",WINDOW_NAME,180,360,nothing) cv2.createTrackbar("beta",WINDOW_NAME,180,360,nothing) cv2.createTrackbar("gama",WINDOW_NAME,180,360,nothing) cv2.createTrackbar("K1",WINDOW_NAME,0,100000,nothing) cv2.createTrackbar("K2",WINDOW_NAME,0,100000,nothing) cv2.createTrackbar("P1",WINDOW_NAME,0,100000,nothing) cv2.createTrackbar("P2",WINDOW_NAME,0,100000,nothing) cv2.createTrackbar("focus",WINDOW_NAME,600,1000,nothing) cv2.createTrackbar("Sx",WINDOW_NAME,100,1000,nothing) cv2.createTrackbar("Sy",WINDOW_NAME,100,1000,nothing) # cap = cv2.VideoCapture(0) # ret,img = cap.read() img = cv2.imread("chess.png") H,W = img.shape[:2] c1 = vcam(H=H,W=W) plane = meshGen(H,W) plane.Z = plane.X*0 + 1 pts3d = plane.getPlane() while True: # ret, img = cap.read() img = cv2.imread("chess.png") X = -cv2.getTrackbarPos("X",WINDOW_NAME) + 500 Y = -cv2.getTrackbarPos("Y",WINDOW_NAME) + 500 Z = -cv2.getTrackbarPos("Z",WINDOW_NAME) alpha = cv2.getTrackbarPos("alpha",WINDOW_NAME) - 180 beta = cv2.getTrackbarPos("beta",WINDOW_NAME) - 180 gamma = -cv2.getTrackbarPos("gama",WINDOW_NAME) - 180 c1.focus = cv2.getTrackbarPos("focus",WINDOW_NAME) - 500 c1.sx = (cv2.getTrackbarPos("Sx",WINDOW_NAME)+1)/100 c1.sy = (cv2.getTrackbarPos("Sy",WINDOW_NAME)+1)/100 k1 = cv2.getTrackbarPos("K1",WINDOW_NAME)/100000 k2 = cv2.getTrackbarPos("K2",WINDOW_NAME)/100000 p1 = cv2.getTrackbarPos("P1",WINDOW_NAME)/100000 p2 = cv2.getTrackbarPos("P2",WINDOW_NAME)/100000 c1.KpCoeff[0] = k1 c1.KpCoeff[1] = k2 c1.KpCoeff[2] = p1 c1.KpCoeff[3] = p2 c1.set_tvec(X,Y,Z) c1.set_rvec(alpha,beta,gamma) pts2d = c1.project(pts3d) map_x,map_y = c1.getMaps(pts2d) output = cv2.remap(img,map_x,map_y,interpolation=cv2.INTER_LINEAR) M = c1.RT print("\n\n############## Camera Matrix ##################") print(M) cv2.imshow("output",output) if cv2.waitKey(1) & 0xFF == ord('q'): break
30.826667
67
0.728374
[ "MIT" ]
kaustubh-sadekar/VirtualCam
GUI.py
2,312
Python
from minpiler.std import M i = 0 M.label .loop M.print(i) i += 1 if i < 10: M.jump .loop
10.444444
26
0.606383
[ "MIT" ]
3e45/minpiler
samples/std/jump.py
94
Python
from django.core.management.base import NoArgsCommand from ella.core.management import regenerate_listing_handlers class Command(NoArgsCommand): def handle_noargs(self, **options): regenerate_listing_handlers()
28.125
60
0.804444
[ "BSD-3-Clause" ]
chr1043086360/ella
ella/core/management/commands/regenerate_listing_handlers.py
225
Python
import _plotly_utils.basevalidators class ExponentformatValidator( _plotly_utils.basevalidators.EnumeratedValidator ): def __init__( self, plotly_name='exponentformat', parent_name='scatterpolar.marker.colorbar', **kwargs ): super(ExponentformatValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type='colorbars', role='style', values=['none', 'e', 'E', 'power', 'SI', 'B'], **kwargs )
25.090909
58
0.592391
[ "MIT" ]
Elpiro/plotly.py
plotly/validators/scatterpolar/marker/colorbar/_exponentformat.py
552
Python
#!/usr/bin/python ''' Gapfilling function that utilizes pFBA and flux sampling to find most parsimonious additional reactions to achieve minimum flux through the objective Author: Matthew Jenior ''' import pandas import math import copy import time import random # Using Cobrapy 0.13.0 import cobra import cobra.test from cobra.flux_analysis.sampling import OptGPSampler from cobra.manipulation.delete import * from cobra.flux_analysis.parsimonious import add_pfba from cobra.medium import find_boundary_types from cobra.util import solver as sutil # pFBA gapfiller def pfba_gapfill(model, reaction_bag, obj=None, obj_lb=10., obj_constraint=False, iters=1, tasks=None, task_lb=0.05, add_exchanges=True, extracellular='e', cores=4): ''' Function that utilizes iterations of pFBA solution with a universal reaction bag in order to gapfill a model. Parameters ---------- model : cobra.Model Model to be gapfilled reaction_bag : cobra.Model Reaction bag reference to use during gapfilling obj : string Reaction ID for objective function in model to be gapfilled. obj_lb : float Lower bound for objective function obj_constraint : bool Sets objective as contstraint which must be maximized tasks : list or None List of reactions IDs (strings) of metabolic tasks to set a minimum lower bound for task_lb : float Lower bound for any metabolic tasks iters : int Number of gapfilling rounds. Unique reactions from each round are saved and the union is added simulatneously to the model add_exchanges : bool Identifies extracellular metabolites added during gapfilling that are not associated with exchange reactions and creates them extracellular : string Label for extracellular compartment of model cores : int Number of processors to utilize during flux sampling ''' start_time = time.time() # Save some basic network info for downstream membership testing orig_rxn_ids = set([str(x.id) for x in model.reactions]) orig_cpd_ids = set([str(y.id) for y in model.metabolites]) univ_rxn_ids = set([str(z.id) for z in reaction_bag.reactions]) # Find overlap in model and reaction bag overlap_rxn_ids = univ_rxn_ids.intersection(orig_rxn_ids) # Get model objective reaction ID if obj == None: obj = get_objective(model) else: obj = obj # Modify universal reaction bag new_rxn_ids = set() print('Creating universal model...') with reaction_bag as universal: # Remove overlapping reactions from universal bag, and reset objective if needed for rxn in overlap_rxn_ids: universal.reactions.get_by_id(rxn).remove_from_model() # Set objective in universal if told by user # Made constraint as fraction of minimum in next step if obj_constraint: universal.add_reactions([model.reactions.get_by_id(obj)]) universal.objective = obj orig_rxn_ids.remove(obj) orig_rxns = [] for rxn in orig_rxn_ids: orig_rxns.append(copy.deepcopy(model.reactions.get_by_id(rxn))) else: orig_rxns = list(copy.deepcopy(model.reactions)) # Add pFBA to universal model and add model reactions add_pfba(universal) #universal = copy.deepcopy(universal) # reset solver universal.add_reactions(orig_rxns) # If previous objective not set as constraint, set minimum lower bound if not obj_constraint: universal.reactions.get_by_id(obj).lower_bound = obj_lb # Set metabolic tasks that must carry flux in gapfilled solution if tasks != None: for task in tasks: try: universal.reactions.get_by_id(task).lower_bound = task_lb except: print(task + 'not found in model. Ignoring.') continue # Run FBA and save solution print('Optimizing model with combined reactions...') solution = universal.optimize() if iters > 1: print('Generating flux sampling object...') sutil.fix_objective_as_constraint(universal, fraction=0.99) optgp_object = OptGPSampler(universal, processes=cores) # Assess the sampled flux distributions print('Sampling ' + str(iters) + ' flux distributions...') flux_samples = optgp_object.sample(iters) rxns = list(flux_samples.columns) for distribution in flux_samples.iterrows(): for flux in range(0, len(list(distribution[1]))): if abs(list(distribution[1])[flux]) > 1e-6: new_rxn_ids |= set([rxns[flux]]).difference(orig_rxn_ids) else: rxns = list(solution.fluxes.index) fluxes = list(solution.fluxes) for flux in range(0, len(fluxes)): if abs(fluxes[flux]) > 1e-6: new_rxn_ids |= set([rxns[flux]]) # Screen new reaction IDs if obj in new_rxn_ids: new_rxn_ids.remove(obj) for rxn in orig_rxn_ids: try: new_rxn_ids.remove(rxn) except: continue # Get reactions and metabolites to be added to the model print('Gapfilling model...') new_rxns = copy.deepcopy([reaction_bag.reactions.get_by_id(rxn) for rxn in new_rxn_ids]) new_cpd_ids = set() for rxn in new_rxns: new_cpd_ids |= set([str(x.id) for x in list(rxn.metabolites)]) new_cpd_ids = new_cpd_ids.difference(orig_cpd_ids) new_cpds = copy.deepcopy([reaction_bag.metabolites.get_by_id(cpd) for cpd in new_cpd_ids]) # Copy model and gapfill new_model = copy.deepcopy(model) new_model.add_metabolites(new_cpds) new_model.add_reactions(new_rxns) # Identify extracellular metabolites with no exchanges if add_exchanges == True: new_exchanges = extend_exchanges(new_model, new_cpd_ids, extracellular) if len(new_exchanges) > 0: new_rxn_ids |= new_exchanges duration = int(round(time.time() - start_time)) print('Took ' + str(duration) + ' seconds to gapfill ' + str(len(new_rxn_ids)) + \ ' reactions and ' + str(len(new_cpd_ids)) + ' metabolites.') new_obj_val = new_model.slim_optimize() if new_obj_val > 1e-6: print('Gapfilled model objective now carries flux (' + str(new_obj_val) + ').') else: print('Gapfilled model objective still does not carry flux.') return new_model # Adds missing exchanges for extracellulart metbaolites def extend_exchanges(model, cpd_ids, ex): model_exchanges = set(find_boundary_types(model, 'exchange', external_compartment=ex)) new_ex_ids = set() for cpd in cpd_ids: cpd = model.metabolites.get_by_id(cpd) if str(cpd.compartment) != ex: continue else: if bool(set(cpd.reactions) & model_exchanges) == False: try: new_id = 'EX_' + cpd.id model.add_boundary(cpd, type='exchange', reaction_id=new_id, lb=-1000.0, ub=1000.0) new_ex_ids |= set([new_id]) except ValueError: pass return new_ex_ids # Returns the reaction ID of the objective reaction def get_objective(model): if len(list(model.objective.variables)) == 0: raise IndexError('Model has no objective set.') expression = str(model.objective.expression).split() if 'reverse' in expression[0]: obj_id = expression[2].split('*')[-1] else: obj_id = expression[0].split('*')[-1] return obj_id
37.40566
103
0.640858
[ "MIT" ]
csbl/CSBL-code-repo
pfba_gapfiller.py
7,930
Python
import torch import time from audio_zen.acoustics.feature import mag_phase from audio_zen.acoustics.mask import decompress_cIRM from audio_zen.inferencer.base_inferencer import BaseInferencer # for log from utils.logger import log print=log def cumulative_norm(input): eps = 1e-10 device = input.device data_type = input.dtype n_dim = input.ndim assert n_dim in (3, 4) if n_dim == 3: n_channels = 1 batch_size, n_freqs, n_frames = input.size() else: batch_size, n_channels, n_freqs, n_frames = input.size() input = input.reshape(batch_size * n_channels, n_freqs, n_frames) step_sum = torch.sum(input, dim=1) # [B, T] step_pow_sum = torch.sum(torch.square(input), dim=1) cumulative_sum = torch.cumsum(step_sum, dim=-1) # [B, T] cumulative_pow_sum = torch.cumsum(step_pow_sum, dim=-1) # [B, T] entry_count = torch.arange(n_freqs, n_freqs * n_frames + 1, n_freqs, dtype=data_type, device=device) entry_count = entry_count.reshape(1, n_frames) # [1, T] entry_count = entry_count.expand_as(cumulative_sum) # [1, T] => [B, T] cum_mean = cumulative_sum / entry_count # B, T cum_var = (cumulative_pow_sum - 2 * cum_mean * cumulative_sum) / entry_count + cum_mean.pow(2) # B, T cum_std = (cum_var + eps).sqrt() # B, T cum_mean = cum_mean.reshape(batch_size * n_channels, 1, n_frames) cum_std = cum_std.reshape(batch_size * n_channels, 1, n_frames) x = (input - cum_mean) / cum_std if n_dim == 4: x = x.reshape(batch_size, n_channels, n_freqs, n_frames) return x class Inferencer(BaseInferencer): def __init__(self, config, checkpoint_path, output_dir): super().__init__(config, checkpoint_path, output_dir) @torch.no_grad() def mag(self, noisy, inference_args): noisy_complex = self.torch_stft(noisy) noisy_mag, noisy_phase = mag_phase(noisy_complex) # [B, F, T] => [B, 1, F, T] enhanced_mag = self.model(noisy_mag.unsqueeze(1)).squeeze(1) enhanced = self.torch_istft((enhanced_mag, noisy_phase), length=noisy.size(-1), use_mag_phase=True) enhanced = enhanced.detach().squeeze(0).cpu().numpy() return enhanced @torch.no_grad() def scaled_mask(self, noisy, inference_args): noisy_complex = self.torch_stft(noisy) noisy_mag, noisy_phase = mag_phase(noisy_complex) # [B, F, T] => [B, 1, F, T] => model => [B, 2, F, T] => [B, F, T, 2] noisy_mag = noisy_mag.unsqueeze(1) scaled_mask = self.model(noisy_mag) scaled_mask = scaled_mask.permute(0, 2, 3, 1) enhanced_complex = noisy_complex * scaled_mask enhanced = self.torch_istft(enhanced_complex, length=noisy.size(-1), use_mag_phase=False) enhanced = enhanced.detach().squeeze(0).cpu().numpy() return enhanced @torch.no_grad() def sub_band_crm_mask(self, noisy, inference_args): pad_mode = inference_args["pad_mode"] n_neighbor = inference_args["n_neighbor"] noisy = noisy.cpu().numpy().reshape(-1) noisy_D = self.librosa_stft(noisy) noisy_real = torch.tensor(noisy_D.real, device=self.device) noisy_imag = torch.tensor(noisy_D.imag, device=self.device) noisy_mag = torch.sqrt(torch.square(noisy_real) + torch.square(noisy_imag)) # [F, T] n_freqs, n_frames = noisy_mag.size() noisy_mag = noisy_mag.reshape(1, 1, n_freqs, n_frames) noisy_mag_padded = self._unfold(noisy_mag, pad_mode, n_neighbor) # [B, N, C, F_s, T] <=> [1, 257, 1, 31, T] noisy_mag_padded = noisy_mag_padded.squeeze(0).squeeze(1) # [257, 31, 200] <=> [B, F_s, T] pred_crm = self.model(noisy_mag_padded).detach() # [B, 2, T] <=> [F, 2, T] pred_crm = pred_crm.permute(0, 2, 1).contiguous() # [B, T, 2] lim = 9.99 pred_crm = lim * (pred_crm >= lim) - lim * (pred_crm <= -lim) + pred_crm * (torch.abs(pred_crm) < lim) pred_crm = -10 * torch.log((10 - pred_crm) / (10 + pred_crm)) enhanced_real = pred_crm[:, :, 0] * noisy_real - pred_crm[:, :, 1] * noisy_imag enhanced_imag = pred_crm[:, :, 1] * noisy_real + pred_crm[:, :, 0] * noisy_imag enhanced_real = enhanced_real.cpu().numpy() enhanced_imag = enhanced_imag.cpu().numpy() enhanced = self.librosa_istft(enhanced_real + 1j * enhanced_imag, length=len(noisy)) return enhanced @torch.no_grad() def full_band_crm_mask(self, noisy, inference_args): noisy_complex = self.torch_stft(noisy) noisy_mag, _ = mag_phase(noisy_complex) noisy_mag = noisy_mag.unsqueeze(1) t1 = time.time() pred_crm = self.model(noisy_mag) t2 = time.time() pred_crm = pred_crm.permute(0, 2, 3, 1) pred_crm = decompress_cIRM(pred_crm) enhanced_real = pred_crm[..., 0] * noisy_complex.real - pred_crm[..., 1] * noisy_complex.imag enhanced_imag = pred_crm[..., 1] * noisy_complex.real + pred_crm[..., 0] * noisy_complex.imag enhanced_complex = torch.stack((enhanced_real, enhanced_imag), dim=-1) enhanced = self.torch_istft(enhanced_complex, length=noisy.size(-1)) enhanced = enhanced.detach().squeeze(0).cpu().numpy() # rtf = (t2 - t1) / (len(enhanced) * 1.0 / self.acoustic_config["sr"]) print(f"model rtf: {rtf}") return enhanced @torch.no_grad() def overlapped_chunk(self, noisy, inference_args): sr = self.acoustic_config["sr"] noisy = noisy.squeeze(0) num_mics = 8 chunk_length = sr * inference_args["chunk_length"] chunk_hop_length = chunk_length // 2 num_chunks = int(noisy.shape[-1] / chunk_hop_length) + 1 win = torch.hann_window(chunk_length, device=noisy.device) prev = None enhanced = None # 模拟语音的静音段,防止一上来就给语音,处理的不好 for chunk_idx in range(num_chunks): if chunk_idx == 0: pad = torch.zeros((num_mics, 256), device=noisy.device) chunk_start_position = chunk_idx * chunk_hop_length chunk_end_position = chunk_start_position + chunk_length # concat([(8, 256), (..., ... + chunk_length)]) noisy_chunk = torch.cat((pad, noisy[:, chunk_start_position:chunk_end_position]), dim=1) enhanced_chunk = self.model(noisy_chunk.unsqueeze(0)) enhanced_chunk = torch.squeeze(enhanced_chunk) enhanced_chunk = enhanced_chunk[256:] # Save the prior half chunk, cur = enhanced_chunk[:chunk_length // 2] # only for the 1st chunk,no overlap for the very 1st chunk prior half prev = enhanced_chunk[chunk_length // 2:] * win[chunk_length // 2:] else: # use the previous noisy data as the pad pad = noisy[:, (chunk_idx * chunk_hop_length - 256):(chunk_idx * chunk_hop_length)] chunk_start_position = chunk_idx * chunk_hop_length chunk_end_position = chunk_start_position + chunk_length noisy_chunk = torch.cat((pad, noisy[:8, chunk_start_position:chunk_end_position]), dim=1) enhanced_chunk = self.model(noisy_chunk.unsqueeze(0)) enhanced_chunk = torch.squeeze(enhanced_chunk) enhanced_chunk = enhanced_chunk[256:] # 使用这个窗函数来对拼接的位置进行平滑? enhanced_chunk = enhanced_chunk * win[:len(enhanced_chunk)] tmp = enhanced_chunk[:chunk_length // 2] cur = tmp[:min(len(tmp), len(prev))] + prev[:min(len(tmp), len(prev))] prev = enhanced_chunk[chunk_length // 2:] if enhanced is None: enhanced = cur else: enhanced = torch.cat((enhanced, cur), dim=0) enhanced = enhanced[:noisy.shape[1]] return enhanced.detach().squeeze(0).cpu().numpy() @torch.no_grad() def time_domain(self, noisy, inference_args): noisy = noisy.to(self.device) enhanced = self.model(noisy) return enhanced.detach().squeeze().cpu().numpy() if __name__ == '__main__': a = torch.rand(10, 2, 161, 200) print(cumulative_norm(a).shape)
39.364929
116
0.624007
[ "Apache-2.0" ]
hit-thusz-RookieCJ/FullSubNet-plus
speech_enhance/fullsubnet/inferencer/inferencer.py
8,392
Python
# test_codecs.py from CPython 2.7, modified for Jython from test import test_support import unittest import codecs import locale import sys, StringIO if not test_support.is_jython: import _testcapi class Queue(object): """ queue: write bytes at one end, read bytes from the other end """ def __init__(self): self._buffer = "" def write(self, chars): self._buffer += chars def read(self, size=-1): if size<0: s = self._buffer self._buffer = "" return s else: s = self._buffer[:size] self._buffer = self._buffer[size:] return s class ReadTest(unittest.TestCase): def check_partial(self, input, partialresults): # get a StreamReader for the encoding and feed the bytestring version # of input to the reader byte by byte. Read everything available from # the StreamReader and check that the results equal the appropriate # entries from partialresults. q = Queue() r = codecs.getreader(self.encoding)(q) result = u"" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): q.write(c) result += r.read() self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(r.read(), u"") self.assertEqual(r.bytebuffer, "") self.assertEqual(r.charbuffer, u"") # do the check again, this time using a incremental decoder d = codecs.getincrementaldecoder(self.encoding)() result = u"" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(c) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode("", True), u"") self.assertEqual(d.buffer, "") # Check whether the reset method works properly d.reset() result = u"" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(c) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode("", True), u"") self.assertEqual(d.buffer, "") # check iterdecode() encoded = input.encode(self.encoding) self.assertEqual( input, u"".join(codecs.iterdecode(encoded, self.encoding)) ) def test_readline(self): def getreader(input): stream = StringIO.StringIO(input.encode(self.encoding)) return codecs.getreader(self.encoding)(stream) def readalllines(input, keepends=True, size=None): reader = getreader(input) lines = [] while True: line = reader.readline(size=size, keepends=keepends) if not line: break lines.append(line) return "|".join(lines) s = u"foo\nbar\r\nbaz\rspam\u2028eggs" sexpected = u"foo\n|bar\r\n|baz\r|spam\u2028|eggs" sexpectednoends = u"foo|bar|baz|spam|eggs" self.assertEqual(readalllines(s, True), sexpected) self.assertEqual(readalllines(s, False), sexpectednoends) self.assertEqual(readalllines(s, True, 10), sexpected) self.assertEqual(readalllines(s, False, 10), sexpectednoends) # Test long lines (multiple calls to read() in readline()) vw = [] vwo = [] for (i, lineend) in enumerate(u"\n \r\n \r \u2028".split()): vw.append((i*200)*u"\3042" + lineend) vwo.append((i*200)*u"\3042") self.assertEqual(readalllines("".join(vw), True), "".join(vw)) self.assertEqual(readalllines("".join(vw), False),"".join(vwo)) # Test lines where the first read might end with \r, so the # reader has to look ahead whether this is a lone \r or a \r\n for size in xrange(80): for lineend in u"\n \r\n \r \u2028".split(): s = 10*(size*u"a" + lineend + u"xxx\n") reader = getreader(s) for i in xrange(10): self.assertEqual( reader.readline(keepends=True), size*u"a" + lineend, ) reader = getreader(s) for i in xrange(10): self.assertEqual( reader.readline(keepends=False), size*u"a", ) def test_bug1175396(self): s = [ '<%!--===================================================\r\n', ' BLOG index page: show recent articles,\r\n', ' today\'s articles, or articles of a specific date.\r\n', '========================================================--%>\r\n', '<%@inputencoding="ISO-8859-1"%>\r\n', '<%@pagetemplate=TEMPLATE.y%>\r\n', '<%@import=import frog.util, frog%>\r\n', '<%@import=import frog.objects%>\r\n', '<%@import=from frog.storageerrors import StorageError%>\r\n', '<%\r\n', '\r\n', 'import logging\r\n', 'log=logging.getLogger("Snakelets.logger")\r\n', '\r\n', '\r\n', 'user=self.SessionCtx.user\r\n', 'storageEngine=self.SessionCtx.storageEngine\r\n', '\r\n', '\r\n', 'def readArticlesFromDate(date, count=None):\r\n', ' entryids=storageEngine.listBlogEntries(date)\r\n', ' entryids.reverse() # descending\r\n', ' if count:\r\n', ' entryids=entryids[:count]\r\n', ' try:\r\n', ' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n', ' except StorageError,x:\r\n', ' log.error("Error loading articles: "+str(x))\r\n', ' self.abort("cannot load articles")\r\n', '\r\n', 'showdate=None\r\n', '\r\n', 'arg=self.Request.getArg()\r\n', 'if arg=="today":\r\n', ' #-------------------- TODAY\'S ARTICLES\r\n', ' self.write("<h2>Today\'s articles</h2>")\r\n', ' showdate = frog.util.isodatestr() \r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'elif arg=="active":\r\n', ' #-------------------- ACTIVE ARTICLES redirect\r\n', ' self.Yredirect("active.y")\r\n', 'elif arg=="login":\r\n', ' #-------------------- LOGIN PAGE redirect\r\n', ' self.Yredirect("login.y")\r\n', 'elif arg=="date":\r\n', ' #-------------------- ARTICLES OF A SPECIFIC DATE\r\n', ' showdate = self.Request.getParameter("date")\r\n', ' self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'else:\r\n', ' #-------------------- RECENT ARTICLES\r\n', ' self.write("<h2>Recent articles</h2>")\r\n', ' dates=storageEngine.listBlogEntryDates()\r\n', ' if dates:\r\n', ' entries=[]\r\n', ' SHOWAMOUNT=10\r\n', ' for showdate in dates:\r\n', ' entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n', ' if len(entries)>=SHOWAMOUNT:\r\n', ' break\r\n', ' \r\n', ] stream = StringIO.StringIO("".join(s).encode(self.encoding)) reader = codecs.getreader(self.encoding)(stream) for (i, line) in enumerate(reader): self.assertEqual(line, s[i]) def test_readlinequeue(self): q = Queue() writer = codecs.getwriter(self.encoding)(q) reader = codecs.getreader(self.encoding)(q) # No lineends writer.write(u"foo\r") self.assertEqual(reader.readline(keepends=False), u"foo") writer.write(u"\nbar\r") self.assertEqual(reader.readline(keepends=False), u"") self.assertEqual(reader.readline(keepends=False), u"bar") writer.write(u"baz") self.assertEqual(reader.readline(keepends=False), u"baz") self.assertEqual(reader.readline(keepends=False), u"") # Lineends writer.write(u"foo\r") self.assertEqual(reader.readline(keepends=True), u"foo\r") writer.write(u"\nbar\r") self.assertEqual(reader.readline(keepends=True), u"\n") self.assertEqual(reader.readline(keepends=True), u"bar\r") writer.write(u"baz") self.assertEqual(reader.readline(keepends=True), u"baz") self.assertEqual(reader.readline(keepends=True), u"") writer.write(u"foo\r\n") self.assertEqual(reader.readline(keepends=True), u"foo\r\n") def test_bug1098990_a(self): s1 = u"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n" s2 = u"offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n" s3 = u"next line.\r\n" s = (s1+s2+s3).encode(self.encoding) stream = StringIO.StringIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), u"") def test_bug1098990_b(self): s1 = u"aaaaaaaaaaaaaaaaaaaaaaaa\r\n" s2 = u"bbbbbbbbbbbbbbbbbbbbbbbb\r\n" s3 = u"stillokay:bbbbxx\r\n" s4 = u"broken!!!!badbad\r\n" s5 = u"againokay.\r\n" s = (s1+s2+s3+s4+s5).encode(self.encoding) stream = StringIO.StringIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), s4) self.assertEqual(reader.readline(), s5) self.assertEqual(reader.readline(), u"") class UTF32Test(ReadTest): encoding = "utf-32" spamle = ('\xff\xfe\x00\x00' 's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00' 's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00') spambe = ('\x00\x00\xfe\xff' '\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m' '\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m') def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = StringIO.StringIO() f = writer(s) f.write(u"spam") f.write(u"spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = StringIO.StringIO(d) f = reader(s) self.assertEqual(f.read(), u"spamspam") def test_badbom(self): s = StringIO.StringIO(4*"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = StringIO.StringIO(8*"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", # first byte of BOM read u"", # second byte of BOM read u"", # third byte of BOM read u"", # fourth byte of BOM read => byteorder known u"", u"", u"", u"\x00", u"\x00", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_handlers(self): self.assertEqual((u'\ufffd', 1), codecs.utf_32_decode('\x01', 'replace', True)) self.assertEqual((u'', 1), codecs.utf_32_decode('\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode, "\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded_le = '\xff\xfe\x00\x00' + '\x00\x00\x01\x00' * 1024 self.assertEqual(u'\U00010000' * 1024, codecs.utf_32_decode(encoded_le)[0]) encoded_be = '\x00\x00\xfe\xff' + '\x00\x01\x00\x00' * 1024 self.assertEqual(u'\U00010000' * 1024, codecs.utf_32_decode(encoded_be)[0]) class UTF32LETest(ReadTest): encoding = "utf-32-le" def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", u"", u"", u"\x00", u"\x00", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_simple(self): self.assertEqual(u"\U00010203".encode(self.encoding), "\x03\x02\x01\x00") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode, "\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = '\x00\x00\x01\x00' * 1024 self.assertEqual(u'\U00010000' * 1024, codecs.utf_32_le_decode(encoded)[0]) class UTF32BETest(ReadTest): encoding = "utf-32-be" def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", u"", u"", u"\x00", u"\x00", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_simple(self): self.assertEqual(u"\U00010203".encode(self.encoding), "\x00\x01\x02\x03") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode, "\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = '\x00\x01\x00\x00' * 1024 self.assertEqual(u'\U00010000' * 1024, codecs.utf_32_be_decode(encoded)[0]) class UTF16Test(ReadTest): encoding = "utf-16" spamle = '\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00' spambe = '\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m' def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = StringIO.StringIO() f = writer(s) f.write(u"spam") f.write(u"spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = StringIO.StringIO(d) f = reader(s) self.assertEqual(f.read(), u"spamspam") def test_badbom(self): s = StringIO.StringIO("\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = StringIO.StringIO("\xff\xff\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", # first byte of BOM read u"", # second byte of BOM read => byteorder known u"", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_handlers(self): self.assertEqual((u'\ufffd', 1), codecs.utf_16_decode('\x01', 'replace', True)) self.assertEqual((u'', 1), codecs.utf_16_decode('\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, "\xff", "strict", True) def test_bug691291(self): # Files are always opened in binary mode, even if no binary mode was # specified. This means that no automatic conversion of '\n' is done # on reading and writing. s1 = u'Hello\r\nworld\r\n' s = s1.encode(self.encoding) self.addCleanup(test_support.unlink, test_support.TESTFN) with open(test_support.TESTFN, 'wb') as fp: fp.write(s) with codecs.open(test_support.TESTFN, 'U', encoding=self.encoding) as reader: self.assertEqual(reader.read(), s1) class UTF16LETest(ReadTest): encoding = "utf-16-le" def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, "\xff", "strict", True) class UTF16BETest(ReadTest): encoding = "utf-16-be" def test_partial(self): self.check_partial( u"\x00\xff\u0100\uffff", [ u"", u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff\u0100", u"\x00\xff\u0100", u"\x00\xff\u0100\uffff", ] ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, "\xff", "strict", True) class UTF8Test(ReadTest): encoding = "utf-8" def test_partial(self): self.check_partial( u"\x00\xff\u07ff\u0800\uffff", [ u"\x00", u"\x00", u"\x00\xff", u"\x00\xff", u"\x00\xff\u07ff", u"\x00\xff\u07ff", u"\x00\xff\u07ff", u"\x00\xff\u07ff\u0800", u"\x00\xff\u07ff\u0800", u"\x00\xff\u07ff\u0800", u"\x00\xff\u07ff\u0800\uffff", ] ) class UTF7Test(ReadTest): encoding = "utf-7" def test_partial(self): self.check_partial( u"a+-b", [ u"a", u"a", u"a+", u"a+-", u"a+-b", ] ) # Jython extra (test supplementary characters) @unittest.skipIf(not test_support.is_jython, "Jython supports surrogate pairs") def test_partial_supp(self): # Check the encoding is what we think it is ustr = u"x\U00023456.\u0177\U00023456\u017az" bstr = b'x+2E3cVg.+AXfYTdxWAXo-z' self.assertEqual(ustr.encode(self.encoding), bstr) self.check_partial( ustr, [ u"x", u"x", # '+' added: begins Base64 u"x", u"x", u"x", u"x", u"x", u"x", u"x\U00023456.", # '.' added: ends Base64 u"x\U00023456.", # '+' added: begins Base64 u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.", u"x\U00023456.\u0177\U00023456\u017a", # '-' added: ends Base64 u"x\U00023456.\u0177\U00023456\u017az", ] ) class UTF16ExTest(unittest.TestCase): def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_ex_decode, "\xff", "strict", 0, True) def test_bad_args(self): self.assertRaises(TypeError, codecs.utf_16_ex_decode) @unittest.skipIf(test_support.is_jython, "Jython has no _codecs.readbuffer_encode method") class ReadBufferTest(unittest.TestCase): def test_array(self): import array self.assertEqual( codecs.readbuffer_encode(array.array("c", "spam")), ("spam", 4) ) def test_empty(self): self.assertEqual(codecs.readbuffer_encode(""), ("", 0)) def test_bad_args(self): self.assertRaises(TypeError, codecs.readbuffer_encode) self.assertRaises(TypeError, codecs.readbuffer_encode, 42) @unittest.skipIf(test_support.is_jython, "Jython has no _codecs.charbuffer_encode method") class CharBufferTest(unittest.TestCase): def test_string(self): self.assertEqual(codecs.charbuffer_encode("spam"), ("spam", 4)) def test_empty(self): self.assertEqual(codecs.charbuffer_encode(""), ("", 0)) def test_bad_args(self): self.assertRaises(TypeError, codecs.charbuffer_encode) self.assertRaises(TypeError, codecs.charbuffer_encode, 42) class UTF8SigTest(ReadTest): encoding = "utf-8-sig" def test_partial(self): self.check_partial( u"\ufeff\x00\xff\u07ff\u0800\uffff", [ u"", u"", u"", # First BOM has been read and skipped u"", u"", u"\ufeff", # Second BOM has been read and emitted u"\ufeff\x00", # "\x00" read and emitted u"\ufeff\x00", # First byte of encoded u"\xff" read u"\ufeff\x00\xff", # Second byte of encoded u"\xff" read u"\ufeff\x00\xff", # First byte of encoded u"\u07ff" read u"\ufeff\x00\xff\u07ff", # Second byte of encoded u"\u07ff" read u"\ufeff\x00\xff\u07ff", u"\ufeff\x00\xff\u07ff", u"\ufeff\x00\xff\u07ff\u0800", u"\ufeff\x00\xff\u07ff\u0800", u"\ufeff\x00\xff\u07ff\u0800", u"\ufeff\x00\xff\u07ff\u0800\uffff", ] ) def test_bug1601501(self): # SF bug #1601501: check that the codec works with a buffer unicode("\xef\xbb\xbf", "utf-8-sig") def test_bom(self): d = codecs.getincrementaldecoder("utf-8-sig")() s = u"spam" self.assertEqual(d.decode(s.encode("utf-8-sig")), s) def test_stream_bom(self): unistring = u"ABC\u00A1\u2200XYZ" bytestring = codecs.BOM_UTF8 + "ABC\xC2\xA1\xE2\x88\x80XYZ" reader = codecs.getreader("utf-8-sig") for sizehint in [None] + range(1, 11) + \ [64, 128, 256, 512, 1024]: istream = reader(StringIO.StringIO(bytestring)) ostream = StringIO.StringIO() while 1: if sizehint is not None: data = istream.read(sizehint) else: data = istream.read() if not data: break ostream.write(data) got = ostream.getvalue() self.assertEqual(got, unistring) def test_stream_bare(self): unistring = u"ABC\u00A1\u2200XYZ" bytestring = "ABC\xC2\xA1\xE2\x88\x80XYZ" reader = codecs.getreader("utf-8-sig") for sizehint in [None] + range(1, 11) + \ [64, 128, 256, 512, 1024]: istream = reader(StringIO.StringIO(bytestring)) ostream = StringIO.StringIO() while 1: if sizehint is not None: data = istream.read(sizehint) else: data = istream.read() if not data: break ostream.write(data) got = ostream.getvalue() self.assertEqual(got, unistring) class EscapeDecodeTest(unittest.TestCase): def test_empty(self): self.assertEqual(codecs.escape_decode(""), ("", 0)) class RecodingTest(unittest.TestCase): def test_recoding(self): f = StringIO.StringIO() f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8") # f2.write(u"a") # Must be bytes in Jython (and probably should have been in CPython) f2.write(b"\x00\x00\x00\x61") f2.close() # Python used to crash on this at exit because of a refcount # bug in _codecsmodule.c # From RFC 3492 punycode_testcases = [ # A Arabic (Egyptian): (u"\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" u"\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn"), # B Chinese (simplified): (u"\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye"), # C Chinese (traditional): (u"\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb"), # D Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky (u"\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" u"\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" u"\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a"), # E Hebrew: (u"\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" u"\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" u"\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b"), # F Hindi (Devanagari): (u"\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" u"\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" u"\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" u"\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd"), #(G) Japanese (kanji and hiragana): (u"\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" u"\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa"), # (H) Korean (Hangul syllables): (u"\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" u"\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" u"\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" "psd879ccm6fea98c"), # (I) Russian (Cyrillic): (u"\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" u"\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" u"\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" u"\u0438", "b1abfaaepdrnnbgefbaDotcwatmq2g4l"), # (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol (u"\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" u"\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" u"\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" u"\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" u"\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a"), # (K) Vietnamese: # T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch\ # <ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t (u"\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" u"\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" u"\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" u"\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"), #(L) 3<nen>B<gumi><kinpachi><sensei> (u"\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b"), # (M) <amuro><namie>-with-SUPER-MONKEYS (u"\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" u"\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" u"\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n"), # (N) Hello-Another-Way-<sorezore><no><basho> (u"\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" u"\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" u"\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b"), # (O) <hitotsu><yane><no><shita>2 (u"\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v"), # (P) Maji<de>Koi<suru>5<byou><mae> (u"\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" u"\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e"), # (Q) <pafii>de<runba> (u"\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d"), # (R) <sono><supiido><de> (u"\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp"), # (S) -> $1.00 <- (u"\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" u"\u003C\u002D", "-> $1.00 <--") ] for i in punycode_testcases: if len(i)!=2: print repr(i) class PunycodeTest(unittest.TestCase): def test_encode(self): for uni, puny in punycode_testcases: # Need to convert both strings to lower case, since # some of the extended encodings use upper case, but our # code produces only lower case. Converting just puny to # lower is also insufficient, since some of the input characters # are upper case. self.assertEqual(uni.encode("punycode").lower(), puny.lower()) def test_decode(self): for uni, puny in punycode_testcases: self.assertEqual(uni, puny.decode("punycode")) class UnicodeInternalTest(unittest.TestCase): def test_bug1251300(self): # Decoding with unicode_internal used to not correctly handle "code # points" above 0x10ffff on UCS-4 builds. if sys.maxunicode > 0xffff: ok = [ ("\x00\x10\xff\xff", u"\U0010ffff"), ("\x00\x00\x01\x01", u"\U00000101"), ("", u""), ] not_ok = [ "\x7f\xff\xff\xff", "\x80\x00\x00\x00", "\x81\x00\x00\x00", "\x00", "\x00\x00\x00\x00\x00", ] for internal, uni in ok: if sys.byteorder == "little": internal = "".join(reversed(internal)) self.assertEqual(uni, internal.decode("unicode_internal")) for internal in not_ok: if sys.byteorder == "little": internal = "".join(reversed(internal)) self.assertRaises(UnicodeDecodeError, internal.decode, "unicode_internal") def test_decode_error_attributes(self): if sys.maxunicode > 0xffff: try: "\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") except UnicodeDecodeError, ex: if test_support.is_jython: # Jython delegates internally to utf-32be and it shows here self.assertEqual("utf-32", ex.encoding) else: self.assertEqual("unicode_internal", ex.encoding) self.assertEqual("\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEqual(4, ex.start) self.assertEqual(8, ex.end) else: self.fail("UnicodeDecodeError not raised") def test_decode_callback(self): if sys.maxunicode > 0xffff: codecs.register_error("UnicodeInternalTest", codecs.ignore_errors) decoder = codecs.getdecoder("unicode_internal") ab = u"ab".encode("unicode_internal") ignored = decoder("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]), "UnicodeInternalTest") self.assertEqual((u"ab", 12), ignored) def test_encode_length(self): # Issue 3739 encoder = codecs.getencoder("unicode_internal") self.assertEqual(encoder(u"a")[1], 1) self.assertEqual(encoder(u"\xe9\u0142")[1], 2) encoder = codecs.getencoder("string-escape") self.assertEqual(encoder(r'\x00')[1], 4) # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html nameprep_tests = [ # 3.1 Map to nothing. ('foo\xc2\xad\xcd\x8f\xe1\xa0\x86\xe1\xa0\x8bbar' '\xe2\x80\x8b\xe2\x81\xa0baz\xef\xb8\x80\xef\xb8\x88\xef' '\xb8\x8f\xef\xbb\xbf', 'foobarbaz'), # 3.2 Case folding ASCII U+0043 U+0041 U+0046 U+0045. ('CAFE', 'cafe'), # 3.3 Case folding 8bit U+00DF (german sharp s). # The original test case is bogus; it says \xc3\xdf ('\xc3\x9f', 'ss'), # 3.4 Case folding U+0130 (turkish capital I with dot). ('\xc4\xb0', 'i\xcc\x87'), # 3.5 Case folding multibyte U+0143 U+037A. ('\xc5\x83\xcd\xba', '\xc5\x84 \xce\xb9'), # 3.6 Case folding U+2121 U+33C6 U+1D7BB. # XXX: skip this as it fails in UCS-2 mode #('\xe2\x84\xa1\xe3\x8f\x86\xf0\x9d\x9e\xbb', # 'telc\xe2\x88\x95kg\xcf\x83'), (None, None), # 3.7 Normalization of U+006a U+030c U+00A0 U+00AA. ('j\xcc\x8c\xc2\xa0\xc2\xaa', '\xc7\xb0 a'), # 3.8 Case folding U+1FB7 and normalization. ('\xe1\xbe\xb7', '\xe1\xbe\xb6\xce\xb9'), # 3.9 Self-reverting case folding U+01F0 and normalization. # The original test case is bogus, it says `\xc7\xf0' ('\xc7\xb0', '\xc7\xb0'), # 3.10 Self-reverting case folding U+0390 and normalization. ('\xce\x90', '\xce\x90'), # 3.11 Self-reverting case folding U+03B0 and normalization. ('\xce\xb0', '\xce\xb0'), # 3.12 Self-reverting case folding U+1E96 and normalization. ('\xe1\xba\x96', '\xe1\xba\x96'), # 3.13 Self-reverting case folding U+1F56 and normalization. ('\xe1\xbd\x96', '\xe1\xbd\x96'), # 3.14 ASCII space character U+0020. (' ', ' '), # 3.15 Non-ASCII 8bit space character U+00A0. ('\xc2\xa0', ' '), # 3.16 Non-ASCII multibyte space character U+1680. ('\xe1\x9a\x80', None), # 3.17 Non-ASCII multibyte space character U+2000. ('\xe2\x80\x80', ' '), # 3.18 Zero Width Space U+200b. ('\xe2\x80\x8b', ''), # 3.19 Non-ASCII multibyte space character U+3000. ('\xe3\x80\x80', ' '), # 3.20 ASCII control characters U+0010 U+007F. ('\x10\x7f', '\x10\x7f'), # 3.21 Non-ASCII 8bit control character U+0085. ('\xc2\x85', None), # 3.22 Non-ASCII multibyte control character U+180E. ('\xe1\xa0\x8e', None), # 3.23 Zero Width No-Break Space U+FEFF. ('\xef\xbb\xbf', ''), # 3.24 Non-ASCII control character U+1D175. ('\xf0\x9d\x85\xb5', None), # 3.25 Plane 0 private use character U+F123. ('\xef\x84\xa3', None), # 3.26 Plane 15 private use character U+F1234. ('\xf3\xb1\x88\xb4', None), # 3.27 Plane 16 private use character U+10F234. ('\xf4\x8f\x88\xb4', None), # 3.28 Non-character code point U+8FFFE. ('\xf2\x8f\xbf\xbe', None), # 3.29 Non-character code point U+10FFFF. ('\xf4\x8f\xbf\xbf', None), # 3.30 Surrogate code U+DF42. ('\xed\xbd\x82', None), # 3.31 Non-plain text character U+FFFD. ('\xef\xbf\xbd', None), # 3.32 Ideographic description character U+2FF5. ('\xe2\xbf\xb5', None), # 3.33 Display property character U+0341. ('\xcd\x81', '\xcc\x81'), # 3.34 Left-to-right mark U+200E. ('\xe2\x80\x8e', None), # 3.35 Deprecated U+202A. ('\xe2\x80\xaa', None), # 3.36 Language tagging character U+E0001. ('\xf3\xa0\x80\x81', None), # 3.37 Language tagging character U+E0042. ('\xf3\xa0\x81\x82', None), # 3.38 Bidi: RandALCat character U+05BE and LCat characters. ('foo\xd6\xbebar', None), # 3.39 Bidi: RandALCat character U+FD50 and LCat characters. ('foo\xef\xb5\x90bar', None), # 3.40 Bidi: RandALCat character U+FB38 and LCat characters. ('foo\xef\xb9\xb6bar', 'foo \xd9\x8ebar'), # 3.41 Bidi: RandALCat without trailing RandALCat U+0627 U+0031. ('\xd8\xa71', None), # 3.42 Bidi: RandALCat character U+0627 U+0031 U+0628. ('\xd8\xa71\xd8\xa8', '\xd8\xa71\xd8\xa8'), # 3.43 Unassigned code point U+E0002. # Skip this test as we allow unassigned #('\xf3\xa0\x80\x82', # None), (None, None), # 3.44 Larger test (shrinking). # Original test case reads \xc3\xdf ('X\xc2\xad\xc3\x9f\xc4\xb0\xe2\x84\xa1j\xcc\x8c\xc2\xa0\xc2' '\xaa\xce\xb0\xe2\x80\x80', 'xssi\xcc\x87tel\xc7\xb0 a\xce\xb0 '), # 3.45 Larger test (expanding). # Original test case reads \xc3\x9f ('X\xc3\x9f\xe3\x8c\x96\xc4\xb0\xe2\x84\xa1\xe2\x92\x9f\xe3\x8c' '\x80', 'xss\xe3\x82\xad\xe3\x83\xad\xe3\x83\xa1\xe3\x83\xbc\xe3' '\x83\x88\xe3\x83\xabi\xcc\x87tel\x28d\x29\xe3\x82' '\xa2\xe3\x83\x91\xe3\x83\xbc\xe3\x83\x88') ] @unittest.skipIf(test_support.is_jython, "FIXME: incomplete unicodedata module") class NameprepTest(unittest.TestCase): def test_nameprep(self): from encodings.idna import nameprep for pos, (orig, prepped) in enumerate(nameprep_tests): if orig is None: # Skipped continue # The Unicode strings are given in UTF-8 orig = unicode(orig, "utf-8") if prepped is None: # Input contains prohibited characters self.assertRaises(UnicodeError, nameprep, orig) else: prepped = unicode(prepped, "utf-8") try: self.assertEqual(nameprep(orig), prepped) except Exception,e: raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) @unittest.skipIf(test_support.is_jython, "FIXME: Jython issue 2000 missing support for IDNA") class IDNACodecTest(unittest.TestCase): def test_builtin_decode(self): self.assertEqual(unicode("python.org", "idna"), u"python.org") self.assertEqual(unicode("python.org.", "idna"), u"python.org.") self.assertEqual(unicode("xn--pythn-mua.org", "idna"), u"pyth\xf6n.org") self.assertEqual(unicode("xn--pythn-mua.org.", "idna"), u"pyth\xf6n.org.") def test_builtin_encode(self): self.assertEqual(u"python.org".encode("idna"), "python.org") self.assertEqual("python.org.".encode("idna"), "python.org.") self.assertEqual(u"pyth\xf6n.org".encode("idna"), "xn--pythn-mua.org") self.assertEqual(u"pyth\xf6n.org.".encode("idna"), "xn--pythn-mua.org.") def test_stream(self): import StringIO r = codecs.getreader("idna")(StringIO.StringIO("abc")) r.read(3) self.assertEqual(r.read(), u"") def test_incremental_decode(self): self.assertEqual( "".join(codecs.iterdecode("python.org", "idna")), u"python.org" ) self.assertEqual( "".join(codecs.iterdecode("python.org.", "idna")), u"python.org." ) self.assertEqual( "".join(codecs.iterdecode("xn--pythn-mua.org.", "idna")), u"pyth\xf6n.org." ) self.assertEqual( "".join(codecs.iterdecode("xn--pythn-mua.org.", "idna")), u"pyth\xf6n.org." ) decoder = codecs.getincrementaldecoder("idna")() self.assertEqual(decoder.decode("xn--xam", ), u"") self.assertEqual(decoder.decode("ple-9ta.o", ), u"\xe4xample.") self.assertEqual(decoder.decode(u"rg"), u"") self.assertEqual(decoder.decode(u"", True), u"org") decoder.reset() self.assertEqual(decoder.decode("xn--xam", ), u"") self.assertEqual(decoder.decode("ple-9ta.o", ), u"\xe4xample.") self.assertEqual(decoder.decode("rg."), u"org.") self.assertEqual(decoder.decode("", True), u"") def test_incremental_encode(self): self.assertEqual( "".join(codecs.iterencode(u"python.org", "idna")), "python.org" ) self.assertEqual( "".join(codecs.iterencode(u"python.org.", "idna")), "python.org." ) self.assertEqual( "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")), "xn--pythn-mua.org." ) self.assertEqual( "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")), "xn--pythn-mua.org." ) encoder = codecs.getincrementalencoder("idna")() self.assertEqual(encoder.encode(u"\xe4x"), "") self.assertEqual(encoder.encode(u"ample.org"), "xn--xample-9ta.") self.assertEqual(encoder.encode(u"", True), "org") encoder.reset() self.assertEqual(encoder.encode(u"\xe4x"), "") self.assertEqual(encoder.encode(u"ample.org."), "xn--xample-9ta.org.") self.assertEqual(encoder.encode(u"", True), "") class CodecsModuleTest(unittest.TestCase): def test_decode(self): self.assertEqual(codecs.decode('\xe4\xf6\xfc', 'latin-1'), u'\xe4\xf6\xfc') self.assertRaises(TypeError, codecs.decode) self.assertEqual(codecs.decode('abc'), u'abc') self.assertRaises(UnicodeDecodeError, codecs.decode, '\xff', 'ascii') def test_encode(self): self.assertEqual(codecs.encode(u'\xe4\xf6\xfc', 'latin-1'), '\xe4\xf6\xfc') self.assertRaises(TypeError, codecs.encode) self.assertRaises(LookupError, codecs.encode, u"foo", "__spam__") self.assertEqual(codecs.encode(u'abc'), 'abc') self.assertRaises(UnicodeEncodeError, codecs.encode, u'\xffff', 'ascii') def test_register(self): self.assertRaises(TypeError, codecs.register) self.assertRaises(TypeError, codecs.register, 42) def test_lookup(self): self.assertRaises(TypeError, codecs.lookup) self.assertRaises(LookupError, codecs.lookup, "__spam__") self.assertRaises(LookupError, codecs.lookup, " ") def test_getencoder(self): self.assertRaises(TypeError, codecs.getencoder) self.assertRaises(LookupError, codecs.getencoder, "__spam__") def test_getdecoder(self): self.assertRaises(TypeError, codecs.getdecoder) self.assertRaises(LookupError, codecs.getdecoder, "__spam__") def test_getreader(self): self.assertRaises(TypeError, codecs.getreader) self.assertRaises(LookupError, codecs.getreader, "__spam__") def test_getwriter(self): self.assertRaises(TypeError, codecs.getwriter) self.assertRaises(LookupError, codecs.getwriter, "__spam__") def test_lookup_issue1813(self): # Issue #1813: under Turkish locales, lookup of some codecs failed # because 'I' is lowercased as a dotless "i" oldlocale = locale.getlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) try: locale.setlocale(locale.LC_CTYPE, 'tr_TR') except locale.Error: # Unsupported locale on this system self.skipTest('test needs Turkish locale') c = codecs.lookup('ASCII') self.assertEqual(c.name, 'ascii') class StreamReaderTest(unittest.TestCase): def setUp(self): self.reader = codecs.getreader('utf-8') self.stream = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') def test_readlines(self): f = self.reader(self.stream) self.assertEqual(f.readlines(), [u'\ud55c\n', u'\uae00']) class EncodedFileTest(unittest.TestCase): def test_basic(self): f = StringIO.StringIO('\xed\x95\x9c\n\xea\xb8\x80') ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') self.assertEqual(ef.read(), '\\\xd5\n\x00\x00\xae') f = StringIO.StringIO() ef = codecs.EncodedFile(f, 'utf-8', 'latin1') ef.write('\xc3\xbc') self.assertEqual(f.getvalue(), '\xfc') class Str2StrTest(unittest.TestCase): def test_read(self): sin = "\x80".encode("base64_codec") reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin)) sout = reader.read() self.assertEqual(sout, "\x80") self.assertIsInstance(sout, str) def test_readline(self): sin = "\x80".encode("base64_codec") reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin)) sout = reader.readline() self.assertEqual(sout, "\x80") self.assertIsInstance(sout, str) all_unicode_encodings = [ "ascii", "base64_codec", # FIXME: Jython issue 1066: "big5", # FIXME: Jython issue 1066: "big5hkscs", "charmap", "cp037", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", "cp875", # FIXME: Jython issue 1066: "cp932", # FIXME: Jython issue 1066: "cp949", # FIXME: Jython issue 1066: "cp950", # FIXME: Jython issue 1066: "euc_jis_2004", # FIXME: Jython issue 1066: 'euc_jisx0213', # FIXME: Jython issue 1066: 'euc_jp', # FIXME: Jython issue 1066: 'euc_kr', # FIXME: Jython issue 1066: 'gb18030', # FIXME: Jython issue 1066: 'gb2312', # FIXME: Jython issue 1066: 'gbk', "hex_codec", "hp_roman8", # FIXME: Jython issue 1066: 'hz', # FIXME: Jython issue 1066: "idna", # FIXME: Jython issue 1066: 'iso2022_jp', # FIXME: Jython issue 1066: 'iso2022_jp_1', # FIXME: Jython issue 1066: 'iso2022_jp_2', # FIXME: Jython issue 1066: 'iso2022_jp_2004', # FIXME: Jython issue 1066: 'iso2022_jp_3', # FIXME: Jython issue 1066: 'iso2022_jp_ext', # FIXME: Jython issue 1066: 'iso2022_kr', "iso8859_1", "iso8859_10", "iso8859_11", "iso8859_13", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8", "iso8859_9", # FIXME: Jython issue 1066: 'johab', "koi8_r", "koi8_u", "latin_1", "mac_cyrillic", "mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "palmos", "ptcp154", "punycode", "raw_unicode_escape", "rot_13", # FIXME: Jython issue 1066: 'shift_jis', # FIXME: Jython issue 1066: 'shift_jis_2004', # FIXME: Jython issue 1066: 'shift_jisx0213', "tis_620", "unicode_escape", "unicode_internal", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", ] if hasattr(codecs, "mbcs_encode"): all_unicode_encodings.append("mbcs") # The following encodings work only with str, not unicode all_string_encodings = [ "quopri_codec", "string_escape", "uu_codec", ] # The following encoding is not tested, because it's not supposed # to work: # "undefined" # The following encodings don't work in stateful mode broken_unicode_with_streams = [ "base64_codec", "hex_codec", "punycode", "unicode_internal" ] broken_incremental_coders = broken_unicode_with_streams[:] # The following encodings only support "strict" mode only_strict_mode = [ "idna", "zlib_codec", "bz2_codec", ] try: import bz2 except ImportError: pass else: all_unicode_encodings.append("bz2_codec") broken_unicode_with_streams.append("bz2_codec") try: import zlib except ImportError: pass else: all_unicode_encodings.append("zlib_codec") broken_unicode_with_streams.append("zlib_codec") class BasicUnicodeTest(unittest.TestCase): @unittest.skipIf(test_support.is_jython, "_testcapi module not present in Jython") def test_basics(self): s = u"abc123" # all codecs should be able to encode these for encoding in all_unicode_encodings: name = codecs.lookup(encoding).name if encoding.endswith("_codec"): name += "_codec" elif encoding == "latin_1": name = "latin_1" self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-")) (bytes, size) = codecs.getencoder(encoding)(s) self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding)) (chars, size) = codecs.getdecoder(encoding)(bytes) self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding)) if encoding not in broken_unicode_with_streams: # check stream reader/writer q = Queue() writer = codecs.getwriter(encoding)(q) encodedresult = "" for c in s: writer.write(c) encodedresult += q.read() q = Queue() reader = codecs.getreader(encoding)(q) decodedresult = u"" for c in encodedresult: q.write(c) decodedresult += reader.read() self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) if encoding not in broken_incremental_coders: # check incremental decoder/encoder (fetched via the Python # and C API) and iterencode()/iterdecode() try: encoder = codecs.getincrementalencoder(encoding)() cencoder = _testcapi.codec_incrementalencoder(encoding) except LookupError: # no IncrementalEncoder pass else: # check incremental decoder/encoder encodedresult = "" for c in s: encodedresult += encoder.encode(c) encodedresult += encoder.encode(u"", True) decoder = codecs.getincrementaldecoder(encoding)() decodedresult = u"" for c in encodedresult: decodedresult += decoder.decode(c) decodedresult += decoder.decode("", True) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) # check C API encodedresult = "" for c in s: encodedresult += cencoder.encode(c) encodedresult += cencoder.encode(u"", True) cdecoder = _testcapi.codec_incrementaldecoder(encoding) decodedresult = u"" for c in encodedresult: decodedresult += cdecoder.decode(c) decodedresult += cdecoder.decode("", True) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) # check iterencode()/iterdecode() result = u"".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding)) self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding)) # check iterencode()/iterdecode() with empty string result = u"".join(codecs.iterdecode(codecs.iterencode(u"", encoding), encoding)) self.assertEqual(result, u"") if encoding not in only_strict_mode: # check incremental decoder/encoder with errors argument try: encoder = codecs.getincrementalencoder(encoding)("ignore") cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore") except LookupError: # no IncrementalEncoder pass else: encodedresult = "".join(encoder.encode(c) for c in s) decoder = codecs.getincrementaldecoder(encoding)("ignore") decodedresult = u"".join(decoder.decode(c) for c in encodedresult) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) encodedresult = "".join(cencoder.encode(c) for c in s) cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore") decodedresult = u"".join(cdecoder.decode(c) for c in encodedresult) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) def test_seek(self): # all codecs should be able to encode these s = u"%s\n%s\n" % (100*u"abc123", 100*u"def456") for encoding in all_unicode_encodings: if encoding == "idna": # FIXME: See SF bug #1163178 continue if encoding in broken_unicode_with_streams: continue reader = codecs.getreader(encoding)(StringIO.StringIO(s.encode(encoding))) for t in xrange(5): # Test that calling seek resets the internal codec state and buffers reader.seek(0, 0) line = reader.readline() self.assertEqual(s[:len(line)], line) def test_bad_decode_args(self): for encoding in all_unicode_encodings: decoder = codecs.getdecoder(encoding) self.assertRaises(TypeError, decoder) if encoding not in ("idna", "punycode"): self.assertRaises(TypeError, decoder, 42) def test_bad_encode_args(self): for encoding in all_unicode_encodings: encoder = codecs.getencoder(encoding) self.assertRaises(TypeError, encoder) def test_encoding_map_type_initialized(self): from encodings import cp1140 # This used to crash, we are only verifying there's no crash. table_type = type(cp1140.encoding_table) self.assertEqual(table_type, table_type) class BasicStrTest(unittest.TestCase): def test_basics(self): s = "abc123" for encoding in all_string_encodings: (bytes, size) = codecs.getencoder(encoding)(s) self.assertEqual(size, len(s)) (chars, size) = codecs.getdecoder(encoding)(bytes) self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding)) class CharmapTest(unittest.TestCase): def test_decode_with_string_map(self): self.assertEqual( codecs.charmap_decode("\x00\x01\x02", "strict", u"abc"), (u"abc", 3) ) self.assertEqual( codecs.charmap_decode("\x00\x01\x02", "replace", u"ab"), (u"ab\ufffd", 3) ) self.assertEqual( codecs.charmap_decode("\x00\x01\x02", "replace", u"ab\ufffe"), (u"ab\ufffd", 3) ) self.assertEqual( codecs.charmap_decode("\x00\x01\x02", "ignore", u"ab"), (u"ab", 3) ) self.assertEqual( codecs.charmap_decode("\x00\x01\x02", "ignore", u"ab\ufffe"), (u"ab", 3) ) allbytes = "".join(chr(i) for i in xrange(256)) self.assertEqual( codecs.charmap_decode(allbytes, "ignore", u""), (u"", len(allbytes)) ) class WithStmtTest(unittest.TestCase): def test_encodedfile(self): f = StringIO.StringIO("\xc3\xbc") with codecs.EncodedFile(f, "latin-1", "utf-8") as ef: self.assertEqual(ef.read(), "\xfc") def test_streamreaderwriter(self): f = StringIO.StringIO("\xc3\xbc") info = codecs.lookup("utf-8") with codecs.StreamReaderWriter(f, info.streamreader, info.streamwriter, 'strict') as srw: self.assertEqual(srw.read(), u"\xfc") class BomTest(unittest.TestCase): def test_seek0(self): data = u"1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", "utf-32", "utf-32-le", "utf-32-be", ) self.addCleanup(test_support.unlink, test_support.TESTFN) for encoding in tests: # Check if the BOM is written only once with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) f.seek(0) self.assertEqual(f.read(), data * 2) # Check that the BOM is written after a seek(0) with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.write(data[0]) self.assertNotEqual(f.tell(), 0) f.seek(0) f.write(data) f.seek(0) self.assertEqual(f.read(), data) # (StreamWriter) Check that the BOM is written after a seek(0) with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.writer.write(data[0]) self.assertNotEqual(f.writer.tell(), 0) f.writer.seek(0) f.writer.write(data) f.seek(0) self.assertEqual(f.read(), data) # Check that the BOM is not written after a seek() at a position # different than the start with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.seek(f.tell()) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) # (StreamWriter) Check that the BOM is not written after a seek() # at a position different than the start with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.writer.write(data) f.writer.seek(f.writer.tell()) f.writer.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) def test_main(): test_support.run_unittest( UTF32Test, UTF32LETest, UTF32BETest, UTF16Test, UTF16LETest, UTF16BETest, UTF8Test, UTF8SigTest, UTF7Test, UTF16ExTest, ReadBufferTest, CharBufferTest, EscapeDecodeTest, RecodingTest, PunycodeTest, UnicodeInternalTest, NameprepTest, IDNACodecTest, CodecsModuleTest, StreamReaderTest, EncodedFileTest, Str2StrTest, BasicUnicodeTest, BasicStrTest, CharmapTest, WithStmtTest, BomTest, ) if __name__ == "__main__": test_main()
35.96849
115
0.557084
[ "EPL-1.0" ]
Gumtree/gumtree
framework/extensions/org.python.jython/Lib/test/test_codecs.py
60,499
Python
import sys import pyodbc from django.db import connections from request.utils import retrieve_server_name_tcp_port def validate_database_name(server_name,database_name): try: server_name = retrieve_server_name_tcp_port(server_name) print(server_name) cnxn = pyodbc.connect(r"Driver={ODBC Driver 17 for SQL Server};Server="+str(server_name)+";Database=master;Trusted_Connection=yes;APP='sql-dashboard check database existance '") custom_cursor = cnxn.cursor() custom_cursor.execute("SELECT name AS database_name FROM sys.databases WHERE name = '{0}'".format(database_name)) database_name_exists = custom_cursor.fetchall() if(database_name_exists): data = { 'is_taken':True } if data['is_taken']: data['error_message'] = "Database " + database_name + " already exists on " + server_name cnxn.close() return data else: data = { 'is_taken':False } return data except: error = sys.exc_info() print(error)
37.548387
186
0.611684
[ "MIT" ]
marcosfreccia/SQLDashboard
request/create_database.py
1,164
Python
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Adam.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.keras import optimizers from tensorflow.python.keras.optimizer_v2 import adam from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test def adam_update_numpy(param, g_t, t, m, v, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-7): lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1)) m_t = beta1 * m + (1 - beta1) * g_t v_t = beta2 * v + (1 - beta2) * g_t * g_t param_t = param - lr_t * m_t / (np.sqrt(v_t) + epsilon) return param_t, m_t, v_t def adam_update_numpy_amsgrad(param, g_t, t, m, v, vhat, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-7): lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1)) m_t = beta1 * m + (1 - beta1) * g_t v_t = beta2 * v + (1 - beta2) * g_t * g_t vhat_t = np.maximum(vhat, v_t) param_t = param - lr_t * m_t / (np.sqrt(vhat_t) + epsilon) return param_t, m_t, v_t, vhat_t def adam_sparse_update_numpy_amsgrad(param, indices, g_t, t, m, v, vhat, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-7): m_t, v_t, vhat_t, param_t = (np.copy(m), np.copy(v), np.copy(vhat), np.copy(param)) lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1)) m_t_slice = beta1 * m[indices] + (1 - beta1) * g_t v_t_slice = beta2 * v[indices] + (1 - beta2) * g_t * g_t m_t[indices] = m_t_slice v_t[indices] = v_t_slice v_hat_t = np.maximum(vhat_t, v_t) v_hat_t_slice = v_hat_t[indices] param_t_slice = param[indices] - ( lr_t * (m_t_slice / (np.sqrt(v_hat_t_slice) + epsilon))) param_t[indices] = param_t_slice return param_t, m_t, v_t, vhat_t def get_beta_accumulators(opt, dtype): local_step = math_ops.cast(opt.iterations + 1, dtype) beta_1_t = math_ops.cast(opt._get_hyper("beta_1"), dtype) beta_1_power = math_ops.pow(beta_1_t, local_step) beta_2_t = math_ops.cast(opt._get_hyper("beta_2"), dtype) beta_2_power = math_ops.pow(beta_2_t, local_step) return (beta_1_power, beta_2_power) class AdamOptimizerTest(test.TestCase): @test_util.run_deprecated_v1 def testSparse(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.0, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.0, 0.01], dtype=dtype.as_numpy_dtype) var0 = resource_variable_ops.ResourceVariable(var0_np) var1 = resource_variable_ops.ResourceVariable(var1_np) grads0_np_indices = np.array([0, 2], dtype=np.int32) grads0 = ops.IndexedSlices( constant_op.constant(grads0_np[grads0_np_indices]), constant_op.constant(grads0_np_indices), constant_op.constant([3])) grads1_np_indices = np.array([0, 2], dtype=np.int32) grads1 = ops.IndexedSlices( constant_op.constant(grads1_np[grads1_np_indices]), constant_op.constant(grads1_np_indices), constant_op.constant([3])) opt = adam.Adam() update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 3.0, 4.0], self.evaluate(var1)) beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) # Run 3 steps of Adam for t in range(3): self.assertAllCloseAccordingToType(0.9**(t + 1), self.evaluate(beta_1_power)) self.assertAllCloseAccordingToType(0.999**(t + 1), self.evaluate(beta_2_power)) update.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) @test_util.run_deprecated_v1 def testSparseDevicePlacement(self): for index_dtype in [dtypes.int32, dtypes.int64]: with self.cached_session(force_gpu=test.is_gpu_available()): # If a GPU is available, tests that all optimizer ops can be placed on # it (i.e. they have GPU kernels). var = variables.Variable([[1.0], [2.0]]) indices = constant_op.constant([0, 1], dtype=index_dtype) g_sum = lambda: math_ops.reduce_sum(array_ops.gather(var, indices)) # pylint: disable=cell-var-from-loop optimizer = adam.Adam(3.0) minimize_op = optimizer.minimize(g_sum, var_list=[var]) variables.global_variables_initializer().run() minimize_op.run() @test_util.run_deprecated_v1 def testSparseRepeatedIndices(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): repeated_index_update_var = variables.Variable( [[1.0], [2.0]], dtype=dtype) aggregated_update_var = variables.Variable( [[1.0], [2.0]], dtype=dtype) grad_repeated_index = ops.IndexedSlices( constant_op.constant( [0.1, 0.1], shape=[2, 1], dtype=dtype), constant_op.constant([1, 1]), constant_op.constant([2, 1])) grad_aggregated = ops.IndexedSlices( constant_op.constant( [0.2], shape=[1, 1], dtype=dtype), constant_op.constant([1]), constant_op.constant([2, 1])) repeated_update = adam.Adam().apply_gradients( [(grad_repeated_index, repeated_index_update_var)]) aggregated_update = adam.Adam().apply_gradients( [(grad_aggregated, aggregated_update_var)]) variables.global_variables_initializer().run() self.assertAllClose(aggregated_update_var.eval(), self.evaluate(repeated_index_update_var)) for _ in range(3): repeated_update.run() aggregated_update.run() self.assertAllClose(aggregated_update_var.eval(), self.evaluate(repeated_index_update_var)) def doTestBasic(self, use_callable_params=False): for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]): with self.session(graph=ops.Graph()): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = resource_variable_ops.ResourceVariable( var0_np, name="var0_%d" % i) var1 = resource_variable_ops.ResourceVariable( var1_np, name="var1_%d" % i) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) learning_rate = lambda: 0.001 beta1 = lambda: 0.9 beta2 = lambda: 0.999 epsilon = lambda: 1e-8 if not use_callable_params: learning_rate = learning_rate() beta1 = beta1() beta2 = beta2() epsilon = epsilon() opt = adam.Adam(learning_rate=learning_rate) if not context.executing_eagerly(): update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(variables.global_variables_initializer()) # Run 3 steps of Adam for t in range(3): beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) self.assertAllCloseAccordingToType(0.9**(t + 1), self.evaluate(beta_1_power)) self.assertAllCloseAccordingToType(0.999**(t + 1), self.evaluate(beta_2_power)) if not context.executing_eagerly(): self.evaluate(update) else: opt.apply_gradients(zip([grads0, grads1], [var0, var1])) var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) @test_util.run_in_graph_and_eager_modes(reset_test=True) def testResourceBasic(self): self.doTestBasic() def testBasicCallableParams(self): with context.eager_mode(): self.doTestBasic(use_callable_params=True) @test_util.run_in_graph_and_eager_modes(reset_test=True) def testBasicWithAmsgrad(self): for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]): with self.session(graph=ops.Graph()): # Initialize variables for numpy implementation. m0, v0, v0hat, m1, v1, v1hat = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = resource_variable_ops.ResourceVariable( var0_np, name="var0_%d" % i) var1 = resource_variable_ops.ResourceVariable( var1_np, name="var1_%d" % i) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = adam.Adam(amsgrad=True) if not context.executing_eagerly(): update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(variables.global_variables_initializer()) # Run 3 steps of Adam for t in range(3): beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) self.assertAllCloseAccordingToType(0.9**(t + 1), self.evaluate(beta_1_power)) self.assertAllCloseAccordingToType(0.999**(t + 1), self.evaluate(beta_2_power)) if not context.executing_eagerly(): self.evaluate(update) else: opt.apply_gradients(zip([grads0, grads1], [var0, var1])) var0_np, m0, v0, v0hat = adam_update_numpy_amsgrad( var0_np, grads0_np, t, m0, v0, v0hat) var1_np, m1, v1, v1hat = adam_update_numpy_amsgrad( var1_np, grads1_np, t, m1, v1, v1hat) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) @test_util.run_in_graph_and_eager_modes def testSparseWithAmsgrad(self): # dtypes.half does not work on gpu + eager. for dtype in [dtypes.float32, dtypes.float64]: with self.cached_session(): m0 = np.array([[0.0], [0.0]]) v0 = np.array([[0.0], [0.0]]) v0hat = np.array([[0.0], [0.0]]) indices_np = np.array([1]) indices = constant_op.constant(indices_np, dtype=dtypes.int32) var0_np = np.array([[1.0], [2.0]], dtype=dtype.as_numpy_dtype) repeated_index_update_var = variables.Variable(var0_np, dtype=dtype) aggregated_update_var = variables.Variable(var0_np, dtype=dtype) grads0_np = np.array([[0.2]], dtype=dtype.as_numpy_dtype) grad_repeated_index = ops.IndexedSlices( constant_op.constant([0.1, 0.1], shape=[2, 1], dtype=dtype), constant_op.constant([1, 1]), constant_op.constant([2, 1])) grad_aggregated = ops.IndexedSlices(grads0_np, indices, constant_op.constant([2, 1])) opt_repeated = adam.Adam(amsgrad=True) opt_aggregated = adam.Adam(amsgrad=True) if not context.executing_eagerly(): repeated_update = opt_repeated.apply_gradients( [(grad_repeated_index, repeated_index_update_var)]) aggregated_update = opt_aggregated.apply_gradients( [(grad_aggregated, aggregated_update_var)]) self.evaluate(variables.global_variables_initializer()) self.assertAllClose( self.evaluate(aggregated_update_var), self.evaluate(repeated_index_update_var)) for t in range(3): if not context.executing_eagerly(): self.evaluate(repeated_update) self.evaluate(aggregated_update) else: opt_repeated.apply_gradients( [(grad_repeated_index, repeated_index_update_var)]) opt_aggregated.apply_gradients( [(grad_aggregated, aggregated_update_var)]) var0_np, m0, v0, v0hat = adam_sparse_update_numpy_amsgrad( var0_np, indices_np, grads0_np, t, m0, v0, v0hat) # Validate updated params self.assertAllCloseAccordingToType( var0_np, self.evaluate(aggregated_update_var)) self.assertAllCloseAccordingToType( self.evaluate(aggregated_update_var), self.evaluate(repeated_index_update_var)) @test_util.run_deprecated_v1 def testBasicWithLearningRateDecay(self): for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]): with self.session(graph=ops.Graph()): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = resource_variable_ops.ResourceVariable( var0_np, name="var0_%d" % i) var1 = resource_variable_ops.ResourceVariable( var1_np, name="var1_%d" % i) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) learning_rate = 0.001 beta_1 = 0.9 beta_2 = 0.999 epsilon = 1e-7 decay = 0.5 opt = adam.Adam( learning_rate=learning_rate, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, decay=decay) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) self.evaluate(variables.global_variables_initializer()) # Run 3 steps of Adam for t in range(3): self.evaluate(update) lr_np = learning_rate / (1 + decay * t) var0_np, m0, v0 = adam_update_numpy( var0_np, grads0_np, t, m0, v0, lr=lr_np) var1_np, m1, v1 = adam_update_numpy( var1_np, grads1_np, t, m1, v1, lr=lr_np) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) @test_util.run_deprecated_v1 def testTensorLearningRate(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = adam.Adam(constant_op.constant(0.001)) update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) # Run 3 steps of Adam for t in range(3): self.assertAllCloseAccordingToType(0.9**(t + 1), self.evaluate(beta_1_power)) self.assertAllCloseAccordingToType(0.999**(t + 1), self.evaluate(beta_2_power)) update.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) @test_util.run_deprecated_v1 def testSharing(self): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype) grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype) var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype) grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype) var0 = variables.Variable(var0_np) var1 = variables.Variable(var1_np) grads0 = constant_op.constant(grads0_np) grads1 = constant_op.constant(grads1_np) opt = adam.Adam() update1 = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) update2 = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) variables.global_variables_initializer().run() beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype) # Fetch params to validate initial values self.assertAllClose([1.0, 2.0], self.evaluate(var0)) self.assertAllClose([3.0, 4.0], self.evaluate(var1)) # Run 3 steps of intertwined Adam1 and Adam2. for t in range(3): self.assertAllCloseAccordingToType(0.9**(t + 1), self.evaluate(beta_1_power)) self.assertAllCloseAccordingToType(0.999**(t + 1), self.evaluate(beta_2_power)) if t % 2 == 0: update1.run() else: update2.run() var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) # Validate updated params self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) def testSlotsUniqueEager(self): with context.eager_mode(): v1 = resource_variable_ops.ResourceVariable(1.) v2 = resource_variable_ops.ResourceVariable(1.) opt = adam.Adam(1.) opt.minimize(lambda: v1 + v2, var_list=[v1, v2]) # There should be iteration, and two unique slot variables for v1 and v2. self.assertEqual(5, len(set(opt.variables()))) self.assertEqual( self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations)) def testSetWeightsFromV1AdamWithoutMinimize(self): keras_v1_adam = optimizers.Adam() keras_v2_adam = adam.Adam() keras_v2_adam.set_weights(keras_v1_adam.get_weights()) keras_v1_iteration = keras_v1_adam.iterations keras_v2_iteration = keras_v2_adam.iterations self.evaluate(variables.global_variables_initializer()) self.assertEqual( self.evaluate(keras_v1_iteration), self.evaluate(keras_v2_iteration)) def testConstructAdamWithLR(self): opt = adam.Adam(lr=1.0) opt_2 = adam.Adam(learning_rate=0.1, lr=1.0) opt_3 = adam.Adam(learning_rate=0.1) self.assertIsInstance(opt.lr, variables.Variable) self.assertIsInstance(opt_2.lr, variables.Variable) self.assertIsInstance(opt_3.lr, variables.Variable) self.evaluate(variables.global_variables_initializer()) self.assertAllClose(self.evaluate(opt.lr), (1.0)) self.assertAllClose(self.evaluate(opt_2.lr), (1.0)) self.assertAllClose(self.evaluate(opt_3.lr), (0.1)) def testConstructAdamWithEpsilonValues(self): opt = adam.Adam(epsilon=None) config = opt.get_config() self.assertEqual(config["epsilon"], 1e-7) opt = adam.Adam(epsilon=1e-8) config = opt.get_config() self.assertEqual(config["epsilon"], 1e-8) if __name__ == "__main__": test.main()
43.27307
113
0.618766
[ "Apache-2.0" ]
5seunghoon/tensorflow
tensorflow/python/keras/optimizer_v2/adam_test.py
22,978
Python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ContainerGroupsOperations: """ContainerGroupsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.containerinstance.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs: Any ) -> AsyncIterable["_models.ContainerGroupListResult"]: """Get a list of container groups in the specified subscription. Get a list of container groups in the specified subscription. This operation returns properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ContainerGroupListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ContainerGroupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ContainerGroupListResult"]: """Get a list of container groups in the specified subscription and resource group. Get a list of container groups in a specified subscription and resource group. This operation returns properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ContainerGroupListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.containerinstance.models.ContainerGroupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ContainerGroupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups'} # type: ignore async def get( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> "_models.ContainerGroup": """Get the properties of the specified container group. Gets the properties of the specified container group in the specified subscription and resource group. The operation returns the properties of each container group including containers, image registry credentials, restart policy, IP address type, OS type, state, and volumes. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ContainerGroup, or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, container_group_name: str, container_group: "_models.ContainerGroup", **kwargs: Any ) -> "_models.ContainerGroup": cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(container_group, 'ContainerGroup') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ContainerGroup', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, container_group_name: str, container_group: "_models.ContainerGroup", **kwargs: Any ) -> AsyncLROPoller["_models.ContainerGroup"]: """Create or update container groups. Create or update container groups with specified configurations. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :param container_group: The properties of the container group to be created or updated. :type container_group: ~azure.mgmt.containerinstance.models.ContainerGroup :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, container_group_name=container_group_name, container_group=container_group, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def update( self, resource_group_name: str, container_group_name: str, resource: "_models.Resource", **kwargs: Any ) -> "_models.ContainerGroup": """Update container groups. Updates container group tags with specified values. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :param resource: The container group resource with just the tags to be updated. :type resource: ~azure.mgmt.containerinstance.models.Resource :keyword callable cls: A custom type or function that will be passed the direct response :return: ContainerGroup, or the result of cls(response) :rtype: ~azure.mgmt.containerinstance.models.ContainerGroup :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(resource, 'Resource') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> Optional["_models.ContainerGroup"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ContainerGroup"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def begin_delete( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> AsyncLROPoller["_models.ContainerGroup"]: """Delete the specified container group. Delete the specified container group in the specified subscription and resource group. The operation does not delete other resources provided by the user, such as volumes. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ContainerGroup or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.containerinstance.models.ContainerGroup] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ContainerGroup"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, container_group_name=container_group_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ContainerGroup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}'} # type: ignore async def _restart_initial( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" # Construct URL url = self._restart_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _restart_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore async def begin_restart( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Restarts all containers in a container group. Restarts all containers in a container group in place. If container image has updates, new image will be downloaded. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._restart_initial( resource_group_name=resource_group_name, container_group_name=container_group_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_restart.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/restart'} # type: ignore async def stop( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: """Stops all containers in a container group. Stops all containers in a container group. Compute resources will be deallocated and billing will stop. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" # Construct URL url = self.stop.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) stop.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/stop'} # type: ignore async def _start_initial( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" accept = "application/json" # Construct URL url = self._start_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _start_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore async def begin_start( self, resource_group_name: str, container_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Starts all containers in a container group. Starts all containers in a container group. Compute resources will be allocated and billing will start. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param container_group_name: The name of the container group. :type container_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._start_initial( resource_group_name=resource_group_name, container_group_name=container_group_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'containerGroupName': self._serialize.url("container_group_name", container_group_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_start.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerInstance/containerGroups/{containerGroupName}/start'} # type: ignore
50.033019
209
0.674484
[ "MIT" ]
Codejune/azure-sdk-for-python
sdk/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py
42,428
Python
from workerInfra.enum import SchedulerTriggerEnum, EnvEnum from workerInfra.domain import LoggerInterface from workerInfra.models import SchedulerJobModel from workerService.envReaderService import EnvReaderService from workerService.scheduler import SchedulerService from workerService.logger import BasicLoggerService from workerService.outputs import DiscordOutputService from workerService.sources import ( WorkerService, RedditWorkerService, YoutubeWorkerService, TwitterWorkerService, TwitchWorkerService, PokemonGoWorkerService, FFXIVWorkerService ) from workerService.sources.rssWorkerService import RssWorkerService class ApiEventsService(): _env: EnvReaderService _logger: LoggerInterface _scheduler: SchedulerService _isDebug: bool def __init__(self) -> None: self._env = EnvReaderService() self._logger = BasicLoggerService() self._scheduler = SchedulerService() self._isDebug = self._env.getValue(EnvEnum.ISDEBUG) pass def startup(self) -> None: self._scheduler.addJob(self.enableSourceReddit()) self._scheduler.addJob(self.enableSourceYoutube()) self._scheduler.addJob(self.enableSourceTwitter()) self._scheduler.addJob(self.enableSourceTwitch()) self._scheduler.addJob(self.enableSourcePokemonGo()) self._scheduler.addJob(self.enableSourceFFXIV()) self._scheduler.addJob(self.enableSourceRss()) self._scheduler.addJob(self.enableOutputDiscord()) self._scheduler.start() def enableSourceRss(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(RssWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=30) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.RSSENABLED) is False: s.enabled = False return s def enableSourceReddit(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(RedditWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=25) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.REDDITENABLED) is False: s.enabled = False return s def enableSourceYoutube(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(YoutubeWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=35) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.YOUTUBEENABLED) is False: s.enabled = False return s def enableSourceTwitter(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(TwitterWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=37) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.TWITCHEANBLED) is False: s.enabled = False return s def enableSourceTwitch(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(TwitchWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=30) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.TWITCHEANBLED) is False: s.enabled = False return s def enableSourcePokemonGo(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(PokemonGoWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=35) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.POKEMONGOENABLED) is False: s.enabled = False return s def enableSourceFFXIV(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=WorkerService(FFXIVWorkerService()).init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=45) if self._isDebug is True: s.trigger = SchedulerTriggerEnum.NONE if self._env.getValue(EnvEnum.FFXIVENABLED) is False: s.enabled = False return s def enableOutputDiscord(self) -> SchedulerJobModel: s = SchedulerJobModel(functionName=DiscordOutputService().init, trigger=SchedulerTriggerEnum.INTERVAL, minutes=3) if self._isDebug is True: s.minutes = 1 return s def shutdown(self) -> None: pass
41.527273
139
0.71563
[ "MIT" ]
jtom38/newsbot.worker
workerApi/apiEventsService.py
4,568
Python
class Debt: def __init__(self, id_nbr, principal, rate, minimum, frequency=12): self.id = id_nbr self.principal = principal self.rate = rate self.minimum = minimum self.frequency = frequency def calculate_compound(self, periods): new_principal = self.principal * (1 + self.rate / self.frequency) ** periods return new_principal def list_compounds(self, periods): balance_list = [] for period in range(periods + 1): balance_list.append(self.calculate_compound(period)) return balance_list def calculate_next_principal(self, current_principal, current_payment = 0): next_principal = current_principal * (1 + self.rate / self.frequency) - current_payment return next_principal def list_minimum_payments(self, current_principal, periods, minimum): balance_list = [float(current_principal)] next_period_principal = current_principal for period in range(periods): next_period_principal = self.calculate_next_principal(current_principal, minimum) if next_period_principal < 0.0: balance_list.append(0.0) break balance_list.append(next_period_principal) current_principal = next_period_principal return balance_list
37.611111
95
0.66839
[ "MIT" ]
Luigi-PastorePica/FreeD
src/freed/debt_class.py
1,354
Python
from typing import Union import Geometry from Geometry import Line from Geometry import Point import cmath class Circle: def __init__(self, center: Union[Point, tuple, list], radius: float): if isinstance(center, tuple) or isinstance(center, list): assert len(center) == 2, "Center must be a 2-tuple or list" center = Point(center[0], center[1]) self.center = center self.radius = radius def area(self) -> float: return cmath.pi * self.radius ** 2 def circumference(self) -> float: return 2 * cmath.pi * self.radius def tangent(self, p: Point) -> Line: # try: # m = Geometry.slope(self.center, p) # except ZeroDivisionError: # return Line(0, 1, -p.y) # if m == 0: # return Line(1, 0, -p.x) # m = -1/m # return Geometry.slope_point_line(m, p) x, y = p.x, p.y c_x , c_y = -self.center.x, -self.center.y return Line(x + c_x, y + c_y, x*c_x + y*c_y + c_x**2 + c_y**2 - self.radius**2) def normal(self, p: Point) -> Line: return Line.construct(p, self.center) def power(self, p: Point) -> float: return Geometry.distance(self.center, p) ** 2 - self.radius ** 2 def is_tangent(self, l: Line) -> bool: return l.distance(self.center) == self.radius def is_normal(self, l: Line) -> bool: return l(self.center) == 0 def equation(self) -> str: (x, y) = self.center return f"x^2 + 2*{-x}*x + 2*{-y}*y + y^2 + {x**2 + y**2 - self.radius**2} = 0" def parametric_equation(self, theta_resolution: float = 0.01, semi=False): i = 0 if semi: k = cmath.pi else: k = 2 * cmath.pi while i < k: yield self.center.x + self.radius * cmath.cos(i), self.center.y + self.radius * cmath.sin(i) i += theta_resolution def sector_length(self, theta: float) -> float: """Returns the length of a sector of the circle which subtended angle theta(radians) at center.""" return self.radius * theta def sector_area(self, theta: float) -> float: """Returns the area of a sector of the circle which subtended angle theta(radians) at center.""" return self.radius ** 2 * theta / 2 def intersetion(self, other) -> Union[Point, None]: if isinstance(other, Circle): c1 = self.center c2 = other.center m = Geometry.slope(c1, c2) theta = cmath.atan(m) d = Geometry.distance(c1, c2) if d == self.radius + other.radius: """Two circles are touching each other""" x = c1.x + self.radius * cmath.cos(theta) y = c1.y + self.radius * cmath.sin(theta) return Point(x, y) elif d < self.radius + other.radius: """Two circles intersect""" r1 = self.radius r2 = other.radius theta = cmath.asin(r2 / d) x = c1.x + r1 * cmath.cos(theta) y = c1.y + r1 * cmath.sin(theta) p1 = Point(x, y) l = Line.construct(c1, c2) p2 = l.image(p1) return (p1, p2) else: return None else: raise ValueError("Can only intersect with another circle") def __repr__(self): return 'Circle(center={0}, radius={1})'.format(self.center, self.radius) def __eq__(self, other): if isinstance(other, Circle): return self.center == other.center and self.radius == other.radius else: return False def __ne__(self, other): return not self == other def __hash__(self): return hash((self.center, self.radius)) def __str__(self): return 'Circle(center={0}, radius={1})'.format(self.center, self.radius) def construct(p0: Point, p1: Point, p2: Point) -> Circle: try: assert not Geometry.colinear(p0, p1, p2) except AssertionError: raise AssertionError("Circle can not be constructed from three points that are colinear") l1 = Geometry.perpendicular_bisector(p0, p1) l2 = Geometry.perpendicular_bisector(p1, p2) center = l1.intersection(l2) radius = Geometry.distance(center, p0) return Circle(center, radius)
31.28169
106
0.55493
[ "MIT" ]
Lakshmikanth2001/ElectricPy
Geometry/circle.py
4,442
Python
from collections import OrderedDict from PyQt5 import QtCore from PyQt5 import QtWidgets from easygraphics.dialog._indexed_order_list import IndexedOrderedDict __all__ = ['MultipleFieldsDialog'] class MultipleFieldsDialog(QtWidgets.QDialog): """Dialog with multiple fields stored in a dict, with the label being the key and the entry being the corresponding value""" def __init__(self, labels=None, title="Demo", masks=None): super(MultipleFieldsDialog, self).__init__(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.enters = IndexedOrderedDict() self.setWindowTitle(title) # set up a special case for quick demo if labels is None: labels = ["Regular field", "Masked field"] masks = [False, True] self.setWindowTitle("MultipleFieldsDialog demo") if masks is not None: assert len(masks) == len(labels) layout = QtWidgets.QGridLayout() layout.setColumnStretch(1, 1) layout.setColumnMinimumWidth(1, 250) self._labels_ = [] self.fields = [] for index, choice in enumerate(labels): self._labels_.append(QtWidgets.QLabel()) self._labels_[index].setText(choice) self.fields.append(QtWidgets.QLineEdit()) self.fields[index].setText('') self.enters[choice] = '' if masks is not None and masks[index]: self.fields[index].setEchoMode(QtWidgets.QLineEdit.Password) layout.addWidget(self._labels_[index], index, 0) layout.addWidget(self.fields[index], index, 1) button_box = QtWidgets.QDialogButtonBox() confirm_button = button_box.addButton(QtWidgets.QDialogButtonBox.Ok) layout.addWidget(button_box, index + 1, 1) confirm_button.clicked.connect(self.confirm) self.setLayout(layout) self.setWindowTitle(title) self.show() self.raise_() def confirm(self): """Selection completed, set the value and close""" o_dict = self.enters for index, item in enumerate(self._labels_): o_dict[item.text()] = self.fields[index].text() self.close() if __name__ == '__main__': app = QtWidgets.QApplication([]) dialog = MultipleFieldsDialog() dialog.exec_() print(dialog.get_ordered_dict())
34.736111
83
0.62375
[ "BSD-3-Clause" ]
royqh1979/PyEasyGraphics
easygraphics/dialog/multifields.py
2,501
Python
from musicautobot.numpy_encode import * from musicautobot.config import * from musicautobot.music_transformer import * from musicautobot.utils.midifile import * from musicautobot.utils.file_processing import process_all from musicautobot.numpy_encode import * from musicautobot.config import * from musicautobot.music_transformer import * from musicautobot.utils.midifile import * from musicautobot.utils.file_processing import process_all import random def create_databunch(files, data_save_name, path): save_file = path/data_save_name if save_file.exists(): data = load_data(path, data_save_name) else: save_file.parent.mkdir(exist_ok=True, parents=True) vocab = MusicVocab.create() processors = [OpenNPFileProcessor(), MusicItemProcessor()] data = MusicDataBunch.from_files(files, path, processors=processors, encode_position=True) data.save(data_save_name) return data def timeout_func(data, seconds): print("Timeout:", seconds) def process_metadata(midi_file): # Get outfile and check if it exists out_file = numpy_path/midi_file.relative_to(midi_path).with_suffix('.npy') out_file.parent.mkdir(parents=True, exist_ok=True) if out_file.exists(): return npenc = transform_midi(midi_file) if npenc is not None: np.save(out_file, npenc) def transform_midi(midi_file): input_path = midi_file # Part 1: Filter out midi tracks (drums, repetitive instruments, etc.) try: # if duet_only and num_piano_tracks(input_path) not in [1, 2]: return None input_file = compress_midi_file(input_path, min_variation=min_variation, cutoff=cutoff) # remove non note tracks and standardize instruments if input_file is None: return None except Exception as e: if 'badly form' in str(e): return None # ignore badly formatted midi errors if 'out of range' in str(e): return None # ignore badly formatted midi errors print('Error parsing midi', input_path, e) return None # Part 2. Compress rests and long notes stream = file2stream(input_file) # 1. try: chordarr = stream2chordarr(stream) # 2. max_dur = quarter_len * sample_freq (4). 128 = 8 bars except Exception as e: print('Could not encode to chordarr:', input_path, e) print(traceback.format_exc()) return None # Part 3. Compress song rests - Don't want songs with really long pauses # (this happens because we filter out midi tracks). chord_trim = trim_chordarr_rests(chordarr) chord_short = shorten_chordarr_rests(chord_trim) delta_trim = chord_trim.shape[0] - chord_short.shape[0] # if delta_trim > 500: # print(f'Removed {delta_trim} rests from {input_path}. Skipping song') # return None chordarr = chord_short # Part 3. Chord array to numpy npenc = chordarr2npenc(chordarr) if not is_valid_npenc(npenc, input_path=input_path): return None return npenc # Location of your midi files midi_path = Path('data/midi/TPD') # Location of preprocessed numpy files numpy_path = Path('data/numpy/preprocessed data') # Location of models and cached dataset data_path = Path('data/cached') data_save_name = 'TPD_musicitem_data_save.pkl' # num_tracks = [1, 2] # number of tracks to support cutoff = 5 # max instruments min_variation = 3 # minimum number of different midi notes played # max_dur = 128 midi_files = get_files(midi_path, '.mid', recurse=True) print('Loading model...') batch_size = 1 encode_position = True dl_tfms = [batch_position_tfm] if encode_position else [] data = load_data(data_path, data_save_name, bs=batch_size, encode_position=encode_position, dl_tfms=dl_tfms) config = default_config() config['encode_position'] = encode_position learn = music_model_learner(data, config=config.copy()) learn.fit_one_cycle(4) learn.save('TPD_model')
36.055046
148
0.724173
[ "MIT" ]
adam1214/musicautobot
transformer code/train.py
3,930
Python
import logging from typing import Dict, List, Tuple import aiosqlite from btcgreen.server.address_manager import ( BUCKET_SIZE, NEW_BUCKET_COUNT, NEW_BUCKETS_PER_ADDRESS, AddressManager, ExtendedPeerInfo, ) log = logging.getLogger(__name__) class AddressManagerStore: """ Metadata table: - private key - new table count - tried table count Nodes table: * Maps entries from new/tried table to unique node ids. - node_id - IP, port, together with the IP, port of the source peer. New table: * Stores node_id, bucket for each occurrence in the new table of an entry. * Once we know the buckets, we can also deduce the bucket positions. Every other information, such as tried_matrix, map_addr, map_info, random_pos, be deduced and it is not explicitly stored, instead it is recalculated. """ db: aiosqlite.Connection @classmethod async def create(cls, connection) -> "AddressManagerStore": self = cls() self.db = connection await self.db.commit() await self.db.execute("CREATE TABLE IF NOT EXISTS peer_metadata(key text,value text)") await self.db.commit() await self.db.execute("CREATE TABLE IF NOT EXISTS peer_nodes(node_id int,value text)") await self.db.commit() await self.db.execute("CREATE TABLE IF NOT EXISTS peer_new_table(node_id int,bucket int)") await self.db.commit() return self async def clear(self) -> None: cursor = await self.db.execute("DELETE from peer_metadata") await cursor.close() cursor = await self.db.execute("DELETE from peer_nodes") await cursor.close() cursor = await self.db.execute("DELETE from peer_new_table") await cursor.close() await self.db.commit() async def get_metadata(self) -> Dict[str, str]: cursor = await self.db.execute("SELECT key, value from peer_metadata") metadata = await cursor.fetchall() await cursor.close() return {key: value for key, value in metadata} async def is_empty(self) -> bool: metadata = await self.get_metadata() if "key" not in metadata: return True if int(metadata.get("new_count", 0)) > 0: return False if int(metadata.get("tried_count", 0)) > 0: return False return True async def get_nodes(self) -> List[Tuple[int, ExtendedPeerInfo]]: cursor = await self.db.execute("SELECT node_id, value from peer_nodes") nodes_id = await cursor.fetchall() await cursor.close() return [(node_id, ExtendedPeerInfo.from_string(info_str)) for node_id, info_str in nodes_id] async def get_new_table(self) -> List[Tuple[int, int]]: cursor = await self.db.execute("SELECT node_id, bucket from peer_new_table") entries = await cursor.fetchall() await cursor.close() return [(node_id, bucket) for node_id, bucket in entries] async def set_metadata(self, metadata) -> None: for key, value in metadata: cursor = await self.db.execute( "INSERT OR REPLACE INTO peer_metadata VALUES(?, ?)", (key, value), ) await cursor.close() await self.db.commit() async def set_nodes(self, node_list) -> None: for node_id, peer_info in node_list: cursor = await self.db.execute( "INSERT OR REPLACE INTO peer_nodes VALUES(?, ?)", (node_id, peer_info.to_string()), ) await cursor.close() await self.db.commit() async def set_new_table(self, entries) -> None: for node_id, bucket in entries: cursor = await self.db.execute( "INSERT OR REPLACE INTO peer_new_table VALUES(?, ?)", (node_id, bucket), ) await cursor.close() await self.db.commit() async def serialize(self, address_manager: AddressManager): metadata = [] nodes = [] new_table_entries = [] metadata.append(("key", str(address_manager.key))) unique_ids = {} count_ids = 0 for node_id, info in address_manager.map_info.items(): unique_ids[node_id] = count_ids if info.ref_count > 0: assert count_ids != address_manager.new_count nodes.append((count_ids, info)) count_ids += 1 metadata.append(("new_count", str(count_ids))) tried_ids = 0 for node_id, info in address_manager.map_info.items(): if info.is_tried: assert info is not None assert tried_ids != address_manager.tried_count nodes.append((count_ids, info)) count_ids += 1 tried_ids += 1 metadata.append(("tried_count", str(tried_ids))) for bucket in range(NEW_BUCKET_COUNT): for i in range(BUCKET_SIZE): if address_manager.new_matrix[bucket][i] != -1: index = unique_ids[address_manager.new_matrix[bucket][i]] new_table_entries.append((index, bucket)) await self.clear() await self.set_metadata(metadata) await self.set_nodes(nodes) await self.set_new_table(new_table_entries) async def deserialize(self) -> AddressManager: address_manager = AddressManager() metadata = await self.get_metadata() nodes = await self.get_nodes() new_table_entries = await self.get_new_table() address_manager.clear() address_manager.key = int(metadata["key"]) address_manager.new_count = int(metadata["new_count"]) # address_manager.tried_count = int(metadata["tried_count"]) address_manager.tried_count = 0 new_table_nodes = [(node_id, info) for node_id, info in nodes if node_id < address_manager.new_count] for n, info in new_table_nodes: address_manager.map_addr[info.peer_info.host] = n address_manager.map_info[n] = info info.random_pos = len(address_manager.random_pos) address_manager.random_pos.append(n) address_manager.id_count = len(new_table_nodes) tried_table_nodes = [(node_id, info) for node_id, info in nodes if node_id >= address_manager.new_count] # lost_count = 0 for node_id, info in tried_table_nodes: tried_bucket = info.get_tried_bucket(address_manager.key) tried_bucket_pos = info.get_bucket_position(address_manager.key, False, tried_bucket) if address_manager.tried_matrix[tried_bucket][tried_bucket_pos] == -1: info.random_pos = len(address_manager.random_pos) info.is_tried = True id_count = address_manager.id_count address_manager.random_pos.append(id_count) address_manager.map_info[id_count] = info address_manager.map_addr[info.peer_info.host] = id_count address_manager.tried_matrix[tried_bucket][tried_bucket_pos] = id_count address_manager.id_count += 1 address_manager.tried_count += 1 # else: # lost_count += 1 # address_manager.tried_count -= lost_count for node_id, bucket in new_table_entries: if node_id >= 0 and node_id < address_manager.new_count: info = address_manager.map_info[node_id] bucket_pos = info.get_bucket_position(address_manager.key, True, bucket) if address_manager.new_matrix[bucket][bucket_pos] == -1 and info.ref_count < NEW_BUCKETS_PER_ADDRESS: info.ref_count += 1 address_manager.new_matrix[bucket][bucket_pos] = node_id for node_id, info in list(address_manager.map_info.items()): if not info.is_tried and info.ref_count == 0: address_manager.delete_new_entry_(node_id) address_manager.load_used_table_positions() return address_manager
39.941176
117
0.627516
[ "Apache-2.0" ]
BTCgreen-Network/btcgreen-blockchain
btcgreen/server/address_manager_store.py
8,148
Python
# Generated by Django 3.0.5 on 2020-05-13 09:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('project_core', '0118_calls_need_to_be_part_of_a_funding_instrument'), ('grant_management', '0041_allows_media_to_not_be_related_blog_post'), ] operations = [ migrations.CreateModel( name='ProjectSocialNetwork', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_on', models.DateTimeField(auto_now_add=True, help_text='Date and time at which the entry was created')), ('modified_on', models.DateTimeField(auto_now=True, help_text='Date and time at which the entry was modified', null=True)), ('url', models.URLField(blank=True, help_text='Address of social media entry (e.g. https://twitter.com/SwissPolar)', null=True)), ('project', models.ForeignKey(help_text='Choose related project', on_delete=django.db.models.deletion.PROTECT, to='project_core.Project')), ], options={ 'abstract': False, }, ), migrations.RenameField( model_name='dataset', old_name='date_published', new_name='published_date', ), migrations.RemoveField( model_name='publication', name='date_time_published', ), migrations.AddField( model_name='publication', name='published_date', field=models.DateField(blank=True, help_text='Date of the publication', null=True), ), migrations.AlterField( model_name='dataset', name='doi', field=models.CharField(blank=True, help_text='DOI reference for entry', max_length=100, null=True), ), migrations.AlterField( model_name='dataset', name='title', field=models.CharField(help_text='Dataset title', max_length=1000), ), migrations.AlterField( model_name='publication', name='doi', field=models.CharField(blank=True, help_text='DOI reference for entry', max_length=100, null=True), ), migrations.AlterField( model_name='publication', name='reference', field=models.CharField(blank=True, help_text='Journal reference for entry', max_length=1000, null=True), ), migrations.AlterField( model_name='publication', name='title', field=models.CharField(help_text='Publication title', max_length=1000), ), migrations.AlterField( model_name='socialnetwork', name='name', field=models.CharField(help_text='Please enter social network title (e.g. Twitter, Facebook, Instagram, Blog)', max_length=100), ), migrations.DeleteModel( name='ProjectSocialMedia', ), migrations.AddField( model_name='projectsocialnetwork', name='social_network', field=models.ForeignKey(help_text='Choose the related social network', on_delete=django.db.models.deletion.PROTECT, to='grant_management.SocialNetwork'), ), ]
41.814815
165
0.61116
[ "MIT" ]
Swiss-Polar-Institute/project-application
ProjectApplication/grant_management/migrations/0042_improves_project_data_publications_social_media_types.py
3,387
Python
import contextlib import os.path import subprocess import pytest from pre_commit import parse_shebang from pre_commit.util import CalledProcessError from pre_commit.util import cmd_output from pre_commit.util import cmd_output_b from testing.auto_namedtuple import auto_namedtuple TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) def docker_is_running() -> bool: # pragma: win32 no cover try: cmd_output_b('docker', 'ps') except CalledProcessError: # pragma: no cover return False else: return True def get_resource_path(path): return os.path.join(TESTING_DIR, 'resources', path) def cmd_output_mocked_pre_commit_home( *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs, ): if pre_commit_home is None: pre_commit_home = tempdir_factory.get() env = env if env is not None else os.environ kwargs.setdefault('stderr', subprocess.STDOUT) # Don't want to write to the home directory env = dict(env, PRE_COMMIT_HOME=pre_commit_home) ret, out, _ = cmd_output(*args, env=env, **kwargs) return ret, out.replace('\r\n', '\n'), None skipif_cant_run_coursier = pytest.mark.skipif( os.name == 'nt' or parse_shebang.find_executable('cs') is None, reason="coursier isn't installed or can't be found", ) skipif_cant_run_docker = pytest.mark.skipif( os.name == 'nt' or not docker_is_running(), reason="Docker isn't running or can't be accessed", ) skipif_cant_run_swift = pytest.mark.skipif( parse_shebang.find_executable('swift') is None, reason="swift isn't installed or can't be found", ) xfailif_windows = pytest.mark.xfail(os.name == 'nt', reason='windows') def run_opts( all_files=False, files=(), color=False, verbose=False, hook=None, remote_branch='', local_branch='', from_ref='', to_ref='', remote_name='', remote_url='', hook_stage='commit', show_diff_on_failure=False, commit_msg_filename='', checkout_type='', is_squash_merge='', rewrite_command='', ): # These are mutually exclusive assert not (all_files and files) return auto_namedtuple( all_files=all_files, files=files, color=color, verbose=verbose, hook=hook, remote_branch=remote_branch, local_branch=local_branch, from_ref=from_ref, to_ref=to_ref, remote_name=remote_name, remote_url=remote_url, hook_stage=hook_stage, show_diff_on_failure=show_diff_on_failure, commit_msg_filename=commit_msg_filename, checkout_type=checkout_type, is_squash_merge=is_squash_merge, rewrite_command=rewrite_command, ) @contextlib.contextmanager def cwd(path): original_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(original_cwd) def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs): kwargs.setdefault('stderr', subprocess.STDOUT) cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args) if all_files: # allow skipping `-a` with `all_files=False` cmd += ('-a',) if msg is not None: # allow skipping `-m` with `msg=None` cmd += ('-m', msg) ret, out, _ = fn(*cmd, **kwargs) return ret, out.replace('\r\n', '\n')
28.4
78
0.659624
[ "MIT" ]
DjKuj/reformat
testing/util.py
3,408
Python
"""Database exceptions.""" class BaseError(Exception): """The base exception.""" class NotFoundError(BaseError): """When an item was not found in the database."""
17.5
53
0.674286
[ "Apache-2.0" ]
jdkandersson/OpenAlchemyPackage
database/open_alchemy/package_database/exceptions.py
175
Python
from spytest import st def init(dut): st.create_init_config_db(dut) def extend(dut): st.log("Extend base config if needed", dut=dut) st.config(dut, "config feature state nat enabled") st.config(dut, "config feature state sflow enabled")
23.272727
56
0.710938
[ "Apache-2.0" ]
akokhan/sonic-mgmt
spytest/apis/common/base_config.py
256
Python
import sys import os import re import importlib import warnings is_pypy = '__pypy__' in sys.builtin_module_names warnings.filterwarnings('ignore', r'.+ distutils\b.+ deprecated', DeprecationWarning) def warn_distutils_present(): if 'distutils' not in sys.modules: return if is_pypy and sys.version_info < (3, 7): # PyPy for 3.6 unconditionally imports distutils, so bypass the warning # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250 return warnings.warn( "Distutils was imported before Setuptools, but importing Setuptools " "also replaces the `distutils` module in `sys.modules`. This may lead " "to undesirable behaviors or errors. To avoid these issues, avoid " "using distutils directly, ensure that setuptools is installed in the " "traditional way (e.g. not an editable install), and/or make sure " "that setuptools is always imported before distutils.") def clear_distutils(): if 'distutils' not in sys.modules: return warnings.warn("Setuptools is replacing distutils.") mods = [name for name in sys.modules if re.match(r'distutils\b', name)] for name in mods: del sys.modules[name] def enabled(): """ Allow selection of distutils by environment variable. """ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') return which == 'local' def ensure_local_distutils(): clear_distutils() distutils = importlib.import_module('setuptools._distutils') distutils.__name__ = 'distutils' sys.modules['distutils'] = distutils # sanity check that submodules load as expected core = importlib.import_module('distutils.core') assert '_distutils' in core.__file__, core.__file__ def do_override(): """ Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ if enabled(): warn_distutils_present() ensure_local_distutils() class DistutilsMetaFinder: def find_spec(self, fullname, path, target=None): if path is not None: return method_name = 'spec_for_{fullname}'.format(**locals()) method = getattr(self, method_name, lambda: None) return method() def spec_for_distutils(self): import importlib.abc import importlib.util class DistutilsLoader(importlib.abc.Loader): def create_module(self, spec): return importlib.import_module('setuptools._distutils') def exec_module(self, module): pass return importlib.util.spec_from_loader('distutils', DistutilsLoader()) def spec_for_pip(self): """ Ensure stdlib distutils when running under pip. See pypa/pip#8761 for rationale. """ if self.pip_imported_during_build(): return clear_distutils() self.spec_for_distutils = lambda: None @staticmethod def pip_imported_during_build(): """ Detect if pip is being imported in a build script. Ref #2355. """ import traceback return any( frame.f_globals['__file__'].endswith('setup.py') for frame, line in traceback.walk_stack(None) ) DISTUTILS_FINDER = DistutilsMetaFinder() def add_shim(): sys.meta_path.insert(0, DISTUTILS_FINDER) def remove_shim(): try: sys.meta_path.remove(DISTUTILS_FINDER) except ValueError: pass
29.581395
120
0.635482
[ "MIT" ]
JE-Chen/je_old_repo
DatabaseControlWrapper_JE/venv/Lib/site-packages/_distutils_hack/__init__.py
3,816
Python
## Start of header boilerplate ################################################# from aocbase import readInput import re import collections def lineParse(s, f, fp): m = fp.match(s) if m==None: raise s return tuple(map(f, m.groups())) def fileParse(inp): return list(inp.splitlines()) ## End of header boilerplate ################################################### def mapMaze(s): mz = dict() for y,line in enumerate(s): for x, c in enumerate(line): if c != ' ': mz[x,y] = c return mz def findTeleporters(mz): loc = dict() for (x, y), value in mz.items(): if isinstance(value, str) and value.isupper(): for dx, dy in ((0,1),(1,0),(-1,0),(0,-1)): nxtChar = mz.get((x+dx, y+dy), '') if isinstance(nxtChar, tuple): continue prevChar = mz.get((x-dx, y-dy), '') if (nxtChar.isupper() and prevChar == '.'): name = (mz[min(x, x+dx),min(y, y+dy)] + mz[max(x+dx, x), max(y+dy, y)]) if name not in loc: loc[name] = list() loc[name].append(((x, y), (x-dx, y-dy))) for l in loc.values(): if len(l) != 2: continue mz[l[0][0]] = l[1][1] mz[l[1][0]] = l[0][1] return loc['AA'][0][0], loc['ZZ'][0][0] def findTeleportersD(mz): start, stop = findTeleporters(mz) minx = min((c[0] for c in mz.keys())) maxx = max((c[0] for c in mz.keys())) miny = min((c[1] for c in mz.keys())) maxy = max((c[1] for c in mz.keys())) portalLocations = [key for key in mz.keys() if isinstance(mz[key], tuple)] for x, y in portalLocations: mz[x, y] = mz[x, y] + (abs(x - minx) < 2 or abs(x - maxx) < 2 or abs(y - miny) < 2 or abs(y - maxy) < 2,) return start, stop def colorMap(mz, start, stop): d = collections.deque() d.append(start) v = dict() v[start] = 0 while len(d)>0: cur = d.popleft() x, y = cur for dx, dy in ((0,1),(1,0),(-1,0),(0,-1)): nx, ny = x+dx, y+dy if (nx, ny) == stop: return v[x,y] -1 if (nx, ny) not in mz: continue if isinstance(mz[nx, ny], tuple): nx, ny = mz[nx, ny] if mz[nx, ny] != '.': continue if (nx, ny) in v and v[x, y] + 1 >= v[nx, ny]: continue v[nx, ny] = v[x, y]+1 d.append((nx, ny)) def colorMapD(mz, start, stop): maxLevel = len([t for t in mz.values() if isinstance(t, tuple)])//2 d = collections.deque() d.append(start+(0, )) v = dict() v[start+(0, )] = 0 while len(d)>0: cur = d.popleft() x, y, lvl = cur for dx, dy in ((0,1),(1,0),(-1,0),(0,-1)): nx, ny, nlvl = x+dx, y+dy, lvl if (nx, ny) == stop and lvl == 0: return v[x,y,lvl] - 1 if (nx, ny) not in mz: continue if isinstance(mz[nx, ny], tuple): nx, ny, outer = mz[nx, ny] if outer: if lvl == 0: continue nlvl -= 1 else: if lvl == maxLevel: continue nlvl += 1 if mz[nx, ny] != '.': continue if (nx, ny, nlvl) in v and v[x, y, lvl] + 1 >= v[nx, ny, nlvl]: continue v[nx, ny, nlvl] = v[x, y, lvl]+1 d.append((nx, ny, nlvl)) def part1(pinp): mz = mapMaze(pinp) start, stop = findTeleporters(mz) return colorMap(mz, start, stop) def part2(pinp): mz = mapMaze(pinp) start, stop = findTeleportersD(mz) return colorMapD(mz, start, stop) ## Start of footer boilerplate ################################################# if __name__ == "__main__": inp = readInput() ## Update for input specifics ############################################## parseInp = fileParse(inp) print("Input is '" + str(parseInp[:10])[:100] + ('...' if len(parseInp)>10 or len(str(parseInp[:10]))>100 else '') + "'") print("Solution to part 1: {}".format(part1(parseInp))) print("Solution to part 2: {}".format(part2(parseInp))) ## End of footer boilerplate ###################################################
33.074074
113
0.439418
[ "Apache-2.0" ]
Dyr-El/advent_of_code_2019
Dyr-El-python/day20.py
4,465
Python
import inspect import warnings from abc import ABCMeta, abstractmethod from mmcv_custom.fileio.zipreader import ZipReader class BaseStorageBackend(metaclass=ABCMeta): """Abstract class of storage backends. All backends need to implement two apis: `get()` and `get_text()`. `get()` reads the file as a byte stream and `get_text()` reads the file as texts. """ @abstractmethod def get(self, filepath): pass @abstractmethod def get_text(self, filepath): pass class CephBackend(BaseStorageBackend): """Ceph storage backend. Args: path_mapping (dict|None): path mapping dict from local path to Petrel path. When `path_mapping={'src': 'dst'}`, `src` in `filepath` will be replaced by `dst`. Default: None. """ def __init__(self, path_mapping=None): try: import ceph warnings.warn('Ceph is deprecate in favor of Petrel.') except ImportError: raise ImportError('Please install ceph to enable CephBackend.') self._client = ceph.S3Client() assert isinstance(path_mapping, dict) or path_mapping is None self.path_mapping = path_mapping def get(self, filepath): filepath = str(filepath) if self.path_mapping is not None: for k, v in self.path_mapping.items(): filepath = filepath.replace(k, v) value = self._client.Get(filepath) value_buf = memoryview(value) return value_buf def get_text(self, filepath): raise NotImplementedError class PetrelBackend(BaseStorageBackend): """Petrel storage backend (for internal use). Args: path_mapping (dict|None): path mapping dict from local path to Petrel path. When `path_mapping={'src': 'dst'}`, `src` in `filepath` will be replaced by `dst`. Default: None. """ def __init__(self, path_mapping=None): try: from petrel_client import client except ImportError: raise ImportError('Please install petrel_client to enable ' 'PetrelBackend.') self._client = client.Client() assert isinstance(path_mapping, dict) or path_mapping is None self.path_mapping = path_mapping def get(self, filepath): filepath = str(filepath) if self.path_mapping is not None: for k, v in self.path_mapping.items(): filepath = filepath.replace(k, v) value = self._client.Get(filepath) value_buf = memoryview(value) return value_buf def get_text(self, filepath): raise NotImplementedError class MemcachedBackend(BaseStorageBackend): """Memcached storage backend. Attributes: server_list_cfg (str): Config file for memcached server list. client_cfg (str): Config file for memcached client. sys_path (str | None): Additional path to be appended to `sys.path`. Default: None. """ def __init__(self, server_list_cfg, client_cfg, sys_path=None): if sys_path is not None: import sys sys.path.append(sys_path) try: import mc except ImportError: raise ImportError( 'Please install memcached to enable MemcachedBackend.') self.server_list_cfg = server_list_cfg self.client_cfg = client_cfg self._client = mc.MemcachedClient.GetInstance(self.server_list_cfg, self.client_cfg) # mc.pyvector servers as a point which points to a memory cache self._mc_buffer = mc.pyvector() def get(self, filepath): filepath = str(filepath) import mc self._client.Get(filepath, self._mc_buffer) value_buf = mc.ConvertBuffer(self._mc_buffer) return value_buf def get_text(self, filepath): raise NotImplementedError class LmdbBackend(BaseStorageBackend): """Lmdb storage backend. Args: db_path (str): Lmdb database path. readonly (bool, optional): Lmdb environment parameter. If True, disallow any write operations. Default: True. lock (bool, optional): Lmdb environment parameter. If False, when concurrent access occurs, do not lock the database. Default: False. readahead (bool, optional): Lmdb environment parameter. If False, disable the OS filesystem readahead mechanism, which may improve random read performance when a database is larger than RAM. Default: False. Attributes: db_path (str): Lmdb database path. """ def __init__(self, db_path, readonly=True, lock=False, readahead=False, **kwargs): try: import lmdb except ImportError: raise ImportError('Please install lmdb to enable LmdbBackend.') self.db_path = str(db_path) self._client = lmdb.open( self.db_path, readonly=readonly, lock=lock, readahead=readahead, **kwargs) def get(self, filepath): """Get values according to the filepath. Args: filepath (str | obj:`Path`): Here, filepath is the lmdb key. """ filepath = str(filepath) with self._client.begin(write=False) as txn: value_buf = txn.get(filepath.encode('ascii')) return value_buf def get_text(self, filepath): raise NotImplementedError def is_zip_path(path): return '.zip@' in path class HardDiskBackend(BaseStorageBackend): """Raw hard disks storage backend.""" def get(self, filepath): filepath = str(filepath) if is_zip_path(filepath): value_buf = ZipReader.read(filepath) else: with open(filepath, 'rb') as f: value_buf = f.read() return value_buf def get_text(self, filepath): filepath = str(filepath) with open(filepath, 'r') as f: value_buf = f.read() return value_buf class FileClient(object): """A general file client to access files in different backend. The client loads a file or text in a specified backend from its path and return it as a binary file. it can also register other backend accessor with a given name and backend class. Attributes: backend (str): The storage backend type. Options are "disk", "ceph", "memcached" and "lmdb". client (:obj:`BaseStorageBackend`): The backend object. """ _backends = { 'disk': HardDiskBackend, 'ceph': CephBackend, 'memcached': MemcachedBackend, 'lmdb': LmdbBackend, 'petrel': PetrelBackend, } def __init__(self, backend='disk', **kwargs): if backend not in self._backends: raise ValueError( f'Backend {backend} is not supported. Currently supported ones' f' are {list(self._backends.keys())}') self.backend = backend self.client = self._backends[backend](**kwargs) @classmethod def register_backend(cls, name, backend): if not inspect.isclass(backend): raise TypeError( f'backend should be a class but got {type(backend)}') if not issubclass(backend, BaseStorageBackend): raise TypeError( f'backend {backend} is not a subclass of BaseStorageBackend') cls._backends[name] = backend def get(self, filepath): return self.client.get(filepath) def get_text(self, filepath): return self.client.get_text(filepath)
31.582996
79
0.613511
[ "Apache-2.0" ]
MendelXu/mmdetection-1
mmcv_custom/fileio/file_client.py
7,801
Python
r""" This app is used to invert the styleGAN series synthesis network. We find the matching latent vector w for given images so that we can manipulate images in the latent feature space. Ref: https://github.com/rosinality/stylegan2-pytorch/blob/master/projector.py # noqa """ import argparse import os import sys import mmcv import numpy as np import torch import torch.nn.functional as F from mmcv import Config from mmcv.runner import load_checkpoint from PIL import Image from torch import optim from torchvision import transforms from torchvision.utils import save_image from tqdm import tqdm # yapf: disable sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) # isort:skip # noqa from mmgen.apis import set_random_seed # isort:skip # noqa from mmgen.models import build_model # isort:skip # noqa from mmgen.models.architectures.lpips import PerceptualLoss # isort:skip # noqa # yapf: enable def parse_args(): parser = argparse.ArgumentParser( description='Image projector to the StyleGAN-based generator latent \ spaces') parser.add_argument('config', help='evaluation config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( 'files', metavar='FILES', nargs='+', help='path to image files to be projected') parser.add_argument( '--results-path', type=str, help='path to store projection results.') parser.add_argument( '--use-cpu', action='store_true', help='whether to use cpu device for sampling') parser.add_argument('--seed', type=int, default=2021, help='random seed') parser.add_argument( '--deterministic', action='store_true', help='whether to set deterministic options for CUDNN backend.') parser.add_argument( '--sample-model', type=str, default='ema', help='use which mode (ema/orig) in sampling.') parser.add_argument( '--lr-rampup', type=float, default=0.05, help='proportion of the learning rate warmup iters in the total iters') parser.add_argument( '--lr-rampdown', type=float, default=0.25, help='proportion of the learning rate decay iters in the total iters') parser.add_argument( '--lr', type=float, default=0.1, help='maximum learning rate') parser.add_argument( '--noise', type=float, default=0.05, help='strength of the noise level') parser.add_argument( '--noise-ramp', type=float, default=0.75, help='proportion of the noise level decay iters in the total iters', ) parser.add_argument( '--total-iters', type=int, default=1000, help='optimize iterations') parser.add_argument( '--noise-regularize', type=float, default=1e5, help='weight of the noise regularization', ) parser.add_argument( '--mse', type=float, default=0, help='weight of the mse loss') parser.add_argument( '--n-mean-latent', type=int, default=10000, help='sampling times to obtain the mean latent') parser.add_argument( '--w-plus', action='store_true', help='allow to use distinct latent codes to each layers', ) args = parser.parse_args() return args def noise_regularize(noises): loss = 0 for noise in noises: size = noise.shape[2] while True: loss = ( loss + (noise * torch.roll(noise, shifts=1, dims=3)).mean().pow(2) + (noise * torch.roll(noise, shifts=1, dims=2)).mean().pow(2)) if size <= 8: break noise = noise.reshape([-1, 1, size // 2, 2, size // 2, 2]) noise = noise.mean([3, 5]) size //= 2 return loss def noise_normalize_(noises): for noise in noises: mean = noise.mean() std = noise.std() noise.data.add_(-mean).div_(std) def get_lr(t, initial_lr, rampdown=0.25, rampup=0.05): lr_ramp = min(1, (1 - t) / rampdown) lr_ramp = 0.5 - 0.5 * np.cos(lr_ramp * np.pi) lr_ramp = lr_ramp * min(1, t / rampup) return initial_lr * lr_ramp def latent_noise(latent, strength): noise = torch.randn_like(latent) * strength return latent + noise def main(): args = parse_args() cfg = Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True # set random seeds if args.seed is not None: print('set random seed to', args.seed) set_random_seed(args.seed, deterministic=args.deterministic) # build the model and load checkpoint model = build_model( cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg) _ = load_checkpoint(model, args.checkpoint, map_location='cpu') # sanity check for models without ema if not model.use_ema: args.sample_model = 'orig' if args.sample_model == 'ema': generator = model.generator_ema else: generator = model.generator mmcv.print_log(f'Sampling model: {args.sample_model}', 'mmgen') generator.eval() device = 'cpu' if not args.use_cpu: generator = generator.cuda() device = 'cuda' img_size = min(generator.out_size, 256) transform = transforms.Compose([ transforms.Resize(img_size), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), ]) # read images imgs = [] for imgfile in args.files: img = Image.open(imgfile).convert('RGB') img = transform(img) img = img[[2, 1, 0], ...] imgs.append(img) imgs = torch.stack(imgs, 0).to(device) # get mean and standard deviation of style latents with torch.no_grad(): noise_sample = torch.randn( args.n_mean_latent, generator.style_channels, device=device) latent_out = generator.style_mapping(noise_sample) latent_mean = latent_out.mean(0) latent_std = ((latent_out - latent_mean).pow(2).sum() / args.n_mean_latent)**0.5 latent_in = latent_mean.detach().clone().unsqueeze(0).repeat( imgs.shape[0], 1) if args.w_plus: latent_in = latent_in.unsqueeze(1).repeat(1, generator.num_latents, 1) latent_in.requires_grad = True # define lpips loss percept = PerceptualLoss(use_gpu=device.startswith('cuda')) # initialize layer noises noises_single = generator.make_injected_noise() noises = [] for noise in noises_single: noises.append(noise.repeat(imgs.shape[0], 1, 1, 1).normal_()) for noise in noises: noise.requires_grad = True optimizer = optim.Adam([latent_in] + noises, lr=args.lr) pbar = tqdm(range(args.total_iters)) # run optimization for i in pbar: t = i / args.total_iters lr = get_lr(t, args.lr, args.lr_rampdown, args.lr_rampup) optimizer.param_groups[0]['lr'] = lr noise_strength = latent_std * args.noise * max( 0, 1 - t / args.noise_ramp)**2 latent_n = latent_noise(latent_in, noise_strength.item()) img_gen = generator([latent_n], input_is_latent=True, injected_noise=noises) batch, channel, height, width = img_gen.shape if height > 256: factor = height // 256 img_gen = img_gen.reshape(batch, channel, height // factor, factor, width // factor, factor) img_gen = img_gen.mean([3, 5]) p_loss = percept(img_gen, imgs).sum() n_loss = noise_regularize(noises) mse_loss = F.mse_loss(img_gen, imgs) loss = p_loss + args.noise_regularize * n_loss + args.mse * mse_loss optimizer.zero_grad() loss.backward() optimizer.step() noise_normalize_(noises) pbar.set_description( f' perceptual: {p_loss.item():.4f}, noise regularize:' f'{n_loss.item():.4f}, mse: {mse_loss.item():.4f}, lr: {lr:.4f}') results = generator([latent_in.detach().clone()], input_is_latent=True, injected_noise=noises) # rescale value range to [0, 1] results = ((results + 1) / 2) results = results[:, [2, 1, 0], ...] results = results.clamp_(0, 1) mmcv.mkdir_or_exist(args.results_path) # save projection results result_file = {} for i, input_name in enumerate(args.files): noise_single = [] for noise in noises: noise_single.append(noise[i:i + 1]) result_file[input_name] = { 'img': img_gen[i], 'latent': latent_in[i], 'injected_noise': noise_single, } img_name = os.path.splitext( os.path.basename(input_name))[0] + '-project.png' save_image(results[i], os.path.join(args.results_path, img_name)) torch.save(result_file, os.path.join(args.results_path, 'project_result.pt')) if __name__ == '__main__': main()
32.313589
88
0.610524
[ "Apache-2.0" ]
DequanWang/actnn-mmgen
apps/stylegan_projector.py
9,274
Python
def main(x): matrix = [] exit_path = [] for i in range(0, x): j = list(input()) if 'e' in j: y = j.index("e") exit_path.append(i) exit_path.append(y) j[y] = "-" matrix.append(j) row, col = 0, 0 matrix[row][col] = "S" path = [] searching_path(matrix, path, exit_path, row, col) def searching_path(m, path, exit_path, i, j): r, c = len(m), len(m[0]) exit_row, exit_col = exit_path # If destination is reached print if i == exit_row and j == exit_col: print("".join(e for e in path[1:]) + m[i][j]) m[exit_row][exit_col] = "-" return # explore path.append(m[i][j]) # move down if 0 <= i + 1 <= r - 1 and 0 <= j <= c - 1 and m[i + 1][j] == "-": m[i + 1][j] = "D" searching_path(m, path, exit_path, i + 1, j) # move right if 0 <= i <= r - 1 and 0 <= j + 1 <= c - 1 and m[i][j + 1] == '-': m[i][j + 1] = 'R' searching_path(m, path, exit_path, i, j + 1) # move left if 0 <= i <= r - 1 and 0 <= j - 1 <= c - 1 and m[i][j - 1] == '-': m[i][j - 1] = "L" searching_path(m, path, exit_path, i, j - 1) # move up if 0 <= i - 1 <= r - 1 and 0 <= j <= c - 1 and m[i - 1][j] == '-': m[i - 1][j] = "U" searching_path(m, path, exit_path, i - 1, j) # if none of the above is explorable or invalid index backtrack path.pop() main(3)
25.877193
70
0.460339
[ "MIT" ]
borislavstoychev/Algorithms
Recursion/labyrinth.py
1,475
Python
from rabbitmq_utils import read_messages def solve_arithmetic_phrase(channel, method, properties, body): with open('output.txt', 'a') as file: try: body_str = eval(body) result = eval(body_str) file.write(f'{body_str} = {result}\n') return result except Exception as e: print(f'Error while calculating "{body_str}": {str(e)}') read_messages(solve_arithmetic_phrase)
28.125
68
0.624444
[ "MIT" ]
ShaharGotshtat/parse-and-calculate-with-rabbitmq
calculator/calculator.py
450
Python
from scrapy.utils.project import get_project_settings from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(get_project_settings().get("CONNECTION_STRING")) def create_table(engine): """ create tables""" Base.metadata.create_all(engine) class Parliament(Base): """Sqlalchemy deals model""" __tablename__ = "parliament" id = Column(Integer, primary_key=True, autoincrement=True) name = Column("name", String) date_born = Column("date_born", String) place_born = Column("place_born", String, nullable=True) profession = Column("profession", String, nullable=True) lang = Column("lang", String, nullable=True) party = Column("party", String, nullable=True) email = Column("email", String, nullable=True) url = Column("url", String, nullable=True) education = Column("education", String, nullable=True) pp = Column("pp", String) dob = Column("dob", String)
30.609756
74
0.723506
[ "MIT" ]
Georgitanev/python38_proj_adata
src/parliamentbg/parliamentbg/models.py
1,255
Python
import usocket as socket import ustruct as struct from ubinascii import hexlify class MQTTException(Exception): pass class MQTTClient: def __init__( self, client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={}, ): if port == 0: port = 8883 if ssl else 1883 self.client_id = client_id self.sock = None self.server = server self.port = port self.ssl = ssl self.ssl_params = ssl_params self.pid = 0 self.cb = None self.user = user self.pswd = password self.keepalive = keepalive self.lw_topic = None self.lw_msg = None self.lw_qos = 0 self.lw_retain = False def _send_str(self, s): self.sock.write(struct.pack("!H", len(s))) self.sock.write(s) def _recv_len(self): n = 0 sh = 0 while 1: b = self.sock.read(1)[0] n |= (b & 0x7F) << sh if not b & 0x80: return n sh += 7 def set_callback(self, f): self.cb = f def set_last_will(self, topic, msg, retain=False, qos=0): assert 0 <= qos <= 2 assert topic self.lw_topic = topic self.lw_msg = msg self.lw_qos = qos self.lw_retain = retain def connect(self, clean_session=True): self.sock = socket.socket() addr = socket.getaddrinfo(self.server, self.port)[0][-1] self.sock.connect(addr) if self.ssl: import ussl self.sock = ussl.wrap_socket(self.sock, **self.ssl_params) premsg = bytearray(b"\x10\0\0\0\0\0") msg = bytearray(b"\x04MQTT\x04\x02\0\0") sz = 10 + 2 + len(self.client_id) msg[6] = clean_session << 1 if self.user is not None: sz += 2 + len(self.user) + 2 + len(self.pswd) msg[6] |= 0xC0 if self.keepalive: assert self.keepalive < 65536 msg[7] |= self.keepalive >> 8 msg[8] |= self.keepalive & 0x00FF if self.lw_topic: sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg) msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3 msg[6] |= self.lw_retain << 5 i = 1 while sz > 0x7F: premsg[i] = (sz & 0x7F) | 0x80 sz >>= 7 i += 1 premsg[i] = sz self.sock.write(premsg, i + 2) self.sock.write(msg) # print(hex(len(msg)), hexlify(msg, ":")) self._send_str(self.client_id) if self.lw_topic: self._send_str(self.lw_topic) self._send_str(self.lw_msg) if self.user is not None: self._send_str(self.user) self._send_str(self.pswd) resp = self.sock.read(4) assert resp[0] == 0x20 and resp[1] == 0x02 if resp[3] != 0: raise MQTTException(resp[3]) return resp[2] & 1 def disconnect(self): self.sock.write(b"\xe0\0") self.sock.close() def ping(self): self.sock.write(b"\xc0\0") def publish(self, topic, msg, retain=False, qos=0): pkt = bytearray(b"\x30\0\0\0") pkt[0] |= qos << 1 | retain sz = 2 + len(topic) + len(msg) if qos > 0: sz += 2 assert sz < 2097152 i = 1 while sz > 0x7F: pkt[i] = (sz & 0x7F) | 0x80 sz >>= 7 i += 1 pkt[i] = sz # print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt, i + 1) self._send_str(topic) if qos > 0: self.pid += 1 pid = self.pid struct.pack_into("!H", pkt, 0, pid) self.sock.write(pkt, 2) self.sock.write(msg) if qos == 1: while 1: op = self.wait_msg() if op == 0x40: sz = self.sock.read(1) assert sz == b"\x02" rcv_pid = self.sock.read(2) rcv_pid = rcv_pid[0] << 8 | rcv_pid[1] if pid == rcv_pid: return elif qos == 2: assert 0 def subscribe(self, topic, qos=0): assert self.cb is not None, "Subscribe callback is not set" pkt = bytearray(b"\x82\0\0\0") self.pid += 1 struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid) # print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt) self._send_str(topic) self.sock.write(qos.to_bytes(1, "little")) while 1: op = self.wait_msg() if op == 0x90: resp = self.sock.read(4) # print(resp) assert resp[1] == pkt[2] and resp[2] == pkt[3] if resp[3] == 0x80: raise MQTTException(resp[3]) return # Wait for a single incoming MQTT message and process it. # Subscribed messages are delivered to a callback previously # set by .set_callback() method. Other (internal) MQTT # messages processed internally. def wait_msg(self): res = self.sock.read(1) self.sock.setblocking(True) if res is None: return None if res == b"": raise OSError(-1) if res == b"\xd0": # PINGRESP sz = self.sock.read(1)[0] assert sz == 0 return None op = res[0] if op & 0xF0 != 0x30: return op sz = self._recv_len() topic_len = self.sock.read(2) topic_len = (topic_len[0] << 8) | topic_len[1] topic = self.sock.read(topic_len) sz -= topic_len + 2 if op & 6: pid = self.sock.read(2) pid = pid[0] << 8 | pid[1] sz -= 2 msg = self.sock.read(sz) self.cb(topic, msg) if op & 6 == 2: pkt = bytearray(b"\x40\x02\0\0") struct.pack_into("!H", pkt, 2, pid) self.sock.write(pkt) elif op & 6 == 4: assert 0 # Checks whether a pending message from server is available. # If not, returns immediately with None. Otherwise, does # the same processing as wait_msg. def check_msg(self): self.sock.setblocking(False) return self.wait_msg()
29.99537
79
0.491897
[ "Apache-2.0" ]
299Soul/AliOS-Things
components/py_engine/micropython-lib/micropython/umqtt.simple/umqtt/simple.py
6,479
Python
from .player import Player class Cell: EMPTY = ' ' def __init__(self, value = EMPTY): self.value = value def __eq__(self, other): return other is not None and self.value == other.value def __str__(self) -> str: return str(self.value) def assign(self, player: Player): self.value = player.symbol
21.9375
62
0.615385
[ "MIT" ]
michelAlexis/tik-tak-toe
tiktaktoe/models/cell.py
351
Python
from bcipy.feedback.visual.visual_feedback import VisualFeedback from psychopy import core from bcipy.helpers.load import load_json_parameters from bcipy.display.display_main import init_display_window # Load a parameters file parameters = load_json_parameters( 'bcipy/parameters/parameters.json', value_cast=True) display = init_display_window(parameters) clock = core.Clock() # Start Visual Feedback visual_feedback = VisualFeedback( display=display, parameters=parameters, clock=clock) stimulus = 'A' assertion = 'B' message = 'Incorrect:' visual_feedback.message_color = 'red' timing = visual_feedback.administer( stimulus, compare_assertion=assertion, message=message) print(timing) print(visual_feedback._type()) display.close()
31.208333
64
0.809079
[ "MIT" ]
CAMBI-tech/BciPy
bcipy/feedback/demo/demo_visual_feedback.py
749
Python
class RevitLinkOperations(object,IDisposable): """ This class is used to extend the IExternalResourceServer interface with methods to support operations specifically related to Revit links. """ def Dispose(self): """ Dispose(self: RevitLinkOperations) """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: RevitLinkOperations,disposing: bool) """ pass def SetGetLocalPathForOpenCallback(self,makeLocalCopyForOpen): """ SetGetLocalPathForOpenCallback(self: RevitLinkOperations,makeLocalCopyForOpen: IGetLocalPathForOpenCallback) Sets the IGetLocalPathForOpenCallback that will support the "Open (and Unload)" command for Revit links obtained from an IExternalResourceServer. makeLocalCopyForOpen: The IGetLocalPathForOpenCallback that will support the "Open (and Unload)" command. """ pass def SetOnLocalLinkSharedCoordinatesSavedCallback(self,onLocalLinkSharedCoordinatesSaved): """ SetOnLocalLinkSharedCoordinatesSavedCallback(self: RevitLinkOperations,onLocalLinkSharedCoordinatesSaved: IOnLocalLinkSharedCoordinatesSavedCallback) Sets the callback that will be called when the Revit user saves new shared coordinate settings to a linked document obtained from an IExternalResourceServer. onLocalLinkSharedCoordinatesSaved: An IOnLocalLinkSharedCoordinatesSavedCallback object that can respond when the user saves new shared coordinates to a Revit link document obtained from IExternalResourceServer. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: RevitLinkOperations) -> bool """
29.641975
215
0.735943
[ "MIT" ]
BCSharp/ironpython-stubs
release/stubs.min/Autodesk/Revit/DB/__init___parts/RevitLinkOperations.py
2,401
Python
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import Gaffer import GafferUI import GafferScene Gaffer.Metadata.registerNode( GafferScene.SceneSwitch, "description", """ Chooses between multiple input scene, passing through the chosen input to the output. """, plugs = { "index" : [ "description", """ The index of the input which is passed through. A value of 0 chooses the first input, 1 the second and so on. Values larger than the number of available inputs wrap back around to the beginning. """ ] } ) GafferUI.PlugValueWidget.registerCreator( GafferScene.SceneSwitch, "in[0-9]*", None )
33.704225
85
0.687004
[ "BSD-3-Clause" ]
goddardl/gaffer
python/GafferSceneUI/SceneSwitchUI.py
2,393
Python
import numpy as np mdf = np.loadtxt('raleighDemandClassesFractions.csv', delimiter=',') mucwp = np.loadtxt('raleighUserClassesWaterPrices.csv', delimiter=',') mstp = np.loadtxt('raleighSewageTreatmentPrice.csv', delimiter=',') print mdf.shape print mucwp.shape print mstp.shape ave_prices_per_tier = mdf * mucwp print ave_prices_per_tier.shape monthly_prices = np.sum(ave_prices_per_tier.T * mstp, axis=0) print monthly_prices
25.411765
70
0.787037
[ "Apache-2.0" ]
SUEZNorthAmerica/WaterPaths
TestFiles/calculate_water_prices.py
432
Python