text:
A UITableViewCell subclass for iOS 7 assisting in autolayout based dynamic height cells for tableviews. It uses the recommended approach of creating a prototype cell and using systemLayoutSizeFittingSize to resize the superview to UILayoutFittingCompressedSize to fit all subviews of the cell's contentView according to their autolayout constraints. Rather than the old method of sizeWithFont etc that is now deprecated.

There is an example project included. Clone the repo and open "DBDynamicHeightTableCellDemo.xcworkspace".

Mentioned by [Orta Therox](https://github.com/orta) of [CocoaPods](http://cocoapods.org) on his [Pod5 podcast - Episode 13](http://pod5.io/episode13/).

## Usage

Create a ```DBDynamicHeightTableCell``` subclass like in the example (InfoCell.h/m/xib).

Implement the abstract method ```- (void)populateWithObject:(id)object;```. This is used to populate your tablecells views. A basic example:

```objc
- (void)populateWithObject:(id)object
{
    self.headlineLabel.text = [object headline];
    self.summaryLabel.text = [object summary];
}
```

[![Plain text labels](/Example/Screenshots/DBDynamicHeightTableCell-PlainLabels-small.png?raw=true)](/Example/Screenshots/DBDynamicHeightTableCell-PlainLabels.png?raw=true)

You can even use attributed strings, different font sizes, colors, etc.

```objc
- (void)populateWithObject:(id)object
{
    NSAttributedString *attributedHeadline = [[NSAttributedString alloc] initWithString:[object headline] attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), NSFontAttributeName: [UIFont boldSystemFontOfSize:16.0], NSForegroundColorAttributeName: [UIColor redColor]}];

    NSAttributedString *attributedSummary = [[NSAttributedString alloc] initWithString:[object summary] attributes:@{NSFontAttributeName: [UIFont italicSystemFontOfSize:14.0]}];

    self.headlineLabel.attributedText = attributedHeadline;
    self.summaryLabel.attributedText = attributedSummary;
}
```

[![Attributed text labels](/Example/Screenshots/DBDynamicHeightTableCell-AttributedLabels-small.png?raw=true)](/Example/Screenshots/DBDynamicHeightTableCell-AttributedLabels.png?raw=true)

To refer to your cell's xib implement the abstract method ```+ (UINib *)nib;```.

```objc
+ (UINib *)nib
{
    return [UINib nibWithNibName:@"InfoCell" bundle:nil];
}
```

![Autolayout constraints](/Example/Screenshots/DBDynamicHeightTableCell-AutolayoutConstraints.png?raw=true "DBDynamicHeightTableCell-AutolayoutConstraints")

Setup your autolayout constraints for the subviews in your cell so that it knows how it can grow/shrink.

## Installation

DBDynamicHeightTableCell is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "DBDynamicHeightTableCell"

## Author

Daniel Bowden

[github.com/danielbowden](https://github.com/danielbowden)

[twitter.com/danielgbowden](https://twitter.com/danielgbowden)

## License

DBDynamicHeightTableCell is available under the MIT license. See the LICENSE file for more info.


text:
package com.doodeec.digitalsandstorm.view;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.doodeec.digitalsandstorm.R;
import com.squareup.picasso.Picasso;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ViewHolder for single recipe in list of recipes
 *
 * @author Dusan Bartos
 */
public class RecipeViewHolder extends RecyclerView.ViewHolder {

    @Bind(R.id.view_recipe_title)
    TextView mTitle;
    @Bind(R.id.view_recipe_image)
    ImageView mImage;

    public RecipeViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

    public void setTitle(String title) {
        mTitle.setText(title);
    }

    /**
     * Loads image asynchronously with Picasso library to specified image view
     *
     * @param imageSrc url of an image
     */
    public void setImage(String imageSrc) {
        Picasso.with(itemView.getContext())
                .load(imageSrc)
                .into(mImage);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package edu.uci.ics.asterix.runtime.evaluators.functions;

import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptor;
import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory;
import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException;
import edu.uci.ics.hyracks.algebricks.common.exceptions.NotImplementedException;
import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory;

public class FuzzyEqDescriptor extends AbstractScalarFunctionDynamicDescriptor {

    private static final long serialVersionUID = 1L;
    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
        public IFunctionDescriptor createFunctionDescriptor() {
            return new FuzzyEqDescriptor();
        }
    };

    @Override
    public ICopyEvaluatorFactory createEvaluatorFactory(ICopyEvaluatorFactory[] args) throws AlgebricksException {
        throw new NotImplementedException();
    }

    @Override
    public FunctionIdentifier getIdentifier() {
        return AsterixBuiltinFunctions.FUZZY_EQ;
    }

}


text:
require 'rubygems'
require 'bundler/setup'
require 'minitest/autorun'
require 'redis/namespace'

$dir = File.dirname(File.expand_path(__FILE__))
$LOAD_PATH.unshift $dir + '/../lib'
require 'resque'
$TESTING = true
$TEST_PID=Process.pid

begin
  require 'leftright'
rescue LoadError
end

#
# make sure we can run redis
#

if !system("which redis-server")
  puts '', "** can't find `redis-server` in your path"
  puts "** try running `sudo rake install`"
  abort ''
end

#
# start our own redis when the tests start,
# kill it when they end
#

MiniTest::Unit.after_tests do
  if Process.pid == $TEST_PID
    processes = `ps -A -o pid,command | grep [r]edis-test`.split("\n")
    pids = processes.map { |process| process.split(" ")[0] }
    puts "Killing test redis server..."
    pids.each { |pid| Process.kill("TERM", pid.to_i) }
    system("rm -f #{$dir}/dump.rdb #{$dir}/dump-cluster.rdb")
  end
end

if ENV.key? 'RESQUE_DISTRIBUTED'
  require 'redis/distributed'
  puts "Starting redis for testing at localhost:9736 and localhost:9737..."
  `redis-server #{$dir}/redis-test.conf`
  `redis-server #{$dir}/redis-test-cluster.conf`
  r = Redis::Distributed.new(['redis://localhost:9736', 'redis://localhost:9737'])
  Resque.redis = Redis::Namespace.new :resque, :redis => r
else
  puts "Starting redis for testing at localhost:9736..."
  `redis-server #{$dir}/redis-test.conf`
  Resque.redis = 'localhost:9736'
end

##
# test/spec/mini 3
# http://gist.github.com/25455
# chris@ozmm.org
#
def context(*args, &block)
  return super unless (name = args.first) && block
  require 'test/unit'
  klass = Class.new(defined?(ActiveSupport::TestCase) ? ActiveSupport::TestCase : Test::Unit::TestCase) do
    def self.test(name, &block)
      define_method("test_#{name.gsub(/\W/,'_')}", &block) if block
    end
    def self.xtest(*args) end
    def self.setup(&block) define_method(:setup, &block) end
    def self.teardown(&block) define_method(:teardown, &block) end
  end
  (class << klass; self end).send(:define_method, :name) { name.gsub(/\W/,'_') }
  klass.class_eval &block
  # XXX: In 1.8.x, not all tests will run unless anonymous classes are kept in scope.
  ($test_classes ||= []) << klass
end

##
# Helper to perform job classes
#
module PerformJob
  def perform_job(klass, *args)
    resque_job = Resque::Job.new(:testqueue, 'class' => klass, 'args' => args)
    resque_job.perform
  end
end

#
# fixture classes
#

class SomeJob
  def self.perform(repo_id, path)
  end
end

class SomeIvarJob < SomeJob
  @queue = :ivar
end

class SomeMethodJob < SomeJob
  def self.queue
    :method
  end
end

class BadJob
  def self.perform
    raise "Bad job!"
  end
end

class GoodJob
  def self.perform(name)
    "Good job, #{name}"
  end
end

class AtExitJob
  def self.perform(filename)
    at_exit do
      File.open(filename, "w") {|file| file.puts "at_exit"}
    end
    "at_exit job"
  end
end

class BadJobWithSyntaxError
  def self.perform
    raise SyntaxError, "Extra Bad job!"
  end
end

class BadFailureBackend < Resque::Failure::Base
  def save
    raise Exception.new("Failure backend error")
  end
end

def with_failure_backend(failure_backend, &block)
  previous_backend = Resque::Failure.backend
  Resque::Failure.backend = failure_backend
  yield block
ensure
  Resque::Failure.backend = previous_backend
end

require 'time'

class Time
  # Thanks, Timecop
  class << self
    attr_accessor :fake_time

    alias_method :now_without_mock_time, :now

    def now
      fake_time || now_without_mock_time
    end
  end

  self.fake_time = nil
end

# From minitest/unit
def capture_io
  require 'stringio'

  orig_stdout, orig_stderr         = $stdout, $stderr
  captured_stdout, captured_stderr = StringIO.new, StringIO.new
  $stdout, $stderr                 = captured_stdout, captured_stderr

  yield

  return captured_stdout.string, captured_stderr.string
ensure
  $stdout = orig_stdout
  $stderr = orig_stderr
end

# Log to log/test.log
def reset_logger
  $test_logger ||= MonoLogger.new(File.open(File.expand_path("../../log/test.log", __FILE__), "w"))
  Resque.logger = $test_logger
end

reset_logger

def suppress_warnings
  old_verbose, $VERBOSE = $VERBOSE, nil
  yield
ensure
  $VERBOSE = old_verbose
end


text:
.search-songs {
  display: flex;
  flex-direction: column; }
  .search-songs .singerContent {
    display: flex;
    flex-direction: row;
    border-top: 1px solid #e5e5e5; }
    .search-songs .singerContent .singerImg {
      padding: 0 8px;
      display: flex;
      align-items: center; }
      .search-songs .singerContent .singerImg img {
        display: block;
        width: 100%;
        border-radius: 50%;
        width: 40px;
        height: 40px; }
    .search-songs .singerContent .singer .name {
      margin: 10px 0 2px;
      line-height: 18px;
      font-size: 16px;
      font-weight: normal;
      color: #000; }
    .search-songs .singerContent .singer .num {
      color: #808080;
      font-size: 12px; }
      .search-songs .singerContent .singer .num .songsNumber {
        margin-right: 10px; }
  .search-songs .songs-item {
    display: flex;
    flex-direction: row;
    border-top: 1px solid #e5e5e5;
    height: 55px; }
    .search-songs .songs-item .musicLogo {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 56px; }
      .search-songs .songs-item .musicLogo span {
        display: block;
        width: 22px;
        height: 20px;
        background-image: url(../img/search-music.png);
        background-position: 0 0;
        background-repeat: no-repeat;
        background-size: 22px 30px; }
    .search-songs .songs-item .song {
      overflow: hidden; }
      .search-songs .songs-item .song .songName {
        margin: 10px 0 2px;
        line-height: 18px;
        font-size: 16px;
        font-weight: normal;
        color: #000;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden; }
      .search-songs .songs-item .song .singer {
        font-size: 12px; }


text:
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:

The following is a set of guidelines for contributing to BioJulia repositories,
which are hosted in the [BioJulia Organization](https://github.com/BioJulia) on
GitHub.

These are mostly guidelines, not rules.
Use your best judgment, and feel free to propose changes to this document in a
pull request.

## Table of contents

[I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question)

[What should I know about BioJulia before I get started?](#what-should-i-know-about-biojulia-before-i-get-started)
  - [BioJulia Package Maintainers](#biojulia-package-maintainers)
  - [BioJulia Administrators](#biojulia-administrators)
  - [Etiquette and conduct](#etiquette-and-conduct)
  - [Package Conventions](#package-conventions)

[How Can I Contribute?](#how-can-i-contribute)
  - [Reporting Bugs](#reporting-bugs)
  - [Suggesting an Enhancement](#suggest-an-enhancement)
  - [Making Pull Requests](#pull-requests)
  - [Become a BioJulia package maintainer](#become-a-biojulia-package-maintainer)

[Styleguides](#styleguides)
  - [Git Commit Messages](#git-commit-messages)
  - [Additional julia style suggestions](#additional-julia-style-suggestions)
  - [Documentation Styleguide](#documentation-styleguide)

[Additional notes](#additional-notes)
  - [A suggested branching model](#a-suggested-branching-model)

## I don't want to read this whole thing I just have a question!!!

We understand you are excited to get involved already!
But please don't file an issue to ask a question.
You'll get faster results by using the resources below.

We have a Gitter message chat room where the community
chimes in with helpful advice if you have questions.
If you just have a question, or a problem that is not covered by this guide,
then come on over to the Gitter and we'll be happy to help.

* [Gitter, BioJulia message board](https://gitter.im/BioJulia/Bio.jl)

## What should I know about BioJulia **BEFORE** I get started?

### BioJulia Package Maintainers

In order to provide the best possible experience for new and existing users of
Julia from the life-sciences, a little bit of structure and organization is
necessary.

Each package is dedicated to introducing a specific data type or algorithm, or
dealing with a specific biological problem or pipeline.

Whilst there are some "meta-packages" such as Bio.jl, which bundle individual
packages together for convenience of installation and use, most of the BioJulia
software ecosystem is quite decentralized.

Therefore, it made sense that maintenance of the packages should also be
fairly decentralized, to achieve this, we created the role of a "Package
Maintainer".

The maintainer(s) for a given package are listed in the packages README.md file.

The maintainers of a package are responsible for the following aspects of the
package they maintain.

1. Deciding the branching model used and how branches are protected.
2. Reviewing pull requests, and issues for that package.
3. To tag releases of a package at suitable points in the lifetime of the package.
4. To be considerate and of assistance to new contributors, new community members and new maintainers.
5. To report potential incidents of antisocial to a BioJulia admin member.

**See [HERE](#additional-notes) for extra
guidance and suggestions on branching models and tagging releases.**

Package maintainers hold **admin** level access for any package(s) for which they
are listed as maintainer, and so new contributors to BioJulia should
rest assured they will not be 'giving up' any package they transfer to BioJulia,
they shall remain that package's administrator. Package maintainers also have
**push** (but not **admin**) access to all other code packages in the BioJulia
ecosystem.

This allows for a community spirit where maintainers who are dedicated primarily
to other packages may step in to help other maintainers to resolve a PR or issue.
As such, newer maintainers and researchers contributing a package to the BioJulia
ecosystem can rest assured help will always be at hand from our community.

However, if you are a maintainer stepping in to help the maintainer(s) dedicated
to another package, please respect them by first offering to step in and help,
before changing anything. Secondly, ask them before doing
advanced and potentially destructive git operations e.g forcing pushes to
branches (especially master), or re-writing history of branches.
Please defer to the judgement of the maintainers dedicated in the README of the
package.

### BioJulia Administrators

BioJulia has a select group of members in an Admin team.
This team has administrative access to all repositories in the BioJulia project.

The admin team is expected to:

1. Respond and resolve any disputes between any two BioJulia contributors.
2. Act as mentors to all other BioJulia maintainers.
3. Assist maintainers in the upkeep of packages when requested. Especially when
   more difficult re-bases and history manipulation are required.
4. Some administrators maintain the BioJulia infrastructure.
   This includes being responsible for the accounts and billing of any
   platforms used by BioJulia, and the maintenance of any hardware like
   servers owned and used by BioJulia.

### Etiquette and conduct

BioJulia outlines a [statement of etiquette and conduct](CODE_OF_CONDUCT.md)
that all members and contributors are expected to uphold. Please take the time
to read and understand this statement.

### Package conventions

First, be familiar with the official julia documentation on:

* [Packages](https://docs.julialang.org/en/stable/manual/packages/)
* [Package Development](https://docs.julialang.org/en/stable/manual/packages/#Package-Development-1)
* [Modules](https://docs.julialang.org/en/stable/manual/modules/)

Package names should be a simple and self explanatory as possible, avoiding
unneeded acronyms.

Packages introducing some key type or method/algorithm should be named
accordingly.

For example, the BioJulia package introducing biological sequence types and
functionality to process sequence data is called "BioSequences".
GitHub repository names of BioJulia packages should end in `.jl`, even though
the package name itself does not.
i.e. "BioSequences" is the name of the package, and the name of its GitHub
repository is "BioSequences.jl".

Considerate and simple naming greatly assists people in finding the kind of
package or functionality they are looking for.

File names of files containing julia code in packages should end in `.jl`.

All user facing types and functions (i.e. all types and functions
exported from the module of a package), should be documented.
Documentation regarding specific implementation details that aren't relevant
to users should be in the form of comments. Please *DO* comment liberally for
complex pieces of code!

We use [Documenter.jl](https://github.com/JuliaDocs/Documenter.jl),
to generate user and developer documentation and host it on the web.
The source markdown files for such manuals is kept in the `docs/src/`
folder of each BioJulia package/repository.

The code in all BioJulia packages is unit tested. Such tests should be
organized into contexts, and into separate files based on module.

Files for tests for a module go into an appropriately named folder, within the
`test` folder in the git repo.

## How can I contribute?

### Reporting Bugs

Here we show you how to submit a bug report for a BioJulia repository.
If you follow the advice here, BioJulia maintainers and the community will
better understand your report :pencil:, be able to reproduce the behaviour
:computer: :computer:, and identify related problems :mag_right:.

#### Before creating a bug report:

Please do the following:

1. Check the GitHub issue list for the package that is giving you problems.

2. If you find an issue already open for your problem, add a comment to let
  everyone know that you are experiencing the same issue.

3. If no **currently open** issue already exists for your problem that has already been
   then you should create a new issue.

   > **Note:** If you find a **Closed** issue that seems like it is the same thing
   > that you're experiencing, open a new issue and include a link to the original
   > issue in the body of your new one.

#### How to create a (good) new bug report:

Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/).
After you've determined [which repository](https://github.com/BioJulia)
your bug is related to, create an issue on that repository and provide the
following information by filling in [template](.github/ISSUE_TEMPLATE.md).
This template will help you to follow the guidance below.

When you are creating a bug report, please do the following:

1. **Explain the problem**

   - *Use a clear and descriptive title* for the issue to identify the problem.
   - *Describe the exact steps which reproduce the problem* in as many details as possible.
     - Which function / method exactly you used?
     - What arguments or parameters were used?
     - *Provide a specific example*. (Includes links to pastebin, gists and so on.)
       If you're providing snippets in the issue, use
       [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).

   - *Describe the behaviour you observed after following the steps*
     - Point out what exactly is the problem with that behaviour.
     - *Explain which behaviour you expected to see instead and why.*
     - *OPTIONALLY: Include screenshots and animated GIFs* which show you
       following the described steps and clearly demonstrate the problem.
       You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on
       macOS and Windows, or [this tool](https://github.com/colinkeenan/silentcast)
       or [this tool](https://github.com/GNOME/byzanz) on Linux.

2. **Provide additional context for the problem (some of these may not always apply)**

   - *Did the problem start happening recently* (e.g. after updating to a new version)?
     - If the problem started recently, *can you reproduce the problem in older versions?*
     - Do you know the most recent package version in which the problem doesn't happen?

   - *Can you reliably reproduce the issue?* If not...
     - Provide details about how often the problem happens.
     - Provide details about under which conditions it normally happens.

   - Is the problem is related to *working with files*? If so....
     - Does the problem happen for all files and projects or only some?
     - Does the problem happen only when working with local or remote files?
     - Does the problem happen for files of a specific type, size, or encoding?
     - Is there anything else special about the files you are using?

3. **Include details about your configuration and environment**

- *Which version of the package are you using?*

- *What's the name and version of the OS you're using?*

- *Which julia packages do you have installed?*

- Are you using local configuration files to customize julia behaviour? If so...
  - Please provide the contents of those files, preferably in a
  [code block](https://help.github.com/articles/markdown-basics/#multiple-lines)
  or with a link to a [gist](https://gist.github.com/).

*Note: All of the above guidance is included in the [template](.github/ISSUE_TEMPLATE.md) for your convenience.*

### Suggest an Enhancement

This section explains how to submit an enhancement proposal for a BioJulia
package. This includes completely new features, as well as minor improvements to
existing functionality.
Following these suggestions will help maintainers and the community understand
your suggestion :pencil: and find related suggestions :mag_right:.

#### Before Submitting An Enhancement Proposal

* **Check if there's already [a package](https://github.com/BioJulia) which provides that enhancement.**

* **Determine which package the enhancement should be suggested in.**

* **Perform a cursory issue search** to see if the enhancement has already been suggested.
  * If it has not, open a new issue as per the guidance below.
  * If it has...
    * Add a comment to the existing issue instead of opening a new one.
    * If it was closed, take the time to understand why this was so (it's ok to
      ask! :) ), and consider whether anything has changed that makes the reason
      outdated. If you can think of a convincing reason to reconsider the
      enhancement, feel free to open a new issue as per the guidance below.

#### How to submit a (good) new enhancement proposal

Enhancement proposals are tracked as
[GitHub issues](https://guides.github.com/features/issues/).
After you've determined which package your enhancement proposals is related to,
create an issue on that repository and provide the following information by
filling in [template](.github/ISSUE_TEMPLATE.md).
This template will help you to follow the guidance below.

1. **Explain the enhancement**
   - *Use a clear and descriptive title* for the issue to identify the suggestion.
   - *Provide a step-by-step description of the suggested enhancement* in as many details as possible.
   - *Provide specific examples to demonstrate the steps*.
     Include copy/pasteable snippets which you use in those examples, as
     [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).

   - If you want to change current behaviour...
     - Describe the *current* behaviour.
     - *Explain which behaviour you expected* to see instead and *why*.
     - *Will the proposed change alter APIs or existing exposed methods/types?*
       If so, this may cause dependency issues and breakages, so the maintainer
       will need to consider this when versioning the next release.

   - *OPTIONALLY: Include screenshots and animated GIFs*.
     You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on
     macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast)
     or [this tool](https://github.com/GNOME/byzanz) on Linux.

2. **Provide additional context for the enhancement**

   - *Explain why this enhancement would be useful* to most BioJulia users and
     isn't something that can or should be implemented as a separate package.

   - *Do you know of other projects where this enhancement exists?*

3. **Include details about your configuration and environment**

   - Specify which *version of the package* you're using.

   - Specify the *name and version of the OS* you're using.

*Note: All of the above guidance is included in the [template](.github/ISSUE_TEMPLATE.md) for your convenience.*

### Making Pull Requests

BioJulia packages (and all julia packages) can be developed locally.
For information on how to do this, see this section of the julia
[documentation](https://docs.julialang.org/en/stable/manual/packages/#Package-Development-1).

Before you start working on code, it is often a good idea to open an enhancement
[suggestion](#suggest-an-enhancement)

Once you decide to start working on code, the first thing you should do is make
yourself an account on [Github](https://github.com).
The chances are you already have one if you've done coding before and wanted to
make any scripts or software from a science project public.

The first step to contributing is to find the
[BioJulia repository](https://github.com/BioJulia) for the package.
Hit the 'Fork' button on the repositories page to create a forked copy of the
package for your own Github account. This is your blank slate to work on, and
will ensure your work and experiments won't hinder other users of the released
and stable package.

From there you can clone your fork of the package and work on it on your
machine using git.
Here's an example of cloning, assuming you already forked the BioJulia package "BioSequences.jl":

```sh
git clone https://github.com/<YOUR_GITHUB_USERNAME_HERE>/BioSequences.jl.git
```

Git will download or "clone" your fork and put it in a folder called
BioSequences.jl it creates in your current directory.

It is beyond the scope of this document to describe good git and github use in
more specific detail, as the folks at Git and GitHub have already done that wonderfully
on their own sites. If you have additional questions, simply ping a BioJulia
member or the [BioJulia Gitter](https://gitter.im/BioJulia/Bio.jl).

#### How to make (good) code contributions and new Pull-Requests

1. **In your code changes**

   - **Branch properly!**
     - If you are making a bug-fix, then you need to checkout your bug-fix branch
       from the last release tag.
     - If you are making a feature addition or other enhancement, checkout your
       branch from master.
     - See [here](#a-suggested-branching-model) for more information (or ask a package maintainer :smile:).

   - Follow the [julia style guide](https://docs.julialang.org/en/stable/manual/style-guide/).

   - Follow the [additional style suggestions](#additional-julia-code-style-suggestions).

   - Follow the [julia performance tips](https://docs.julialang.org/en/stable/manual/performance-tips/).

   - Update and add docstrings for new code, consistent with the [documentation styleguide](https://docs.julialang.org/en/stable/manual/documentation/).

   - Update information in the documentation located in the `docs/src/`
     folder of the package/repository if necessary.

   - Ensure that unit tests have been added which cover your code changes.

   - Ensure that you have added an entry to the `[UNRELEASED]` section of the
     manually curated `CHANGELOG.md` file for the package. Use previous entries as
     an example. Ensure the `CHANGELOG.md` is consistent with the
    recommended [changelog style](EXAMPLE_CHANGELOG.md).

   - All changes should be compatible with the latest stable version of
     Julia.

   - Please comment liberally for complex pieces of internal code to facilitate comprehension.

2. **In your pull request**

   - **Use the [pull request template](.github/PULL_REQUEST_TEMPLATE.md)**

   - *Describe* the changes in the pull request

   - Provide a *clear, simple, descriptive title*.

   - Do not include issue numbers in the PR title.

   - If you have implemented *new features* or behaviour
     - *Provide a description of the addition* in as many details as possible.
     - *Provide justification of the addition*.
     - *Provide a runnable example of use of your addition*. This lets reviewers
       and others try out the feature before it is merged or makes it's way to release.

   - If you have *changed current behaviour*...
     - *Describe the behaviour prior to you changes*
     - *Describe the behaviour after your changes* and justify why you have made the changes.
     - *Does your change alter APIs or existing exposed methods/types?*
       If so, this may cause dependency issues and breakages, so the maintainer
       will need to consider this when versioning the next release.
     - If you are implementing changes that are intended to increase performance, you
       should provide the results of a simple performance benchmark exercise
       demonstrating the improvement. Especially if the changes make code less legible.

*Note: All of the above guidance is included in the [template](.github/PULL_REQUEST_TEMPLATE.md) for your convenience.*

#### Reviews and merging

You can open a pull request early on and push changes to it until it is ready,
or you can do all your editing locally and make a pull request only when it is
finished - it is up to you.

When your pull request is ready on Github, mention one of the maintainers of the repo
in a comment e.g. `@Ward9250` and ask them to review it. You can also use Github's
review feature. They will review the code and documentation in the pull request,
and will assess it.

Your pull request will be accepted and merged if:

1. The dedicated package maintainers approve the pull request for merging.
2. The automated build system confirms that all unit tests pass without any issues.

There may be package-specific requirements or guidelines for contributors with
some of BioJulia's packages. Most of the time there will not be, the maintainers
will let you know.

It may also be that the reviewers or package maintainers will want to you to make
changes to your pull request before they will merge it. Take the time to
understand why any such request has been made, and freely discuss it with the
reviewers. Feedback you receive should be constructive and considerate
(also see [here](#etiquette-and-conduct)).

### Submitting a package to BioJulia

If you have written a package, and would like to have it listed under -
and endorsed by - the BioJulia organization, you're agreeing to the following:

1. Allowing BioJulia to have joint ownership of the package.
   This is so that the members can help you review and merge pull requests and
   other contributions, and also help you to develop new features.
   This policy ensures that you (as the package author and current maintainer)
   will have good support in maintaining your package to the highest possible
   quality.

2. Go through a joint review/decision on a suitable package name.
   This usually the original package name. However, package authors may be asked
   to rename their package to something more official and discoverable (by
   search engines and such) if it is contentious or non-standard.

To submit your package, follow these steps:

1. Introduce yourself and your package on the BioJulia Gitter channel.
2. At this point maintainers will reach out to mentor and vouch for you and your package. They will:
  1. Discuss with you a suitable name.
  2. Help you ensure the the package is up to standard, and meets the code and contribution guidelines described on this site.
  3. Add you to the BioJulia organisation if you wish to become a BioJulia maintainer.
  4. Transfer ownership of the package.

### Become a BioJulia package maintainer

You may ask the current admin or maintainers of a BioJulia package to invite you.

They will generally be willing to do so if you have done one or
more of the following to [contribute](#how-can-i-contribute) to BioJulia in the past:

1. You have [submitted a new package](#submitting-a-package-to-biojulia) to BioJulia.
2. [Reported a bug](#reporting-bugs).
3. [Suggested enhancements](#suggesting-enhancements).
4. [Made one or more pull requests](#pull-requests) implementing one or more...
    - Fixed bugs.
    - Improved performance.
    - Added new functionality.
    - Increased test coverage.
    - Improved documentation.

None of these requirements are set in stone, but we prefer you to have done one
or more of the above, as it gives good confidence that you are familiar with the
tasks and responsibilities of maintaining a package used by others, and are
willing to do so.
Any other avenue for demonstrating commitment to the community and the
GitHub organisation will also be considered.

### BioJulia members can sometimes become administrators

Members of the admin team have often been contributing to BioJulia for a long
time, and may even be founders present at the inception of the project.
In order to become an admin, one does not necessarily have to contribute large
amounts of code to the project.
Rather the decision to on-board a member to an admin position requires a history
of using and contributing to BioJulia, and a positive
interaction and involvement with the community. Any BioJulia member fulfilling
this, may offer to take on this [responsibility](#biojulia-administrators).

## Styleguides

### Git Commit messages

* Use the present tense ("Add feature" not "Added feature").
* Use the imperative mood ("Move cursor to..." not "Moves cursor to...").
* Limit the first line to 72 characters or less.
* Reference issues and pull requests liberally after the first line.
* Consider starting the commit message with an applicable emoji:
    * :art: `:art:` when improving the format/structure of the code
    * :racehorse: `:racehorse:` when improving performance
    * :memo: `:memo:` when writing docs
    * :penguin: `:penguin:` when fixing something on Linux
    * :apple: `:apple:` when fixing something on macOS
    * :checkered_flag: `:checkered_flag:` when fixing something on Windows
    * :bug: `:bug:` when fixing a bug
    * :fire: `:fire:` when removing code or files
    * :green_heart: `:green_heart:` when fixing the CI build
    * :white_check_mark: `:white_check_mark:` when adding tests
    * :arrow_up: `:arrow_up:` when upgrading dependencies
    * :arrow_down: `:arrow_down:` when downgrading dependencies
    * :exclamation: `:exclamation:` when removing warnings or depreciations

### Additional julia style suggestions

- Source code files should have the following style of header:

  ```julia
  # Title
  # =====
  #
  # Short description.
  #
  # [Long description (optional)]
  #
  # This file is a part of BioJulia. License is MIT: <link to the license file>
  ```

- Indent with 4 spaces.

- For functions that are not a single expression, it is preferred to use an explicit `return`.
  Be aware that functions in julia implicitly return the the result of the last
  expression in the function, so plain `return` should be used to indicate that
  the function returns `nothing`.

- Type names are camel case, with the first letter capitalized. E.g.
  `SomeVeryUsefulType`.

- Module names should be camel case.

- Separate logical blocks of code with one blank line. Although it is common
  and acceptable for short single-line functions to be defined together on
  consecutive lines with no blank lines between them.

- Function names, apart from constructors, are all lowercase.
  Include underscores between words only if the name would be hard
  to read without.
  E.g.  `start`, `stop`, `find_letter` `find_last_digit`.
  It is good to separate concepts in a name with a `_`.

- Generally try to keep lines below 100-columns, unless splitting a long line
  onto multiple lines makes it harder to read.

- Files that declare modules should only declare the module, and import any
  modules that it requires. Any subsequent significant code should be included
  from separate files. E.g.

```julia
module AwesomeFeatures

using IntervalsTrees, JSON

include("feature1.jl")
include("feature2.jl")

end
```

- Files that declare modules should have the same name name of the module.
  E.g the module `SomeModule` is declared under the file `SomeModule.jl`.

- When extending method definitions, define the methods with a module name prefix. E.g.

```julia
function Base.start(iter::YourType)
  ...
end

Base.done(iter::YourType, state) = ...
```

- Functions that get or set variables in a struct should not be
  prefixed with 'get' or 'set'.
  The getter should be named for the variable it gets, and the setter
  should have the same name as the getter, with the suffix `!`.
  For example, for the variable `names`:

```julia
name(node) # get node name
name!(node, "somename") # set node name
```

- When using conditional branching, if code is statement-like, an
  if-else block should be used. However if the code is expression-like
  then julia's ternary operator should be used.
  ```julia
  matches == sketchlen ? 1.0 : matches / (2 * sketchlen - matches)
  ```
  Some simple checks and expressions are also expressed using the `&&` or `||`
  operators instead of if-else syntax. For example:
  ```julia
  isvalid(foo) || throw(ArgumentError("$foo is not valid"))
  ```

## Additional Notes

### A suggested branching model

If you are a [dedicated maintainer](#biojulia-package-maintainers) on a BioJulia
package, you may be wondering which branching model to choose for development
and maintenance of your code.

If you are a contributor, knowing the branching model of a package may help
you work more smoothly with the maintainer of the package.

There are several options available, including git-flow.

Below is a recommended branching model for your repo, but it is
only a suggestion. What is best for you as the
[dedicated maintainer(s)](#biojulia-package-maintainers), is best for _you_.

The model below is a brief summary of the ['OneFlow model'](http://endoflineblog.com/oneflow-a-git-branching-model-and-workflow).
We describe it in summary here for convenience, but we recommend you check out
the blog article as a lot more justification and reasoning is presented on _why_
this model is the way it is.

#### During development

1. There is only one main branch - you can call it anything, but usually it's
   called `master`.

2. Use temporary branches for features, releases, and bug-fixes. These temporary
   branches are used as a convenience to share code with other developers and as a
   backup measure. They are always removed once the changes present on them are
   added to master.

3. Features are integrated onto the master branch primarily in a way which keeps
   the history linear and simple. A good compromise to the rebase vs. merge commit
   debate for this step is to first do an interactive rebase of the feature branch
   on master, and then do a non-fast-forward merge.
   Github now does squashed commits when merging a PR and this is fine too.

_Feature Example:_

```sh
git checkout -b feature/my-feature master

... Make commits to feature/my-feature to finish the feature ...

git rebase -i master
git checkout master
git merge --no-ff feature/my-feature
git push origin master
git branch -d feature/my-feature
```

#### :sparkles: Making new releases

1. You create a new branch for a new release. It branches off from `master` at the
   point that you decided `master` has all the necessary features. This is not
   necessarily the tip of the `master` branch.

2. From then on new work, aimed for the _next_ release, is pushed to `master` as
   always, and any necessary changes for the _current_ release are pushed to the
   release branch. Once the release is ready, you tag the top of the release branch.

3. Once the release is ready, tag the top of the release branch with a version
   number. Then do a typical merge of the release branch into `master`.
   Any changes that were made during the release will now be part of `master`.
   Delete the release branch.

_Release Example:_

```sh
git checkout -b release/2.3.0 9efc5d

... Make commits to release/2.3.0 to finish the release ...

git tag 2.3.0
git checkout master
git merge release/2.3.0
git push --tags origin master
git branch -d release/2.3.0
git push origin :release/2.3.0
```

7. Do your pushes, and go to GitHub to make your release available.

#### :bug: Hot-fixes and hot-fix releases

1. When a hot-fix is needed, create a hot-fix branch, that branches from the
   release tag that you want to apply the fix to.

2. Push the needed fixes to the hot-fix branch.

3. When the fix is ready, tag the top of the fix branch with a new release,
    merge it into master, finally delete the hot-fix branch.

_Hot-fix example:_

```sh
git checkout -b hotfix/2.3.1 2.3.0

... Add commits which fix the problem ...

git tag 2.3.1
git checkout master
git merge hotfix/2.3.1
git push --tags origin master
git branch -d hotfix/2.3.1
```

**IMPORTANT:**
There is one special case when finishing a hot-fix branch.
If a release branch has already been cut in preparation for the next release
before the hot-fix was finished, you need to merge the hot-fix branch not to
master, but to that release branch.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class FieldDecimal
   | Picturepark.SDK.V1 API </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class FieldDecimal
   | Picturepark.SDK.V1 API ">
    <meta name="generator" content="docfx 2.59.4.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

    <meta property="docfx:rel" content="../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

Search Results for

          Show / Hide Table of Contents

Class FieldDecimal

The field used to store a decimal value

Inheritance

System.Object

FieldBase

FieldDecimal

Inherited Members

      FieldBase.Id

      FieldBase.IndexId

      FieldBase.FieldNamespace

      FieldBase.Names

      FieldBase.Descriptions

      FieldBase.Required

      FieldBase.Index

      FieldBase.SimpleSearch

      FieldBase.Sortable

      System.Object.ToString()

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

Namespace: System.Dynamic.ExpandoObject

Syntax

public class FieldDecimal : FieldBase

Properties

Boost

Value to prioritize search results. Set to 1 by default. Ignored if SimpleSearch not set to true.

Declaration

public double Boost { get; set; }

Property Value

        System.Double

Maximum

The maximum possible value.

Declaration

public decimal? Maximum { get; set; }

Property Value

        System.Nullable<System.Decimal>

Minimum

The minimum possible value.

Declaration

public decimal? Minimum { get; set; }

Property Value

        System.Nullable<System.Decimal>

Pattern

The decimal pattern structure.

Declaration

public string Pattern { get; set; }

Property Value

        System.String

Methods

FromJson(String)

Declaration

public static FieldDecimal FromJson(string data)

Parameters

        System.String
        data

Returns

        FieldDecimal

ToJson()

Declaration

public string ToJson()

Returns

        System.String

              Back to top

            Generated by DocFX


text:
<?php

/* webStudentStageBundle:Entreprise:consulterEntreprise.html.twig */
class __TwigTemplate_f8b2663a32d9fa0ee66073e31475f54fe5093c07b0b75df27fd6f1682d6d553f extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo " Entreprise ";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "nom"), "html", null, true);
        echo "  ";
    }

    // line 4
    public function block_body($context, array $blocks = array())
    {
        // line 5
        echo "

 Information concernant l'entreprise ";
        // line 6
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "nom"), "html", null, true);
        echo "

\t

\t\tNom
\t\tActivité
\t\tNumero rue
\t\tNom rue
\t\tCode Postal
\t\tVille
\t\tTelephone
\t\tMail
\t

\t

\t    ";
        // line 20
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "nom"), "html", null, true);
        echo "
\t\t";
        // line 21
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "activite"), "html", null, true);
        echo "
\t\t";
        // line 22
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "numeroRue"), "html", null, true);
        echo "
\t\t";
        // line 23
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "nomRue"), "html", null, true);
        echo "
\t\t";
        // line 24
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "codePostal"), "html", null, true);
        echo "
\t\t";
        // line 25
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "ville"), "html", null, true);
        echo "
\t\t";
        // line 26
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "numeroTel"), "html", null, true);
        echo "
\t\t";
        // line 27
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entreprise"]) ? $context["entreprise"] : $this->getContext($context, "entreprise")), "adresseMail"), "html", null, true);
        echo "
\t

";
    }

    public function getTemplateName()
    {
        return "webStudentStageBundle:Entreprise:consulterEntreprise.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  88 => 27,  84 => 26,  80 => 25,  76 => 24,  72 => 23,  68 => 22,  64 => 21,  60 => 20,  43 => 6,  40 => 5,  37 => 4,  29 => 2,);
    }
}


text:
<?php
/** @noinspection ALL */

use Diskerror\Typed\TypedArray;
use PHPUnit\Framework\TestCase;
use TestClasses\SimpleTyped;

class ConstructTest extends TestCase
{
	public function testEmptyConstructor()
	{
		$simp = new SimpleTyped();

		$this->assertIsBool($simp->myBool);
		$this->assertIsInt($simp->myInt);
		$this->assertIsFloat($simp->myFloat);
		$this->assertIsString($simp->myString);
		$this->assertInstanceOf(TypedArray::class, $simp->myArray);
		$this->assertInstanceOf('stdClass', $simp->myObj);

		/**
		 * The method "toArray" is used in the function "json_encode" so as to
		 * not invoke the method "jsonSerialize".
		 */
// 		tprint($simp); exit;
//		fprintf(STDERR, var_export($simp));exit;
		$this->assertJsonStringEqualsJsonFile(
			__DIR__ . '/results/simp1-15.json',
			json_encode($simp->toArray())
		);

		$simp->myBool    = 76;
		$simp->myFloat   = 4;
		$simp->myObj->nv = 'new variable';
		$simp->myArray   = null;

		$this->assertIsBool($simp->myBool);
		$this->assertIsInt($simp->myInt);
		$this->assertIsFloat($simp->myFloat);
		$this->assertIsString($simp->myString);
		$this->assertInstanceOf(TypedArray::class, $simp->myArray);
		$this->assertInstanceOf('stdClass', $simp->myObj);

//		tprint($simp->toArray());exit;
		$this->assertJsonStringEqualsJsonFile(
			__DIR__ . '/results/simp1-32.json',
			json_encode($simp->toArray())
		);
	}

	public function testIndexedArrayConstruct()
	{
		$input = [false, 77, .5, 'simpppp2'];
		$simp  = new SimpleTyped($input);

		$this->assertIsBool($simp->myBool);
		$this->assertIsInt($simp->myInt);
		$this->assertIsFloat($simp->myFloat);
		$this->assertIsString($simp->myString);
		$this->assertInstanceOf(TypedArray::class, $simp->myArray);
		$this->assertInstanceOf('stdClass', $simp->myObj);

//		tprint($simp); exit;
		$this->assertJsonStringEqualsJsonFile(
			__DIR__ . '/results/simp2-48.json',
			json_encode($simp)
		);
	}

	public function testAssocArrayConstruct()
	{
		$arr  = ['myString' => 234445, 'myInt' => 3.14, 'myNotExist' => 'to be ignored'];
		$simp = new SimpleTyped($arr);

		$this->assertIsBool($simp->myBool);
		$this->assertIsInt($simp->myInt);
		$this->assertIsFloat($simp->myFloat);
		$this->assertIsString($simp->myString);
		$this->assertInstanceOf(TypedArray::class, $simp->myArray);
		$this->assertInstanceOf('stdClass', $simp->myObj);

//		tprint($simp); exit;
		$this->assertJsonStringEqualsJsonFile(
			__DIR__ . '/results/simp3-65.json',
			json_encode($simp)
		);
	}

	public function testWithClassConstruct()
	{
		$obj                  = new stdClass();
		$obj->myNothing       = 'ignored';
		$obj->myDouble        = '314 dropped';
		$obj->myString        = 'very complicated';
		$obj->myArray         = ['a', 'b', 'c'];
		$obj->myObj           = new stdClass();
		$obj->myObj->anything = 'ha!';
		$obj->myObj->more     = 'much!';

		$simp = new SimpleTyped($obj);

		$this->assertIsBool($simp->myBool);
		$this->assertIsInt($simp->myInt);
		$this->assertIsFloat($simp->myFloat);
		$this->assertIsString($simp->myString);
		$this->assertInstanceOf(TypedArray::class, $simp->myArray);
		$this->assertInstanceOf('stdClass', $simp->myObj);

		$simp->myDouble = 3.14;
		$simp->myInt    = null;
		$simp->myInt    = 2.54;

//		tprint($simp); exit;
		$this->assertJsonStringEqualsJsonFile(
			__DIR__ . '/results/simp4-93.json',
			json_encode($simp)
		);
	}

}


text:
"""
WSGI config for scholar_scrapy 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.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scholar_scrapy.settings")

application = get_wsgi_application()


text:
package org.strangeforest.tcb.stats.util;

import java.io.*;
import java.net.*;

public abstract class URLUtil {

	private static final int CONNECT_TIMEOUT = 10000;
	private static final int READ_TIMEOUT = 10000;

	public static int checkURL(String url) throws IOException {
		var con = (HttpURLConnection)new URL(url).openConnection();
		con.setRequestMethod("HEAD");
		con.setConnectTimeout(CONNECT_TIMEOUT);
		con.setReadTimeout(READ_TIMEOUT);
		return con.getResponseCode();
	}
}


text:
BSLS_IDENT("$Id$ $CSID$")

#include <bslma_default.h>            // for testing only
#include <bslma_testallocator.h>      // for testing only

namespace BloombergLP {

namespace bslma {

                       // -------------------------
                       // class SequentialAllocator
                       // -------------------------

// CREATORS
SequentialAllocator::~SequentialAllocator()
{
}

}  // close package namespace

}  // close enterprise namespace

#endif // BDE_OPENSOURCE_PUBLICATION -- DEPRECATED

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package org.keycloak.email.freemarker;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.jboss.logging.Logger;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailProvider;
import org.keycloak.email.freemarker.beans.EventBean;
import org.keycloak.events.Event;
import org.keycloak.events.EventType;
import org.keycloak.freemarker.FreeMarkerException;
import org.keycloak.freemarker.FreeMarkerUtil;
import org.keycloak.freemarker.LocaleHelper;
import org.keycloak.freemarker.Theme;
import org.keycloak.freemarker.ThemeProvider;
import org.keycloak.freemarker.beans.MessageFormatterMethod;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;

/**
 * @author Stian Thorgersen
 */
public class FreeMarkerEmailProvider implements EmailProvider {

    private static final Logger log = Logger.getLogger(FreeMarkerEmailProvider.class);

    private KeycloakSession session;
    private FreeMarkerUtil freeMarker;
    private RealmModel realm;
    private UserModel user;

    public FreeMarkerEmailProvider(KeycloakSession session, FreeMarkerUtil freeMarker) {
        this.session = session;
        this.freeMarker = freeMarker;
    }

    @Override
    public EmailProvider setRealm(RealmModel realm) {
        this.realm = realm;
        return this;
    }

    @Override
    public EmailProvider setUser(UserModel user) {
        this.user = user;
        return this;
    }

    @Override
    public void sendEvent(Event event) throws EmailException {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("event", new EventBean(event));

        send(toCamelCase(event.getType()) + "Subject", "event-" + event.getType().toString().toLowerCase() + ".ftl", attributes);
    }

    @Override
    public void sendPasswordReset(String link, long expirationInMinutes) throws EmailException {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("link", link);
        attributes.put("linkExpiration", expirationInMinutes);

        String realmName = realm.getName().substring(0, 1).toUpperCase() + realm.getName().substring(1);
        attributes.put("realmName", realmName);

        send("passwordResetSubject", "password-reset.ftl", attributes);
    }

    @Override
    public void sendChangePassword(String link, long expirationInMinutes) throws EmailException {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("link", link);
        attributes.put("linkExpiration", expirationInMinutes);

        String realmName = realm.getName().substring(0, 1).toUpperCase() + realm.getName().substring(1);
        attributes.put("realmName", realmName);

        send("changePasswordSubject", "changePassword.ftl", attributes);

    }

    @Override
    public void sendVerifyEmail(String link, long expirationInMinutes) throws EmailException {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("link", link);
        attributes.put("linkExpiration", expirationInMinutes);

        String realmName = realm.getName().substring(0, 1).toUpperCase() + realm.getName().substring(1);
        attributes.put("realmName", realmName);

        send("emailVerificationSubject", "email-verification.ftl", attributes);
    }

    private void send(String subjectKey, String template, Map<String, Object> attributes) throws EmailException {
        try {
            ThemeProvider themeProvider = session.getProvider(ThemeProvider.class, "extending");
            Theme theme = themeProvider.getTheme(realm.getEmailTheme(), Theme.Type.EMAIL);
            Locale locale = LocaleHelper.getLocale(realm, user);
            attributes.put("locale", locale);
            Properties rb = theme.getMessages(locale);
            attributes.put("msg", new MessageFormatterMethod(locale, rb));
            String subject = new MessageFormat(rb.getProperty(subjectKey,subjectKey),locale).format(new Object[0]);
            String textTemplate = String.format("text/%s", template);
            String textBody;
            try {
            	textBody = freeMarker.processTemplate(attributes, textTemplate, theme);
            } catch (final FreeMarkerException e ) {
            	textBody = null;
            }
            String htmlTemplate = String.format("html/%s", template);
            String htmlBody;
            try {
            	htmlBody = freeMarker.processTemplate(attributes, htmlTemplate, theme);
            } catch (final FreeMarkerException e ) {
            	htmlBody = null;
            }

            send(subject, textBody, htmlBody);
        } catch (Exception e) {
            throw new EmailException("Failed to template email", e);
        }
    }

    private void send(String subject, String textBody, String htmlBody) throws EmailException {
        try {
            String address = user.getEmail();
            Map<String, String> config = realm.getSmtpConfig();

            Properties props = new Properties();
            props.setProperty("mail.smtp.host", config.get("host"));

            boolean auth = "true".equals(config.get("auth"));
            boolean ssl = "true".equals(config.get("ssl"));
            boolean starttls = "true".equals(config.get("starttls"));

            if (config.containsKey("port")) {
                props.setProperty("mail.smtp.port", config.get("port"));
            }

            if (auth) {
                props.put("mail.smtp.auth", "true");
            }

            if (ssl) {
                props.put("mail.smtp.socketFactory.port", config.get("port"));
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            }

            if (starttls) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            String from = config.get("from");

            Session session = Session.getInstance(props);

            Multipart multipart = new MimeMultipart("alternative");

            if(textBody != null) {
            	MimeBodyPart textPart = new MimeBodyPart();
            	textPart.setText(textBody, "UTF-8");
            	multipart.addBodyPart(textPart);
            }

            if(htmlBody != null) {
            	MimeBodyPart htmlPart = new MimeBodyPart();
            	htmlPart.setContent(htmlBody, "text/html; charset=UTF-8");
            	multipart.addBodyPart(htmlPart);
            }

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setHeader("To", address);
            msg.setSubject(subject);
            msg.setContent(multipart);
            msg.saveChanges();
            msg.setSentDate(new Date());

            Transport transport = session.getTransport("smtp");
            if (auth) {
                transport.connect(config.get("user"), config.get("password"));
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, new InternetAddress[]{new InternetAddress(address)});
        } catch (Exception e) {
            log.warn("Failed to send email", e);
            throw new EmailException(e);
        }
    }

    @Override
    public void close() {
    }

    private String toCamelCase(EventType event){
        StringBuilder sb = new StringBuilder("event");
        for(String s : event.name().toString().toLowerCase().split("_")){
            sb.append(s.substring(0,1).toUpperCase()).append(s.substring(1));
        }
        return sb.toString();
    }

}


text:
def check_tf_version():
    import logging
    try:
        import tensorflow as tf
    except Exception as e:
        return False, RuntimeError("Importing TensorFlow failed, "
                                   "please install tensorflow 1.15.0.", e)

    v_str = tf.__version__
    major, minor, patch = v_str.split(".")
    if v_str != "1.15.0":
        if int(major) == 1:
            logging.warning("\n######################### WARNING ##########################\n"
                            "\nAnalytics Zoo TFPark has only been tested on TensorFlow 1.15.0,"
                            " but your current TensorFlow installation is {}.".format(v_str) +
                            "\nYou may encounter some version incompatibility issues. "
                            "\n##############################################################")
        else:
            message = "Currently Analytics Zoo TFPark only supports TensorFlow 1.15.0, " + \
                      "but your current TensorFlow installation is {}".format(v_str)
            return False, RuntimeError(message)
    return True, None

passed, error = check_tf_version()

if passed:
    from .model import KerasModel
    from .estimator import TFEstimator
    from .tf_optimizer import TFOptimizer
    from .tf_dataset import TFDataset
    from .zoo_optimizer import ZooOptimizer
    from .tf_predictor import TFPredictor
    from .tfnet import TFNet
else:
    CLASSES_WITH_MAGIC_METHODS = (str(), object, float(), dict())

    # Combines all magic methods I can think of.
    MAGIC_METHODS_TO_CHANGE = set()
    for i in CLASSES_WITH_MAGIC_METHODS:
        MAGIC_METHODS_TO_CHANGE |= set(dir(i))
    MAGIC_METHODS_TO_CHANGE.add('__call__')
    # __init__ and __new__ must not raise an UnusableObjectError
    # otherwise it would raise error even on creation of objects.
    MAGIC_METHODS_TO_CHANGE -= {'__class__', '__init__', '__new__'}

    def error_func(*args, **kwargs):
        """(nearly) all magic methods will be set to this function."""
        raise error

    class UnusableClass(object):
        def __init__(*args, **kwargs):
            pass

    for i in MAGIC_METHODS_TO_CHANGE:
        setattr(UnusableClass, i, error_func)

    KerasModel = UnusableClass
    TFEstimator = UnusableClass
    TFOptimizer = UnusableClass
    TFDataset = UnusableClass
    ZooOptimizer = UnusableClass
    TFPredictor = UnusableClass
    TFNet = UnusableClass


text:
namespace silifuzz {

namespace {
ABSL_CONST_INIT absl::once_flag global_init_once_;
}  // namespace

Subprocess::Subprocess(const Options& options)
    : child_pid_(-1), child_stdout_(-1), options_(options) {
  absl::call_once(global_init_once_, GlobalInit);
}

Subprocess::~Subprocess() {
  if (child_stdout_ != -1) {
    close(child_stdout_);
  }
}

absl::Status Subprocess::Start(const std::vector<std::string>& argv) {
  VLOG_INFO(1, "Running ", absl::StrJoin(argv, " "));
  // Note that we assume that there are no other threads, thus we don't have to
  // do crazy stuff like using socket pairs or avoiding libc locks.

  // [0] is read end, [1] is write end.
  int stdout_pipe[2] = {-1, -1};
  CHECK_NE(pipe(stdout_pipe), -1);

  auto argv_exec = std::make_unique<const char*[]>(argv.size() + 1);
  for (int argc = 0; argc < argv.size(); ++argc) {
    argv_exec[argc] = argv[argc].c_str();
  }
  argv_exec[argv.size()] = nullptr;
  child_pid_ = vfork();
  if (child_pid_ == -1) {
    return absl::InternalError(absl::StrCat("vfork: ", strerror(errno)));
  }

  if (child_pid_ == 0) {
    // We are the child.
    for (const auto& r : options_.rlimit_tuples_) {
      struct rlimit lim = {r.soft_limit, r.hard_limit};
      CHECK_EQ(setrlimit(r.resource, &lim), 0);
    }
    for (const auto& i : options_.itimer_vals_) {
      CHECK_EQ(setitimer(i.which, &i.value, nullptr), 0);
    }
    if (options_.disable_aslr_) {
      int current_persona = personality(0xffffffff);
      if (personality(current_persona | ADDR_NO_RANDOMIZE) == -1) {
        ASS_LOG_FATAL("personality errno =  ", ErrnoStr(errno));
      }
    }
    if (options_.parent_death_signal_ > 0) {
      CHECK_EQ(prctl(PR_SET_PDEATHSIG, options_.parent_death_signal_), 0);
    }
    dup2(stdout_pipe[1], STDOUT_FILENO);
    switch (options_.map_stderr_) {
      case kNoMapping:
        // Same stderr as the parent.
        break;
      case kMapToStdout:
        dup2(stdout_pipe[1], STDERR_FILENO);
        break;
      case kMapToDevNull: {
        int dev_null = open("/dev/null", O_RDWR | O_APPEND);
        CHECK_NE(dev_null, -1);
        CHECK_GE(dup2(dev_null, STDERR_FILENO), 0);
        close(dev_null);
        break;
      }
    }

    close(stdout_pipe[0]);
    close(stdout_pipe[1]);

    execv(argv_exec[0], const_cast<char**>(argv_exec.get()));
    // Can only reach here if exec didn't succeed.

    // Write directly to STDERR_FILENO to avoid stdio code paths that may do
    // stuff that is unsafe here.
    write(STDERR_FILENO, argv_exec[0], strlen(argv_exec[0]));
    const char* message =
        ": program not found or is not executable\n"
        "Please specify a program using absolute path.\n";
    write(STDERR_FILENO, message, strlen(message));

    // Must use _exit() rather than exit() to avoid flushing output buffers
    // that will also be flushed by the parent.
    _exit(1);
    __builtin_unreachable();
  } else {
    // Parent
    close(stdout_pipe[1]);
    child_stdout_ = stdout_pipe[0];
    return absl::OkStatus();
  }
}

int Subprocess::Communicate(std::string* stdout_output) {
  if (child_pid_ == -1 || child_stdout_ == -1) {
    LOG_FATAL("Must call Start() first.");
  }

  while (true) {
    char buffer[4096] = {0};
    int n = read(child_stdout_, buffer, sizeof(buffer));
    if (n == 0) {
      // We've reached a EOF.
      break;
    }
    if (n > 0) {
      stdout_output->append(buffer, n);
    } else {
      if (errno == EINTR) {
        continue;
      }
      LOG_FATAL("read: ", strerror(errno));
    }
  }
  close(child_stdout_);
  child_stdout_ = -1;

  int status = 0;
  while (waitpid(child_pid_, &status, 0) == -1) {
    if (errno == EINTR) {
      continue;
    }
    if (errno == ECHILD) {
      // Someone else snagged the status before we could
      break;
    } else {
      LOG_FATAL("waitpid: ", strerror(errno));
    }
  }

  child_pid_ = -1;
  return status;
}

void Subprocess::GlobalInit() {
  // Make sure SIGPIPE is disabled so that if the child dies it doesn't kill us.
  IgnoreSignal(SIGPIPE);
}

}  // namespace silifuzz


text:
package ru.job4j.profession;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * This class tests class Profession.
 *
 * @author Kucykh Vasily (mailto:basil135@mail.ru)
 * @version $Id$
 * @since 11.04.2017
 */
public class ProfessionTest {

    /**
     * This method tests method getName.
     */
    @Test
    public void whenNameJohnThenGetNameJohn() {

        Profession man = new Profession("John", "MSU", "doctor", 30);

        String expectedValue = "John";
        String actualValue = man.getName();

        assertThat(actualValue, is(expectedValue));

    }

    /**
     * This metho tests method getDiploma.
     */
    @Test
    public void whenDiplomaMSUThenGetDiplomaMSU() {

        Profession man = new Profession("John", "MSU", "doctor", 30);

        String expectedValue = "MSU";
        String actualValue = man.getDiploma();

        assertThat(actualValue, is(expectedValue));

    }

    /**
     * This method tests method getSpeciality.
     */
    @Test
    public void whenSpecialityDoctorThenGetSpecialityDoctor() {

        Profession man = new Profession("John", "MSU", "doctor", 30);

        String expectedValue = "doctor";
        String actualValue = man.getSpeciality();

        assertThat(actualValue, is(expectedValue));

    }

    /**
     * This method tests method getWorkExp.
     */
    @Test
    public void whenWorkExpThirtyThenGetWorkExpThirty() {

        Profession man = new Profession("John", "MSU", "doctor", 30);

        int expectedValue = 30;
        int actualValue = man.getWorkExp();

        assertThat(actualValue, is(expectedValue));

    }

}


text:
package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/appleboy/easyssh-proxy"
)

var (
	errMissingHost          = errors.New("Error: missing server host")
	errMissingPasswordOrKey = errors.New("Error: can't connect without a private SSH key or password")
	errCommandTimeOut       = errors.New("Error: command timeout")
	errSetPasswordandKey    = errors.New("can't set password and key at the same time")
)

type (
	// Config for the plugin.
	Config struct {
		Key               string
		Passphrase        string
		KeyPath           string
		Username          string
		Password          string
		Host              []string
		Port              int
		Fingerprint       string
		Timeout           time.Duration
		CommandTimeout    time.Duration
		Script            []string
		ScriptStop        bool
		Envs              []string
		Proxy             easyssh.DefaultConfig
		Debug             bool
		Sync              bool
		Ciphers           []string
		UseInsecureCipher bool
	}

	// Plugin structure
	Plugin struct {
		Config Config
		Writer io.Writer
	}
)

func escapeArg(arg string) string {
	return "'" + strings.Replace(arg, "'", `'\''`, -1) + "'"
}

func (p Plugin) hostPort(host string) (string, string) {
	hosts := strings.Split(host, ":")
	port := strconv.Itoa(p.Config.Port)
	if len(hosts) > 1 {
		host = hosts[0]
		port = hosts[1]
	}

	return host, port
}

func (p Plugin) exec(host string, wg *sync.WaitGroup, errChannel chan error) {
	host, port := p.hostPort(host)
	// Create MakeConfig instance with remote username, server address and path to private key.
	ssh := &easyssh.MakeConfig{
		Server:            host,
		User:              p.Config.Username,
		Password:          p.Config.Password,
		Port:              port,
		Key:               p.Config.Key,
		KeyPath:           p.Config.KeyPath,
		Passphrase:        p.Config.Passphrase,
		Timeout:           p.Config.Timeout,
		Ciphers:           p.Config.Ciphers,
		Fingerprint:       p.Config.Fingerprint,
		UseInsecureCipher: p.Config.UseInsecureCipher,
		Proxy: easyssh.DefaultConfig{
			Server:            p.Config.Proxy.Server,
			User:              p.Config.Proxy.User,
			Password:          p.Config.Proxy.Password,
			Port:              p.Config.Proxy.Port,
			Key:               p.Config.Proxy.Key,
			KeyPath:           p.Config.Proxy.KeyPath,
			Passphrase:        p.Config.Proxy.Passphrase,
			Timeout:           p.Config.Proxy.Timeout,
			Ciphers:           p.Config.Proxy.Ciphers,
			Fingerprint:       p.Config.Proxy.Fingerprint,
			UseInsecureCipher: p.Config.Proxy.UseInsecureCipher,
		},
	}

	p.log(host, "======CMD======")
	p.log(host, strings.Join(p.Config.Script, "\n"))
	p.log(host, "======END======")

	env := []string{}
	for _, key := range p.Config.Envs {
		key = strings.ToUpper(key)
		if val, found := os.LookupEnv(key); found {
			env = append(env, key+"="+escapeArg(val))
		}
	}

	p.Config.Script = append(env, p.scriptCommands()...)

	if p.Config.Debug {
		p.log(host, "======ENV======")
		p.log(host, strings.Join(env, "\n"))
		p.log(host, "======END======")
	}

	stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream(strings.Join(p.Config.Script, "\n"), p.Config.CommandTimeout)
	if err != nil {
		errChannel <- err
	} else {
		// read from the output channel until the done signal is passed
		isTimeout := true
	loop:
		for {
			select {
			case isTimeout = <-doneChan:
				break loop
			case outline := <-stdoutChan:
				p.log(host, "out:", outline)
			case errline := <-stderrChan:
				p.log(host, "err:", errline)
			case err = <-errChan:
			}
		}

		// get exit code or command error.
		if err != nil {
			errChannel <- err
		}

		// command time out
		if !isTimeout {
			errChannel <- errCommandTimeOut
		}
	}

	wg.Done()
}

func (p Plugin) log(host string, message ...interface{}) {
	if p.Writer == nil {
		p.Writer = os.Stdout
	}
	if count := len(p.Config.Host); count == 1 {
		fmt.Fprintf(p.Writer, "%s", fmt.Sprintln(message...))
	} else {
		fmt.Fprintf(p.Writer, "%s: %s", host, fmt.Sprintln(message...))
	}
}

// Exec executes the plugin.
func (p Plugin) Exec() error {
	if len(p.Config.Host) == 0 {
		return errMissingHost
	}

	if len(p.Config.Key) == 0 && len(p.Config.Password) == 0 && len(p.Config.KeyPath) == 0 {
		return errMissingPasswordOrKey
	}

	if len(p.Config.Key) != 0 && len(p.Config.Password) != 0 {
		return errSetPasswordandKey
	}

	wg := sync.WaitGroup{}
	wg.Add(len(p.Config.Host))
	errChannel := make(chan error)
	finished := make(chan struct{})
	for _, host := range p.Config.Host {
		if p.Config.Sync {
			p.exec(host, &wg, errChannel)
		} else {
			go p.exec(host, &wg, errChannel)
		}
	}

	go func() {
		wg.Wait()
		close(finished)
	}()

	select {
	case <-finished:
	case err := <-errChannel:
		if err != nil {
			return err
		}
	}

	fmt.Println("==============================================")
	fmt.Println("✅ Successfully executed commands to all host.")
	fmt.Println("==============================================")

	return nil
}

func (p Plugin) scriptCommands() []string {
	scripts := []string{}

	for _, cmd := range p.Config.Script {
		if p.Config.ScriptStop {
			scripts = append(scripts, strings.Split(cmd, "\n")...)
		} else {
			scripts = append(scripts, cmd)
		}
	}

	commands := make([]string, 0)

	for _, cmd := range scripts {
		cmd = strings.TrimSpace(cmd)
		if strings.TrimSpace(cmd) == "" {
			continue
		}
		commands = append(commands, cmd)
		if p.Config.ScriptStop && cmd[(len(cmd)-1):] != "\\" {
			commands = append(commands, "DRONE_SSH_PREV_COMMAND_EXIT_CODE=$? ; if [ $DRONE_SSH_PREV_COMMAND_EXIT_CODE -ne 0 ]; then exit $DRONE_SSH_PREV_COMMAND_EXIT_CODE; fi;")
		}
	}

	return commands
}


text:
using System.Collections.Generic;

namespace Palwyn.Domain.Infrastructure.Tests.Helpers.Values
{
	/// <summary>
	/// A wrapper to provide a strongly typed generic List(ValueDictionary)
	/// </summary>
	class ValueTestList : List<ValueTestDictionary>
	{
	}
}


text:
require_relative "test_helper"

class MessageTest < Minitest::Test
  def test_default
    MessageMailer.welcome.deliver_now
    assert_nil ahoy_message
  end

  def test_false
    MessageMailer.other.deliver_now
    assert_nil ahoy_message
  end

  def test_prevent_delivery
    MessageMailer.no_deliver.deliver_now
    assert_nil ahoy_message
  end

  def test_default_false
    with_default(message: false) do
      MessageMailer.welcome.deliver_now
      assert_nil ahoy_message
    end
  end

  def test_default_false_track
    with_default(message: false) do
      MessageMailer.other2.deliver_now
      assert ahoy_message
    end
  end

  def test_ahoy_message
    message = MessageMailer.other2.deliver_now
    assert_equal message.ahoy_message, ahoy_message
    assert_nil ahoy_message.token
  end
end


text:
'use strict';

const { objectType } = require('nexus');

module.exports = ({ strapi }) => {
  const { PAGINATION_TYPE_NAME } = strapi.plugin('graphql').service('constants');

  return {
    /**
     * Type definition for a Pagination object
     * @type {NexusObjectTypeDef}
     */
    Pagination: objectType({
      name: PAGINATION_TYPE_NAME,

      definition(t) {
        t.nonNull.int('total');
        t.nonNull.int('page');
        t.nonNull.int('pageSize');
        t.nonNull.int('pageCount');
      },
    }),
  };
};


text:
import os, sys, json, requests, time
import subprocess, argparse, getpass
import datetime as dt
from praxyk_exception import PraxykException
from base import PraxykBase
from results import Results

# @info - This class represents a single Praxyk user and the actions that can be made that are directly
#         related to each user. That means this class can be used to set user info then post that info to
#         create a new user, or you can just set the user_id and auth_token and use the get() function to
#         get all of the rest of the info on a user. Deletion a updates are also supported through put() and
#         update()
class Transaction(PraxykBase) :

    def __init__(self, trans_id=None, name=None, user_id=None, status=None, created_at=None,
                 finished_at=None, command_url=None, service=None, model=None, uploads_total=None,
                 uploads_success=None, uploads_failed=None, size_total_KB=None, **kwargs) :
        super(Transaction, self).__init__(**kwargs)
        self.trans_id = trans_id
        self.name = name
        self.user_id = user_id
        self.status = status
        self.created_at = created_at
        self.finished_at = finished_at
        self.command_url = command_url
        self.service = service
        self.model = model
        self.uploads_total = uploads_total
        self.uploads_success = uploads_success
        self.uploads_failed = uploads_failed
        self.size_total_KB = size_total_KB

    def get(self) :
        if not self.trans_id : return None
        payload = {'token' : self.auth_token}
        try :
            route = self.TRANSACTIONS_ROUTE+str(self.trans_id)
            response = super(Transaction, self).get(route, payload)
            if response :
                self.transaction = response['transaction']
                self.trans_id = self.transaction.get('trans_id', None)
                self.name = self.transaction.get('name', None)
                self.user_id = self.transaction.get('user_id', None)
                self.status = self.transaction.get('status', None)
                self.created_at = self.transaction.get('created_at', None)
                self.finished_at = self.transaction.get('finished_at', None)
                self.command_url = self.transaction.get('command_url', None)
                self.service = self.transaction.get('service', None)
                self.model = self.transaction.get('model', None)
                self.uploads_total = self.transaction.get('uploads_total', None)
                self.uploads_success = self.transaction.get('uploads_success', None)
                self.uploads_failed = self.transaction.get('uploads_failed', None)
                self.size_total_KB = self.transaction.get('size_total_KB', None)
                return self

        except Exception as e:
            raise PraxykException('Error: malformed response from GET request for transaction \'%s\'. Unable to load result dictionary' % self.trans_id)
        return {}

    # @info - wait for the transaction to either finish or fail, sleeps for interval seconds, timesout at timeout seconds
    #         The optional argument @callback is a function that we call during each interval with the status of the transction,
    #         so the function should take one argument which is the transction
    def spin(self, interval=1, timeout=60, callback=None) :
        length = 0
        if interval <= 0 : return False
        while self.status in ['active', 'new'] and length <= timeout:
            time.sleep(interval)
            length += interval
            self.get()
            if callback : callback(self)
        return self.status in ['finished', 'failed']

    # @info - return the results object associated with this transction
    def results(self, *args, **kwargs) :
        return Results(trans_id=self.trans_id, auth_token=self.auth_token, caller=self.caller,
                       local=self.local, port=self.port, *args, **kwargs)

    def put(self, cancel=False):
        if self.trans_id and cancel:
            try:
                payload = {'token' : self.auth_token, 'cancel' : cancel}
                response = super(Transaction, self).put(self.TRANSACTIONS_ROUTE+str(self.trans_id), payload)
                if response:
                    self.transaction = response['transaction']
                    self.trans_id = self.transaction.get('trans_id', None)
                    self.command_url = self.transaction.get('command_url', None)
                    self.data_url = self.transaction.get('data_url', None)
                    self.results_url = self.transaction.get('results_url', None)
                    self.status = self.transaction.get('status', None)
                    self.service = self.transaction.get('service', None)
                    self.model = self.transaction.get('model', None)
                    self.created_at = self.transaction.get('created_at', None)
                    self.uploads_total = self.transaction.get('uploads_total', None)
                    self.uploads_success = self.transaction.get('uploads_success', None)
                    self.uploads_failed = self.transaction.get('uploads_failed', None)
                    self.size_total_KB = self.transaction.get('size_total_KB', None)
                    return self.transaction
            except:
                raise PraxykException('Error with response received from call to \'put\', updating transaction \'%s\'' % self.trans_id)

    def to_dict(self) :
        try:
            base_dict = super(Transaction, self).to_dict()
            transaction_dict = {
                    'name' : self.name,
                    'status' : self.status,
                    'trans_id' : self.trans_id,
                    'user_id' : self.user_id,
                    'created_at' : self.created_at,
                    'finished_at' : self.finished_at,
                    'command_url' : self.command_url,
                    'service' : self.service,
                    'model' : self.model,
                    'uploads_total' : self.uploads_total,
                    'uploads_success' : self.uploads_success,
                    'uploads_failed' : self.uploads_failed,
                    'size_total_KB' : self.size_total_KB,
            }
            base_dict.update(transaction_dict)
            return base_dict
        except Exception as e:
            raise PraxykException('Error converting transaction to dictionary in call to \'to_dict\'', errors=self)


text:
import { McuParams, Xyz } from "farmbot";
import { transform } from "lodash";

interface AxisStatus {
  axis: Xyz;
  disabled: boolean;
}

/** Farmbot prevents itself from ramming into walls via two mechanisms:
 *
 *  - Encoders (count steps) or stall detection (motor feedback)
 *  - Limit switches (detect collision with end switch)
 *
 * If neither of these are enabled, FarmBot can do some pretty dangerous things,
 * such as smashing tools and ramming into tool bays.
 *
 * This function returns a 2 dimensional array describing whether or not
 * a particular axis has at least one of the precautions in place.
 * Useful for checking if it is safe to proceed with certain actions that
 * could damage the bot.
 */
export function axisTrackingStatus(
  mcuParams: McuParams, disableEncoderUse = false,
): AxisStatus[] {
  const stats = enabledAxisMap(mcuParams, disableEncoderUse);
  const mapper = (a: keyof typeof stats) => ({ axis: a, disabled: !stats[a] });
  return Object.keys(stats).map(mapper);
}

export function enabledAxisMap(
  mcuParams: McuParams, disableEncoderUse = false,
): Record<Xyz, boolean> {
  const encoderOrStallUseEnabled = {
    x: !disableEncoderUse && mcuParams.encoder_enabled_x,
    y: !disableEncoderUse && mcuParams.encoder_enabled_y,
    z: !disableEncoderUse && mcuParams.encoder_enabled_z,
  };
  return {
    x: !!(encoderOrStallUseEnabled.x || mcuParams.movement_enable_endpoints_x),
    y: !!(encoderOrStallUseEnabled.y || mcuParams.movement_enable_endpoints_y),
    z: !!(encoderOrStallUseEnabled.z || mcuParams.movement_enable_endpoints_z)
  };
}

export function disabledAxisMap(h: McuParams): Record<Xyz, boolean> {
  return transform<boolean, Record<Xyz, boolean>>(
    enabledAxisMap(h),
    (d: Record<Xyz, boolean>, value: boolean, key: Xyz) => { d[key] = !value; },
    { x: false, y: false, z: false });
}


text:
import { IterableX } from '../../iterable';
import { _while as whileStatic } from '../../iterable/while';

IterableX['while'] = whileStatic;

export declare namespace iterable {
  let _while: typeof whileStatic;
}

declare module '../../iterable' {
  namespace IterableX {
    export { whileStatic as while };
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BaseAnimationController (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.graphics.g3d.utils

Class BaseAnimationController

java.lang.Object

com.badlogic.gdx.graphics.g3d.utils.BaseAnimationController

Direct Known Subclasses:

AnimationController

public class BaseAnimationController
extends java.lang.Object

Base class for applying one or more Animations to a ModelInstance. This class only applies the actual
 Node transformations, it does not manage animations or keep track of animation states. See AnimationController
 for an implementation of this class which does manage animations.

Author:

Xoppa

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
BaseAnimationController.Transform

Field Summary

Fields

Modifier and Type
Field and Description

ModelInstance
target

The ModelInstance on which the animations are being performed.

Constructor Summary

Constructors

Constructor and Description

BaseAnimationController(ModelInstance target)

Construct a new BaseAnimationController.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

protected void
apply(Animation animation,
     float time,
     float weight)

Apply an animation, must be called between {begin() and {end().

protected void
applyAnimation(Animation animation,
              float time)

Apply a single animation to the ModelInstance and update the it to reflect the changes.

protected static void
applyAnimation(ObjectMap<Node,BaseAnimationController.Transform> out,
              Pool<BaseAnimationController.Transform> pool,
              float alpha,
              Animation animation,
              float time)

Helper method to apply one animation to either an objectmap for blending or directly to the bones.

protected void
applyAnimations(Animation anim1,
               float time1,
               Animation anim2,
               float time2,
               float weight)

Apply two animations, blending the second onto to first using weight.

protected void
begin()

Begin applying multiple animations to the instance, must followed by one or more calls to {
 apply(Animation, float, float) and finally {end().

protected void
end()

End applying multiple animations to the instance and update it to reflect the changes.

protected void
removeAnimation(Animation animation)

Remove the specified animation, by marking the affected nodes as not animated.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

target

public final ModelInstance target

The ModelInstance on which the animations are being performed.

Constructor Detail

BaseAnimationController

public BaseAnimationController(ModelInstance target)

Construct a new BaseAnimationController.

Parameters:

target - The ModelInstance on which the animations are being performed.

Method Detail

begin

protected void begin()

Begin applying multiple animations to the instance, must followed by one or more calls to {
 apply(Animation, float, float) and finally {end().

apply

protected void apply(Animation animation,
                     float time,
                     float weight)

Apply an animation, must be called between {begin() and {end().

Parameters:

weight - The blend weight of this animation relative to the previous applied animations.

end

protected void end()

End applying multiple animations to the instance and update it to reflect the changes.

applyAnimation

protected void applyAnimation(Animation animation,
                              float time)

Apply a single animation to the ModelInstance and update the it to reflect the changes.

applyAnimations

protected void applyAnimations(Animation anim1,
                               float time1,
                               Animation anim2,
                               float time2,
                               float weight)

Apply two animations, blending the second onto to first using weight.

applyAnimation

protected static void applyAnimation(ObjectMap<Node,BaseAnimationController.Transform> out,
                                     Pool<BaseAnimationController.Transform> pool,
                                     float alpha,
                                     Animation animation,
                                     float time)

Helper method to apply one animation to either an objectmap for blending or directly to the bones.

removeAnimation

protected void removeAnimation(Animation animation)

Remove the specified animation, by marking the affected nodes as not animated. When switching animation, this should be call
 prior to applyAnimation(s).

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)