text:
<?php

use \Paperwork\UserRegistrator;

/**
 * Class UserController
 *
 * Provides user login and registration functionality.
 *
 * @todo provide documentation for every action.
 *       Clean up the commented legacy code. We use git for history.
 */
class UserController extends BaseController
{

    private $userRegistrator;
    private $isLdap;

    public function __construct(UserRegistrator $userRegistrator)
    {
        $this->userRegistrator = $userRegistrator;
        $this->isLdap          = PaperworkHelpers::isLdap();
    }

    public function showRegistrationForm()
    {
        if(Auth::user()) {
            $admin = User::find(Auth::user()->id)->is_admin;
        }else{
            $admin = false;
        }

        return View::make('user.register')->with('admin', $admin);
    }

    /**
     * Register action.
     *
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function register()
    {
        $validator = $this->getRegistrationValidator();

        if ($validator->passes()) {
            //only allow users to register who actually have a valid ldap account
            if ($this->isLdap) {
                $creds               = $this->getLoginCredentials();
                $creds['isRegister'] = true;
                if (!Auth::validate($creds)) {
                    return Redirect::back()
                                   ->withInput()
                                   ->withErrors(["password" => [Lang::get('messages.invalid_credentials')]]);
                }
            }
            //if we are using ldap and auto registration, the user will have been created in the Auth::attemp call above
            //thus, we need to just load the user using eloquent and not create a new one.
            if ($this->isLdap && Config::get('ldap.autoRegister')) {
                $user = User::query()
                            ->where('username', Input::get('username'))
                            ->first();
            } else {
                $user =
                  $this->userRegistrator->registerUser(Input::except('_token',
                    'password_confirmation', 'ui_language', 'admin_creator'),
                    Input::get('ui_language'));
            }

            if(Input::get('admin_creator') == true) {
                return Redirect::route("admin/console");
            }else if ($user && !Request::ajax()) {
                Auth::login($user);

                Session::put('ui_language', Input::get('ui_language'));

                return Redirect::route("/");
            }else if($user) {
                return PaperworkHelpers::apiResponse(PaperworkHelpers::STATUS_SUCCESS, array());
            }

            if(!Request::ajax()) {
                return Redirect::back()
                           ->withErrors(["password" => [Lang::get('messages.account_creation_failed')]]);
            }else{
                return Response::json(array('html' => View::make('partials/registration-form', array('password' => Lang::get('messages.account_creation_failed'))), 'input' => Input::all()), 400);

            }
        } else {
            if(!Request::ajax()) {
                return Redirect::back()->withInput()->withErrors($validator);
            }else{
                return Response::json(array('html' => View::make('partials/registration-form')->withErrors($validator)->render(), 'input' => Input::all()), 400);
            }
        }
    }

    public function login()
    {
        $validator = $this->getLoginValidator();

        if ($validator->passes()) {
            $credentials = $this->getLoginCredentials();

            if (Auth::attempt($credentials, Input::has('remember_me'))) {
                $settings =
                  Setting::where('user_id', '=', Auth::user()->id)->first();

                Session::put('ui_language', $settings->ui_language);

                return Redirect::route("/");
            }

            return Redirect::back()
                           ->withErrors(["password" => [Lang::get('messages.invalid_credentials')]]);

        } else {
            return Redirect::back()->withInput()->withErrors($validator);
        }
    }

    public function showLoginForm()
    {
        return View::make('user/login');
    }

    public function checkSandstormUsers()
    {

      // get permission via HTTP_X_SANDSTORM header
      $sandstorm_permissions = $_SERVER[ 'HTTP_X_SANDSTORM_PERMISSIONS'];
      // Only when we are admin, we check and create users
      if ($sandstorm_permissions == "admin,write,read") {
        // check for admin user
        if (User::where('username', '=', 'sandstorm_admin')->count() == 0) {
          $sandstorm_admin = User::create(Input::except('_token', 'password_confirmation', 'ui_language'));
          if ($sandstorm_admin) {
            //make the first user an admin
            $sandstorm_admin->firstname = "sandstorm_admin";
            $sandstorm_admin->lastname  = " ";
            $sandstorm_admin->username = "sandstorm_admin";
            $sandstorm_admin->password = "sandstorm_admin";
            $sandstorm_admin->is_admin = 1;
            $sandstorm_admin->save();
            $setting_sandstorm_admin = Setting::create(['ui_language' => 'en' , 'user_id' => $sandstorm_admin->id]);
          }
        } else {
          $sandstorm_admin = User::where('username', '=', 'sandstorm_admin');
        }
        // Then the read & write  user
        if (User::where('username', '=', 'sandstorm_readwrite')->count() == 0) {
          $sandstorm_readwrite = User::create(Input::except('_token', 'password_confirmation', 'ui_language'));
          if ($sandstorm_readwrite) {
            $sandstorm_readwrite->firstname = "sandstorm_readwrite";
            $sandstorm_readwrite->lastname  = " ";
            $sandstorm_readwrite->username = "sandstorm_readwrite";
            $sandstorm_readwrite->password = "sandstorm_readwrite";
            $sandstorm_readwrite->save();
            $setting_sandstorm_readwrite = Setting::create(['ui_language' => 'en' , 'user_id' => $sandstorm_readwrite->id]);
          }
        } else {
          $sandstorm_readwrite = User::where('username', '=', 'sandstorm_readwrite');
        }
        // Then the read only  user
        if (User::where('username', '=', 'sandstorm_readonly')->count() == 0) {
          $sandstorm_readonly = User::create(Input::except('_token', 'password_confirmation', 'ui_language'));
          if ($sandstorm_readonly) {
            $sandstorm_readonly->firstname = "sandstorm_readonly";
            $sandstorm_readonly->lastname  = " ";
            $sandstorm_readonly->username = "sandstorm_readonly";
            $sandstorm_readonly->password = "sandstorm_readonly";
            $sandstorm_readonly->save();
            $setting_sandstorm_readonly = Setting::create(['ui_language' => 'en' , 'user_id' => $sandstorm_readonly->id]);
          }
        } else {
          $sandstorm_readonly = User::where('username', '=', 'sandstorm_readonly');
        }
        // Now that the required users are there we create the default
        if ((Notebook::all()->count() == 0) && (Tag::all()->count() == 0) && (Note::all()->count() == 0)) {
          // Notebook ...
          $notebookCreate = new Notebook();
          $notebookCreate->title = Lang::get('notebooks.welcome_notebook_title');
          $notebookCreate->save();
          $notebookCreate->users()->attach($sandstorm_readonly->id, ['umask' => PaperworkHelpers::UMASK_READONLY]);
          $notebookCreate->users()->attach($sandstorm_readwrite->id, ['umask' => PaperworkHelpers::UMASK_READWRITE]);
          $notebookCreate->users()->attach($sandstorm_admin->id, ['umask' => PaperworkHelpers::UMASK_OWNER]);
          // Tag ...
          $tagCreate = new Tag();
          $tagCreate->title = Lang::get('notebooks.welcome_note_tag');
          $tagCreate->visibility = 1;
          $tagCreate->user_id=$sandstorm_admin->id;
          $tagCreate->save();
          // Note ...
          $noteCreate = new Note;
          $versionCreate = new Version([
            'title'           => Lang::get('notebooks.welcome_note_title'),
            'content'         => Lang::get('notebooks.welcome_note_content'),
            'content_preview' => mb_substr(strip_tags(Lang::get('notebooks.welcome_note_content')), 0, 255),
            'user_id'         => $sandstorm_admin->id
          ]);
          $versionCreate->save();
          $noteCreate->version()->associate($versionCreate);
          $noteCreate->notebook_id = $notebookCreate->id;
          $noteCreate->save();
          $noteCreate->users()->attach($sandstorm_readonly->id, ['umask' => PaperworkHelpers::UMASK_READONLY]);
          $noteCreate->users()->attach($sandstorm_readwrite->id, ['umask' => PaperworkHelpers::UMASK_READWRITE]);
          $noteCreate->users()->attach($sandstorm_admin->id, ['umask' => PaperworkHelpers::UMASK_OWNER]);
          $noteCreate->tags()->sync([$tagCreate->id]);
        }
      }

      // login
      if ($sandstorm_permissions == "read") {
        $credentials = ["username" => "sandstorm_readonly", "password" => "sandstorm_readonly"];
      }
      if ($sandstorm_permissions == "write,read") {
        $credentials = ["username" => "sandstorm_readwrite", "password" => "sandstorm_readwrite"];
      }
      if ($sandstorm_permissions == "admin,write,read") {
        $credentials = ["username" => "sandstorm_admin", "password" => "sandstorm_admin"];
      }
      if (Auth::attempt($credentials)) {
        $settings = Setting::where('user_id', '=', Auth::user()->id)->first();
        Session::put('ui_language', $settings->ui_language);
        return Redirect::route("/");
      }

    }

    protected function isPostRequest()
    {
        return Input::server("REQUEST_METHOD") == "POST";
    }

    protected function getRegistrationValidator()
    {
        $attributes = ["username" => "email address"];
        $validator  = Validator::make(Input::all(), [
          "username"              => $this->isLdap ? "required|unique:users" :
            "required|email|unique:users",
          "password"              => "required|min:5|confirmed",
          "password_confirmation" => "required",
          "firstname"             => "required|name_validator",
          "lastname"              => "required|name_validator"
        ]);

        $validator->setAttributeNames($attributes);

        return $validator;
    }

    protected function getLoginValidator()
    {
        return Validator::make(Input::all(), [
          "username" => $this->isLdap ? "required" : "required|email",
          "password" => "required"
        ]);
    }

    protected function getProfileValidator()
    {
        return Validator::make(Input::all(), [
          "password"  => "min:5|confirmed",
          "firstname" => "required|name_validator",
          "lastname"  => "required|name_validator"
        ]);
    }

    protected function getSettingsValidator()
    {
        return Validator::make(Input::all(), ["ui_language" => "required"]);
    }

    protected function getLoginCredentials()
    {
        return [
          "username" => Input::get("username"),
          "password" => Input::get("password")
        ];
    }

    public function profile()
    {
        $user = User::find(Auth::user()->id);

        if ($this->isPostRequest()) {
            $validator = $this->getProfileValidator();

            if ($validator->passes()) {
                $user->firstname = Input::get('firstname');
                $user->lastname  = Input::get('lastname');

                $passwd = Input::get('password');

                if (!is_null($passwd) && trim($passwd) != "") {
                    $user->password = Input::get('password');
                }

                if (!$user->save()) {
                    return Redirect::back()
                                   ->withErrors(["password" => [Lang::get('messages.account_update_failed')]]);
                }
            } else {
                return Redirect::back()->withInput()->withErrors($validator);
            }
        }

        return View::make("user/profile")->with('user', $user);
    }

    public function settings()
    {
        $user     = User::find(Auth::user()->id);
        $settings = Setting::where('user_id', '=', $user->id)->first();

        if ($this->isPostRequest()) {
            $validator = $this->getSettingsValidator();

            if ($validator->passes()) {
                $settings->ui_language = Input::get('ui_language');
                $document_languages    = Input::get('document_languages');

                // TODO: I think this whole thing could be done nicer...
                DB::Table('language_user')
                  ->where('user_id', '=', $user->id)
                  ->delete();

                if (!is_null($document_languages)) {
                    foreach ($document_languages as $document_lang) {
                        $foundLanguage =
                          Language::where('language_code', '=', $document_lang)
                                  ->first();
                        if (!is_null($foundLanguage)) {
                            $user->languages()->save($foundLanguage);
                        }
                    }
                }

                Session::put('ui_language', $settings->ui_language);
                App::setLocale($settings->ui_language);
            } else {
                return Redirect::back()->withInput()->withErrors($validator);
            }
        }

        $languages             = [];
        $userDocumentLanguages = $user->languages()->get();
        foreach ($userDocumentLanguages as $userDocumentLanguage) {
            $languages[$userDocumentLanguage->language_code] = true;
        }

        return View::make("user/settings")
                   ->with('settings', $settings)
                   ->with('languages', $languages);

        // TODO:
        // Think about whether we need to run an OCRing process in background, if document languages selection changed.
    }

    public function request()
    {
        if (Config::get('paperwork.forgot_password')) {
            if ($this->isPostRequest()) {
                $response = $this->getPasswordRemindResponse();
                if ($this->isInvalidUser($response)) {
                    return Redirect::back()
                                   ->withInput()
                                   ->with("error", Lang::get($response));
                }

                return Redirect::back()->with("status", Lang::get($response));
            }

            return View::make("user/request");
        } else {
            return View::make("404");
        }
    }

    // TODO: Password reminders not working out of the box, since we don't have an "email" column.
    protected function getPasswordRemindResponse()
    {
        return Password::remind(Input::only("username"), function ($message) {
            $message->subject(Lang::get('keywords.password_reset_request'));
        });
    }

    protected function isInvalidUser($response)
    {
        return $response === Password::INVALID_USER;
    }

    public function reset($token)
    {
        if ($this->isPostRequest()) {
            $credentials =
              Input::only("username", "password", "password_confirmation") +
              compact("token");
            $response    = $this->resetPassword($credentials);
            if ($response === Password::PASSWORD_RESET) {
                return Redirect::route("user/profile");
            }

            return Redirect::back()
                           ->withInput()
                           ->with("error", Lang::get($response));
        }

        return View::make("user/reset", compact("token"));
    }

    protected function resetPassword($credentials)
    {
        return Password::reset($credentials, function ($user, $pass) {
            $user->password = Hash::make($pass);
            $user->save();
        });
    }

    public function help($topic = "index")
    {
        if ($topic[0] == '.') {
            $topic = "index";
        }

        $topic_path = $this->helpGenerateTopicPath($topic);

        if (is_null($topic_path)) {
            return View::make('404');
        }

        $topic_content = $this->helpGetAndPrepareContent($topic_path);

        return View::make("user/help")->with(['topic' => $topic_content]);
    }

    private function helpGenerateTopicPath($topic)
    {
        $topic_clean = str_replace('.', '/', $topic);

        $topic_path             =
          app_path() . '/help/' . $topic_clean . '.' . App::getLocale() . '.md';
        $topic_path_alternative =
          app_path() . '/help/' . $topic_clean . '/index.' . App::getLocale() .
          '.md';

        if (File::exists($topic_path)) {
            return $topic_path;
        } elseif (File::exists($topic_path_alternative)) {
            return $topic_path_alternative;
        } else {
            return null;
        }

    }

    private function helpGetAndPrepareContent($path)
    {
        $content = File::get($path);

        $conent_prepared =
          preg_replace_callback('/(\@(help|image))((.[A-Za-z0-9]+)+)/',
            function ($match) {
                if (is_null($match) || count($match) < 4) {
                    return $match;
                }
                $topic = ltrim($match[3], '.');
                if ($match[1] === "@help") {
                    return URL::route("user/help", $topic);
                } elseif ($match[1] === "@image") {
                    return url('/images/help/' . $topic);
                }
            }, $content);

        $pdown = new Parsedown();

        return $pdown->text($conent_prepared);
    }

    public function logout()
    {
        Auth::logout();
        Session::flush();

        return Redirect::route("user/login");
    }

    public function import()
    {
        if ($this->isPostRequest()) {
            if(Input::hasFile('enex')) {
                $notebookNew = with(new \Paperwork\Import\EvernoteImport())->import(Input::file('enex'));
                if($notebookNew[0]) {
                    return Redirect::route("user/settings")
                                   ->withErrors(["enex_file_success" => $notebookNew[1]]);
                }
                else {
                    return Redirect::route("user/settings")
                                   ->withErrors(["enex_file" => $notebookNew[1]]);
                }
            } else {
              return Redirect::route("user/settings")
                            ->withErrors(["enex_file" => "You must choose an ENEX file!"]);
            }
        } else {
          return Redirect::route("user/settings")
                        ->withErrors(["enex_file" => "Nothing selected!"]);
        }
    }

    public function export()
    {
        $file_content = "";
        $noteNumber   = 0;

        $notes = DB::table('notes')
                   ->join('note_user', function ($join) {
                       $join->on('notes.id', '=', 'note_user.note_id')
                            ->where('note_user.user_id', '=', Auth::user()->id)
                            ->where('note_user.umask', '=', '7');
                   })
                   ->join('notebooks', function ($join) {
                       $join->on('notes.notebook_id', '=', 'notebooks.id');
                   })
                   ->join('versions', function ($join) {
                       $join->on('notes.version_id', '=', 'versions.id');
                   })
                   ->select('notes.id', 'notebooks.title as notebook_title',
                     'versions.id as version_id', 'versions.title',
                     'versions.content', 'notes.created_at',
                     'notes.updated_at')
                   ->whereNull('notes.deleted_at')
                   ->whereNull('notebooks.deleted_at')
                   ->get();

        $noteCount = count($notes);
        foreach ($notes as $note) {
            $noteNumber++;
            $versionId = $note->version_id;
            $noteid    = $note->id;

            $noteArray = [
              'title'   => $note->title,
              'content' => $note->content,
              'created' => date('omd', strtotime($note->created_at)) . 'T' .
                           date('His', strtotime($note->created_at)) . 'Z',
              'updated' => date('omd', strtotime($note->updated_at)) . 'T' .
                           date('His', strtotime($note->updated_at)) . 'Z'
            ];

            $attachments = DB::table('attachment_version')
                             ->join('versions',
                               function ($join) use (&$versionId) {
                                   $join->on('attachment_version.version_id',
                                     '=', 'versions.id')
                                        ->where('versions.id', '=', $versionId);
                               })
                             ->join('attachments', function ($join) {
                                 $join->on('attachment_version.attachment_id',
                                   '=', 'attachments.id');
                             })
                             ->select('attachments.id', 'attachments.filename',
                               'attachments.mimetype')
                             ->whereNull('attachments.deleted_at')
                             ->get();

            $tags = DB::table('tags')
                      ->join('tag_note', function ($join) use (&$noteid) {
                          $join->on('tags.id', '=', 'tag_note.tag_id')
                               ->where('tag_note.note_id', '=', $noteid);
                      })
                      ->select('tags.title')
                      ->get();

            foreach ($tags as $tag) {
                $noteArray['tags'][] = ['title' => $tag->title];
            }

            $noteArray['firstname'] = Auth::user()->firstname;
            $noteArray['lastname']  = Auth::user()->lastname;

            foreach ($attachments as $attachment) {
                $attachments_directory =
                  Config::get('paperwork.attachmentsDirectory');
                $path                  =
                  $attachments_directory . "/" . $attachment->id . "/" .
                  $attachment->filename;
                $file_contents         = File::get($path);
                $data                  = base64_encode($file_contents);

                $noteArray['attachments'][] = [
                  'hash'     => md5($file_contents),
                  'filename' => $attachment->filename,
                  'mimetype' => $attachment->mimetype,
                  'encoded'  => $data
                ];
            }

            if ($noteNumber == 1) {
                $noteArray['start'] = 1;
            }

            if ($noteNumber == $noteCount) {
                $noteArray['end'] = 1;
            }

            $file_content .= View::make('user/settings/export_file', $noteArray)
                                 ->render();
        }

        $headers = [
          "Content-Type"        => "application/xml",
          "Content-Disposition" => "attachment; filename=\"export.enex\""
        ];

        return Response::make(rtrim($file_content, "\r\n"), 200, $headers);
    }
}


text:
package jp.pycon.pyconjp2016app.Feature.Talks.List;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
import jp.pycon.pyconjp2016app.API.Client.APIClient;
import jp.pycon.pyconjp2016app.App;
import jp.pycon.pyconjp2016app.Model.PyConJP.PresentationListEntity;
import jp.pycon.pyconjp2016app.Model.Realm.RealmDaysObject;
import jp.pycon.pyconjp2016app.Model.Realm.RealmStringObject;
import jp.pycon.pyconjp2016app.R;
import jp.pycon.pyconjp2016app.Util.RealmUtil;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by rhoboro on 4/22/16.
 */
public class TalksFragment extends Fragment implements ViewPager.OnPageChangeListener {

    private Context mContext;
    private View view;
    private Realm realm;

    public static TalksFragment newInstance() {
        return new TalksFragment();
    }

    public TalksFragment() {
        // nop
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_view_pager, container, false);
        realm = Realm.getDefaultInstance();
        final RealmDaysObject days = realm.where(RealmDaysObject.class).findFirst();
        if (days != null) {
            setupTalkList();
        } else {
            getPyConJPTalks();
        }
        setHasOptionsMenu(true);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ViewPager pager = (ViewPager)view.findViewById(R.id.view_pager);
        pager.setAdapter(null);
        realm.close();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_refresh, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_refresh) {
            RealmUtil.deleteTalkList(mContext, realm);
            getPyConJPTalks();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    /**
     * トーク一覧を取得します
     */
    private void getPyConJPTalks() {
        APIClient apiClient = ((App)getActivity().getApplication()).getAPIClient();
        rx.Observable<PresentationListEntity> observable = apiClient.getPyConJPTalks();
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PresentationListEntity>() {
                               @Override
                               public void onCompleted() {
                                   setupTalkList();
                               }

                               @Override
                               public void onError(Throwable e) {
                                   e.printStackTrace();
                                   Toast.makeText(mContext, "error" + e, Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(PresentationListEntity presentationList) {
                                   RealmUtil.saveTalkList(mContext, realm, presentationList);
                               }
                           }
                );
    }

    /**
     * トーク一覧画面を作成します
     */
    private void setupTalkList() {
        TabLayout tab= (TabLayout)view.findViewById(R.id.tab_layout);
        tab.setTabMode(TabLayout.MODE_FIXED);
        tab.setTabGravity(TabLayout.GRAVITY_FILL);
        ViewPager pager = (ViewPager)view.findViewById(R.id.view_pager);

        final RealmDaysObject days = realm.where(RealmDaysObject.class).findFirst();
        final RealmList<RealmStringObject> list = days.getDays();
        final RealmResults<RealmStringObject> results = list.sort("string");

        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                TalkListFragment f = TalkListFragment.newInstance(position, false);
                return f;
            }

            @Override
            public int getCount() {
                return results.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return results.get(position).getString();
            }
        };
        pager.setAdapter(adapter);
        pager.addOnPageChangeListener(this);
        tab.setupWithViewPager(pager);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace sml {

class bpnn {
public:
    bpnn() = default;

    bool dump(const std::string& file) const;
    bool load(const std::string& file);
    void init(int ninput, int nhidden, int noutput, double rate1, double rate2);

    const arma::vec& forward(const arma::vec& input);
    void backward(const arma::vec& target);

private:
    arma::vec _input;
    arma::vec _hidden;
    arma::vec _output;
    arma::mat _hiddenweight;
    arma::vec _hiddenbias;
    arma::mat _outputweight;
    arma::vec _outputbias;

    arma::mat _hiddenwchanged;
    arma::vec _hiddenbchanged;
    arma::mat _outputwchanged;
    arma::vec _outputbchanged;

    double _rate1;
    double _rate2;
};

}

#endif


text:
package com.jbox2d.collision.shapes;

import com.jbox2d.collision.AABB;
import com.jbox2d.collision.RayCastInput;
import com.jbox2d.collision.RayCastOutput;
import com.jbox2d.common.MathUtils;
import com.jbox2d.common.Rot;
import com.jbox2d.common.Settings;
import com.jbox2d.common.Transform;
import com.jbox2d.common.Vec2;

/**
 * A chain shape is a free form sequence of line segments. The chain has two-sided collision, so you
 * can use inside and outside collision. Therefore, you may use any winding order. Connectivity
 * information is used to create smooth collisions. WARNING: The chain will not collide properly if
 * there are self-intersections.
 *
 * @author Daniel
 */
public class ChainShape extends Shape {

  public Vec2[] m_vertices;
  public int m_count;
  public final Vec2 m_prevVertex = new Vec2(), m_nextVertex = new Vec2();
  public boolean m_hasPrevVertex = false, m_hasNextVertex = false;

  private final EdgeShape pool0 = new EdgeShape();

  public ChainShape() {
    super(ShapeType.CHAIN);
    m_vertices = null;
    m_radius = Settings.polygonRadius;
    m_count = 0;
  }

  public void clear() {
    m_vertices = null;
    m_count = 0;
  }

  @Override
  public int getChildCount() {
    return m_count - 1;
  }

  /**
   * Get a child edge.
   */
  public void getChildEdge(EdgeShape edge, int index) {
    assert (0 <= index && index < m_count - 1);
    edge.m_radius = m_radius;

    final Vec2 v0 = m_vertices[index + 0];
    final Vec2 v1 = m_vertices[index + 1];
    edge.m_vertex1.x = v0.x;
    edge.m_vertex1.y = v0.y;
    edge.m_vertex2.x = v1.x;
    edge.m_vertex2.y = v1.y;

    if (index > 0) {
      Vec2 v = m_vertices[index - 1];
      edge.m_vertex0.x = v.x;
      edge.m_vertex0.y = v.y;
      edge.m_hasVertex0 = true;
    } else {
      edge.m_vertex0.x = m_prevVertex.x;
      edge.m_vertex0.y = m_prevVertex.y;
      edge.m_hasVertex0 = m_hasPrevVertex;
    }

    if (index < m_count - 2) {
      Vec2 v = m_vertices[index + 2];
      edge.m_vertex3.x = v.x;
      edge.m_vertex3.y = v.y;
      edge.m_hasVertex3 = true;
    } else {
      edge.m_vertex3.x = m_nextVertex.x;
      edge.m_vertex3.y = m_nextVertex.y;
      edge.m_hasVertex3 = m_hasNextVertex;
    }
  }

  @Override
  public float computeDistanceToOut(Transform xf, Vec2 p, int childIndex, Vec2 normalOut) {
    final EdgeShape edge = pool0;
    getChildEdge(edge, childIndex);
    return edge.computeDistanceToOut(xf, p, 0, normalOut);
  }

  @Override
  public boolean testPoint(Transform xf, Vec2 p) {
    return false;
  }

  @Override
  public boolean raycast(RayCastOutput output, RayCastInput input, Transform xf, int childIndex) {
    assert (childIndex < m_count);

    final EdgeShape edgeShape = pool0;

    int i1 = childIndex;
    int i2 = childIndex + 1;
    if (i2 == m_count) {
      i2 = 0;
    }
    Vec2 v = m_vertices[i1];
    edgeShape.m_vertex1.x = v.x;
    edgeShape.m_vertex1.y = v.y;
    Vec2 v1 = m_vertices[i2];
    edgeShape.m_vertex2.x = v1.x;
    edgeShape.m_vertex2.y = v1.y;

    return edgeShape.raycast(output, input, xf, 0);
  }

  @Override
  public void computeAABB(AABB aabb, Transform xf, int childIndex) {
    assert (childIndex < m_count);
    final Vec2 lower = aabb.lowerBound;
    final Vec2 upper = aabb.upperBound;

    int i1 = childIndex;
    int i2 = childIndex + 1;
    if (i2 == m_count) {
      i2 = 0;
    }

    final Vec2 vi1 = m_vertices[i1];
    final Vec2 vi2 = m_vertices[i2];
    final Rot xfq = xf.q;
    final Vec2 xfp = xf.p;
    float v1x = (xfq.c * vi1.x - xfq.s * vi1.y) + xfp.x;
    float v1y = (xfq.s * vi1.x + xfq.c * vi1.y) + xfp.y;
    float v2x = (xfq.c * vi2.x - xfq.s * vi2.y) + xfp.x;
    float v2y = (xfq.s * vi2.x + xfq.c * vi2.y) + xfp.y;

    lower.x = v1x < v2x ? v1x : v2x;
    lower.y = v1y < v2y ? v1y : v2y;
    upper.x = v1x > v2x ? v1x : v2x;
    upper.y = v1y > v2y ? v1y : v2y;
  }

  @Override
  public void computeMass(MassData massData, float density) {
    massData.mass = 0.0f;
    massData.center.setZero();
    massData.I = 0.0f;
  }

  @Override
  public Shape clone() {
    ChainShape clone = new ChainShape();
    clone.createChain(m_vertices, m_count);
    clone.m_prevVertex.set(m_prevVertex);
    clone.m_nextVertex.set(m_nextVertex);
    clone.m_hasPrevVertex = m_hasPrevVertex;
    clone.m_hasNextVertex = m_hasNextVertex;
    return clone;
  }

  /**
   * Create a loop. This automatically adjusts connectivity.
   *
   * @param vertices an array of vertices, these are copied
   * @param count the vertex count
   */
  public void createLoop(final Vec2[] vertices, int count) {
    assert (m_vertices == null && m_count == 0);
    assert (count >= 3);
    m_count = count + 1;
    m_vertices = new Vec2[m_count];
    for (int i = 1; i < count; i++) {
      Vec2 v1 = vertices[i - 1];
      Vec2 v2 = vertices[i];
      // If the code crashes here, it means your vertices are too close together.
      if (MathUtils.distanceSquared(v1, v2) < Settings.linearSlop * Settings.linearSlop) {
        throw new RuntimeException("Vertices of chain shape are too close together");
      }
    }
    for (int i = 0; i < count; i++) {
      m_vertices[i] = new Vec2(vertices[i]);
    }
    m_vertices[count] = new Vec2(m_vertices[0]);
    m_prevVertex.set(m_vertices[m_count - 2]);
    m_nextVertex.set(m_vertices[1]);
    m_hasPrevVertex = true;
    m_hasNextVertex = true;
  }

  /**
   * Create a chain with isolated end vertices.
   *
   * @param vertices an array of vertices, these are copied
   * @param count the vertex count
   */
  public void createChain(final Vec2 vertices[], int count) {
    assert (m_vertices == null && m_count == 0);
    assert (count >= 2);
    m_count = count;
    m_vertices = new Vec2[m_count];
    for (int i = 1; i < m_count; i++) {
      Vec2 v1 = vertices[i - 1];
      Vec2 v2 = vertices[i];
      // If the code crashes here, it means your vertices are too close together.
      if (MathUtils.distanceSquared(v1, v2) < Settings.linearSlop * Settings.linearSlop) {
        throw new RuntimeException("Vertices of chain shape are too close together");
      }
    }
    for (int i = 0; i < m_count; i++) {
      m_vertices[i] = new Vec2(vertices[i]);
    }
    m_hasPrevVertex = false;
    m_hasNextVertex = false;

    m_prevVertex.setZero();
    m_nextVertex.setZero();
  }

  /**
   * Establish connectivity to a vertex that precedes the first vertex. Don't call this for loops.
   *
   * @param prevVertex
   */
  public void setPrevVertex(final Vec2 prevVertex) {
    m_prevVertex.set(prevVertex);
    m_hasPrevVertex = true;
  }

  /**
   * Establish connectivity to a vertex that follows the last vertex. Don't call this for loops.
   *
   * @param nextVertex
   */
  public void setNextVertex(final Vec2 nextVertex) {
    m_nextVertex.set(nextVertex);
    m_hasNextVertex = true;
  }
}


text:
<?php

namespace SellerWorks\Amazon\FulfillmentInbound\Entity;

use SellerWorks\Amazon\Common\Serializer\MetadataInterface;

/**
 * Item information for an inbound shipment. Submitted with a call to the CreateInboundShipment or UpdateInboundShipment
 * operation.
 */
final class InboundShipmentItem implements MetadataInterface
{
    /**
     * @var string
     */
    public $ShipmentId;

    /**
     * @var string
     */
    public $SellerSKU;

    /**
     * @var string
     */
    public $FulfillmentNetworkSKU;

    /**
     * @var int
     */
    public $QuantityShipped;

    /**
     * @var int
     */
    public $QuantityReceived;

    /**
     * @var int
     */
    public $QuantityInCase;

    /**
     * @var Array<PrepDetails>
     */
    public $PrepDetailsList;

    /**
     * @var string
     */
    public $ReleaseDate;

    /**
     * {@inheritDoc}
     */
    public function getMetadata()
    {
        return [
            'ShipmentId'            => ['type' => 'scalar'],
            'SellerSKU'             => ['type' => 'scalar'],
            'FulfillmentNetworkSKU' => ['type' => 'scalar'],
            'QuantityShipped'       => ['type' => 'scalar'],
            'QuantityReceived'      => ['type' => 'scalar'],
            'QuantityInCase'        => ['type' => 'scalar'],
            'PrepDetailsList'       => ['type' => 'array', 'subtype' => PrepDetails::class, 'namespace' => 'member'],
            'ReleaseDate'           => ['type' => 'datetime'],
        ];
    }
}


text:
bash "apt-get_update" do
    code "apt-get update"
end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes</title>
<meta name="date" content="2015-07-25">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AppTester

AppTester.DefaultPrintStream

AppTester.Rank

AppTester.ReadoutCondition

BackgroundEvent_Interface

ByteArrays

FileFinder

Networking_Utilities


text:
<?php
namespace Discord\OAuth2\Client\Provider\ValueObject;

use Discord\OAuth2\Client\Provider\Exception\ValueObject\InvalidUserDiscriminatorException;

/**
 * Class UserDiscriminator
 * @package Discord\OAuth2\Client\Provider\ValueObject
 * @author Dominik Szymański <toja@chonsser.me>
 */
final class UserDiscriminator
{
    const
        LENGTH = 4;

    /**
     * @var string
     */
    private $discriminator;

    /**
     * UserDiscriminator constructor.
     *
     * @param $discriminator
     * @throws InvalidUserDiscriminatorException
     */
    public function __construct($discriminator)
    {
        $this->guardDiscriminator($discriminator);

        $this->discriminator = $discriminator;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return (string)$this->discriminator;
    }

    /**
     * @param $discriminator
     *
     * @throws InvalidUserDiscriminatorException
     */
    private function guardDiscriminator($discriminator)
    {
        if (!preg_match('/^\d{4}$/', $discriminator)) {
            throw new InvalidUserDiscriminatorException("Discriminator must consist of 4 numbers");
        }
    }

    /**
     * @param UserDiscriminator $userDiscriminator
     *
     * @return bool
     */
    public function isEqualTo(UserDiscriminator $userDiscriminator)
    {
        return $this->discriminator === (string)$userDiscriminator;
    }
}


text:
<config>
  <modules>
    <Epoint_SwissPostSales>
      <active>true</active>
      <codePool>local</codePool>
      <depends>
		<Epoint_SwissPost_Api/>
      </depends>
    </Epoint_SwissPostSales>
  </modules>
</config>


text:
from __future__ import annotations

import unittest
from unittest import mock

from airflow.providers.google.cloud.operators.translate import CloudTranslateTextOperator

GCP_CONN_ID = 'google_cloud_default'
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]

class TestCloudTranslate(unittest.TestCase):
    @mock.patch('airflow.providers.google.cloud.operators.translate.CloudTranslateHook')
    def test_minimal_green_path(self, mock_hook):
        mock_hook.return_value.translate.return_value = [
            {
                'translatedText': 'Yellowing self Gęśle',
                'detectedSourceLanguage': 'pl',
                'model': 'base',
                'input': 'zażółć gęślą jaźń',
            }
        ]
        op = CloudTranslateTextOperator(
            values=['zażółć gęślą jaźń'],
            target_language='en',
            format_='text',
            source_language=None,
            model='base',
            gcp_conn_id=GCP_CONN_ID,
            task_id='id',
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        context = mock.MagicMock()
        return_value = op.execute(context=context)
        mock_hook.assert_called_once_with(
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.translate.assert_called_once_with(
            values=['zażółć gęślą jaźń'],
            target_language='en',
            format_='text',
            source_language=None,
            model='base',
        )
        assert [
            {
                'translatedText': 'Yellowing self Gęśle',
                'detectedSourceLanguage': 'pl',
                'model': 'base',
                'input': 'zażółć gęślą jaźń',
            }
        ] == return_value


text:
<?php

namespace SelfService\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\EmbeddedDocument
 * @author Ryan J. Geyer <me@ryangeyer.com>
 */
class ServerTemplate extends AbstractResource {

  public $resource_type = "server_template";

  /**
   * @ODM\Hash
   * @var array|string
   */
  public $name;

  /**
   * @ODM\Hash
   * @var array|string
   */
  public $revision;

  /**
   * @ODM\Hash
   * @var array|string
   */
  public $publication_id;
}


text:
import Ember from 'ember';

export default Ember.Object.extend({
  emberOauth2: Ember.inject.service(),
  auth: null,

  provider: Ember.computed('auth', {
    /*jshint unused: false*/
    get(key) {
      return this.get('auth');
    },
    set(key, value) {
      this.set('providerId', value);
      // check if the value is falsey ie: most likely set to null
      if (value) {
        this.set('auth', this.get('emberOauth2').setProvider(value));
      } else {
        this.set('auth', value);
      }
      return value;
    }
  }),

  isExpired: Ember.computed('auth', {
    /*jshint unused: false*/
    get(key) {
      if (this.get('auth')) {
        return this.get('auth').accessTokenIsExpired();
      } else {
        return true;
      }
    }
  }),

  isNotExpired: Ember.computed('isExpired', {
    /*jshint unused: false*/
    get(key) {
      return !this.get('isExpired');
    }
  }),

  token: Ember.computed('auth', {
    /*jshint unused: false*/
    get(key) {
      return this.get('auth') ? this.get('auth').getToken() : null;
    }
  }),

  accessToken: Ember.computed('auth', {
    /*jshint unused: false*/
    get(key) {
      return this.get('auth') ? this.get('auth').getAccessToken() : false;
    }
  }),

  authorize: function() {
    return this.auth.authorize();
  },

  signout: function() {
    if (this.get('auth')) {
      this.auth.removeToken();
      this.set('auth', null);
      this.set('providerId', null);
    } else {
      return null;
    }
  }

});


text:
<TS language="gl" version="2.1">
<context>
    <name>AddressBookPage</name>
    <message>
        <source>Create a new address</source>
        <translation>Crear unha nova dirección</translation>
    </message>
    <message>
        <source>&New</source>
        <translation>&Novo</translation>
    </message>
    <message>
        <source>Copy the currently selected address to the system clipboard</source>
        <translation>Copiar a dirección seleccionada ao cartafol</translation>
    </message>
    <message>
        <source>&Copy</source>
        <translation>&Copiar</translation>
    </message>
    <message>
        <source>C&lose</source>
        <translation>&Pechar</translation>
    </message>
    <message>
        <source>Delete the currently selected address from the list</source>
        <translation>Borrar a dirección actualmente seleccionada da listaxe</translation>
    </message>
    <message>
        <source>Enter address or label to search</source>
        <translation>Introduce dirección ou etiqueta para buscar</translation>
    </message>
    <message>
        <source>Export the data in the current tab to a file</source>
        <translation>Exportar os datos da pestaña actual a un arquivo.</translation>
    </message>
    <message>
        <source>&Export</source>
        <translation>&Exportar</translation>
    </message>
    <message>
        <source>&Delete</source>
        <translation>&Borrar</translation>
    </message>
    </context>
<context>
    <name>AddressTableModel</name>
    </context>
<context>
    <name>AskPassphraseDialog</name>
    <message>
        <source>Passphrase Dialog</source>
        <translation>Diálogo de Contrasinal</translation>
    </message>
    <message>
        <source>Enter passphrase</source>
        <translation>Introduce contrasinal</translation>
    </message>
    <message>
        <source>New passphrase</source>
        <translation>Novo contrasinal</translation>
    </message>
    <message>
        <source>Repeat new passphrase</source>
        <translation>Repite novo contrasinal</translation>
    </message>
    </context>
<context>
    <name>BanTableModel</name>
    </context>
<context>
    <name>BitcoinGUI</name>
    <message>
        <source>Sign &message...</source>
        <translation>&Asinar mensaxe...</translation>
    </message>
    <message>
        <source>Synchronizing with network...</source>
        <translation>Sincronizando coa rede...</translation>
    </message>
    <message>
        <source>&Overview</source>
        <translation>&Vista xeral</translation>
    </message>
    <message>
        <source>Show general overview of wallet</source>
        <translation>Amosar vista xeral do moedeiro</translation>
    </message>
    <message>
        <source>&Transactions</source>
        <translation>&Transacciones</translation>
    </message>
    <message>
        <source>Browse transaction history</source>
        <translation>Navegar historial de transaccións</translation>
    </message>
    <message>
        <source>E&xit</source>
        <translation>&Saír</translation>
    </message>
    <message>
        <source>Quit application</source>
        <translation>Saír da aplicación</translation>
    </message>
    <message>
        <source>About &Qt</source>
        <translation>Acerca de &Qt</translation>
    </message>
    <message>
        <source>Show information about Qt</source>
        <translation>Amosar información acerca de Qt</translation>
    </message>
    <message>
        <source>&Options...</source>
        <translation>&Opcións...</translation>
    </message>
    <message>
        <source>&Encrypt Wallet...</source>
        <translation>&Encriptar Moedeiro...</translation>
    </message>
    <message>
        <source>&Backup Wallet...</source>
        <translation>Copia de &Seguridade do Moedeiro...</translation>
    </message>
    <message>
        <source>&Change Passphrase...</source>
        <translation>&Cambiar contrasinal...</translation>
    </message>
    <message>
        <source>&Receiving addresses...</source>
        <translation>Direccións para recibir</translation>
    </message>
    <message>
        <source>Reindexing blocks on disk...</source>
        <translation>Reindexando bloques no disco...</translation>
    </message>
    <message>
        <source>Send coins to a UFO address</source>
        <translation>Enviar moedas a unha dirección UFO</translation>
    </message>
    <message>
        <source>Backup wallet to another location</source>
        <translation>Facer copia de seguridade do moedeiro noutra localización</translation>
    </message>
    <message>
        <source>Change the passphrase used for wallet encryption</source>
        <translation>Cambiar o contrasinal empregado para a encriptación do moedeiro</translation>
    </message>
    <message>
        <source>&Debug window</source>
        <translation>Ventana de &Depuración</translation>
    </message>
    <message>
        <source>Open debugging and diagnostic console</source>
        <translation>Abrir consola de depuración e diagnóstico</translation>
    </message>
    <message>
        <source>&Verify message...</source>
        <translation>&Verificar mensaxe...</translation>
    </message>
    <message>
        <source>UFO</source>
        <translation>UFO</translation>
    </message>
    <message>
        <source>Wallet</source>
        <translation>Moedeiro</translation>
    </message>
    <message>
        <source>&Send</source>
        <translation>&Enviar</translation>
    </message>
    <message>
        <source>&Receive</source>
        <translation>&Recibir</translation>
    </message>
    <message>
        <source>&Show / Hide</source>
        <translation>&Amosar/Agachar</translation>
    </message>
    <message>
        <source>Show or hide the main Window</source>
        <translation>Amosar ou agachar a ventana principal</translation>
    </message>
    <message>
        <source>Encrypt the private keys that belong to your wallet</source>
        <translation>Encriptar as claves privadas que pertencen ao teu moedeiro</translation>
    </message>
    <message>
        <source>Sign messages with your UFO addresses to prove you own them</source>
        <translation>Asina mensaxes coas túas direccións UFO para probar que te pertencen</translation>
    </message>
    <message>
        <source>Verify messages to ensure they were signed with specified UFO addresses</source>
        <translation>Verificar mensaxes para asegurar que foron asinados con direccións UFO dadas.</translation>
    </message>
    <message>
        <source>&File</source>
        <translation>&Arquivo</translation>
    </message>
    <message>
        <source>&Settings</source>
        <translation>Axus&tes</translation>
    </message>
    <message>
        <source>&Help</source>
        <translation>A&xuda</translation>
    </message>
    <message>
        <source>Tabs toolbar</source>
        <translation>Barra de ferramentas</translation>
    </message>
    <message>
        <source>Request payments (generates QR codes and ufo: URIs)</source>
        <translation>Solicitar pagos (xenera códigos QR e ufo: URIs)</translation>
    </message>
    <message>
        <source>Show the list of used sending addresses and labels</source>
        <translation>Amosar a listaxe de direccións e etiquetas para enviar empregadas</translation>
    </message>
    <message>
        <source>Show the list of used receiving addresses and labels</source>
        <translation>Amosar a listaxe de etiquetas e direccións para recibir empregadas</translation>
    </message>
    <message>
        <source>Open a ufo: URI or payment request</source>
        <translation>Abrir un ufo: URI ou solicitude de pago</translation>
    </message>
    <message>
        <source>&Command-line options</source>
        <translation>Opcións da liña de comandos</translation>
    </message>
    <message>
        <source>%1 behind</source>
        <translation>%1 detrás</translation>
    </message>
    <message>
        <source>Last received block was generated %1 ago.</source>
        <translation>O último bloque recibido foi xerado fai %1.</translation>
    </message>
    <message>
        <source>Transactions after this will not yet be visible.</source>
        <translation>As transaccións despois desta non serán todavía visibles.</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Erro</translation>
    </message>
    <message>
        <source>Warning</source>
        <translation>Precaución</translation>
    </message>
    <message>
        <source>Information</source>
        <translation>Información</translation>
    </message>
    <message>
        <source>Up to date</source>
        <translation>Actualizado</translation>
    </message>
    <message>
        <source>Catching up...</source>
        <translation>Poñendo ao día...</translation>
    </message>
    <message>
        <source>Sent transaction</source>
        <translation>Transacción enviada</translation>
    </message>
    <message>
        <source>Incoming transaction</source>
        <translation>Transacción entrante</translation>
    </message>
    <message>
        <source>Wallet is encrypted and currently unlocked</source>
        <translation>O moedeiro está encriptado e actualmente desbloqueado</translation>
    </message>
    <message>
        <source>Wallet is encrypted and currently locked</source>
        <translation>O moedeiro está encriptado e actualmente bloqueado</translation>
    </message>
    </context>
<context>
    <name>CoinControlDialog</name>
    <message>
        <source>Quantity:</source>
        <translation>Cantidade:</translation>
    </message>
    <message>
        <source>Bytes:</source>
        <translation>Bytes:</translation>
    </message>
    <message>
        <source>Amount:</source>
        <translation>Importe:</translation>
    </message>
    <message>
        <source>Fee:</source>
        <translation>Pago:</translation>
    </message>
    <message>
        <source>Change:</source>
        <translation>Cambiar:</translation>
    </message>
    <message>
        <source>(un)select all</source>
        <translation>(des)selecciona todo</translation>
    </message>
    <message>
        <source>Tree mode</source>
        <translation>Modo árbore</translation>
    </message>
    <message>
        <source>List mode</source>
        <translation>Modo lista</translation>
    </message>
    <message>
        <source>Amount</source>
        <translation>Cantidade</translation>
    </message>
    <message>
        <source>Date</source>
        <translation>Data</translation>
    </message>
    <message>
        <source>Confirmations</source>
        <translation>Confirmacións</translation>
    </message>
    <message>
        <source>Confirmed</source>
        <translation>Confirmado</translation>
    </message>
    </context>
<context>
    <name>EditAddressDialog</name>
    <message>
        <source>Edit Address</source>
        <translation>Modificar Dirección</translation>
    </message>
    <message>
        <source>&Label</source>
        <translation>&Etiqueta</translation>
    </message>
    <message>
        <source>The label associated with this address list entry</source>
        <translation>A etiqueta asociada con esta entrada da listaxe de direccións</translation>
    </message>
    <message>
        <source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
        <translation>A dirección asociada con esta entrada na listaxe de dirección. Esta so pode ser modificada por direccións para enviar.</translation>
    </message>
    <message>
        <source>&Address</source>
        <translation>&Dirección</translation>
    </message>
    </context>
<context>
    <name>FreespaceChecker</name>
    <message>
        <source>A new data directory will be created.</source>
        <translation>Crearáse un novo directorio de datos.</translation>
    </message>
    <message>
        <source>name</source>
        <translation>nome</translation>
    </message>
    <message>
        <source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
        <translation>O directorio xa existe. Engade %1 se queres crear un novo directorio aquí.</translation>
    </message>
    <message>
        <source>Path already exists, and is not a directory.</source>
        <translation>A ruta xa existe e non é un directorio.</translation>
    </message>
    <message>
        <source>Cannot create data directory here.</source>
        <translation>Non se pode crear directorio de datos aquí</translation>
    </message>
</context>
<context>
    <name>HelpMessageDialog</name>
    <message>
        <source>version</source>
        <translation>versión</translation>
    </message>
    <message>
        <source>Command-line options</source>
        <translation>Opcións da liña de comandos</translation>
    </message>
</context>
<context>
    <name>Intro</name>
    <message>
        <source>Welcome</source>
        <translation>Benvido</translation>
    </message>
    <message>
        <source>Use the default data directory</source>
        <translation>Empregar o directorio de datos por defecto</translation>
    </message>
    <message>
        <source>Use a custom data directory:</source>
        <translation>Empregar un directorio de datos personalizado</translation>
    </message>
    <message>
        <source>UFO</source>
        <translation>UFO</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Erro</translation>
    </message>
    </context>
<context>
    <name>ModalOverlay</name>
    <message>
        <source>Form</source>
        <translation>Formulario</translation>
    </message>
    <message>
        <source>Last block time</source>
        <translation>Hora do último bloque</translation>
    </message>
    </context>
<context>
    <name>OpenURIDialog</name>
    <message>
        <source>Open URI</source>
        <translation>Abrir URI</translation>
    </message>
    <message>
        <source>Open payment request from URI or file</source>
        <translation>Abrir solicitude de pago dende URI ou ficheiro</translation>
    </message>
    <message>
        <source>URI:</source>
        <translation>URI:</translation>
    </message>
    <message>
        <source>Select payment request file</source>
        <translation>Seleccionar ficheiro de solicitude de pago</translation>
    </message>
    </context>
<context>
    <name>OptionsDialog</name>
    <message>
        <source>Options</source>
        <translation>Opcións</translation>
    </message>
    <message>
        <source>&Main</source>
        <translation>&Principal</translation>
    </message>
    <message>
        <source>Reset all client options to default.</source>
        <translation>Restaurar todas as opcións de cliente ás por defecto</translation>
    </message>
    <message>
        <source>&Reset Options</source>
        <translation>Opcións de &Restaurar</translation>
    </message>
    <message>
        <source>&Network</source>
        <translation>&Rede</translation>
    </message>
    <message>
        <source>W&allet</source>
        <translation>Moedeiro</translation>
    </message>
    <message>
        <source>Automatically open the UFO client port on the router. This only works when your router supports UPnP and it is enabled.</source>
        <translation>Abrir automáticamente o porto do cliente UFO no router. Esto so funciona se o teu router soporta UPnP e está habilitado.</translation>
    </message>
    <message>
        <source>Map port using &UPnP</source>
        <translation>Mapear porto empregando &UPnP</translation>
    </message>
    <message>
        <source>Proxy &IP:</source>
        <translation>&IP do Proxy:</translation>
    </message>
    <message>
        <source>&Port:</source>
        <translation>&Porto:</translation>
    </message>
    <message>
        <source>Port of the proxy (e.g. 9050)</source>
        <translation>Porto do proxy (exemplo: 9050)</translation>
    </message>
    <message>
        <source>&Window</source>
        <translation>&Xanela</translation>
    </message>
    <message>
        <source>Show only a tray icon after minimizing the window.</source>
        <translation>Amosar so un icono na bandexa tras minimiza-la xanela.</translation>
    </message>
    <message>
        <source>&Minimize to the tray instead of the taskbar</source>
        <translation>&Minimizar á bandexa en lugar de á barra de tarefas.</translation>
    </message>
    <message>
        <source>M&inimize on close</source>
        <translation>M&inimizar ao pechar</translation>
    </message>
    <message>
        <source>&Display</source>
        <translation>&Visualización</translation>
    </message>
    <message>
        <source>User Interface &language:</source>
        <translation>&Linguaxe de interface de usuario:</translation>
    </message>
    <message>
        <source>&Unit to show amounts in:</source>
        <translation>&Unidade na que amosar as cantidades:</translation>
    </message>
    <message>
        <source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
        <translation>Escolle a unidade de subdivisión por defecto para amosar na interface e ao enviar moedas.</translation>
    </message>
    <message>
        <source>&OK</source>
        <translation>&OK</translation>
    </message>
    <message>
        <source>&Cancel</source>
        <translation>&Cancelar</translation>
    </message>
    <message>
        <source>default</source>
        <translation>por defecto</translation>
    </message>
    <message>
        <source>Confirm options reset</source>
        <translation>Confirmar opcións de restaurar</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Erro</translation>
    </message>
    <message>
        <source>The supplied proxy address is invalid.</source>
        <translation>A dirección de proxy suministrada é inválida.</translation>
    </message>
</context>
<context>
    <name>OverviewPage</name>
    <message>
        <source>Form</source>
        <translation>Formulario</translation>
    </message>
    <message>
        <source>The displayed information may be out of date. Your wallet automatically synchronizes with the UFO network after a connection is established, but this process has not completed yet.</source>
        <translation>A información amosada por estar desactualizada. O teu moedeiro sincronízase automáticamente coa rede UFO despois de que se estableza unha conexión, pero este proceso non está todavía rematado.</translation>
    </message>
    <message>
        <source>Your current spendable balance</source>
        <translation>O teu balance actualmente dispoñible</translation>
    </message>
    <message>
        <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
        <translation>Total de transaccións que aínda teñen que ser confirmadas, e non contan todavía dentro do balance gastable</translation>
    </message>
    <message>
        <source>Immature:</source>
        <translation>Inmaduro:</translation>
    </message>
    <message>
        <source>Mined balance that has not yet matured</source>
        <translation>O balance minado todavía non madurou</translation>
    </message>
    <message>
        <source>Total:</source>
        <translation>Total:</translation>
    </message>
    <message>
        <source>Your current total balance</source>
        <translation>O teu balance actual total</translation>
    </message>
    </context>
<context>
    <name>PaymentServer</name>
    </context>
<context>
    <name>PeerTableModel</name>
    </context>
<context>
    <name>QObject</name>
    <message>
        <source>Amount</source>
        <translation>Cantidade</translation>
    </message>
    <message>
        <source>%1 h</source>
        <translation>%1 h</translation>
    </message>
    <message>
        <source>%1 m</source>
        <translation>%1 m</translation>
    </message>
    <message>
        <source>N/A</source>
        <translation>N/A</translation>
    </message>
    <message>
        <source>%1 B</source>
        <translation>%1 B</translation>
    </message>
    <message>
        <source>%1 KB</source>
        <translation>%1 KB</translation>
    </message>
    <message>
        <source>%1 MB</source>
        <translation>%1 MB</translation>
    </message>
    <message>
        <source>%1 GB</source>
        <translation>%1 GB</translation>
    </message>
    <message>
        <source>unknown</source>
        <translation>descoñecido</translation>
    </message>
</context>
<context>
    <name>QObject::QObject</name>
    </context>
<context>
    <name>QRImageWidget</name>
    </context>
<context>
    <name>RPCConsole</name>
    <message>
        <source>N/A</source>
        <translation>N/A</translation>
    </message>
    <message>
        <source>Client version</source>
        <translation>Versión do cliente</translation>
    </message>
    <message>
        <source>&Information</source>
        <translation>&Información</translation>
    </message>
    <message>
        <source>Debug window</source>
        <translation>Ventana de Depuración</translation>
    </message>
    <message>
        <source>Startup time</source>
        <translation>Tempo de arranque</translation>
    </message>
    <message>
        <source>Network</source>
        <translation>Rede</translation>
    </message>
    <message>
        <source>Number of connections</source>
        <translation>Número de conexións</translation>
    </message>
    <message>
        <source>Block chain</source>
        <translation>Cadea de bloques</translation>
    </message>
    <message>
        <source>Current number of blocks</source>
        <translation>Número actual de bloques</translation>
    </message>
    <message>
        <source>Last block time</source>
        <translation>Hora do último bloque</translation>
    </message>
    <message>
        <source>&Open</source>
        <translation>&Abrir</translation>
    </message>
    <message>
        <source>&Console</source>
        <translation>&Consola</translation>
    </message>
    <message>
        <source>&Network Traffic</source>
        <translation>&Tráfico de Rede</translation>
    </message>
    <message>
        <source>Totals</source>
        <translation>Totais</translation>
    </message>
    <message>
        <source>In:</source>
        <translation>Dentro:</translation>
    </message>
    <message>
        <source>Out:</source>
        <translation>Fóra:</translation>
    </message>
    <message>
        <source>Debug log file</source>
        <translation>Arquivo de log de depuración</translation>
    </message>
    <message>
        <source>Clear console</source>
        <translation>Limpar consola</translation>
    </message>
    </context>
<context>
    <name>ReceiveCoinsDialog</name>
    <message>
        <source>&Amount:</source>
        <translation>&Cantidade:</translation>
    </message>
    <message>
        <source>&Label:</source>
        <translation>&Etiqueta:</translation>
    </message>
    <message>
        <source>&Message:</source>
        <translation>&Mensaxe:</translation>
    </message>
    <message>
        <source>Clear all fields of the form.</source>
        <translation>Limpar tódolos campos do formulario</translation>
    </message>
    <message>
        <source>Clear</source>
        <translation>Limpar</translation>
    </message>
    <message>
        <source>&Request payment</source>
        <translation>&Solicitar pago</translation>
    </message>
    </context>
<context>
    <name>ReceiveRequestDialog</name>
    <message>
        <source>QR Code</source>
        <translation>Código QR</translation>
    </message>
    <message>
        <source>Copy &URI</source>
        <translation>Copiar &URI</translation>
    </message>
    <message>
        <source>Copy &Address</source>
        <translation>Copiar &Dirección</translation>
    </message>
    <message>
        <source>&Save Image...</source>
        <translation>&Gardar Imaxe...</translation>
    </message>
    <message>
        <source>Wallet</source>
        <translation>Moedeiro</translation>
    </message>
    </context>
<context>
    <name>RecentRequestsTableModel</name>
    </context>
<context>
    <name>SendCoinsDialog</name>
    <message>
        <source>Send Coins</source>
        <translation>Moedas Enviadas</translation>
    </message>
    <message>
        <source>Insufficient funds!</source>
        <translation>Fondos insuficientes</translation>
    </message>
    <message>
        <source>Quantity:</source>
        <translation>Cantidade:</translation>
    </message>
    <message>
        <source>Bytes:</source>
        <translation>Bytes:</translation>
    </message>
    <message>
        <source>Amount:</source>
        <translation>Importe:</translation>
    </message>
    <message>
        <source>Fee:</source>
        <translation>Pago:</translation>
    </message>
    <message>
        <source>Change:</source>
        <translation>Cambiar:</translation>
    </message>
    <message>
        <source>Transaction Fee:</source>
        <translation>Tarifa de transacción:</translation>
    </message>
    <message>
        <source>Send to multiple recipients at once</source>
        <translation>Enviar a múltiples receptores á vez</translation>
    </message>
    <message>
        <source>Add &Recipient</source>
        <translation>Engadir &Receptor</translation>
    </message>
    <message>
        <source>Clear all fields of the form.</source>
        <translation>Limpar tódolos campos do formulario</translation>
    </message>
    <message>
        <source>Clear &All</source>
        <translation>Limpar &Todo</translation>
    </message>
    <message>
        <source>Balance:</source>
        <translation>Balance:</translation>
    </message>
    <message>
        <source>Confirm the send action</source>
        <translation>Confirmar a acción de envío</translation>
    </message>
    <message>
        <source>S&end</source>
        <translation>&Enviar</translation>
    </message>
    <message>
        <source>Transaction fee</source>
        <translation>Tarifa de transacción</translation>
    </message>
    </context>
<context>
    <name>SendCoinsEntry</name>
    <message>
        <source>A&mount:</source>
        <translation>&Cantidade:</translation>
    </message>
    <message>
        <source>Pay &To:</source>
        <translation>Pagar &A:</translation>
    </message>
    <message>
        <source>&Label:</source>
        <translation>&Etiqueta:</translation>
    </message>
    <message>
        <source>Choose previously used address</source>
        <translation>Escoller dirección previamente empregada</translation>
    </message>
    <message>
        <source>This is a normal payment.</source>
        <translation>Este é un pago normal</translation>
    </message>
    <message>
        <source>Alt+A</source>
        <translation>Alt+A</translation>
    </message>
    <message>
        <source>Paste address from clipboard</source>
        <translation>Pegar dirección dende portapapeis</translation>
    </message>
    <message>
        <source>Alt+P</source>
        <translation>Alt+P</translation>
    </message>
    <message>
        <source>Remove this entry</source>
        <translation>Eliminar esta entrada</translation>
    </message>
    <message>
        <source>Message:</source>
        <translation>Mensaxe:</translation>
    </message>
    <message>
        <source>Enter a label for this address to add it to the list of used addresses</source>
        <translation>Introduce unha etiqueta para esta dirección para engadila á listaxe de direccións empregadas</translation>
    </message>
    <message>
        <source>Pay To:</source>
        <translation>Pagar A:</translation>
    </message>
    <message>
        <source>Memo:</source>
        <translation>Memo:</translation>
    </message>
    </context>
<context>
    <name>SendConfirmationDialog</name>
    </context>
<context>
    <name>ShutdownWindow</name>
    </context>
<context>
    <name>SignVerifyMessageDialog</name>
    <message>
        <source>Signatures - Sign / Verify a Message</source>
        <translation>Sinaturas - Asinar / Verificar unha Mensaxe</translation>
    </message>
    <message>
        <source>&Sign Message</source>
        <translation>&Asinar Mensaxe</translation>
    </message>
    <message>
        <source>Choose previously used address</source>
        <translation>Escoller dirección previamente empregada</translation>
    </message>
    <message>
        <source>Alt+A</source>
        <translation>Alt+A</translation>
    </message>
    <message>
        <source>Paste address from clipboard</source>
        <translation>Pegar dirección dende portapapeis</translation>
    </message>
    <message>
        <source>Alt+P</source>
        <translation>Alt+P</translation>
    </message>
    <message>
        <source>Enter the message you want to sign here</source>
        <translation>Introduce a mensaxe que queres asinar aquí</translation>
    </message>
    <message>
        <source>Signature</source>
        <translation>Sinatura</translation>
    </message>
    <message>
        <source>Copy the current signature to the system clipboard</source>
        <translation>Copiar a sinatura actual ao portapapeis do sistema</translation>
    </message>
    <message>
        <source>Sign the message to prove you own this UFO address</source>
        <translation>Asina a mensaxe para probar que posees esta dirección UFO</translation>
    </message>
    <message>
        <source>Sign &Message</source>
        <translation>Asinar &Mensaxe</translation>
    </message>
    <message>
        <source>Reset all sign message fields</source>
        <translation>Restaurar todos os campos de sinatura de mensaxe</translation>
    </message>
    <message>
        <source>Clear &All</source>
        <translation>Limpar &Todo</translation>
    </message>
    <message>
        <source>&Verify Message</source>
        <translation>&Verificar Mensaxe</translation>
    </message>
    <message>
        <source>Verify the message to ensure it was signed with the specified UFO address</source>
        <translation>Verificar a mensaxe para asegurar que foi asinada coa dirección UFO especificada</translation>
    </message>
    <message>
        <source>Verify &Message</source>
        <translation>Verificar &Mensaxe</translation>
    </message>
    <message>
        <source>Reset all verify message fields</source>
        <translation>Restaurar todos os campos de verificación de mensaxe</translation>
    </message>
    </context>
<context>
    <name>SplashScreen</name>
    <message>
        <source>[testnet]</source>
        <translation>[testnet]</translation>
    </message>
</context>
<context>
    <name>TrafficGraphWidget</name>
    <message>
        <source>KB/s</source>
        <translation>KB/s</translation>
    </message>
</context>
<context>
    <name>TransactionDesc</name>
    </context>
<context>
    <name>TransactionDescDialog</name>
    <message>
        <source>This pane shows a detailed description of the transaction</source>
        <translation>Este panel amosa unha descripción detallada da transacción</translation>
    </message>
    </context>
<context>
    <name>TransactionTableModel</name>
    </context>
<context>
    <name>TransactionView</name>
    </context>
<context>
    <name>UnitDisplayStatusBarControl</name>
    </context>
<context>
    <name>WalletFrame</name>
    </context>
<context>
    <name>WalletModel</name>
    </context>
<context>
    <name>WalletView</name>
    </context>
<context>
    <name>bitcoin-core</name>
    <message>
        <source>UFO Core</source>
        <translation>Core de UFO</translation>
    </message>
    <message>
        <source>Corrupted block database detected</source>
        <translation>Detectada base de datos de bloques corrupta.</translation>
    </message>
    <message>
        <source>Do you want to rebuild the block database now?</source>
        <translation>Queres reconstruír a base de datos de bloques agora?</translation>
    </message>
    <message>
        <source>Error initializing block database</source>
        <translation>Erro inicializando a base de datos de bloques</translation>
    </message>
    <message>
        <source>Error initializing wallet database environment %s!</source>
        <translation>Erro inicializando entorno de base de datos de moedeiro %s!</translation>
    </message>
    <message>
        <source>Error loading block database</source>
        <translation>Erro cargando base de datos do bloque</translation>
    </message>
    <message>
        <source>Error opening block database</source>
        <translation>Erro abrindo base de datos de bloques</translation>
    </message>
    <message>
        <source>Error: Disk space is low!</source>
        <translation>Erro: Espacio en disco escaso!</translation>
    </message>
    <message>
        <source>Failed to listen on any port. Use -listen=0 if you want this.</source>
        <translation>Fallou escoitar en calquera porto. Emprega -listen=0 se queres esto.</translation>
    </message>
    <message>
        <source>Incorrect or no genesis block found. Wrong datadir for network?</source>
        <translation>Bloque genesis incorrecto o no existente. Datadir erróneo para a rede?</translation>
    </message>
    <message>
        <source>Not enough file descriptors available.</source>
        <translation>Non hai suficientes descritores de arquivo dispoñibles.</translation>
    </message>
    <message>
        <source>Verifying blocks...</source>
        <translation>Verificando bloques...</translation>
    </message>
    <message>
        <source>Information</source>
        <translation>Información</translation>
    </message>
    <message>
        <source>Signing transaction failed</source>
        <translation>Fallou a sinatura da transacción</translation>
    </message>
    <message>
        <source>Transaction amount too small</source>
        <translation>A cantidade da transacción é demasiado pequena</translation>
    </message>
    <message>
        <source>Transaction too large</source>
        <translation>A transacción é demasiado grande</translation>
    </message>
    <message>
        <source>Warning</source>
        <translation>Precaución</translation>
    </message>
    <message>
        <source>Unknown network specified in -onlynet: '%s'</source>
        <translation>Rede descoñecida especificada en -onlynet: '%s'</translation>
    </message>
    <message>
        <source>Insufficient funds</source>
        <translation>Fondos insuficientes</translation>
    </message>
    <message>
        <source>Loading block index...</source>
        <translation>Cargando índice de bloques...</translation>
    </message>
    <message>
        <source>Loading wallet...</source>
        <translation>Cargando moedeiro...</translation>
    </message>
    <message>
        <source>Cannot downgrade wallet</source>
        <translation>Non se pode desactualizar o moedeiro</translation>
    </message>
    <message>
        <source>Rescanning...</source>
        <translation>Rescaneando...</translation>
    </message>
    <message>
        <source>Done loading</source>
        <translation>Carga completa</translation>
    </message>
    <message>
        <source>Error</source>
        <translation>Erro</translation>
    </message>
</context>
</TS>


text:
using System;

namespace FlappyButterfly
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (FlappyGame game = new FlappyGame())
            {
                game.Run();
            }
        }
    }
#endif
}


text:
from collections import OrderedDict
from datetime import timedelta

import django.utils.timezone
from django.db.models import Q
from django.shortcuts import get_object_or_404

import sal.plugin
from server.models import Machine, MachineGroup, BusinessUnit

class Status(sal.plugin.Widget):

    description = 'General status'
    only_use_deployed_machines = False

    def _get_statuses(self):
        now = django.utils.timezone.now()
        today = now - timedelta(hours=24)
        week_ago = today - timedelta(days=7)
        month_ago = today - timedelta(days=30)
        three_months_ago = today - timedelta(days=90)

        return {
            'broken_clients': ('Machines with broken Python', Q(broken_client=True)),
            'errors': ('Machines with errors', Q(messages__message_type='ERROR')),
            'warnings': ('Machines with warnings', Q(messages__message_type='WARNING')),
            'sevendayactive': ('7 day active machines', Q(last_checkin__gte=week_ago)),
            'thirtydayactive': ('30 day active machines', Q(last_checkin__gte=month_ago)),
            'ninetydayactive': ('90 day active machines', Q(last_checkin__gte=three_months_ago)),
            'all_machines': ('All machines', None),
            'deployed_machines': ('Deployed Machines', None),
            'undeployed_machines': ('Undeployed Machines', Q(deployed=False))}

    def get_context(self, queryset, **kwargs):
        context = self.super_get_context(queryset, **kwargs)

        context['data'] = {}
        for key, item in self._get_statuses().items():
            context['data'][key] = (item[0], self._filter(queryset, key).count())

        return context

    def filter(self, machines, data):
        statuses = self._get_statuses()
        if data not in statuses:
            return None, None
        machines = self._filter(machines, data)
        title = statuses[data][0]
        return machines, title

    def _filter(self, machines, data):
        try:
            machine_filter = self._get_statuses()[data][1]
        except KeyError:
            return None

        # Since this plugin gets _all_ machines, we may need to filter
        # out undeployed machines depending on the type of status we're
        # checking.
        if data not in ('undeployed_machines', 'all_machines'):
            machines = machines.filter(deployed=True)

        # Only filter if a filter from the STATUSES table is defined.
        return machines.filter(machine_filter).distinct() if machine_filter else machines


text:
/**
 * Created with JetBrains PhpStorm.
 * User: Mrkupi
 * Date: 10/16/13
 * Time: 5:42 PM
 * To change this template use File | Settings | File Templates.
 */

//-----------------------------------------------------------------------------------------------------------//
//---------------------------------           GRIDCELL DEFINITIONS              ---------------------------------------//
//-----------------------------------------------------------------------------------------------------------//
/**
 * Constructor
 * @param iRow index of row in grid
 * @param jColumn index of column in grid
 * @constructor
 */

var Cell = cc.Node.extend({

    width:0,
    height:0,

    locationX:0,
    locationY:0,

    positionX:0,
    positionY:0,

    // Array
    contents:null,

    initialize:function(width, height, lX, lY, posX, posY)
    {
        this.width = width;
        this.height = height;
        this.locationX = lX;
        this.locationY = lY;
        this.positionX = posX;
        this.positionY = posY;

        this.contents = new Array();
    }
});

Cell.prototype.Add = function(entity)
{
    this.contents.push(entity);
}

Cell.prototype.Remove = function(entity)
{
    var index = this.contents.indexOf(entity);
    if(index >= 0)
    {
        this.contents.splice(index, 1);
    }
}

Cell.prototype.Clear = function()
{
    this.contents.splice(0, this.contents.length);
}

Cell.prototype.IsContain = function(entity)
{
    var index = this.contents.indexOf(entity);
    return (index >= 0);
}


text:
@implementation User

- (instancetype)initWithName:(NSString *)name
{
	self = [super init];
	if (self) {
		_name = name;
		_ratings = [[NSMutableSet alloc] init];
	}
	return self;
}

+(User *)userWithName:(NSString *)name {
	return [[User alloc] initWithName:name];
}

-(NSString *)description {
	return [NSString stringWithFormat:@"User '%@', %lu ratings",_name,(unsigned long)_ratings.count];
}

-(void)addRating:(Rating *)rating {
	[_ratings addObject:[NSValue valueWithNonretainedObject:rating]];
}

-(double)meanRating {
	double sum = 0.0;
	for (NSValue *weak_r in _ratings) {
		Rating *r = [weak_r nonretainedObjectValue];
		sum += r.rating;
	}
	return (sum/(double)_ratings.count);
}

-(NSUInteger)hash {
	return _name.hash;
}

-(BOOL)isEqual:(id)object {
	if(![object isKindOfClass:[User class]]) return NO;

	User *otherUser = (User*)object;
	return [otherUser.name isEqualToString:_name] && [_ratings isEqualToSet:otherUser.ratings];
}

-(double)predictionForItem:(Item *)item {
	// check if item is already rated
	for (NSValue *weak_r in _ratings) {
		Rating *r = [weak_r nonretainedObjectValue];
		if(r.item == item) {
			NSLog(@"WARNING - predictionForItem: called with rated item");
			return r.rating;
		}
	}

	double sumMul = 0.0;
	double sumSim = 0.0;

	for (NSValue *weak_r in _ratings) {
		Rating *r = [weak_r nonretainedObjectValue];
		double sim = [r.item similarityTo:item];
		if(isnan(sim)) {
			continue;
		}

		NSLog(@"Similarity between %@ and %@: %f * %f = %f",r.item.name,item.name,r.rating,sim,(r.rating*sim));

		sumMul += r.rating*sim;
		sumSim += fabs(sim);
	}

	return (sumMul/sumSim);
}

@end


text:
A hash table allows you to store and retrieve objects by a "key".

Also called dictionary, map, associative array. There are other ways to implement these, such as with a tree or even a plain array, but hash table is the most common.

This should explain why Swift's built-in `Dictionary` type requires that keys conform to the `Hashable` protocol: internally it uses a hash table, just like the one you'll learn about here.

## How it works

At its most basic, a hash table is nothing more than an array. Initially, this array is empty. When you put a value into the hash table under a certain key, it uses that key to calculate an index in the array, like so:

```swift
hashTable["firstName"] = "Steve"

	The hashTable array:
	+--------------+
	| 0:           |
	+--------------+
	| 1:           |
	+--------------+
	| 2:           |
	+--------------+
	| 3: firstName |---> Steve
	+--------------+
	| 4:           |
	+--------------+
```

In this example, the key `"firstName"` maps to array index 3.

Adding a value under a different key puts it at another array index:

```swift
hashTable["hobbies"] = "Programming Swift"

	The hashTable array:
	+--------------+
	| 0:           |
	+--------------+
	| 1: hobbies   |---> Programming Swift
	+--------------+
	| 2:           |
	+--------------+
	| 3: firstName |---> Steve
	+--------------+
	| 4:           |
	+--------------+
```

The trick is in how the hash table calculates those array indices. That's where the hashing comes in. When you write,

```swift
hashTable["firstName"] = "Steve"
```

the hash table takes the key `"firstName"` and asks it for its `hashValue` property. That's why keys must be `Hashable`.

When you do `"firstName".hashValue`, it returns a big integer: -4799450059917011053. Likewise, `"hobbies".hashValue` has the hash value 4799450060928805186. (The values you see may vary.)

Of course, these numbers are way too big to be used as indices into our array. One of them is even negative! A common way to make these big numbers more suitable is to first make the hash positive and then take the modulo with the array size.

Our array has size 5, so the index for the `"firstName"` key becomes `abs(-4799450059917011053) % 5 = 3`. You can calculate for yourself that the array index for `"hobbies"` is 1.

Using hashes in this manner is what makes the dictionary so efficient: to find an element in the hash table you only have to hash the key to get an array index and then look up the element in the underlying array. All these operations take a constant amount of time, so inserting, retrieving, and removing are all **O(1)**.

> **Note:** As you can see, it's hard to predict where in the array your objects end up. That's why dictionaries do not guarantee any particular order of the elements in the hash table.

## Avoiding collisions

There is one problem: because we take the modulo of the hash value with the size of the array, it can happen that two or more keys get assigned the same array index. This is called a collision.

One way to avoid collisions is to have a very large array. That reduces the likelihood of two keys mapping to the same index. Another trick is to use a prime number for the array size. However, collisions are bound to occur so you need some way to handle them.

Because our table is so small it's easy to show a collision. For example, the array index for the key `"lastName"` is also 3. That's a problem, as we don't want to overwrite the value that's already at this array index.

There are a few ways to handle collisions. A common one is to use chaining. The array now looks as follows:

```swift
	buckets:
	+-----+
	|  0  |
	+-----+     +----------------------------+
	|  1  |---> | hobbies: Programming Swift |
	+-----+     +----------------------------+
	|  2  |
	+-----+     +------------------+     +----------------+
	|  3  |---> | firstName: Steve |---> | lastName: Jobs |
	+-----+     +------------------+     +----------------+
	|  4  |
	+-----+
```

With chaining, keys and their values are not stored directly in the array. Instead, each array element is really a list of zero or more key/value pairs. The array elements are usually called the *buckets* and the lists are called the *chains*. So here we have 5 buckets and two of these buckets have chains. The other three buckets are empty.

If we now write the following to retrieve an item from the hash table,

```swift
let x = hashTable["lastName"]
```

then this first hashes the key `"lastName"` to calculate the array index, which is 3. Bucket 3 has a chain, so we step through that list to find the value with the key `"lastName"`. That is done by comparing the keys, so here that involves a string comparison. The hash table sees that this key belongs to the last item in the chain and returns the corresponding value, `"Jobs"`.

Common ways to implement this chaining mechanism are to use a linked list or another array. Technically speaking the order of the items in the chain doesn't matter, so you also can think of it as a set instead of a list. (Now you can also imagine where the term "bucket" comes from; we just dump all the objects together into the bucket.)

It's important that chains do not become too long or looking up items in the hash table becomes really slow. Ideally, we would have no chains at all but in practice it is impossible to avoid collisions. You can improve the odds by giving the hash table enough buckets and by using high-quality hash functions.

> **Note:** An alternative to chaining is "open addressing". The idea is this: if an array index is already taken, we put the element in the next unused bucket. Of course, this approach has its own upsides and downsides.

## The code

Let's look at a basic implementation of a hash table in Swift. We'll build it up step-by-step.

```swift
public struct HashTable<Key: Hashable, Value> {
  private typealias Element = (key: Key, value: Value)
  private typealias Bucket = [Element]

  private var buckets: [Bucket]
  private(set) var count = 0

  public init(capacity: Int) {
    assert(capacity > 0)
    buckets = .init(count: capacity, repeatedValue: [])
  }

  public var isEmpty: Bool {
    return count == 0
  }
```

The `HashTable` is a generic container and the two generic types are named `Key` (which must be `Hashable`) and `Value`. We also define two other types: `Element` is a key/value pair for use in a chain and `Bucket` is an array of such `Elements`.

The main array is named `buckets`. It has a fixed size, the so-called capacity, provided by the `init(capacity)` method. We're also keeping track of how many items have been added to the hash table using the `count` variable.

An example of how to create a new hash table object:

```swift
var hashTable = HashTable<String, String>(capacity: 5)
```

Currently the hash table doesn't do anything yet, so let's add the remaining functionality. First, add a helper method that calculates the array index for a given key:

```swift
  private func indexForKey(key: Key) -> Int {
    return abs(key.hashValue) % buckets.count
  }
```

This performs the calculation you saw earlier: it takes the absolute value of the key's `hashValue` modulo the size of the buckets array. We've put this in a function of its own because it gets used in a few different places.

There are four common things you'll do with a hash table or dictionary:

- insert a new element
- look up an element
- update an existing element
- remove an element

The syntax for these is:

```swift
hashTable["firstName"] = "Steve"   // insert
let x = hashTable["firstName"]     // lookup
hashTable["firstName"] = "Tim"     // update
hashTable["firstName"] = nil       // delete
```

We can do all these things with a `subscript` function:

```swift
  public subscript(key: Key) -> Value? {
    get {
      return valueForKey(key)
    }
    set {
      if let value = newValue {
        updateValue(value, forKey: key)
      } else {
        removeValueForKey(key)
      }
    }
  }
```

This calls three helper functions to do the actual work. Let's take a look at `valueForKey()` first, which retrieves an object from the hash table.

```swift
  public func valueForKey(key: Key) -> Value? {
    let index = indexForKey(key)

    for element in buckets[index] {
      if element.key == key {
        return element.value
      }
    }
    return nil  // key not in hash table
  }
```

First it calls `indexForKey()` to convert the key into an array index. That gives us the bucket number, but if there were collisions this bucket may be used by more than one key. So `valueForKey()` loops through the chain from that bucket and compares the keys one-by-one. If found, it returns the corresponding value, otherwise it returns `nil`.

The code to insert a new element or update an existing element lives in `updateValue(forKey)`. It's a little bit more complicated:

```swift
  public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
    let index = indexForKey(key)

    // Do we already have this key in the bucket?
    for (i, element) in buckets[index].enumerate() {
      if element.key == key {
        let oldValue = element.value
        buckets[index][i].value = value
        return oldValue
      }
    }

    // This key isn't in the bucket yet; add it to the chain.
    buckets[index].append((key: key, value: value))
    count += 1
    return nil
  }
```

Again, the first thing we do is convert the key into an array index to find the bucket. Then we loop through the chain for that bucket. If we find the key in the chain, it means we must update it with the new value. If the key is not in the chain, we insert the new key/value pair to the end of the chain.

As you can see, it's important that chains are kept short (by making the hash table large enough). Otherwise, you spend a lot of time in these `for`...`in` loops and the performance of the hash table will no longer be **O(1)** but more like **O(n)**.

Removing is similar in that again it loops through the chain:

```swift
  public mutating func removeValueForKey(key: Key) -> Value? {
    let index = indexForKey(key)

    // Find the element in the bucket's chain and remove it.
    for (i, element) in buckets[index].enumerate() {
      if element.key == key {
        buckets[index].removeAtIndex(i)
        count -= 1
        return element.value
      }
    }
    return nil  // key not in hash table
  }
```

These are the basic functions of the hash table. They all work the same way: convert the key into an array index using its hash value, find the bucket, then loop through that bucket's chain and perform the desired operation.

Try this stuff out in a playground. It should work just like a standard Swift `Dictionary`.

## Resizing the hash table

This version of `HashTable` always uses an array of a fixed size or capacity. That's fine if you've got a good idea of many items you'll be storing in the hash table. For the capacity, choose a prime number that is greater than the maximum number of items you expect to store and you're good to go.

The *load factor* of a hash table is the percentage of the capacity that is currently used. If there are 3 items in a hash table with 5 buckets, then the load factor is `3/5 = 60%`.

If the hash table is too small and the chains are long, the load factor can become greater than 1. That's not a good idea.

If the load factor becomes too high, say > 75%, you can resize the hash table. Adding the code for this is left as an exercise for the reader. Keep in mind that making the buckets array larger will change the array indices that the keys map to! To account for this, you'll have to insert all the elements again after resizing the array.

## Where to go from here?

`HashTable` is quite basic. It might be fun to integrate it better with the Swift standard library by making it a `SequenceType`, for example.

*Written for Swift Algorithm Club by Matthijs Hollemans*


text:
template <class N>
struct double_number :
  boost::mpl::times<typename N::type, boost::mpl::int_<2> >
{};

#endif


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import dogsFilterComponent from './dogs-filter.component';

let dogsFilterModule = angular.module('dogs-filter', [
  uiRouter
])

.component('dogsFilter', dogsFilterComponent)

.name;

export default dogsFilterModule;