text:
import argparse
import collections
import datetime
import os
import shutil
import subprocess
import sys
import tempfile

########
## Attributes

attributes = {
    'long_name': 'Sudoers Manager',
    'name':      os.path.basename(sys.argv[0]),
    'version':   '1.4.0'
}

########
## Comments
#
# These are used to build a brand new sudoers file with nice comments so people
# know what's going on.

comment_header = '''\
# sudoers file
#
# This file should be edited with the 'visudo' command as root to ensure there
# are no errors. Seriously, don't break the rules.
#
# All alias names should be in all caps and without spaces.
# Group names must have a percent sign % prepended to them.
# Whitespace can be either tabs or spaces, depending on your preference.
#
# Relevant man pages:
#   sudoers
#   visudo
#   sudo
'''

comment_user_alias = '''
##################
## User aliases ##
##################
# Create shorthand names for users and groups. These can be used anywhere in
# this file that a regular username is used.
#
# Format:
#   User_Alias <alias_name> = <user>,<user>,<group>, ...
# Example:
#   User_Alias ADMINS = alice,bob,%staff
'''

comment_runas_alias = '''
###################
## Runas aliases ##
###################
# Defines a name for user IDs under which sudo-invoked programs will run. The
# default is 'root'.
#
# Aliases defined here can be used in the user rules further down.
#
# Format:
#   Runas_Alias <alias_name> = <user>,<user>,<group>, ...
# Example:
#   Runas_Alias USERS = alice,bob,charlie
#   %admin ALL = (USERS) ALL
#
#   The above example would allow all users in the %admin group to execute all
#   commands as any of the users in the USERS runas alias.
'''

comment_host_alias = '''
##################
## Host aliases ##
##################
# Shorthand names for other hosts on which commands can be run. To use this
# really requires the use of rsh or other remote execution commands, as a host
# alias can prevent remote users from executing sudo.
#
# This is also helpful if you manage many machines. You can define rules for
# specific machines and then those rules will only take effect if the user is
# on one of those machines.
#
# Format:
#   Host_Alias <alias_name> = <host's fully-qualified domain name or short name>
# Example:
#   Host_Alias STAFF = 192.168.1.10,192.168.1.11,alice-computer.staff.school.edu
'''

comment_command_alias = '''
#####################
## Command aliases ##
#####################
# Defines shorthand names for various commands. They may contain parameters
# (although they may need to be escaped). Multiple commands can be assigned to
# a single alias, separated by commas. You can use a backslash \ to continue
# onto additional lines.
#
# Format:
#   Cmnd_Alias <alias_name> = <command> <arguments>,<command> <arguments>
# Example:
#   Cmnd_Alias SHELLS = /bin/sh, /bin/bash, /bin/csh, /bin/tcsh, /bin/zsh
'''

comment_defaults = '''
#######################
## Default overrides ##
#######################
# The sudoers file allows for many different options to be specified. Check out
# the sudoers man page, and in particular look in the subsections for both
# 'Defaults' and 'SUDOERS OPTIONS'.
'''

comment_user_rules = '''
##########################
## User and group rules ##
##########################
# Defines who can do what. If a runas alias is not specified, 'root' is assumed.
#
# Format:
#   <user|group> <host> = (<runas>) <command>
# Examples:
#   alice ALL    = (root) /full/path/to/command with arguments
#   %admin ALL   = (root) ALL
#   ADMINS STAFF = (USERS) SHELLS
'''

# All of the valid sections for the sudoers file. This is pretty important, so
# please don't break it.
sections = [
    'User_Alias',
    'Runas_Alias',
    'Host_Alias',
    'Cmnd_Alias',
    'Defaults',
    'User_Rule',
]

# This makes it easier to build a new sudoers file from scratch. Note that the
# keys in this dictionary MUST line up with those in the 'sections' list above.
comments = {
    'User_Alias': comment_user_alias,
    'Runas_Alias': comment_runas_alias,
    'Host_Alias': comment_host_alias,
    'Cmnd_Alias': comment_command_alias,
    'Defaults': comment_defaults,
    'User_Rule': comment_user_rules,
}

def build_clean_from_template(to_file):
    """
    Takes a file location and creates a brand new sudoers file from the template
    contained herein. This has comments explaining each section, as well as the
    necessary section tags to keep it updated.

    :param to_file: The location to write the new file to.
    """
    file_text = comment_header
    for section in sections:
        # For each section, add the comment, add the start/stop points, and add
        # whatever rules were declared for the section.
        file_text += comments[section]
        file_text += '#@start {}\n'.format(section)
        for rule in rules[section]:
            file_text += '{}\n'.format(rule)
        file_text += '#@end {}\n'.format(section)
    # Write the new file to the given location.
    with open(to_file, 'w') as f:
        f.write(file_text)

def write_rules(rules, to_file):
    """
    Takes a list of rules and writes the changes to the given sudoers file. This
    will keep all commented lines intact (this is non-destructive to the file).

    :param rules: A dictionary mapping section names to a list of rules for that
        section.
    :param to_file: The absolute path to the desired sudoers file.
    """
    # Set up a dict to describe which sections have been written out.
    section_written = {section: False for section in sections}
    # Get the text of the original file.
    text = []
    with open(to_file) as f:
        text = f.read().split('\n')
    # Open up the file and begin making changes.
    with open(to_file, 'w') as f:
        index = 0
        # Iterate over the sections one-by-one (in order).
        for section in sections:
            # If the section hasn't been finished yet...
            while not section_written[section]:
                # Pull a line.
                line = text[index]
                if line.strip().startswith('#') or line.strip() == '':
                    # If the line is a comment or blank space, just write it
                    # back without changes.
                    f.write(line)
                    f.write('\n')
                if '#@start {}'.format(section) in line:
                    # If the line was the start line, then write all the rules.
                    for rule in rules[section]:
                        f.write(rule)
                        f.write('\n')
                elif '#@end {}'.format(section) in line:
                    # If the line was the end line, then the section is done.
                    section_written[section] = True
                # Keep moving over the lines.
                index += 1

def commit(from_file, to_file):
    """
    Takes a temporary sudoers file, ensures it's valid, and then moves it into
    the place of the real sudoers file. Also handles backing up of the original.

    :param source_file: The proposed new sudoers file.
    :param to_file: The actual existing sudoers file.
    """
    # Check that the proposed sudoers file is good to move.
    if not validate(from_file):
        print("The proposed sudoers file is not valid: {}".format(from_file))
        sys.exit(4)
    if not verify(from_file):
        print("The proposed sudoers file could not be verified: {}".format(from_file))
        sys.exit(4)
    # The source file is fine.
    print("Successful parse.")
    # Now we'll make a copy of the original (leaving the original in place
    # for the moment to avoid a race condition). Then we'll move the new
    # one into place.
    # Ensure that the original exists before attempting to back it up.
    if os.path.isfile(to_file):
        print("Backing up original...")
        backup(to_file)
    print("Moving new file into place...")
    # Set the appropriate sudoers file permissions and owners.
    os.chmod(from_file, 0440)
    os.chown(from_file, 0, 0)
    shutil.move(from_file, to_file)
    timestamp(to_file)

def validate(sudoers_file):
    """
    Checks a sudoers file to see if it has all of the proper sections labeled
    with start and end points in the correct order. It will print to standard
    output any errors and return False if an error is encountered.

    :param sudoers_file: The absolute path to the sudoers file.
    """
    file_text = None
    # Read in the current sudoers file.
    with open(sudoers_file) as f:
        file_text = f.read().split('\n')
    # Iterate over the lines, finding all instances of the @start and @stop
    # keywords for each section.
    section_tags = {section: (None, None) for section in sections}
    for i in xrange(0, len(file_text)):
        for section in sections:
            if file_text[i] == "#@start {}".format(section):
                section_tags[section] = (i, section_tags[section][1])
                break
            elif file_text[i] == "#@end {}".format(section):
                section_tags[section] = (section_tags[section][0], i)
                break
    # Verify that all of the sections have a beginning and an end.
    valid = True
    for section in sections: # This iteration is used to preserve order.
        lines = section_tags[section]
        try:
            int(lines[0])
        except TypeError:
            valid = False
            print("Section '{}' has no start point.".format(section))
        try:
            int(lines[1])
        except TypeError:
            valid = False
            print("Section '{}' has no end point.".format(section))
    if not valid:
        print("The sudoers file is not valid for automaintenance.")
        return False
    # Verify that all of the sections appear in order.
    previous = 0
    for section in sections:
        lines = section_tags[section]
        start = lines[0]
        end   = lines[1]
        if start <= previous and previous != 0:
            print("Section '{}' is out of order.".format(section))
            valid = False
        if end <= start:
            print("Section '{}' has out-of-order start ({}) and end ({})points.".format(section, start, end))
            valid = False
        previous = end
    if not valid:
        print("The sudoers file is not valid for automaintenance.")
        return False
    # Success!
    return True

def verify(sudoers_file):
    """
    Checks that a file is parseable as a valid sudoers file. Prints output
    explaining the situation to the user.

    :param sudoers_file: The absolute path to the sudoers file.
    """
    print("Checking file for syntax errors...")
    print("***")
    # 'visudo' can check the validity of any proposed sudoers file.
    result = subprocess.call(['/usr/sbin/visudo', '-c', '-f', sudoers_file])
    print("***")
    if result:
        # Something went wrong. Exit with an error and leave the proposed file
        # in place so the user can investigate what went wrong.
        print("Invalid syntax. Try 'visudo -cf {}'".format(sudoers_file))
        return False
    return True

def timestamp(sudoers_file):
    """
    Takes a sudoers file and checks if there was a previous timestamp from auto-
    modification. If so, this updates that timestamp. If not, this adds a
    timestamp to the bottom of the file.
    """
    # Create the timestamp line.
    stamp = '#@timestamp: {}\n'.format(str(datetime.datetime.now()).split('.')[0])
    # Open a temporary file where we'll write the changes.
    handle, temp_file = tempfile.mkstemp()
    with open(temp_file, 'w') as f:
        # Search the file for an existing timestamp line.
        stamped = False
        with open(sudoers_file) as old_file:
            # Iterate over the lines of the file.
            for line in old_file:
                # Is this line a timestamp?
                if line.strip().startswith('#@timestamp'):
                    # If yes, print a new timestamp line instead.
                    f.write(stamp)
                    stamped = True
                else:
                    # Otherwise, just write the line out.
                    f.write(line)
        if not stamped:
            # If there was no timestamp, add one to the end.
            f.write(stamp)
    # Close the file and move it back into place.
    os.close(handle)
    # Set the appropriate sudoers file permissions and owners.
    os.chmod(temp_file, 0440)
    os.chown(temp_file, 0, 0)
    shutil.move(temp_file, sudoers_file)

def get_rules_from_file(sudoers_file, verbose=False):
    """
    Pulls rules out of a sudoers file and sorts them into their appropriate
    sections. This method assumes that the file is a valid sudoers file as
    checked by validate().

    :param sudoers_file: The absolute path to the sudoers file.
    :returns: A dictionary mapping section names to lists of rules that belong
        in that section.
    """
    rules = {section: [] for section in sections}
    # To make things easier, just pull all the lines from the file into a list.
    lines = []
    with open(sudoers_file) as f:
        lines = f.read().splitlines()
    # Now we iterate over the list by section. We're already guaranteed that the
    # file exists in the proper format.
    index = 0
    for section in sections:
        line = lines[index]
        # Search for the section we need.
        while (not line.startswith('#@start {}'.format(section))):
            if verbose:
                print("line: {}".format(line))
            index += 1
            line = lines[index]
        # (Need to iterate over the '#@start' line.)
        index += 1
        line = lines[index]
        # Until we get to the end, add things to the rules list.
        while (not line.startswith('#@end {}'.format(section))):
            # Is the line a comment?
            if line and not line.strip().startswith('#'):
                # No, so add it to the rules.
                if verbose:
                    print("rule: {}".format(line))
                rules[section].append(line)
            elif verbose:
                # It's a comment. Ignore it!
                print("cmnt: {}".format(line))
            index += 1
            line = lines[index]
    if verbose:
        print("rules: {}".format(rules))
    return rules

def get_rules_from_nonconforming_file(sudoers_file):
    """
    Pulls out non-commented content-containing lines from a given file. It is
    assumed that this file is a valid sudoers file according to the system
    (i.e. it passes `visudo -c`).

    :param sudoers_file: The absolute path to a supposed sudoers file.
    :returns: A dictionary mapping section names to lists of rules that belong
        in that section.
    """
    rules = {section: [] for section in sections}
    # Read in the existing file to a list.
    lines = []
    with open(sudoers_file) as f:
        lines = f.read().splitlines()
    # Iterate over the list and pull out the lines that are useful.
    raw_rules = []
    for line in lines:
        # Make sure the line isn't whitespace and isn't a comment.
        if line and not line.strip().startswith('#'):
            raw_rules.append(line)
    # Take all of the rules we've found and sort them into their sections.
    for rule in raw_rules:
        # Check each possible section and see if the line starts with it.
        added = False
        for section in sections:
            # Does the line start with the current section?
            if rule.strip().startswith(section):
                # Add it in and mark the rule as 'added'.
                rules[section].append(rule)
                added = True
                break
        if not added:
            # The rule wasn't added. Put it in the user rules!
            rules['User_Rule'].append(rule)
    # Give back the results!
    return rules

def backup(sudoers_file):
    """
    Given a sudoers file, this method creates one of two possible new files:
        1. sudoers.original - keeps at least one original copy of a sudoers file
        2. sudoers.backup   - if sudoers.original exists, the backup will be
                              made here
    This is useful in the event that you want to save an original sudoers file
    that you had prior to using this script. The original will be preserved
    indefinitely, while backups will overwrite one another.

    :param sudoers_file: The absolute path to the sudoers file.
    """
    # If the sudoers file doesn't exist, raise an error.
    if not os.path.isfile(sudoers_file):
        raise ValueError("The given sudoers file does not exist: {}".format(sudoers_file))
    # Declare names for the necessary files.
    parent_dir = os.path.dirname(sudoers_file)
    basename   = os.path.basename(sudoers_file)
    original   = os.path.join(parent_dir, '{}.original'.format(basename))
    backup     = os.path.join(parent_dir, '{}.backup'.format(basename))
    # Make the backup copy.
    if not os.path.isfile(original):
        # If the original backup doesn't exist, make it.
        shutil.copy2(sudoers_file, original)
    else:
        # Otherwise make a copy in the regular backup location.
        shutil.copy2(sudoers_file, backup)

def find_default_sudoers_file():
    """
    Attempts to find a valid sudoers file being used by the system. This uses
    the output of 'sudo -V', which lists the sudoers path.

    If, for some reason, a valid sudoers path cannot be found, then this will
    return the hardcoded default (/etc/sudoers). This method will not raise an
    error.

    :returns: The absolute path of the default sudoers file.
    """
    # Set a hardcoded default value.
    default = '/etc/sudoers'
    print("Finding default sudoers file.")
    # Get the output of 'sudo -V'. This should include a line like:
    #   Sudoers path: /etc/sudoers
    # We'll use this to pull the path of the sudoers file.
    sudo_out = subprocess.check_output(['/usr/bin/sudo', '-V']).split('\n')
    sudoers_path = None
    for line in sudo_out:
        # Iterate over the lines and look for "Sudoers path". If we find it,
        # then we should use it.
        if "Sudoers path" in line:
            sudoers_path = line
            break
    if sudoers_path:
        # We found it. Split it apart and take the path.
        sudoers_file = os.path.abspath(sudoers_path.split(': ')[1])
        if not os.path.isfile(sudoers_file):
            # If that's not a file (for some reason), return the default.
            return default
    else:
        # Couldn't find a sudoers path via 'sudo'. Use the default.
        return default
    # Return the found sudoers path.
    return os.path.abspath(sudoers_file)

def prompt_user(prompt):
    """
    Asks the user for confirmation before proceeding.

    :param prompt: The string to output to ask the user's input.
    :return: A boolean for the user's response (True = affirmative).
    """
    valid = {
        "yes": True, "ye": True, "y": True,
        "no": False, "n": False
    }
    prompt = "{} [Y/n] ".format(prompt)
    while True:
        choice = raw_input(prompt).lower()
        if choice in valid:
            return valid[choice]
        elif choice == '':
            return True
        else:
            print("Please respond with 'yes' or 'no'.")

def show_help():
    """
    Prints the version and usage information.
    """
    show_version()
    print('''\
usage: {name} [-hvcrb] [-f file] [-d rule[,-d rule,...]] rule[,rule,...]

Modify the sudoers file safely and atomically, keeping all of the rules
organized into the appropriate sections.

    -h, --help
        Prints this help message and quits.
    -v, --version
        Prints the version information and quits.
    -V, --verbose
        Prints out how the script sees the existing sudoers file as it is read.
        More for minor debugging. Not terribly helpful.
    -r, --replace-rules
        Discards previously-existing rules, if there are any. Keeps the existing
        comments by default, but this can be overridden with --build-templated.
    -b, --build-templated
        Discards the previously-existing sudoers file. Keeps the existing rules
        by default, but this can be overridden with --replace-rules.
    -c, --create
        Prevents the script from prompting for permission to create a new file
        if one does not exist in the expected location.
    -m, --migrate
        Prevents the script from prompting for permission to migrate from an
        existing sudoers file that is not properly marked for use with Sudoers
        Manager.

    -f file, --file file
        Uses 'file' as the sudoers file instead of the system default.
    -d rule, --delete rule
        Removes rules from the list (if they exist). This will not cause an
        error if the specified rule is not in the list of rules.

    rule(s)
        Sudoers rule(s) to be added to the file.
        These should be QUOTED. Seriously. It'll break if you don't quote your
        rules.
'''.format(name = attributes['name']))

def show_version():
    """
    Prints the version information.
    """
    print("{name}, version {version}\n".format(name=attributes['long_name'], version=attributes['version']))

########
## Program entry point.
#
# Here is where all the logic is handled.

if __name__ == '__main__':
    if os.geteuid():
        # User must be root to run this command.
        print("You do not have permission to run this script!")
        sys.exit(2)
    # Build the argument parser.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--help', '-h', action='store_true')
    parser.add_argument('--version', '-v', action='store_true')
    parser.add_argument('--verbose', '-V', action='store_true')
    parser.add_argument('--replace-rules', '-r', action='store_true')
    parser.add_argument('--discard', '-D', action='store_true')
    parser.add_argument('--build-templated', '-b', action='store_true')
    parser.add_argument('--create', '-c', action='store_true') # prevents prompts
    parser.add_argument('--migrate', '-m', action='store_true') # prevents prompts too
    parser.add_argument('--file', '-f')
    parser.add_argument('--delete', '-d', action='append', default=[]) # rules to be removed
    parser.add_argument('rules', nargs='*')
    # Parse the arguments.
    args = parser.parse_args()
    # This is the default, blank rules dict.
    rules = {key: [] for key in sections}
    # Print help information and quit.
    if args.help:
        show_help()
        sys.exit(0)
    # Print version information and quit.
    if args.version:
        show_version()
        sys.exit(0)
    # Should we use the default location?
    if args.file:
        # No, so set our location to the user-specified.
        sudoers_file = os.path.abspath(args.file)
    else:
        # Otherwise, find the default sudoers file location.
        sudoers_file = find_default_sudoers_file()
    # Will we be creating from the template?
    create_from_template = args.build_templated
    # Does the file exist?
    if os.path.isfile(sudoers_file):
        # Yes, it exists. Do we care to save it?
        if args.discard:
            # Nope!
            create_from_template = True
        else:
            # Let's save it. Does it conform to our specifications?
            if validate(sudoers_file):
                # Yes, it conforms. Should we replace the existing rules?
                if not args.replace_rules:
                    # No, don't replace them. Let's pull the existing rules from it.
                    rules = get_rules_from_file(sudoers_file, args.verbose)
            else:
                # The file is not a conforming sudoers file for Sudoers Manager.
                # Is the file even a system-recognized sudoers file?
                if verify(sudoers_file):
                    # Yes it is. Let's see if we should try to migrate.
                    if args.migrate or prompt_user("The sudoers file doesn't conform. Would you like to migrate your existing rules to a new file?"):
                        # Pull out the rules that are already in the file.
                        rules = get_rules_from_nonconforming_file(sudoers_file)
                        create_from_template = True
                    else:
                        # The user didn't want to migrate, so let's quit.
                        print("The file that exists does not conform to Sudoers Manager specifications: {}".format(sudoers_file))
                        sys.exit(4)
                else:
                    # The file is not valid, which is an error.
                    print("No valid sudoers file exists at: {}".format(sudoers_file))
                    sys.exit(3)
    else:
        # The file does not exist. Should we create a new file from template?
        if args.create or prompt_user("No sudoers file exists. Would you like to create one from the template?"):
            # Create the file from scratch.
            create_from_template = True
        else:
            # The user didn't want to create the file from scratch, so quit.
            print("No file exists and one is not going to be created at: {}".format(sudoers_file))
            sys.exit(4)
    # Add the user-specified rules to the rules dict.
    for rule in args.rules:
        rule = rule.strip()
        added = False
        # Try to match the rule to a specific section.
        for section in sections:
            if rule.startswith(section):
                rules[section].append(rule)
                added = True
                break
        # If the rule doesn't match a section, then it's a user specification.
        if not added:
            rules['User_Rule'].append(rule)
    # Remove duplicate rules by throwing the list into an OrderedDict.
    for section, rules_list in rules.iteritems():
        rules_list = list(collections.OrderedDict.fromkeys(rules_list))
        rules[section] = rules_list
    # Remove rules specified for deletion.
    for rule in args.delete:
        for section, rules_list in rules.iteritems():
            if rule in rules_list:
                rules_list = [x for x in rules_list if x != rule]
                rules[section] = rules_list
    # Organize the defaults specification rules so that any rules beginning with
    # 'Defaults:' will be pushed to the end of the list.
    defaults_spec_rules  = []
    defaults_rules_count = 0
    for rule in rules['Defaults']:
        # Is the rule a 'Defaults:' rule?
        if rule.strip().startswith('Defaults:'):
            # Yes, so push the rule to the end of the list.
            defaults_spec_rules.append(rule)
            defaults_rules_count += 1
        else:
            # No, so insert the rule after the previous non-'Defaults:' rules
            # but ahead of the 'Defaults:' rules in the list.
            defaults_spec_rules.insert(len(defaults_spec_rules) - defaults_rules_count, rule)
    rules['Defaults'] = defaults_spec_rules
    # Organize the user specification rules so that any ALL rules will be pushed
    # to the end of the list.
    user_spec_rules = []
    all_rules_count = 0
    for rule in rules['User_Rule']:
        # Is the rule an 'ALL' rule?
        if rule.strip().startswith('ALL'):
            # Yes, so push the rule to the end of the list.
            user_spec_rules.append(rule)
            all_rules_count += 1
        else:
            # No, so insert the rule after the previous non-ALL rules but ahead
            # of the ALL rules in the list.
            user_spec_rules.insert(len(user_spec_rules) - all_rules_count, rule)
    rules['User_Rule'] = user_spec_rules
    # Sometimes empty strings sneak in there. Let's get rid of those.
    for section, rules_list in rules.iteritems():
        rules_list = [x for x in rules_list if x]
        rules[section] = rules_list
    # Should we create a new file from the template?
    if create_from_template:
        # Build the new file.
        handle, temp_file = tempfile.mkstemp()
        build_clean_from_template(temp_file)
    else:
        # Copy the original to a temp file.
        handle, temp_file = tempfile.mkstemp()
        shutil.copy(sudoers_file, temp_file)
    # Write the changes to the temp file.
    write_rules(rules, temp_file)
    os.close(handle)
    # Commit the changes from the temp file to the sudoers file.
    commit(temp_file, sudoers_file)
    print("Done.")


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Introduction — phpMyAdmin 4.7.1 documentation</title>

    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="top" title="phpMyAdmin 4.7.1 documentation" href="index.html" />
    <link rel="next" title="Requirements" href="require.html" />
    <link rel="prev" title="Welcome to phpMyAdmin's documentation!" href="index.html" />

Navigation

          index

          next |

          previous |

phpMyAdmin 4.7.1 documentation »

Introduction¶

phpMyAdmin can manage a whole MySQL server (needs a super-user) as
well as a single database. To accomplish the latter you’ll need a
properly set up MySQL user who can read/write only the desired
database. It’s up to you to look up the appropriate part in the MySQL
manual.

Supported features¶

Currently phpMyAdmin can:

browse and drop databases, tables, views, columns and indexes

display multiple results sets through stored procedures or queries

create, copy, drop, rename and alter databases, tables, columns and
indexes

maintenance server, databases and tables, with proposals on server
configuration

execute, edit and bookmark any SQL-statement, even batch-queries

load text files into tables

create [1] and read dumps of tables

export [1] data to various formats: CSV, XML, PDF,
ISO/IEC 26300 - OpenDocument Text and Spreadsheet, Microsoft
Word 2000, and LATEX formats

import data and MySQL structures from OpenDocument spreadsheets, as
well as XML, CSV, and SQL files

administer multiple servers

manage MySQL users and privileges

check referential integrity in MyISAM tables

using Query-by-example (QBE), create complex queries automatically
connecting required tables

create PDF graphics of your
database layout

search globally in a database or a subset of it

transform stored data into any format using a set of predefined
functions, like displaying BLOB-data as image or download-link

track changes on databases, tables and views

support InnoDB tables and foreign keys

support mysqli, the improved MySQL extension see 1.17 Which Database versions does phpMyAdmin support?

create, edit, call, export and drop stored procedures and functions

create, edit, export and drop events and triggers

communicate in 80 different languages

Shortcut keys¶

Currently phpMyAdmin supports following shortcuts:

k - Toggle console

h - Go to home page

s - Open settings

d + s - Go to database structure (Provided you are in database related page)

d + f - Search database (Provided you are in database related page)

t + s - Go to table structure (Provided you are in table related page)

t + f - Search table (Provided you are in table related page)

backspace - Takes you to older page.

A word about users¶

Many people have difficulty understanding the concept of user
management with regards to phpMyAdmin. When a user logs in to
phpMyAdmin, that username and password are passed directly to MySQL.
phpMyAdmin does no account management on its own (other than allowing
one to manipulate the MySQL user account information); all users must
be valid MySQL users.

Footnotes

<colgroup><col class="label" /><col /></colgroup>

[1]	(1, 2) phpMyAdmin can compress (Zip, GZip or RFC 1952
formats) dumps and CSV exports if you use PHP with
Zlib support (--with-zlib).
Proper support may also need changes in php.ini.

Table Of Contents

Introduction

Supported features

Shortcut keys

A word about users

Previous topic

Welcome to phpMyAdmin’s documentation!

Next topic

Requirements

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

phpMyAdmin 4.7.1 documentation »

        © Copyright 2012 - 2017, The phpMyAdmin devel team.
      Created using Sphinx 1.4.9.

redpajama_set_name: RedPajamaGithub


text:
mediawiki-LinkService
=====================

## Problem

Usage wiki markup is very hard for any people. Ok! Simple don't use wiki markup! Embeding any resources by simple url-link!

May be it not customazable, but very simple.

## LinkService extension

Allow change same url-link on external resources to any embed code.

Example:

 http://www.youtube.com/watch?v=Jn4dbySjj3Y can changed on YouTube player.

Also you can define any url extensions for change to any html code.

Example:

 http://example.com/file.mp4 replace to ```<video src="http://example.com/file.mp4"></video>```

You can simple extend this modules for any online services.

Many services include in modules.

## Install

Your must copy extension from github to extensions folder and added require_once( "$IP/extensions/LinkService/LinkService.php" ); in LocalSettings.php.

## Extend

### Replace by url-extension

You can add any extension from url in extensions/LinkService/services/ExtensionList.Services.php

### Replace by hostname and replace pattern

You can replace url-link by any preg_replace pattern by extend global array $wgLinkServiceSimpleLink. See extensions/LinkService/service/SimpleLiset.Services.php

### Define class for change any url with your class helper.

Define url-extension or replace pattern is very small functionality? Your can define class for replace link in extensions/LinkService/LinkService.php.

Replace by extension and hostname + pattern is my defined classes. So, you can add class to. Good idea usage ```$wgLinkService[]['class'] = 'LinkServiceYourClassExample';``` for this. Also your can add your class in autoloading.


text:
- This is an implementation of [strategy map](https://en.wikipedia.org/wiki/Strategy_map)

## Install with Bower
```
$ bower install strategy-map
```
## Screen shot
![Strategy map screenshot](screenshot.png "Strategy map screenshot")

## Getting started
After you install strategy map in your project, you can easily call this jquery plugin as below:

```js
$('#map').strategyMap({
  groupHeight: 200, //px
  groups: testData,
  links: links,
  allowEdit: true,
  onAddNode: function (groupId) {
    log('Created new node in group ' + groupId);
    var node = {
      id: Date.now(),
      title: 'node title',
      type: 'node type',
      score: {color: {bg: ''}, value: ''},
      posi: {x: 0, y: 0}
    };
    map.addNewNode(node, groupId);
  },
  onDeleteNode: function (node) {
    log('Clicked node ' + node.data.id);
  },
  onClickNode: function (node) {
    log('Clicked node ' + node.data.id);
  },
  onAddGroup: function (groups) {
    log(JSON.stringify(groups));
  },
  onDeleteGroup: function (groups, links) {
    log(JSON.stringify(groups));
  },
  onEditGroupName: function (groups) {
    log('Edit group name');
  },
  onLinkBtnClick: function (links) {
    log('add link');
  },
  onUnlinkBtnClick: function (links) {
    log('unlink');
  },
  onSwapLinkBtnClick: function (links) {
    log('swap links');
  },
  onClearLinksBtnClick: function () {
    log('remove all links');
  },
  onClearNodesBtnClick: function () {
    log('remove all nodes');
  },
  onClearAllBtnClick: function () {
    log('remove all');
  },
  onDragEnd: function (groups) {
    log(JSON.stringify(groups));
  },
  onResize: function (groups) {
    log(JSON.stringify(groups));
  }
})
```

## Debug locally

### Clone the strategy map repository using git
```
git clone https://github.com/jackietian/strategy-map.git
cd strategy-map
```
### Install dependencies
```
bower install
```
You should find that you have one new folder in your project.

- vendor - contains the bower packages

### Fire the browser
open demo.html in your favorite browser, then you will see the map.

### License
> The MIT License


text:
#include <teem/air.h>
#include <teem/hest.h>
#include <teem/nrrd.h>

char *info = ("Converts from floating-point \"index\" to floating-point "
              "\"position\", given the centering of the data "
              "(cell vs. node), the range of positions, and the number "
              "of intervals into which position has been quantized. ");

int
main(int argc, char *argv[]) {
  char *me;
  hestOpt *hopt = NULL;
  int center;
  double minPos, maxPos, pos, index, size;

  me = argv[0];
  hestOptAdd(&hopt, NULL, "center", airTypeEnum, 1, 1, &center, NULL,
             "which centering applies to the quantized position.\n "
             "Possibilities are:\n "
             "\b\bo \"cell\": for histogram bins, quantized values, and "
             "pixels-as-squares\n "
             "\b\bo \"node\": for non-trivially interpolated "
             "sample points", NULL, nrrdCenter);
  hestOptAdd(&hopt, NULL, "minPos", airTypeDouble, 1, 1, &minPos, NULL,
             "smallest position associated with index 0");
  hestOptAdd(&hopt, NULL, "maxPos", airTypeDouble, 1, 1, &maxPos, NULL,
             "highest position associated with highest index");
  hestOptAdd(&hopt, NULL, "num", airTypeDouble, 1, 1, &size, NULL,
             "number of intervals into which position has been quantized");
  hestOptAdd(&hopt, NULL, "index", airTypeDouble, 1, 1, &index, NULL,
             "the input index, to be converted to position");
  hestParseOrDie(hopt, argc-1, argv+1, NULL, me, info,
                 AIR_TRUE, AIR_TRUE, AIR_TRUE);

  pos = NRRD_POS(center, minPos, maxPos, size, index);
  printf("%g\n", pos);

  hestParseFree(hopt);
  hestOptFree(hopt);
  exit(0);
}


text:
using System;
using System.Buffers;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;

namespace MicroBenchmarks.Hashing;

[Config(typeof(Config))]
public class DeterministicGuidImprovements
{
    private class Config : ManualConfig
    {
        public Config()
        {
            AddExporter(RPlotExporter.Default);
            AddExporter(MarkdownExporter.GitHub);
            AddDiagnoser(MemoryDiagnoser.Default);
            AddJob(Job.Default.WithInvocationCount(960000));
        }
    }

    private string part1;
    private string part2;
    private string part3;

    [Params(1)]
    public int Length { get; set; }

    [IterationSetup]
    public void Setup()
    {
        part1 = string.Join(string.Empty, Enumerable.Range(0, Length).Select(_ => Guid.NewGuid()));
        part2 = string.Join(string.Empty, Enumerable.Range(0, Length).Select(_ => Guid.NewGuid()));
        part3 = string.Join(string.Empty, Enumerable.Range(0, Length).Select(_ => Guid.NewGuid()));
    }

    [Benchmark(Baseline = true)]
    public Guid ComputeAndResize()
    {
        var src = $"{part1}{part2}{part3}";

        var stringBytes = Encoding.UTF8.GetBytes(src);

        using var sha1CryptoServiceProvider = SHA1.Create();
        var hashedBytes = sha1CryptoServiceProvider.ComputeHash(stringBytes);
        Array.Resize(ref hashedBytes, 16);
        return new Guid(hashedBytes);
    }

    [Benchmark]
    public Guid RentAndSpan()
    {
        var src = $"{part1}{part2}{part3}";
        var byteCount = Encoding.UTF8.GetByteCount(src);
        var buffer = ArrayPool<byte>.Shared.Rent(byteCount);
        try
        {
            var numberOfBytesWritten = Encoding.UTF8.GetBytes(src.AsSpan(), buffer);

            using var sha1CryptoServiceProvider = SHA1.Create();
            var guidBytes = sha1CryptoServiceProvider.ComputeHash(buffer, 0, numberOfBytesWritten).AsSpan().Slice(0, 16);
            if (!MemoryMarshal.TryRead<Guid>(guidBytes, out var deterministicGuid))
            {
                deterministicGuid = new Guid(guidBytes.ToArray());
            }
            return deterministicGuid;
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
        }
    }

    [Benchmark]
    public Guid RentAndSpanTryCompute()
    {
        var src = $"{part1}{part2}{part3}";
        var byteCount = Encoding.UTF8.GetByteCount(src);
        var stringBuffer = ArrayPool<byte>.Shared.Rent(byteCount);
        var hashBuffer = ArrayPool<byte>.Shared.Rent(20);
        var hashBufferReturned = false;
        try
        {
            var numberOfBytesWritten = Encoding.UTF8.GetBytes(src.AsSpan(), stringBuffer);

            using var sha1CryptoServiceProvider = SHA1.Create();
            byte[] hashBufferLocal;
            if (!sha1CryptoServiceProvider.TryComputeHash(stringBuffer.AsSpan().Slice(0, numberOfBytesWritten), hashBuffer, out _))
            {
                ArrayPool<byte>.Shared.Return(hashBuffer, clearArray: false);
                hashBufferReturned = true;
                hashBufferLocal = sha1CryptoServiceProvider.ComputeHash(stringBuffer, 0, numberOfBytesWritten);
            }
            else
            {
                hashBufferLocal = hashBuffer;
            }

            var guidBytes = hashBufferLocal.AsSpan().Slice(0, 16);
            return new Guid(guidBytes);
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(stringBuffer, clearArray: true);
            if (!hashBufferReturned)
            {
                ArrayPool<byte>.Shared.Return(hashBuffer, clearArray: false);
            }
        }
    }

    [Benchmark]
    public Guid RentAndSpanTryComputeAndStackalloc()
    {
        var src = $"{part1}{part2}{part3}";
        var byteCount = Encoding.UTF8.GetByteCount(src);
        var stringBuffer = ArrayPool<byte>.Shared.Rent(byteCount);
        try
        {
            var numberOfBytesWritten = Encoding.UTF8.GetBytes(src.AsSpan(), stringBuffer);

            using var sha1CryptoServiceProvider = SHA1.Create();
            Span<byte> hashBuffer = stackalloc byte[20];
            if (!sha1CryptoServiceProvider.TryComputeHash(stringBuffer.AsSpan().Slice(0, numberOfBytesWritten), hashBuffer, out _))
            {
                var hashBufferLocal = sha1CryptoServiceProvider.ComputeHash(stringBuffer, 0, numberOfBytesWritten);
                hashBufferLocal.CopyTo(hashBuffer);
            }

            var guidBytes = hashBuffer.Slice(0, 16);
            return new Guid(guidBytes);
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(stringBuffer, clearArray: true);
        }
    }

    [Benchmark]
    [SkipLocalsInit]
    public Guid RentAndSpanTryComputeAndStackallocWithStaticAndNoStringAlloc()
    {
        var length = part1.Length + part2.Length +
                     part3.Length + 2; // two separators

        const int MaxStackLimit = 256;
        const byte SeperatorByte = 95;
        var encoding = Encoding.UTF8;
        var maxByteCount = encoding.GetMaxByteCount(length);

        byte[]? sharedBuffer = null;
        var stringBufferSpan = maxByteCount <= MaxStackLimit ?
            stackalloc byte[MaxStackLimit] :
            sharedBuffer = ArrayPool<byte>.Shared.Rent(maxByteCount);

        try
        {
            var numberOfBytesWritten = encoding.GetBytes(part1.AsSpan(), stringBufferSpan);
            stringBufferSpan[numberOfBytesWritten++] = SeperatorByte;

            numberOfBytesWritten += encoding.GetBytes(part2.AsSpan(), stringBufferSpan[numberOfBytesWritten..]);
            stringBufferSpan[numberOfBytesWritten++] = SeperatorByte;

            numberOfBytesWritten += encoding.GetBytes(part3.AsSpan(), stringBufferSpan[numberOfBytesWritten..]);

            Span<byte> hashBuffer = stackalloc byte[20];
            _ = SHA1.HashData(stringBufferSpan[..numberOfBytesWritten], hashBuffer);
            var guidBytes = hashBuffer[..16];
            return new Guid(guidBytes);
        }
        finally
        {
            if (sharedBuffer != null)
            {
                ArrayPool<byte>.Shared.Return(sharedBuffer, clearArray: true);
            }
        }
    }
}


text:
. "./configuration.sh"

nova volume-list


text:
<?php

namespace Pinq\Tests\Integration\Parsing;

use Pinq\Expressions as O;
use Pinq\Parsing\FunctionInterpreter;
use Pinq\Parsing\IFunctionInterpreter;
use Pinq\Parsing\IFunctionSignature;
use Pinq\Tests\PinqTestCase;

function func($foo = __LINE__)
{

    return ['start' => $foo, 'end' => __LINE__]; }

class ReflectionTest extends PinqTestCase
{
    /**
     * @var IFunctionInterpreter
     */
    protected $interpreter;

    protected function setUp(): void
    {
        $this->interpreter = FunctionInterpreter::getDefault();
    }

    public function testClosure()
    {
        $usedVariable = new \stdClass();
        $usedVariable2 = [[]];
        $startLine  = __LINE__; $closure = function (\stdClass &$i = null, $var = __CLASS__) use ($usedVariable, $usedVariable2) {

        }; $endLine = __LINE__;

        $reflection = $this->interpreter->getReflection($closure);
        $location  = $reflection->getLocation();
        $scope     = $reflection->getScope();
        $signature = $reflection->getSignature();

        $this->assertSame(__FILE__, $location->getFilePath());
        $this->assertSame(true, $location->inNamespace());
        $this->assertSame(__NAMESPACE__, $location->getNamespace());
        $this->assertSame($startLine, $location->getStartLine());
        $this->assertSame($endLine, $location->getEndLine());
        $this->assertSame($this, $scope->getThis());
        $this->assertEquals(['usedVariable' => $usedVariable, 'usedVariable2' => $usedVariable2], $scope->getVariableTable());
        $this->assertSame(__CLASS__, $scope->getScopeType());
        $this->assertSame(__CLASS__, $scope->getThisType());
        $this->assertSame(IFunctionSignature::TYPE_CLOSURE, $signature->getType());
        $this->assertSame(null, $signature->getAccessModifier());
        $this->assertSame(null, $signature->isStatic());
        $this->assertSame(false, $signature->returnsReference());
        $this->assertSame(null, $signature->getName());
        $this->assertSame(null, $signature->getPolymorphModifier());
        $this->assertEquals([
                        O\Expression::parameter('i', '\\stdClass',  O\Expression::value(null), true),
                        O\Expression::parameter('var', null,  O\Expression::value(__CLASS__))],
                $signature->getParameterExpressions());
        $this->assertEquals(['usedVariable', 'usedVariable2'], $signature->getScopedVariableNames());
    }

    final public function & method($start = __LINE__)
    {

        $var = ['start' => $start, 'end' => __LINE__]; return $var; }

    public function testMethod()
    {
        $reflection = $this->interpreter->getReflection([$this, 'method']);
        $location  = $reflection->getLocation();
        $scope     = $reflection->getScope();
        $signature = $reflection->getSignature();

        $this->assertSame(__FILE__, $location->getFilePath());
        $this->assertSame(true, $location->inNamespace());
        $this->assertSame(__NAMESPACE__, $location->getNamespace());
        $this->assertSame($this->method()['start'], $location->getStartLine());
        $this->assertSame($this->method()['end'], $location->getEndLine());
        $this->assertSame($this, $scope->getThis());
        $this->assertEquals([], $scope->getVariableTable());
        $this->assertSame(__CLASS__, $scope->getScopeType());
        $this->assertSame(__CLASS__, $scope->getThisType());
        $this->assertSame(IFunctionSignature::TYPE_METHOD, $signature->getType());
        $this->assertSame(IFunctionSignature::ACCESS_PUBLIC, $signature->getAccessModifier());
        $this->assertSame(false, $signature->isStatic());
        $this->assertSame(true, $signature->returnsReference());
        $this->assertSame('method', $signature->getName());
        $this->assertSame(IFunctionSignature::POLYMORPH_FINAL, $signature->getPolymorphModifier());
        $this->assertEquals([O\Expression::parameter('start', null,  O\Expression::value($this->method()['start']))],
                $signature->getParameterExpressions());
        $this->assertEquals(null, $signature->getScopedVariableNames());
    }

    public static function & staticMethod($start = __LINE__)
    {

        $var = ['start' => $start, 'end' => __LINE__]; return $var; }

    public function testStaticMethod()
    {
        $reflection = $this->interpreter->getReflection([__CLASS__, 'staticMethod']);
        $location  = $reflection->getLocation();
        $scope     = $reflection->getScope();
        $signature = $reflection->getSignature();

        $this->assertSame(__FILE__, $location->getFilePath());
        $this->assertSame(true, $location->inNamespace());
        $this->assertSame(__NAMESPACE__, $location->getNamespace());
        $this->assertSame(self::staticMethod()['start'], $location->getStartLine());
        $this->assertSame(self::staticMethod()['end'], $location->getEndLine());
        $this->assertSame(null, $scope->getThis());
        $this->assertEquals([], $scope->getVariableTable());
        $this->assertSame(__CLASS__, $scope->getScopeType());
        $this->assertSame(null, $scope->getThisType());
        $this->assertSame(IFunctionSignature::TYPE_METHOD, $signature->getType());
        $this->assertSame(IFunctionSignature::ACCESS_PUBLIC, $signature->getAccessModifier());
        $this->assertSame(true, $signature->isStatic());
        $this->assertSame(true, $signature->returnsReference());
        $this->assertSame('staticMethod', $signature->getName());
        $this->assertSame(null, $signature->getPolymorphModifier());
        $this->assertEquals([O\Expression::parameter('start', null,  O\Expression::value(self::staticMethod()['start']))],
                $signature->getParameterExpressions());
        $this->assertEquals(null, $signature->getScopedVariableNames());
    }

    public function testFunction()
    {
        $reflection = $this->interpreter->getReflection(__NAMESPACE__ . '\\func');
        $location  = $reflection->getLocation();
        $scope     = $reflection->getScope();
        $signature = $reflection->getSignature();

        $this->assertSame(__FILE__, $location->getFilePath());
        $this->assertSame(true, $location->inNamespace());
        $this->assertSame(__NAMESPACE__, $location->getNamespace());
        $this->assertSame(func()['start'], $location->getStartLine());
        $this->assertSame(func()['end'], $location->getEndLine());
        $this->assertSame(null, $scope->getThis());
        $this->assertEquals([], $scope->getVariableTable());
        $this->assertSame(null, $scope->getScopeType());
        $this->assertSame(null, $scope->getThisType());
        $this->assertSame(IFunctionSignature::TYPE_FUNCTION, $signature->getType());
        $this->assertSame(null, $signature->getAccessModifier());
        $this->assertSame(null, $signature->isStatic());
        $this->assertSame(false, $signature->returnsReference());
        $this->assertSame(null, $signature->getPolymorphModifier());
        $this->assertSame('func', $signature->getName());
        $this->assertEquals([O\Expression::parameter('foo', null,  O\Expression::value(func()['start']))],
                $signature->getParameterExpressions());
        $this->assertEquals(null, $signature->getScopedVariableNames());
    }

    public function testReflectionSupportsInternalFunctions()
    {
        $reflection = $this->interpreter->getReflection('strlen');

        $this->assertSame('strlen', $reflection->getSignature()->getName());
        $this->assertSame('strlen', $reflection->getInnerReflection()->getName());
        $this->assertSame('strlen', (new \ReflectionFunction($reflection->getCallable()))->getName());
    }

    public function testSameInternalFunctionsProduceSameGlobalHashes()
    {
        $reflection1 = $this->interpreter->getReflection('strlen');
        $reflection2 = $this->interpreter->getReflection('strlen');

        $this->assertSame($reflection1->getGlobalHash(), $reflection2->getGlobalHash());
    }

    public function testInternalFunctionsProduceDifferentGlobalHashes()
    {
        $reflection1 = $this->interpreter->getReflection('strlen');
        $reflection2 = $this->interpreter->getReflection('strpos');

        $this->assertNotSame($reflection1->getGlobalHash(), $reflection2->getGlobalHash());
    }
}


text:
Grapple
=======

.. image:: https://travis-ci.org/tinybike/grapple.svg?branch=master
    :target: https://travis-ci.org/tinybike/grapple

.. image:: https://coveralls.io/repos/tinybike/grapple/badge.png
  :target: https://coveralls.io/r/tinybike/grapple

.. image:: https://badge.fury.io/py/grapple.svg
    :target: http://badge.fury.io/py/grapple

Grapple extracts the full Ripple ledger directly from rippled via websocket.  It queries rippled for the current ledger index, then walks backwards until it reaches the genesis ledger, recording every transaction it finds.

Data can be collected from a local or a remote rippled instance.  If you have a local rippled instance running that has downloaded all or most of the ledger, I strongly recommend doing local data collection.  Fetching data from Ripple's public websocket is very slow!

Grapple also resamples each currency pair's price time series to create "Open-Hi-Lo-Close" time series.  These resampled datasets can be useful for statistical tests, technical market analysis, or simply for drawing charts.

Donations::

    Bitcoin: 1NUqhGjJEedXxUSxJThfDAHzF2mFosk3fo
    Ripple: ~tinybike (rLvcQ6ctvr12aQq29AcZT6JMWH7iZ8esHS)

Installation
^^^^^^^^^^^^

The easiest way to install Grapple is using pip::

    pip install grapple

Grapple is designed to integrate with PostgreSQL, using connection information in config.py.  By default, it assumes that your database is located on localhost (127.0.0.1), and that your database's name, password, username and are all "grapple".

(While this is certainly not a secure setup, it may be convenient for people who install Grapple via pip, and do not wish to edit its source code.)

Usage
^^^^^

Grapple can be used as a Python module:

.. code-block:: python

    from grapple import Grapple

    grapple = Grapple()
    grapple.download()

The Grapple constructor accepts the following keyword arguments:

    socket_url (str):
        rippled websocket URL (default="ws://127.0.0.1:6006/")

    full (bool):
        True if downloading the full ledger (starting from the current ledger
        and walking back to the genesis ledger). False if the download should
        stop at the last current ledger (i.e., the last time grapple was run).
        (default=True)

    genesis (int):
        Genesis block index and download halting point. (default=152370)

    quiet (bool):
        If True, suppress console output. (default=True)

    resampling_frequencies (tuple):
        Resampling frequencies, using pandas frequency codes.  If None, then
        resampling is disabled. (default=('D',) or daily)

It can also be run as a script::

    python grapple.py [-flags]

Optional flags::

    -w, --websocket [websocket url]:
        Specify the rippled websocket url. (default=ws://127.0.0.1:6006/)

    -p, --public:
        Use Ripple Labs' public websocket, wss://s1.ripple.com:51233.

    -f, --full:
        Download the full Ripple ledger.  Automatic on your first run.

    -g, --genesis [ledger index]:
        Genesis ledger index and download halting point.

    -q, --quiet:
        Suppress command line output.

Tests
^^^^^

Unit tests are in the test/ directory.  Coverage is limited at the moment, but slowly improving!

Note: tests that require a local rippled and/or Postgres database connection are disabled by default.  See test/test_grapple.py for details.


text:
import {Vector3, Geometry, BufferGeometry, Quaternion} from "three";

/**
 * The twist modifier applies a tornado twist like deformation to the geometry.
 *
 * It follows a vector from a start to and end point in the vector and rotates all vertex for each point up to a defined final angle.
 *
 * @class TwistModifier
 */
function TwistModifier(angle, start, end)
{
	/**
	 * Indicates if the output should be a buffer geometry or a regular geometry.
	 *
	 * @attribute bufferGeometry
	 * @type {boolean}
	 */
	this.bufferGeometry = false;

	/**
	 * Twist direction vector, the twist is performed around this vector in its direction.
	 *
	 * @attribute direction
	 * @type {Vector3}
	 */
	this.direction = new Vector3(0, 1, 0);

	/**
	 * Twist angle of rotation, applied from the start to the end of rotation.
	 *
	 * @attribute angle
	 * @type {number}
	 */
	this.angle = angle !== undefined ? angle : Math.PI;

	/**
	 * Start height of the twist rotation.
	 *
	 * This values is in geometry coordinate space.
	 *
	 * @attribute start
	 * @type {number}
	 */
	this.start = start !== undefined ? start : 0;

	/*
	 * End height of the twist rotation.
	 *
	 * This values is in geometry coordinate space.
	 *
	 * @attribute end
	 * @type {number}
	 */
	this.end = end !== undefined ? end : 1;
}

/**
 * Apply the modifier to a geometry object, creates a new geometry with the result.
 *
 * @method modify
 * @param {Geometry | BufferGeometry} geometry Geometry to be transformed.
 * @return {Geometry | BufferGeometry} Result geometry after applying the modifier.
 */
TwistModifier.prototype.modify = function(geometry)
{
	// Convert the geometry from buffer geometry to regular geometry
	if (geometry instanceof BufferGeometry)
	{
		geometry = new Geometry();
		geometry.fromBufferGeometry(Editor.selection[0].geometry);
		geometry.mergeVertices();
	}
	else
	{
		geometry = geometry.clone();
	}

	// Apply transformation to all vertices in the geometry.
	var quaternion = new Quaternion();

	for (var i = 0; i < geometry.vertices.length; i++)
	{
		var y = geometry.vertices[i].y;

		if (y >= this.start && y <= this.end)
		{
			// Calculate angle to apply interpolated from start to end
			var interpolate = (y - this.start) / (this.end - this.start);

			quaternion.setFromAxisAngle(this.direction, this.angle * interpolate);
			geometry.vertices[i].applyQuaternion(quaternion);
		}
		else if (y > this.end)
		{
			quaternion.setFromAxisAngle(this.direction, this.angle);
			geometry.vertices[i].applyQuaternion(quaternion);
		}
	}

	geometry.computeVertexNormals();
	geometry.verticesNeedUpdate = true;

	// Convert to buffer geometry if necessary
	if (this.bufferGeometry)
	{
		var bufferGeometry = new BufferGeometry();
		bufferGeometry.fromGeometry(geometry);
		return bufferGeometry;
	}

	return geometry;
};

export {TwistModifier};


text:
require 'spec_helper'

describe FakeWebMatcher::Extension do
  it "should be included into the FakeWeb::Registry class" do
    FakeWeb::Registry.included_modules.should include(FakeWebMatcher::Extension)
  end

  describe '#requests' do
    it "should return an empty Array by default" do
      FakeWeb::Registry.instance.requests.should == []
    end
  end

  describe '#clear_requests' do
    it "should clear the requests array" do
      registry = FakeWeb::Registry.instance
      registry.requests << :something
      registry.requests.should == [:something]

      registry.clear_requests
      registry.requests.should == []
    end
  end

  describe '#response_for' do
    before :each do
      @registry = FakeWeb::Registry.instance
    end

    it "should track request" do
      @registry.response_for(:any, 'http://uri.com')

      @registry.requests.should == [[:any, 'http://uri.com']]
    end

    it "should return the underlying response from response_without_request_tracking" do
      @registry.stub!(:response_without_request_tracking => :response)

      @registry.response_for(:any, 'http://uri.com').should == :response
    end
  end
end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component.provider;

/**
 * A freezable which supports listening
 *
 * @author bratseth
 */
public interface ListenableFreezable extends Freezable {

    /** Adds a listener which will be called when this is frozen */
    void addFreezeListener(java.lang.Runnable runnable, java.util.concurrent.Executor executor);

}


text:
module Jpmobile
  class PathSet < ActionView::PathSet
    private

    def typecast(paths)
      paths.map do |path|
        case path
        when Pathname, String
          Jpmobile::Resolver.new path.to_s
        else
          super(paths)
        end
      end
    end
  end
end


text:
<?php

namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;

use Predis\Response\ErrorInterface;

/**
 * Redis based session storage handler based on the Redis class
 * provided by the PHP redis extension.
 *
 * @author Dalibor Karlović <dalibor@flexolabs.io>
 */
class RedisSessionHandler extends AbstractSessionHandler
{
    /**
     * Key prefix for shared environments.
     */
    private string $prefix;

    /**
     * Time to live in seconds.
     */
    private int|\Closure|null $ttl;

    /**
     * List of available options:
     *  * prefix: The prefix to use for the keys in order to avoid collision on the Redis server
     *  * ttl: The time to live in seconds.
     *
     * @throws \InvalidArgumentException When unsupported client or options are passed
     */
    public function __construct(
        private \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis,
        array $options = [],
    ) {
        if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) {
            throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
        }

        $this->prefix = $options['prefix'] ?? 'sf_s';
        $this->ttl = $options['ttl'] ?? null;
    }

    protected function doRead(string $sessionId): string
    {
        return $this->redis->get($this->prefix.$sessionId) ?: '';
    }

    protected function doWrite(string $sessionId, string $data): bool
    {
        $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
        $result = $this->redis->setEx($this->prefix.$sessionId, (int) $ttl, $data);

        return $result && !$result instanceof ErrorInterface;
    }

    protected function doDestroy(string $sessionId): bool
    {
        static $unlink = true;

        if ($unlink) {
            try {
                $unlink = false !== $this->redis->unlink($this->prefix.$sessionId);
            } catch (\Throwable) {
                $unlink = false;
            }
        }

        if (!$unlink) {
            $this->redis->del($this->prefix.$sessionId);
        }

        return true;
    }

    #[\ReturnTypeWillChange]
    public function close(): bool
    {
        return true;
    }

    public function gc(int $maxlifetime): int|false
    {
        return 0;
    }

    public function updateTimestamp(string $sessionId, string $data): bool
    {
        $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');

        return $this->redis->expire($this->prefix.$sessionId, (int) $ttl);
    }
}


text:
Introduction

          Collapsibles are accordion elements that expand when clicked on. They allow you to hide content that is not immediately relevant to the user.

filter_dramaFirst

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

placeSecond

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

whatshotThird

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Popout

          To create a popout collapsible, just add the class popout.

subtitlesFirst

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

gamesSecond

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

library_booksThird

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <ul class="collapsible popout" data-collapsible="accordion">

Collapsible HTML Structure

  <ul class="collapsible" data-collapsible="accordion">
    <li>
      <div class="collapsible-header"><i class="material-icons">filter_drama</i>First</div>
      <div class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div>
    </li>
    <li>
      <div class="collapsible-header"><i class="material-icons">place</i>Second</div>
      <div class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div>
    </li>
    <li>
      <div class="collapsible-header"><i class="material-icons">whatshot</i>Third</div>
      <div class="collapsible-body"><span>Lorem ipsum dolor sit amet.</span></div>
    </li>
  </ul>

Initialization

        Collapsible elements only need initialization if they are added dynamically. You can also pass in options inside the initialization, however this can be done in the HTML markup as well.

  $(document).ready(function(){
    $('.collapsible').collapsible();
  });

Preselected Section

        If you want a collapsible with a preopened section just add the active class to the collapsible-header.

filter_dramaFirst

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

placeSecond

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

whatshotThird

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <div class="collapsible-header active"><i class="mdi-maps-place"></i>Second</div>

Options

        You can customize the behavior of each collapsible using these options. For example, you can call a custom function to run when a collapsbile is opened or closed. The function passes the li element that was opened or closed as an argument.

  $('.collapsible').collapsible({
    accordion: false, // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    onOpen: function(el) { alert('Open'); }, // Callback for Collapsible open
    onClose: function(el) { alert('Closed'); } // Callback for Collapsible close
  });

Collapsible Types

        There are two ways a collapsible can behave. It can either allow multiple sections to stay open, or it can only allow one section to stay open at a time, which is called an accordion. See below for a demo of each type

Accordion

filter_dramaFirst

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

placeSecond

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

whatshotThird

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

            This is default behavior, but you can explicitly set it by setting the data-collapsible attribute in HTML.

    <ul class="collapsible" data-collapsible="accordion">

Expandable

filter_dramaFirst

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

placeSecond

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

whatshotThird

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <ul class="collapsible" data-collapsible="expandable">

Introduction

Popout

Structure

Initialization

Options

Accordion

Expandable


text:
{% trans %}Choose a occupation or type what you are looking for{% endtrans %}

<form action="" class="form-dataviva form-inline filter">

            {% trans %}Families{% endtrans %}

            {% trans %}Big Groups{% endtrans %}

                    <input type="text"
                    name="families_filter"
                    class="form-control"
                    ng-model="selector_model.families.filter_string"
                    ng-trim="true"
                    autocomplete="false"
                    placeholder="{% trans %}Search by name or CBO number:{% endtrans %}" />

                        {$ occ.name $}

CBO: {$ occ.id $}

                    <input type="text"
                    name="groups_filter"
                    class="form-control"
                    ng-model="selector_model.groups.filter_string"
                    ng-trim="true"
                    autocomplete="false"
                    placeholder="{% trans %}Search by name or CBO number:{% endtrans %}" />

                        {$ occ.name $}

CBO: {$ occ.id $}

</form>


text:
<?php

/**
 * IXR_Client
 *
 * @package IXR
 * @since 1.5.0
 *
 */
class IXR_Client
{
    var $server;
    var $port;
    var $path;
    var $useragent;
    var $response;
    var $message = false;
    var $debug = false;
    var $timeout;
    var $headers = array();

    // Storage place for an error message
    var $error = false;

	/**
	 * PHP5 constructor.
	 */
    function __construct( $server, $path = false, $port = 80, $timeout = 15 )
    {
        if (!$path) {
            // Assume we have been given a URL instead
            $bits = parse_url($server);
            $this->server = $bits['host'];
            $this->port = isset($bits['port']) ? $bits['port'] : 80;
            $this->path = isset($bits['path']) ? $bits['path'] : '/';

            // Make absolutely sure we have a path
            if (!$this->path) {
                $this->path = '/';
            }

            if ( ! empty( $bits['query'] ) ) {
                $this->path .= '?' . $bits['query'];
            }
        } else {
            $this->server = $server;
            $this->path = $path;
            $this->port = $port;
        }
        $this->useragent = 'The Incutio XML-RPC PHP Library';
        $this->timeout = $timeout;
    }

	/**
	 * PHP4 constructor.
	 */
	public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
		self::__construct( $server, $path, $port, $timeout );
	}

	/**
	 * @since 1.5.0
	 * @since 5.5.0 Formalized the existing `...$args` parameter by adding it
	 *              to the function signature.
	 *
	 * @return bool
	 */
    function query( ...$args )
    {
        $method = array_shift($args);
        $request = new IXR_Request($method, $args);
        $length = $request->getLength();
        $xml = $request->getXml();
        $r = "\r\n";
        $request  = "POST {$this->path} HTTP/1.0$r";

        // Merged from WP #8145 - allow custom headers
        $this->headers['Host']          = $this->server;
        $this->headers['Content-Type']  = 'text/xml';
        $this->headers['User-Agent']    = $this->useragent;
        $this->headers['Content-Length']= $length;

        foreach( $this->headers as $header => $value ) {
            $request .= "{$header}: {$value}{$r}";
        }
        $request .= $r;

        $request .= $xml;

        // Now send the request
        if ($this->debug) {
            echo '
'.htmlspecialchars($request)."\n
\n\n";
        }

        if ($this->timeout) {
            $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout);
        } else {
            $fp = @fsockopen($this->server, $this->port, $errno, $errstr);
        }
        if (!$fp) {
            $this->error = new IXR_Error(-32300, 'transport error - could not open socket');
            return false;
        }
        fputs($fp, $request);
        $contents = '';
        $debugContents = '';
        $gotFirstLine = false;
        $gettingHeaders = true;
        while (!feof($fp)) {
            $line = fgets($fp, 4096);
            if (!$gotFirstLine) {
                // Check line for '200'
                if (strstr($line, '200') === false) {
                    $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
                    return false;
                }
                $gotFirstLine = true;
            }
            if (trim($line) == '') {
                $gettingHeaders = false;
            }
            if (!$gettingHeaders) {
            	// merged from WP #12559 - remove trim
                $contents .= $line;
            }
            if ($this->debug) {
            	$debugContents .= $line;
            }
        }
        if ($this->debug) {
            echo '
'.htmlspecialchars($debugContents)."\n
\n\n";
        }

        // Now parse what we've got back
        $this->message = new IXR_Message($contents);
        if (!$this->message->parse()) {
            // XML error
            $this->error = new IXR_Error(-32700, 'parse error. not well formed');
            return false;
        }

        // Is the message a fault?
        if ($this->message->messageType == 'fault') {
            $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
            return false;
        }

        // Message must be OK
        return true;
    }

    function getResponse()
    {
        // methodResponses can only have one param - return that
        return $this->message->params[0];
    }

    function isError()
    {
        return (is_object($this->error));
    }

    function getErrorCode()
    {
        return $this->error->code;
    }

    function getErrorMessage()
    {
        return $this->error->message;
    }
}


text:
require 'jblas/proxies'

module JBLAS
  # Mixin for general operations not fitting in any other category.
  #
  # Collected in MatrixMixin.
  module MatrixGeneralMixin
    # Transpose the matrix. You obtain a transposed view of the matrix.
    # Some operations are not possible on such views, for example
    # most in-place operations. For such, do a +compact+ first.
    def t; transpose; end

    if false
      # Transpose the matrix. See t.
      def transpose
        JAVA_METHOD
      end
    end

    # Get the size of the matrix as <tt>[rows, columns]</tt>
    def dims
      [rows, columns]
    end

    # Get the total number of elements. Synonymous to length.
    def size
      length
    end

    # Check whether the column index +i+ is valid.
    def check_column_index(i)
      unless 0 <= i and i < columns
        raise IndexError, "column index out of bounds"
      end
    end

    # Check whether the row index +i+ is valid.
    def check_row_index(i)
      unless 0 <= i and i < rows
        raise IndexError, "column index out of bounds"
      end
    end

    # Returns true if the matrix is square and symmetric.
    def symmetric?
      square? and self.sub(self.t).normmax < 1e-6
    end

    # Compute the inverse of self.
    def inv
      unless square?
        raise ArgumentError, 'Inverses can only be computed from square ' +
          'matrices. Use solve instead!'
      end
      self.solve(self.class.eye(rows))
    end

    # Solve the linear equation self * x = b.
    def solve(b)
      if symmetric?
        Solve.solve_symmetric(self, b)
      else
        Solve.solve(self, b)
      end
    end

    # Return a new matrix which consists of the _self_ and _y_ side by
    # side.  In general the hcat method should be used sparingly as it
    # creates a new matrix and copies everything on each use. You
    # should always ask yourself if an array of vectors or matrices
    # doesn't serve you better. That said, you _can_ do funny things
    # with +inject+. For example,
    #
    #   a = mat[1,2,3]
    #   [a, 2*a, 3*a].inject {|s,x| s = s.hcat(x)}
    #   => 1.0  2.0  3.0
    #      2.0  4.0  6.0
    #      3.0  6.0  9.0
    def hcat(y)
      unless self.dims[0] == y.dims[0]
        raise ArgumentError, "Matrices must have same number of rows"
      end
      DoubleMatrix.concat_horizontally(self, y)
    end

    # Return a new matrix which consists of the _self_ on top of _y_.
    # In general the hcat methods should be used sparingly. You
    # should always ask yourself if an array of vectors or matrices
    # doesn't serve you better. See also hcat.
    def vcat(y)
      unless self.dims[1] == y.dims[1]
        raise ArgumentError, "Matrices must have same number of columns"
      end
      DoubleMatrix.concat_vertically(self, y)
    end

    # Returns a proxy of the matrix for which '*' is defined as elementwise.
    #
    # That is:
    # * a * b => matrix multiplication
    # * a.e * b => element wise multiplication
    #
    # For extra coolness, try writing it as "a .e* b", such that it looks
    # more like the ".e" belongs to the operator, not the object. (Not sure
    # whether this is really worth it, though ;) )
    def e
      JBLAS::MatrixElementWiseProxy.new(self)
    end

    # Returns a proxy for the matrix for which '*' is defined as the scalar
    # product. See also +e+
    #
    # * a * b => matrix multiplication (a.mmul(b))
    # * a .d* b => scalar product (a.dot(b))
    def d
      MatrixDotProxy.new(self)
    end

    if false
      # Returns true if self is a vector
      def vector?; JAVA_METHOD; end

      # Returns true if self is a row vector.
      def row_vector?; JAVA_METHOD; end

      # Returns true if self is a column vector.
      def column_vector?; JAVA_METHOD; end

      # Returns true if self is a scalar.
      def scalar?; JAVA_METHOD; end

      # Returns the first entry of self.
      def scalar; JAVA_METHOD; end
    end

    # Return a vector as row vector.
    def as_row
      unless vector?
        self
      else
        row_vector? ? self : self.t
      end
    end

    # Return a column vector.
    def as_column
      unless vector?
        self
      else
        column_vector? ? self : self.t
      end
    end

    # Save as ascii (tab-separated list, every row is a line)
    def save_ascii(fn)
      o = open(fn, 'w')
      rows.times do |i|
        columns.times do |j|
          o.print get(i,j)
          o.print "\t" if j < columns - 1
        end
        o.puts
      end
      o.close
    end
  end
end


text:
package main

import (
	"os"
	"testing"

	"github.com/kmulvey/gen-gorm/graph"
	"github.com/stretchr/testify/assert"
)

var users = graph.Vertex{
	Name: "Users", HasMany: "Posts", Cols: map[string]graph.Col{
		"Id":   {Name: "Id", Type: "int", Key: "PRI"},
		"Name": {Name: "Name", Type: "string", Key: ""},
	},
}
var id = graph.Col{Name: "Id", Type: "int", Key: "PRI"}
var userID = graph.Col{Name: "UserId", Type: "int", Key: "MUL"}

var database = graph.Graph{Name: "some_schema", Vertices: map[string]*graph.Vertex{
	"Users": &users,
	"Posts": {
		Name: "Posts", HasMany: "", Cols: map[string]graph.Col{
			"Id":     id,
			"Name":   {Name: "Name", Type: "string", Key: ""},
			"UserId": userID,
		},
		Edges: []graph.Edge{{DestinationTable: &users, DestinationCol: &id, OriginCol: &userID}},
	},
},
}

func TestProcessTemplates(t *testing.T) {
	t.Parallel()
	var dir = "dist"

	// delete it if it exists
	if _, err := os.Stat(dir); err == nil {
		os.RemoveAll(dir)
	}
	processTemplates(database, "dist")

	_, err := os.Stat(dir)
	assert.NoError(t, err, "directory should exist")
	f, err := os.Stat(dir + "/models.go")
	assert.NoError(t, err, "models.go should exist")
	assert.True(t, f.Size() > 0, "file should not be empty")

	// clean up
	os.RemoveAll(dir)
}


text:
/* ========================================================================
 * Copyright 2006 University of Washington
 *
 * 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
 *
 * ========================================================================
 */

#ifdef TCL_XT_TEST
#include <X11/Intrinsic.h>
#endif

#include "tcl.h"

/********** (start mihodge) *************************************/
#include "wp_uidmapper_lib.h"
#include <errno.h>
#include <stdlib.h> /* getenv */
/********** (end mihodge) *************************************/

/*
 * The following variable is a special hack that is needed in order for
 * Sun shared libraries to be used for Tcl.
 */

extern int matherr();
int *tclDummyMathPtr = (int *) matherr;

#ifdef TCL_TEST
extern int		Procbodytest_Init _ANSI_ARGS_((Tcl_Interp *interp));
extern int		Procbodytest_SafeInit _ANSI_ARGS_((Tcl_Interp *interp));
extern int		TclObjTest_Init _ANSI_ARGS_((Tcl_Interp *interp));
extern int		Tcltest_Init _ANSI_ARGS_((Tcl_Interp *interp));
#endif /* TCL_TEST */
#ifdef TCL_XT_TEST
extern int		Tclxttest_Init _ANSI_ARGS_((Tcl_Interp *interp));
#endif

/*
 *----------------------------------------------------------------------
 *
 * main --
 *
 *	This is the main program for the application.
 *
 * Results:
 *	None: Tcl_Main never returns here, so this procedure never
 *	returns either.
 *
 * Side effects:
 *	Whatever the application does.
 *
 *----------------------------------------------------------------------
 */

int
main(argc, argv)
    int argc;			/* Number of command-line arguments. */
    char **argv;		/* Values of command-line arguments. */
{
  /********** PUBCOOKIE-Specific Inclusion **************************/
  char *user,sessid[WP_BUF_SIZE],*cookie;
  int uid;
  unsigned key[WP_KEY_LEN];

  memset((void *) key, 0, sizeof(unsigned int) * WP_KEY_LEN);
  sessid[0] = '\0';
  user = getenv("REMOTE_USER");
  if(!((((cookie = getenv("QUERY_STRING"))
	 && wp_parse_cookie(cookie,"sessid","&@% ",sessid,WP_BUF_SIZE))
	|| ((cookie = getenv("HTTP_COOKIE"))
	    && wp_parse_cookie(cookie,"sessid",";@ ",sessid,WP_BUF_SIZE)))
       && wp_sessid2key(sessid,key)))
    cookie = NULL;

  if((getuid() == WEBSERVER_UID) && (user || cookie)){
    if(wp_uidmapper_getuid(user ? user : "",key,&uid) == -1) {
      fprintf(stderr,"wp_uidmapper_getname(%s,%s) failed\n",user ? user : "",sessid);
      return 1;
    } else if(setuid(uid)) {
      fprintf(stderr,"setuid(%i) failed: %s\n",uid,strerror(errno));
      return 1;
    }
  } else {
    setuid(getuid());
  }
  /********** (end PUBCOOKIE) *************************************/

#ifdef TCL_XT_TEST
    XtToolkitInitialize();
#endif
    Tcl_Main(argc, argv, Tcl_AppInit);
    return 0;			/* Needed only to prevent compiler warning. */
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_AppInit --
 *
 *	This procedure performs application-specific initialization.
 *	Most applications, especially those that incorporate additional
 *	packages, will have their own version of this procedure.
 *
 * Results:
 *	Returns a standard Tcl completion code, and leaves an error
 *	message in interp->result if an error occurs.
 *
 * Side effects:
 *	Depends on the startup script.
 *
 *----------------------------------------------------------------------
 */

int
Tcl_AppInit(interp)
    Tcl_Interp *interp;		/* Interpreter for application. */
{
    if (Tcl_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }

#ifdef TCL_TEST
#ifdef TCL_XT_TEST
     if (Tclxttest_Init(interp) == TCL_ERROR) {
	 return TCL_ERROR;
     }
#endif
    if (Tcltest_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }
    Tcl_StaticPackage(interp, "Tcltest", Tcltest_Init,
            (Tcl_PackageInitProc *) NULL);
    if (TclObjTest_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }
    if (Procbodytest_Init(interp) == TCL_ERROR) {
	return TCL_ERROR;
    }
    Tcl_StaticPackage(interp, "procbodytest", Procbodytest_Init,
            Procbodytest_SafeInit);
#endif /* TCL_TEST */

    /*
     * Call the init procedures for included packages.  Each call should
     * look like this:
     *
     * if (Mod_Init(interp) == TCL_ERROR) {
     *     return TCL_ERROR;
     * }
     *
     * where "Mod" is the name of the module.
     */

    /*
     * Call Tcl_CreateCommand for application-specific commands, if
     * they weren't already created by the init procedures called above.
     */

    /*
     * Specify a user-specific startup file to invoke if the application
     * is run interactively.  Typically the startup file is "~/.apprc"
     * where "app" is the name of the application.  If this line is deleted
     * then no user-specific startup file will be run under any conditions.
     */

    Tcl_SetVar(interp, "tcl_rcFileName", "~/.tclshrc", TCL_GLOBAL_ONLY);
    return TCL_OK;
}


text:
/**
 * Test suite
 *
 * @package phidget
 * @author Sinyeol An <Sinyeol.An@gmail.com>
 */

/**
 * Dependencies
 */
var async   = require('async'),
    test    = require('tap').test,
    phidget = require(__dirname + '/../lib/index.js');

var target  = new phidget.bridge();

/**
 * Suite
 */
async.auto({

    test:   function (callback, obj) {
        test('Component definition', function (t) {

            t.type(target, 'object', 'Component should be an object');
            t.type(target.ready, 'boolean', 'Value should be a boolean');
            t.type(target.GAIN, 'object', 'Enum should be an object');
            t.type(target.GAIN._1, 'number', 'Member of enum should be a number');
            t.type(target.GAIN._8, 'number', 'Member of enum should be a number');

            t.type(target.GAIN._16, 'number', 'Member of enum should be a number');
            t.type(target.GAIN._32, 'number', 'Member of enum should be a number');
            t.type(target.GAIN._64, 'number', 'Member of enum should be a number');
            t.type(target.GAIN._128, 'number', 'Member of enum should be a number');
            t.type(target.GAIN._UNKNOWN, 'number', 'Member of enum should be a number');

            t.type(target.attach, 'function', 'Method should be a function');
            t.type(target.close, 'function', 'Method should be a function');
            t.type(target.setEnabled, 'function', 'Method should be a function');
            t.type(target.setGain, 'function', 'Method should be a function');
            t.type(target.setDataRate, 'function', 'Method should be a function');

            t.type(target.getValue, 'function', 'Method should be a function');
            t.type(target.getMax, 'function', 'Method should be a function');
            t.type(target.getMin, 'function', 'Method should be a function');
            t.type(target.getEnabled, 'function', 'Method should be a function');
            t.type(target.getGain, 'function', 'Method should be a function');

            t.type(target.getDataRate, 'function', 'Method should be a function');

            t.end();
        });

        callback();
    }

}, function (err, obj) {
    test('Catch errors', function (t) {
        t.equal(err, null, 'Errors should be null');
        t.end();
    });
});