text:
module Milkshake
  class Template

    class << self
      attr_accessor :template_dir

      def [](name)
        (@templates ||= {})[name] ||= load(name)
      end

      def evaluate(name, context={})
        self[name].evaluate(context)
      end
    end
    self.template_dir = File.join(File.dirname(__FILE__), '..', '..', 'templates')

    def self.load(name)
      path = File.join(self.template_dir, name)
      if File.exist?(path)
        new IO.read(path)
      else
        raise "Missing template #{name}"
      end
    end

    def initialize(template)
      @template = template
    end

    def evaluate(context={})
      result = @template.dup
      result.gsub!(/\{\{([a-zA-Z0-9_.-]+)\}\}/) do |match|
        (context[$1] || context[$1.to_sym]).to_s
      end
      result.extend SourceFile
      result
    end

    module SourceFile
      def write_to(path)
        FileUtils.mkdir_p(File.dirname(path))
        File.open(path, 'w+') { |file| file.write self }
        self
      end
    end

  end
end


text:
/*
$elements: project-covers, user-tooltip, sorting-bar, modals, navigation;
$modal-elements: fields, form-controls, errors, autocomplete-dropdown;

.modal {
   z-index: index($elements, modals);

   .field {
      z-index: index($modal-elements, fields);
   }
   .form-controls {
      z-index: index($modal-elements, form-controls);
   }
   .error {
      z-index: index($modal-elements, errors);
   }
   .autocomplete-dropdown {
      z-index: index($modal-elements, autocomplete-dropdown);
   }

}
*/
/*
$zindex: (
  modal     : "9000",
  overlay   : "8000",
  dropdown  : "7000",
  header    : "6000",
  footer    : "5000"
);

.header {
  z-index: map-get($zindex, header);
}
*/

redpajama_set_name: RedPajamaGithub


text:
package com.iluwatar.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 *  Thread Pool pattern is where a number of threads are created to perform a number of tasks,
 *  which are usually organized in a queue. The results from the tasks being executed might
 *  also be placed in a queue, or the tasks might return no result. Typically, there are many
 *  more tasks than threads. As soon as a thread completes its task, it will request the next
 *  task from the queue until all tasks have been completed. The thread can then terminate, or
 *  sleep until there are new tasks available.
 *
 *  In this example we create a list of tasks presenting work to be done. Each task is then
 *  wrapped into a Worker object that implements Runnable. We create an ExecutorService with
 *  fixed number of threads (Thread Pool) and use them to execute the Workers.
 *
 */
public class App {

    public static void main( String[] args ) {

    	System.out.println("Program started");

    	// Create a list of tasks to be executed
    	List<Task> tasks = new ArrayList<>();
    	tasks.add(new PotatoPeelingTask(3));
    	tasks.add(new PotatoPeelingTask(6));
    	tasks.add(new CoffeeMakingTask(2));
    	tasks.add(new CoffeeMakingTask(6));
    	tasks.add(new PotatoPeelingTask(4));
    	tasks.add(new CoffeeMakingTask(2));
    	tasks.add(new PotatoPeelingTask(4));
    	tasks.add(new CoffeeMakingTask(9));
    	tasks.add(new PotatoPeelingTask(3));
    	tasks.add(new CoffeeMakingTask(2));
    	tasks.add(new PotatoPeelingTask(4));
    	tasks.add(new CoffeeMakingTask(2));
    	tasks.add(new CoffeeMakingTask(7));
    	tasks.add(new PotatoPeelingTask(4));
    	tasks.add(new PotatoPeelingTask(5));

    	// Creates a thread pool that reuses a fixed number of threads operating off a shared
    	// unbounded queue. At any point, at most nThreads threads will be active processing
    	// tasks. If additional tasks are submitted when all threads are active, they will wait
    	// in the queue until a thread is available.
    	ExecutorService executor = Executors.newFixedThreadPool(3);

    	// Allocate new worker for each task
    	// The worker is executed when a thread becomes
    	// available in the thread pool
    	for (int i=0; i<tasks.size(); i++) {
	    	Runnable worker = new Worker(tasks.get(i));
	    	executor.execute(worker);
    	}
    	// All tasks were executed, now shutdown
    	executor.shutdown();
    	while (!executor.isTerminated()) {
    	}
    	System.out.println("Program finished");
    }
}


text:
nmo-help(1) -- get help
=======================

## SYNOPSIS

    nmo help

## DESCRIPTION

Prints the available commands.


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('promgen', '0042_description_field'),
    ]

    operations = [
        migrations.AddField(
            model_name='rule',
            name='description',
            field=models.TextField(blank=True),
        ),
    ]


text:
package org.gislers.chinook.persistence.dao;

import org.gislers.chinook.entities.InvoiceEntity;

/**
 * Created by:   jgisle
 * Created date: 9/10/15
 */
public interface InvoiceDao extends BaseDao<InvoiceEntity> {

}


text:
GiGA Genie 서비스SDK를 이용한 2048 게임입니다.

![2048](https://user-images.githubusercontent.com/32326946/31001833-9185505c-a521-11e7-918f-dde677fa4e08.png)

### 사용한 API
* Best Score를 appdata API로 구현했습니다.

 1. `appdata.createNameSpace`로 Best Scroe를 저장할 namespace 생성

        function createnamespace(){
         var options={};
         options.namespace="bestscore";
         options.shareflag='N';
         gigagenie.appdata.createNameSpace(options,function(result_cd,result_msg,extra){
                if(result_cd===200){
                        console.log("Namespace creation is success.");
                } else{
                        console.log("Namespace creation is fail.");
                }
          });
        }

 2. `appdata.setKeyData`로 Best Score 저장

        function setkeydata(score){
          var options={};
          options.namespace='bestscore';
          options.key='bestscore';
          options.data=score;
          gigagenie.appdata.setKeyData(options,function(result_cd,result_msg,extra){
                if(result_cd===200){
                        console.log(options.key);
                } else {
                        console.log("Error");
                }
          });
        }
 3. `appdata.getKeyData`로 Best Score 가져오기

        function getkeydata(){
          var options={};
          options.namespace='bestscore';
          options.key='bestscore';
          gigagenie.appdata.getKeyData(options,function(result_cd,result_msg,extra){
                if(result_cd===200){
                        console.log('getKeyData:'+extra.data);
                        document.getElementById('bestscore').innerHTML=extra.data;
                } else document.getElementById('bestscore').innerHTML="0";
          });
        }

* 스트리밍 음성인식을 이용하여 음성으로 게임을 즐길 수 있습니다.
 1. `voice.setStreamingRecognize`로 스트리밍 음성인식 API 설정

        function setStreamingRecognize(){
	         var options = {};
	         options.mode = 1;
	         options.waittimeout = 1;
	         options.waitthreshold = 1;
	         options.voicelanguage = 0;
	         gigagenie.voice.setStreamingRecognize(options,function(result_cd,result_msg,extra){
		           if(result_cd===200){
		           	 console.log("Streaming recognize mode has been set.");
		           };
	          });
        }

 2. `voice.onStreamingRecognize`로 '위','아래','왼쪽','오른쪽' 음성명령으로 게임 진행

        gigagenie.voice.onStreamingRecognize=function(extra){
        	 console.log('partial: '+JSON.stringify(extra));
        	 switch(extra.result){
        		  case 'segment':
        			var msg = extra.word;
        			console.log('msg: '+msg);
        			if(msg.indexOf('위') != -1){
        				console.log('위로');
        			   	var event = document.createEvent("Events");
        				event.initEvent("keydown",true,true);
        				event.which=38;
        				document.dispatchEvent(event);
        			}
        			else if(msg.indexOf('아래') != -1){
	        			console.log('아래로');
	        			var event = document.createEvent("Events");
	        		      	event.initEvent("keydown",true,true);
        			      	event.which=40;
        			      	document.dispatchEvent(event);
        			}
        			else if(msg.indexOf('왼') != -1){
        				console.log('왼쪽');
        				var event = document.createEvent("Events");
        				event.initEvent("keydown",true,true);
        				event.which=37;
        			      	document.dispatchEvent(event);
        			}
        		     	else if(msg.indexOf('오른') != -1){
        				console.log('오른쪽');
        			      	var event = document.createEvent("Events");
        			      	event.initEvent("keydown",true,true);
        				event.which=39;
        				document.dispatchEvent(event);
        			}
        			else if(msg.indexOf('그만') != -1 || msg.indexOf('종료') != -1){
        				gigagenie.voice.svcFinished(options,function(result_cd,result_msg,extra){
        					console.log("svcFinished");
        				     	if(result_cd===200){
        						console.log("service finish success");
        					};
        				});
        			}
        			break;
        		case 'text':
        			console.log('Partial Result Received:'+extra.text);
        			break;
        		case 'endOfSegment':
        			console.log('Segment Fianl Result Received:'+extra.endOfSegment);
        			break;
        		case 'waitTimeout':
        			console.log('Streaming recognize mode has been unset.');
        			break;
        	}
        }

## License
GiGA Genie 2048 is licensed under the [MIT license.](https://github.com/GiGAGenie-ServiceSDK/gigagenie-2048/blob/master/LICENSE)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".wallet.WalletAnimationActivity">

    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/coin_iv"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:src="@drawable/icon"
        android:layout_centerInParent="true"
        app:civ_border_width="1dp"
        app:civ_border_color="@color/colorWhite" />

    <TextView
        android:text="钱包"
        android:textColor="@color/colorWhite"
        android:gravity="center"
        android:id="@+id/wallet_iv"
        android:layout_centerInParent="true"
        android:background="@color/colorPrimary"
        android:layout_width="90dp"
        android:layout_height="60dp" />

    <Button
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="START"
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


text:
from oslo_log import log as logging

from nova.tests.functional.api import client
from nova.tests.functional import integrated_helpers

LOG = logging.getLogger(__name__)

class LoginTest(integrated_helpers._IntegratedTestBase):
    _api_version = 'v2'

    def test_login(self):
        # Simple check - we list flavors - so we know we're logged in.
        flavors = self.api.get_flavors()
        for flavor in flavors:
            LOG.debug("flavor: %s", flavor)

class LoginTestV3(client.TestOpenStackClientV3Mixin, LoginTest):
    _api_version = 'v3'


text:
module Seek
  module Subscribable
    def self.included(klass)
      klass.class_eval do
        has_many :subscriptions, as: :subscribable, dependent: :destroy, autosave: true, before_add: proc { |item, sub| sub.subscribable = item } # ,:required_access_to_owner => false,
        after_create :set_subscription_job if self.subscribable?
        after_update :update_subscription_job_if_study_or_assay if self.subscribable?
        extend ClassMethods
      end
    end

    def current_users_subscription
      subscriptions.detect { |ss| ss.person == User.current_user.person }
    end

    def subscribed?(person = User.current_user.person)
      !subscriptions.detect { |sub| sub.person == person }.nil?
    end

    def subscribed=(subscribed)
      if subscribed
        subscribe
      else
        unsubscribe
      end
    end

    def subscribe(person = User.current_user.person)
      subscriptions << Subscription.new(person: person) unless subscribed?(person)
    end

    def unsubscribe(person = User.current_user.person)
      subscriptions.detect { |sub| sub.person == person }.try(:destroy)
    end

    def send_immediate_subscriptions(activity_log)
      if Seek::Config.email_enabled && subscribers_are_notified_of?(activity_log.action)
        subscriptions.each do |subscription|
          if !subscription.person.user.nil? && subscription.person.receive_notifications? && subscription.immediately? && can_view?(subscription.person.user)
            SubMailer.send_immediate_subscription(subscription.person, activity_log).deliver
          end
        end
      end
    end

    def subscribers_are_notified_of?(action)
      self.class.subscribers_are_notified_of? action
    end

    def set_default_subscriptions(projects)
      unless projects.empty?
        Person.scoped(include: :project_subscriptions).each do |person|
          project_subscriptions = person.project_subscriptions
          project_subscriptions.each do |ps|
            if projects.include? ps.project
              subscriptions.create(person: person, project_subscription_id: ps.id) if !ps.unsubscribed_types.include?(self.class.name) && !self.subscribed?(person)
              # also build subscriptions for studies and assays associating with this investigation
              if self.is_a?(Investigation)
                (studies | assays).each do |item|
                  item.subscriptions << Subscription.create(person: person, project_subscription_id: ps.id) unless item.subscribed?(person)
                end
              end
            end
          end
        end
      end
    end

    def remove_subscriptions(projects)
      unless projects.empty?
        project_subscription_ids = projects.collect(&:project_subscriptions).flatten.collect(&:id)
        subscriptions = Subscription.where(['subscribable_type=? AND subscribable_id=? AND project_subscription_id IN (?)', self.class.name, id, project_subscription_ids])
        # remove also subcriptions for studies and assays association with this investigation
        if self.is_a?(Investigation)
          study_ids = studies.collect(&:id)
          assay_ids = assays.collect(&:id)
          subscriptions |= Subscription.where(['subscribable_type=? AND subscribable_id IN (?) AND project_subscription_id IN (?)', 'Study', study_ids, project_subscription_ids])
          subscriptions |= Subscription.where(['subscribable_type=? AND subscribable_id IN (?) AND project_subscription_id IN (?)', 'Assay', assay_ids, project_subscription_ids])
        end
        subscriptions.each(&:destroy)
      end
    end

    def set_subscription_job
      projects = (Seek::Config.project_hierarchy_enabled) ? projects_and_descendants : self.projects
      SetSubscriptionsForItemJob.new(self, projects).queue_job
    end

    def update_subscription_job_if_study_or_assay
      if self.is_a?(Study) && self.investigation_id_changed?
        # update subscriptions for study
        old_investigation_id = investigation_id_was
        old_investigation = Investigation.find_by_id old_investigation_id
        projects_to_remove = old_investigation.nil? ? [] : old_investigation.projects
        projects_to_add = investigation.projects
        update_subscriptions_for self, projects_to_add, projects_to_remove
        # update subscriptions for assays associated with this study
        assays.each do |assay|
          update_subscriptions_for assay, projects_to_add, projects_to_remove
        end
      elsif self.is_a?(Assay) && self.study_id_changed?
        old_study_id = study_id_was
        old_study = Study.find_by_id old_study_id
        projects_to_remove = old_study.nil? ? [] : old_study.projects
        projects_to_add = study.projects
        update_subscriptions_for self, projects_to_add, projects_to_remove
      end
    end

    module ClassMethods
      def subscribers_are_notified_of?(action)
        action == 'create' || action == 'update'
      end
    end

    private

    def update_subscriptions_for(item, projects_to_add, projects_to_remove)
      SetSubscriptionsForItemJob.new(item, projects_to_add).queue_job
      RemoveSubscriptionsForItemJob.new(item, projects_to_remove).queue_job
    end
  end
end

ActiveRecord::Base.class_eval do
  def self.subscribable?
    include? Seek::Subscribable
  end

  def subscribable?
    self.class.subscribable?
  end
end


text:
from django.contrib import messages
from django.contrib.auth import get_backends, get_user_model, login as user_login, views
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.signing import BadSignature, SignatureExpired, Signer, TimestampSigner
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.module_loading import import_string
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, RedirectView, TemplateView, UpdateView

from quickstartup.settings_utils import get_configuration, get_object_from_configuration
from .signals import user_activated
from .forms import AuthenticationForm

# noinspection PyUnresolvedReferences
class ProfileMixin(object):
    # noinspection PyUnusedLocal
    def get_object(self, *args, **kwargs):
        return self.request.user

class LoginView(views.LoginView):
    redirect_authenticated_user = True
    template_name = "accounts/signin.html"
    authentication_form = AuthenticationForm

class LogoutView(views.LogoutView):
    next_page = "/"

class PasswordResetView(FormView):
    template_name = "accounts/reset.html"
    success_url = reverse_lazy("qs_accounts:signin")

    def get_form_class(self):
        return get_object_from_configuration("QS_PASSWORD_RESET_FORM")

    def form_valid(self, form):
        form.save(self.request)
        messages.success(self.request, _("We've e-mailed you instructions for setting a new password to the "
                                         "e-mail address you've submitted."))
        return super().form_valid(form)

class PasswordResetConfirmView(FormView):
    template_name = "accounts/reset-confirm.html"
    success_url = reverse_lazy("qs_accounts:signin")

    # noinspection PyMethodOverriding
    @method_decorator(sensitive_post_parameters())
    @method_decorator(never_cache)
    def dispatch(self, request, reset_token, *args, **kwargs):
        try:
            self.get_username()
        except SignatureExpired:
            messages.error(request, _("Password reset token expired."))
            return redirect(self.get_success_url())
        except BadSignature:
            messages.error(request, _("Invalid password reset token."))
            return redirect(self.get_success_url())
        return super().dispatch(request, reset_token, *args, **kwargs)

    def get_username(self):
        reset_token = self.kwargs["reset_token"]
        signer = TimestampSigner()
        expiration = get_configuration("PASSWORD_RESET_TIMEOUT")
        return signer.unsign(reset_token, max_age=expiration)

    def get_user(self):
        user_model = get_user_model()

        try:
            user = user_model.objects.get_by_natural_key(self.get_username())
        except user_model.DoesNotExist:
            return

        return user

    def get_form_class(self):
        return get_object_from_configuration("QS_PASSWORD_RESET_CONFIRM_FORM")

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        if 'user' in kwargs:
            return kwargs

        kwargs['user'] = self.get_user()
        return kwargs

    def form_valid(self, form):
        form.save(self.request)
        messages.success(self.request, _("Password has been reset successfully."))
        return super().form_valid(form)

class SignupView(FormView):
    template_name = "accounts/signup.html"
    disallowed_url = reverse_lazy("qs_accounts:signup_closed")
    success_url = reverse_lazy("qs_accounts:signup_complete")

    def dispatch(self, request, *args, **kwargs):
        allowed = get_configuration("QS_SIGNUP_OPEN")
        if not allowed:
            return redirect(self.disallowed_url)
        return super().dispatch(request, *args, **kwargs)

    def get_form_class(self):
        return get_object_from_configuration("QS_SIGNUP_FORM")

    def form_valid(self, form):
        form.save(request=self.request)
        messages.success(self.request, _("We've e-mailed you instructions for setting a new password to the "
                                         "e-mail address you've submitted."))

        return super().form_valid(form)

class SignupActivationView(TemplateView):
    template_name = 'accounts/activation-error.html'

    def get_success_url(self):
        return get_configuration("LOGIN_REDIRECT_URL")

    # noinspection PyMethodOverriding
    def get(self, request, activation_key, *args, **kwargs):
        signer = TimestampSigner()
        expiration = get_configuration("QS_SIGNUP_TOKEN_EXPIRATION")
        try:
            username = signer.unsign(activation_key, max_age=expiration)
        except (BadSignature, SignatureExpired):
            return super().get(request, *args, **kwargs)

        user_model = get_user_model()
        try:
            user = user_model.objects.activate(username)
        except user_model.DoesNotExist:
            return super().get(request, *args, **kwargs)

        if user.is_active:
            user_activated.send(sender=self.__class__, user=user, request=request)

        if get_configuration("QS_SIGNUP_AUTO_LOGIN"):
            self._login_user(request, user)
        return redirect(self.get_success_url())

    def _login_user(self, request, user):
        backend = get_backends()[0]  # Hack to bypass `authenticate()`.
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
        user_login(request, user)
        request.session['QS_SIGNUP_AUTO_LOGIN'] = True
        request.session.modified = True

class UserProfileView(LoginRequiredMixin, ProfileMixin, UpdateView):
    success_url = reverse_lazy('qs_accounts:profile')
    form_class = import_string(get_configuration("QS_PROFILE_FORM"))
    template_name = 'accounts/profile.html'

    def form_valid(self, form):
        messages.success(self.request, _(u'Succesfully updated profile.'))
        return super().form_valid(form)

class PasswordChangeView(LoginRequiredMixin, ProfileMixin, UpdateView):
    success_url = reverse_lazy('qs_accounts:profile')
    form_class = get_object_from_configuration("QS_PASSWORD_CHANGE_FORM")
    template_name = 'accounts/password-change.html'

    @method_decorator(sensitive_post_parameters())
    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        messages.success(self.request, _(u'Succesfully updated your password.'))
        return super().form_valid(form)

class EmailChangeView(LoginRequiredMixin, ProfileMixin, UpdateView):
    success_url = reverse_lazy('qs_accounts:profile')
    form_class = get_object_from_configuration("QS_EMAIL_CHANGE_FORM")
    template_name = 'accounts/email-change.html'

    def form_valid(self, form):
        messages.success(self.request, _(u"You'll receive an message in your new e-mail to check it."))
        return super().form_valid(form)

class EmailChangeConfirmationView(LoginRequiredMixin, ProfileMixin, RedirectView):
    url = reverse_lazy("qs_accounts:profile")

    # noinspection PyMethodOverriding
    def get(self, request, activation_key, *args, **kwargs):
        signer = Signer()
        try:
            username = signer.unsign(activation_key)
        except BadSignature:
            messages.error(self.request, _(u"Invalid e-mail configuration token."))
            return super().get(request, *args, **kwargs)

        user_model = get_user_model()
        try:
            user_model.objects.confirm_new_email(username)
            messages.success(self.request, _(u"New e-mail has been successfully configured."))
        except user_model.DoesNotExist:
            messages.error(self.request, _(u"E-mail not found."))

        return super().get(request, *args, **kwargs)


text:
package org.apache.ignite.internal.visor.verify;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.VisorDataTransferObject;

import static java.util.Objects.nonNull;
import static org.apache.ignite.internal.visor.verify.CacheFilterEnum.DEFAULT;

/**
 * Arguments for task {@link VisorIdleVerifyTask}.
 * <br/>
 */
public class VisorIdleVerifyTaskArg extends VisorDataTransferObject {
    /** */
    private static final long serialVersionUID = 0L;

    /** Caches. */
    private Set<String> caches;

    /** Exclude caches or groups. */
    private Set<String> excludeCaches;

    /** Check CRC */
    private boolean checkCrc;

    /** */
    private boolean skipZeros;

    /** Cache kind. */
    private CacheFilterEnum cacheFilterEnum = DEFAULT;

    /**
     * Default constructor.
     */
    public VisorIdleVerifyTaskArg() {
        // No-op.
    }

    /**
     * @param caches Caches.
     * @param excludeCaches Exclude caches or group.
     * @param skipZeros Skip zeros partitions.
     * @param cacheFilterEnum Cache kind, require non null.
     * @param checkCrc Check CRC sum on stored pages on disk.
     */
    public VisorIdleVerifyTaskArg(
        Set<String> caches,
        Set<String> excludeCaches,
        boolean skipZeros,
        CacheFilterEnum cacheFilterEnum,
        boolean checkCrc
    ) {
        assert nonNull(cacheFilterEnum) : "Cache filter can't be null";

        this.caches = caches;
        this.excludeCaches = excludeCaches;
        this.skipZeros = skipZeros;
        this.checkCrc = checkCrc;
        this.cacheFilterEnum = cacheFilterEnum;
    }

    /**
     * @param caches Caches.
     * @param checkCrc Check CRC sum on stored pages on disk.
     */
    public VisorIdleVerifyTaskArg(Set<String> caches, boolean checkCrc) {
        this(caches, null, false, DEFAULT, false);
    }

    /**
     * @param caches Caches.
     */
    public VisorIdleVerifyTaskArg(Set<String> caches) {
        this(caches, null, false, DEFAULT, false);
    }

    /** */
    public boolean checkCrc() {
        return checkCrc;
    }

    /**
     * @return Caches.
     */
    public Set<String> caches() {
        return caches;
    }

    /**
     * @return Exclude caches or groups.
     */
    public Set<String> excludeCaches() {
        return excludeCaches;
    }

    /** {@inheritDoc} */
    @Override public byte getProtocolVersion() {
        return V5;
    }

    /** {@inheritDoc} */
    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
        U.writeCollection(out, caches);

        /**
         * Instance fields since protocol version 2 must be serialized if, and only if class instance isn't child of
         * current class. Otherwise, these fields must be serialized in child class.
         *
         * TODO: https://issues.apache.org/jira/browse/IGNITE-10932 Will remove in 3.0
         */
        if (instanceOfCurrentClass()) {
            U.writeCollection(out, excludeCaches);

            out.writeBoolean(checkCrc);

            out.writeBoolean(skipZeros);

            U.writeEnum(out, cacheFilterEnum);
        }
    }

    /** {@inheritDoc} */
    @Override protected void readExternalData(
        byte protoVer,
        ObjectInput in
    ) throws IOException, ClassNotFoundException {
        caches = U.readSet(in);

        /**
         * Instance fields since protocol version 2 must be deserialized if, and only if class instance isn't child of
         * current class. Otherwise, these fields must be deserialized in child class.
         *
         * TODO: https://issues.apache.org/jira/browse/IGNITE-10932 Will remove in 3.0
         */
        if (instanceOfCurrentClass()) {
            if (protoVer >= V2)
                excludeCaches = U.readSet(in);

            if (protoVer >= V3)
                checkCrc = in.readBoolean();

            if (protoVer >= V4) {
                skipZeros = in.readBoolean();

                cacheFilterEnum = CacheFilterEnum.fromOrdinal(in.readByte());
            }
        }
    }

    /** */
    protected void excludeCaches(Set<String> excludeCaches) {
        this.excludeCaches = excludeCaches;
    }

    /** */
    protected void checkCrc(boolean checkCrc) {
        this.checkCrc = checkCrc;
    }

    /**
     * @return Skip zeros partitions.
     */
    public boolean skipZeros() {
        return skipZeros;
    }

    /** */
    protected void skipZeros(boolean skipZeros) {
        this.skipZeros = skipZeros;
    }

    /** */
    protected void cacheFilterEnum(CacheFilterEnum cacheFilterEnum) {
        assert nonNull(cacheFilterEnum);

        this.cacheFilterEnum = cacheFilterEnum;
    }

    /**
     * @return Kind fo cache.
     */
    public CacheFilterEnum cacheFilterEnum() {
        return cacheFilterEnum;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(VisorIdleVerifyTaskArg.class, this);
    }

    /**
     * @return {@code True} if current instance is a instance of current class (not a child class) and {@code False} if
     * current instance is a instance of extented class (i.e child class).
     */
    private boolean instanceOfCurrentClass() {
        return VisorIdleVerifyTaskArg.class == getClass();
    }
}


text:
namespace onode {

EmbeddedResource::EmbeddedResource(Sandbox *sandbox) : AbstractResource(sandbox) {
    mParent = NULL;

}

EmbeddedResource::EmbeddedResource(Sandbox *sandbox, AbstractResource *parent) : AbstractResource(sandbox) {
    mParent = parent;

    mParent->RegisterEmbeddedResource(this);
}

EmbeddedResource::~EmbeddedResource() {
    if (mParent != NULL) {
        mParent->UnregisterEmbeddedResource(this);
    }
}

void EmbeddedResource::Ready() {

    assert(mSandbox != NULL);

}

}


text:
0.1.6

- Allows passing Symbols instead of Procs for calling other object methods, usage: agis_defm0($redis, :methodname) - no proc
- Redis parameter no longer passed in to method calls

0.1.7

- Removed agis_push
- Fixed size queue frames
- Idempotent retrying approach

0.1.9

- Retry if exceptions or crash, only remove from queue if return

0.1.10

- Fixed a deadly mailbox failure

0.2

- Introduced return box for return value fidelity

0.2.1

- Added timeout parameter
- Retry the lock if it expires and we don't have a result yet

0.2.8

- Introduced :retry and :once options in agis_defm* methods

0.2.9

- Introduced agis_call with no parameters No-op call

0.3.0

- Adds all mailboxes to global list
- Added agis_crunch_all_records for global behavior

0.3.1

- Automatically remove from global list


text:
package com.intellij.openapi.editor.impl;

import com.intellij.openapi.editor.ex.EditorGutterComponentEx;
import com.intellij.openapi.editor.impl.view.EditorPainter;
import com.intellij.openapi.util.registry.Registry;
import consulo.annotation.DeprecationInfo;
import consulo.editor.impl.CodeEditorCaretBase;
import consulo.logging.Logger;

import javax.annotation.Nonnull;
import java.awt.*;

@Deprecated
@DeprecationInfo("Desktop only")
@SuppressWarnings("deprecation")
public class DesktopCaretImpl extends CodeEditorCaretBase {
  private static final Logger LOG = Logger.getInstance(DesktopCaretImpl.class);

  DesktopCaretImpl(@Nonnull DesktopEditorImpl editor, @Nonnull DesktopCaretModelImpl caretModel) {
    super(editor, caretModel);
  }

  @Override
  protected void requestRepaint(VerticalInfo oldVerticalInfo) {
    if (oldVerticalInfo == null) oldVerticalInfo = new VerticalInfo(0, 0, myEditor.getLineHeight());
    if (myVerticalInfo == null) myVerticalInfo = new VerticalInfo(0, 0, myEditor.getLineHeight());

    int oldY, oldHeight, newY, newHeight;
    if (oldVerticalInfo.logicalLineY == myVerticalInfo.logicalLineY && oldVerticalInfo.logicalLineHeight == myVerticalInfo.logicalLineHeight) {
      // caret moved within the same soft-wrapped line, repaint only original and target visual lines
      oldY = oldVerticalInfo.y;
      newY = myVerticalInfo.y;
      oldHeight = newHeight = myEditor.getLineHeight();
    }
    else {
      // caret moved between different (possible soft-wrapped) lines, repaint whole lines
      // (to repaint soft-wrap markers and line numbers in gutter)
      oldY = oldVerticalInfo.logicalLineY;
      oldHeight = oldVerticalInfo.logicalLineHeight;
      newY = myVerticalInfo.logicalLineY;
      newHeight = myVerticalInfo.logicalLineHeight;
    }

    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    final EditorGutterComponentEx gutter = myEditor.getGutterComponentEx();
    final EditorComponentImpl content = (EditorComponentImpl)myEditor.getContentComponent();

    int editorUpdateWidth = myEditor.getScrollPane().getHorizontalScrollBar().getValue() + visibleArea.width;
    int gutterUpdateWidth = gutter.getWidth();
    int additionalRepaintHeight = this == myCaretModel.getPrimaryCaret() && Registry.is("editor.adjust.right.margin") && EditorPainter.isMarginShown(myEditor) ? 1 : 0;
    if ((oldY <= newY + newHeight) && (oldY + oldHeight >= newY)) { // repaint regions overlap
      int y = Math.min(oldY, newY);
      int height = Math.max(oldY + oldHeight, newY + newHeight) - y;
      content.repaintEditorComponent(0, y - additionalRepaintHeight, editorUpdateWidth, height + additionalRepaintHeight);
      gutter.repaint(0, y, gutterUpdateWidth, height);
    }
    else {
      content.repaintEditorComponent(0, oldY - additionalRepaintHeight, editorUpdateWidth, oldHeight + additionalRepaintHeight);
      gutter.repaint(0, oldY, gutterUpdateWidth, oldHeight);
      content.repaintEditorComponent(0, newY - additionalRepaintHeight, editorUpdateWidth, newHeight + additionalRepaintHeight);
      gutter.repaint(0, newY, gutterUpdateWidth, newHeight);
    }
  }
}


text:
{% extends 'base/base.html' %}
{% block sidebar %}
  {% include 'base/include_sidebar.html' %}
{% endblock %}
{% block body %}

{% block header %}{% endblock %}

      {% block content %}
      {% endblock %}

{% endblock %}


text:
exports.allow = [
  // We frequently refer to form props by their name "disabled".
  // Ideally we would alex-ignore only the valid uses (PRs accepted).
  "invalid",

  // Unfortunately "watchman" is a library name that we depend on.
  "watchman-watchwoman"
];

// Use a "maybe" level of profanity instead of the default "unlikely".
exports.profanitySureness = 1;


text:
<?php

abstract class Admin_FormAction_Abstract extends CM_FormAction_Abstract {

    protected function _checkData(CM_Params $params, CM_Http_Response_View_Form $response, CM_Form_Abstract $form) {
        if (!$response->getViewer(true)->getRoles()->contains(Denkmal_Role::ADMIN, Denkmal_Role::PUBLISHER)) {
            $response->addError($response->getRender()->getTranslation('Not Allowed'));
        }
    }
}


text:
import { inject, injectable } from "inversify";
import { CommandContribution, CommandRegistry, Command } from '@theia/core/lib/common';
import { SHOW_REFERENCES } from "@theia/editor/lib/browser";
import { WorkspaceEdit, Workspace } from "@theia/languages/lib/common";

/**
 * Show Java references
 */
export const SHOW_JAVA_REFERENCES: Command = {
    id: 'java.show.references'
};

/**
 * Apply Workspace Edit
 */
export const APPLY_WORKSPACE_EDIT: Command = {
    id: 'java.apply.workspaceEdit'
};

@injectable()
export class JavaCommandContribution implements CommandContribution {

    constructor(
        @inject(Workspace) protected readonly workspace: Workspace
    ) { }

    registerCommands(commands: CommandRegistry): void {
        commands.registerCommand(SHOW_JAVA_REFERENCES, {
            execute: (uri: string, position: Position, locations: Location[]) =>
                commands.executeCommand(SHOW_REFERENCES.id, uri, position, locations)
        });
        commands.registerCommand(APPLY_WORKSPACE_EDIT, {
            execute: (changes: WorkspaceEdit) =>
                !!this.workspace.applyEdit && this.workspace.applyEdit(changes)
        });
    }

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

exports.createReverseLink = createReverseLink;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _utils = require('./utils');

function createReverseLink(React, Link) {
  return (function (_React$Component) {
    _inherits(ReverseLink, _React$Component);

    function ReverseLink() {
      _classCallCheck(this, ReverseLink);

      _get(Object.getPrototypeOf(ReverseLink.prototype), 'constructor', this).apply(this, arguments);
    }

    _createClass(ReverseLink, [{
      key: 'render',
      value: function render() {
        var path = (0, _utils.reverse)(this.props.routes, this.props.to, this.props.params);

        return React.createElement(Link, _extends({}, this.props, { to: path }));
      }
    }], [{
      key: 'propTypes',
      value: {
        to: React.PropTypes.string,
        routes: React.PropTypes.array.isRequired,
        params: React.PropTypes.object
      },
      enumerable: true
    }]);

    return ReverseLink;
  })(React.Component);
}


text:
'use strict'
const url = '/api/priv/movimientos'
const urlS = '/api/pub/sesiones'
let sessionId
module.exports.test = (req) => {
    describe(url, () => {
        before((done) => {
            req
                .post(urlS)
                .send({ email: 'a@b.c', password: '1234' })
                .end((err, res) => {
                    if (err) return done(err)
                    sessionId = res.body
                    return done()
                })
        })
        it('GET respond with 401 unauthorized to non authenticated users',
            (done) =>
                req
                    .get(url)
                    .expect(401, done))
        it('GET respond with 204 no content to a new authenticated user',
            (done) => {
                req
                    .get(url)
                    .set('sessionId', sessionId)
                    .expect(204, done)
            })
        it('POST respond with 201 created to a new movimiento by authenticated user', (done) => {
            req
                .post(url)
                .send({ esIngreso: 1, importe: 199, fecha: new Date() })
                .set('sessionId', sessionId)
                .expect(201, done)
        })
        it('GET respond with 200 ok to a pos-write user', (done) => {
            req
                .get(url)
                .set('sessionId', sessionId)
                .expect(200, done)
        })
        it('GET respond with 200 ok to a real movimiento id', (done) => {
            req
                .get(`${url}/0`)
                .set('sessionId', sessionId)
                .expect(200, done)
        })
        it('GET respond with 404 not found to a non real movimiento id', (done) => {
            req
                .get(`${url}/999`)
                .set('sessionId', sessionId)
                .expect(404, done)
        })
        it('PUT respond with 200 ok to a modification on a movimiento by authenticated user', (done) => {
            req
                .put(`${url}/0`)
                .send({ esIngreso: 1, importe: 299, fecha: new Date() })
                .set('sessionId', sessionId)
                .expect(200, done)
        })
        it('PUT respond with 404 not found to a modification on a movimiento not found', (done) => {
            req
                .put(`${url}/999`)
                .send({ esIngreso: 1, importe: 299, fecha: new Date() })
                .set('sessionId', sessionId)
                .expect(404, done)
        })
        it('DELETE respond with 204 no content to a deletion on a movimiento by authenticated user', (done) => {
            req
                .delete(`${url}/0`)
                .set('sessionId', sessionId)
                .expect(204, done)
        })
        it('DELETE respond with 404 not found to a deletion on a movimiento not found', (done) => {
            req
                .delete(`${url}/999`)
                .set('sessionId', sessionId)
                .expect(404, done)
        })
        it('GET respond with 204 no content to a new authenticated user',
            (done) => {
                req
                    .get(url)
                    .set('sessionId', sessionId)
                    .expect(204, done)
            })
    })
}


text:
package org.apache.accumulo.test.randomwalk.bulk;

import org.apache.accumulo.test.randomwalk.State;
import org.apache.hadoop.io.Text;

public class Compact extends BulkTest {

  @Override
  protected void runLater(State state) throws Exception {
    Text[] points = Merge.getRandomTabletRange(state);
    log.info("Compacting " + Merge.rangeToString(points));
    state.getConnector().tableOperations().compact(Setup.getTableName(), points[0], points[1], false, true);
  }

}


text:
package org.infinispan.factories.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation is used for components that will be registered in the {@link org.infinispan.factories.ComponentRegistry},
 * that are meant to be retained in the component registry even after the component registry is stopped.  Components
 * annotated as such would not have to be recreated and rewired between stopping and starting a component registry.
 *

 * As a rule of thumb though, use of this annotation on components should be avoided, since resilient components are
 * retained even after a component registry is stopped and consume resources.  Only components necessary for and critical
 * to bootstrapping and restarting the component registry should be annotated as such.
 *
 * @author Manik Surtani (manik@jboss.org)
 * @since 4.0
 */
// ensure this annotation is available at runtime.
@Retention(RetentionPolicy.RUNTIME)

// only applies to classes.
@Target(ElementType.TYPE)
public @interface SurvivesRestarts {
}


text:
@interface MagnetPopoverView : UIView

@property CGFloat horizontalPadding;

@property CGFloat verticalPadding;

@property CGFloat arrowHeight;

@property CGFloat arrowWidth;

@property (nonatomic, readonly) UIView *contentView;

- (instancetype)initWithContentView:(UIView *)contentView;

- (void)showPopover:(CGRect)targetRect;

- (void)dismissPopover;

- (BOOL)isVisible;

@end


text:
({
	singleSort: "Jedan sort",
	nestedSort: "Ugniježđeni sort",
	ascending: "Uzlazno",
	descending: "Silazno",
	sortingState: "${0} - ${1}",
	unsorted: "Ne sortiraj ovaj stupac",
	indirectSelectionRadio: "Red ${0}, jedan izbor, radio kućica",
	indirectSelectionCheckBox: "Red ${0}, više izbora, kontrolna kućica",
	selectAll: "Izaberi sve"
})


text:
package com.planet_ink.coffee_mud.Items.BasicTech;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.Technical.TechType;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class GenDeflectionShield extends GenPersonalShield
{
	@Override
	public String ID()
	{
		return "GenDeflectionShield";
	}

	public GenDeflectionShield()
	{
		super();
		setName("a deflection shield generator");
		setDisplayText("a deflection shield generator sits here.");
		setDescription("The deflection shield generator is worn about the body and activated to use. It deflects all manner of weapon types. ");
	}

	@Override
	protected String fieldOnStr(MOB viewerM)
	{
		return L((owner() instanceof MOB)?
			"A deflectant field of energy surrounds <O-NAME>.":
			"A deflectant field of energy surrounds <T-NAME>.");
	}

	@Override
	protected String fieldDeadStr(MOB viewerM)
	{
		return L((owner() instanceof MOB)?
			"The deflection field around <O-NAME> flickers and dies out.":
			"The deflection field around <T-NAME> flickers and dies out.");
	}

	@Override
	protected boolean doShield(MOB mob, CMMsg msg, double successFactor)
	{
		if(mob.location()!=null)
		{
			if(msg.tool() instanceof Weapon)
			{
				final String s="^F"+((Weapon)msg.tool()).hitString(0)+"^N";
				if(s.indexOf("<DAMAGE> <T-HIM-HER>")>0)
					mob.location().show(msg.source(),msg.target(),msg.tool(),CMMsg.MSG_OK_VISUAL,CMStrings.replaceAll(s, "<DAMAGE>", L("it deflects off the shield around")));
				else
				if(s.indexOf("<DAMAGES> <T-HIM-HER>")>0)
					mob.location().show(msg.source(),msg.target(),msg.tool(),CMMsg.MSG_OK_VISUAL,CMStrings.replaceAll(s, "<DAMAGES>", L("deflects off the shield around")));
				else
					mob.location().show(mob,msg.source(),msg.tool(),CMMsg.MSG_OK_VISUAL,L("The field around <S-NAME> deflects the <O-NAMENOART> damage."));
			}
			else
				mob.location().show(mob,msg.source(),msg.tool(),CMMsg.MSG_OK_VISUAL,L("The field around <S-NAME> deflects the <O-NAMENOART> damage."));
		}
		return false;
	}

	@Override
	protected boolean doesShield(MOB mob, CMMsg msg, double successFactor)
	{
		return activated() ?( (Math.random() >= successFactor) ) : false ;
	}
}


text:
import { StacksMessage, serializeStacksMessage, deserializeStacksMessage } from '../src/types';
import { BufferReader } from '../src/bufferReader';
import { StacksMessageType } from '../src/constants';

export function serializeDeserialize(value: StacksMessage, type: StacksMessageType): StacksMessage {
  const serialized = serializeStacksMessage(value);
  const bufferReader = new BufferReader(serialized);
  return deserializeStacksMessage(bufferReader, type);
}


text: CKEDITOR.plugins.setLang("selectall","nl",{toolbar:"Alles selecteren"});


text:
import os
import unittest
from cloudify.mocks import MockCloudifyContext
from cloudify.state import current_ctx
from jboss import utils

class TestUtils(unittest.TestCase):

    def setUp(self):
        ctx = MockCloudifyContext()
        current_ctx.set(ctx)

    def test_utils_temp_folder(self):
        util = utils.Utils()
        tempdir = util.tempdir
        self.assertTrue(os.path.exists(tempdir))
        del util
        self.assertFalse(os.path.exists(tempdir))

    def test_utils_to_script(self):
        util = utils.Utils()
        filename = util.tempdir + '/' + 'test'
        command = 'Test'
        util.save_command_to_file(command, filename)
        f = open(filename, 'r')
        self.assertEqual(f.read(), command)

    def test_utils_append_flags_to_script(self):
        util = utils.Utils()
        filename = util.tempdir + '/' + 'test'
        command = 'Test'
        util.save_command_to_file(command, filename)
        flags = '--Flags'
        util.append_command_flags(flags, filename)
        f = open(filename, 'r')
        self.assertEqual(f.read(), command + ' ' + flags)

    def test_utils_append_command_to_script(self):
        util = utils.Utils()
        filename = util.tempdir + '/' + 'test'
        command = 'Test'
        util.save_command_to_file(command, filename)
        command2 = 'Test2'
        util.append_command_to_file(command2, filename)
        f = open(filename, 'r')
        self.assertEqual(f.read(), command + '\n' + command2)

    def test_utils_subproces(self):
        command = 'Test'
        out = utils.Utils.system('echo', command)
        self.assertEqual(out, command + '\n')

if __name__ == '__main__':
    unittest.main()


text:
package de.fhb;

import org.apache.commons.io.output.FileWriterWithEncoding;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public final class Utils {

    private final String rootPath;
    private final String packageName;
    private final String packagePath;
    private final String workDir;

    private final FolderPackage rootPackage;

    private final Map<FileType, FolderPackage> fileMetaData;

    public Utils(String rootPath, String packageName, String workDir) {
        this.workDir = workDir;
        this.rootPath = (workDir + rootPath);
        this.packageName = packageName;
        this.packagePath = this.rootPath + packageName.replace('.', '/');
        rootPackage = new FolderPackage(packagePath, packageName);

        fileMetaData = new HashMap<FileType, FolderPackage>() {{
            put(FileType.DTO, rootPackage.withAdded("dto"));
            put(FileType.APPLICATION_PROPERTIES, new FolderPackage(workDir + "src/main/resources", ""));
            put(FileType.MODEL, rootPackage.withAdded("model"));
            put(FileType.SERVICE_INTERFACE, rootPackage.withAdded("service.interfaces"));
            put(FileType.SERVICE, rootPackage.withAdded("service"));
            put(FileType.REPOSITORY, rootPackage.withAdded("repository"));
            put(FileType.CONTROLLER, rootPackage.withAdded("controller"));
            put(FileType.MAIN_CLASS, rootPackage);
            put(FileType.BUILD_SETTINGS, new FolderPackage(workDir + "/.", ""));
            put(FileType.DTO_MAPPER, rootPackage.withAdded("util"));
        }};
    }

    public void createMainClass() throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriterWithEncoding(new File(
                rootPackage.getFolder(), "Application.java"), "UTF-8"));
        final String content = "package " + packageName + ";\n\n" +
                "import org.springframework.boot.SpringApplication;\n" +
                "import org.springframework.boot.autoconfigure.SpringBootApplication;\n" +
                "import org.springframework.boot.builder.SpringApplicationBuilder;\n" +
                "import org.springframework.boot.context.web.SpringBootServletInitializer;\n" +
                "\n" +
                "@SpringBootApplication\n" +
                "public class Application extends SpringBootServletInitializer {\n" +
                "\n" +
                "    @Override\n" +
                "    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {\n" +
                "        return application.sources(Application.class);\n" +
                "    }\n" +
                "\n" +
                "    public static void main(String[] args) {\n" +
                "        SpringApplication.run(Application.class, args);\n" +
                "    }\n" +
                "}";
        bufferedWriter.write(content);
        bufferedWriter.flush();

    }

    public void createDataSourceConfiguration() throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriterWithEncoding(new File(
                rootPackage.getFolder(), "DataSourceConfiguration.java"), "UTF-8"));
        final String content = "package " + packageName + ";\n\n" + "import com.zaxxer.hikari.HikariConfig;\n" +
                "import com.zaxxer.hikari.HikariDataSource;\n" +
                "\n" +
                "import org.springframework.beans.factory.annotation.Value;\n" +
                "import org.springframework.context.annotation.Bean;\n" +
                "import org.springframework.context.annotation.Configuration;\n" +
                "\n" +
                "import java.util.Properties;\n" +
                "\n" +
                "import javax.sql.DataSource;\n" +
                "\n" +
                "@Configuration\n" +
                "public class DataSourceConfiguration {\n" +
                "\n" +
                "    @Value(\"${spring.datasource.username}\")\n" +
                "    private String user;\n" +
                "\n" +
                "    @Value(\"${spring.datasource.password}\")\n" +
                "    private String password;\n" +
                "\n" +
                "    @Value(\"${spring.datasource.url}\")\n" +
                "    private String dataSourceUrl;\n" +
                "\n" +
                "    @Value(\"${spring.datasource.driver-class-name}\")\n" +
                "    private String driverClassName;\n" +
                "\n" +
                "    @Value(\"${spring.datasource.connection-test-query}\")\n" +
                "    private String connectionTestQuery;\n" +
                "\n" +
                "\n" +
                "    @Bean\n" +
                "    public DataSource primaryDataSource() {\n" +
                "        Properties dsProps = new Properties();\n" +
                "        dsProps.setProperty(\"url\", dataSourceUrl);\n" +
                "        dsProps.setProperty(\"user\", user);\n" +
                "        dsProps.setProperty(\"password\", password);\n" +
                "\n" +
                "        Properties configProps = new Properties();\n" +
                "        configProps.setProperty(\"connectionTestQuery\", connectionTestQuery);\n" +
                "        configProps.setProperty(\"driverClassName\", driverClassName);\n" +
                "        configProps.setProperty(\"jdbcUrl\", dataSourceUrl);\n" +
                "\n" +
                "        HikariConfig hc = new HikariConfig(configProps);\n" +
                "        hc.setDataSourceProperties(dsProps);\n" +
                "        HikariDataSource dataSource =  new HikariDataSource(hc);\n" +
                "        dataSource.setMaximumPoolSize(100);\n" +
                "        dataSource.addDataSourceProperty(\"cachePrepStmts\", true);\n" +
                "        dataSource.addDataSourceProperty(\"prepStmtCacheSize\", 250);\n" +
                "        dataSource.addDataSourceProperty(\"prepStmtCacheSqlLimit\", 2048);\n" +
                "        dataSource.addDataSourceProperty(\"useServerPrepStmts\", true);\n" +
                "        return dataSource;\n" +
                "    }\n" +
                "\n" +
                "}\n";
        bufferedWriter.write(content);
        bufferedWriter.flush();
    }

    public Map<FileType, FolderPackage> getFileMetaData() {
        return fileMetaData;
    }

    public String getPackagePath() {
        return packagePath;
    }

    public FolderPackage getRootPackage() {
        return rootPackage;
    }

    public String getWorkDir() {
        return workDir;
    }

    public String getRootPath() {
        return rootPath;
    }

    public String getPackageName() {
        return packageName;
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + "/spec_helper")

Dir[File.expand_path(File.dirname(__FILE__) + "/../../vendor/rails/*/lib")].each do |rails_lib|
  $:.unshift rails_lib
end

ENV["RAILS_ENV"] = "test"
$:.unshift File.expand_path(File.dirname(__FILE__) + "/../support/rails_app/controllers")

require "initializer"
require "action_controller"

ActionController::Base.session = {:key => "_myapp_session", :secret => "a"*30}

require "spectie/rails"

module HelperToTestRailsIntegration
  def method_missing(method, *args, &block)
    if method.to_sym == :i_dont_exist_in_the_integration_session
      # handled here
    else
      super
    end
  end
end

Spec::Runner.configure do |config|
  config.include HelperToTestRailsIntegration
end


text:
<?php

namespace BionicUniversity\Bundle\UserBundle\Routing;

use Symfony\Bundle\FrameworkBundle\Routing\Router as Base;
use Symfony\Component\Routing\Router as BaseRouter;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

class Router extends Base
{
    public function __construct(ContainerInterface $container, $resource, array $options = array(), RequestContext $context = null)
    {
        $this->con = $container;
        parent::__construct($container, $resource, $options, $context);

    }

    public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
    {
        return parent::generate($name, array_merge($parameters, ['_token' => $this->con->get('form.csrf_provider')->generateCsrfToken('anything')]), $referenceType);
    }
}


text:
<?php

defined('JPATH_BASE') or die;
?>
<div class="btn-wrapper" <?php echo $displayData['id']; ?>>
	<?php echo $displayData['action']; ?>
</div>


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>CreateMnyDbPlugin (sunriise-core 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2018-10-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.hungle.sunriise.gui

Interface CreateMnyDbPlugin

public interface CreateMnyDbPlugin

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

MnyDb
openDb(String dbFileName,
      char[] passwordChars,
      boolean readOnly,
      boolean encrypted)

Open db.

Method Detail

openDb

MnyDb openDb(String dbFileName,
             char[] passwordChars,
             boolean readOnly,
             boolean encrypted)

Open db.

Parameters:

dbFileName - the db file name

passwordChars - the password chars

readOnly - the read only

encrypted - the encrypted

Returns:

the opened db

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2018. All rights reserved.


text: bool allowedFamily(NSString* familyName);


text:
FactoryGirl.define do
  factory :problem do
  end
end


text:
package org.sculptor.examples.library.media.domain;

import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.sculptor.examples.library.media.domain.MediaBase;
import org.sculptor.examples.library.media.domain.PhysicalMedia;

/**
 *
 * Entity representing Media. This class is responsible for the domain object
 * related business logic for Media. Properties and associations are implemented
 * in the generated base class
 * {@link org.sculptor.examples.library.media.domain.MediaBase}.
 */
@Entity(name = "Media")
@Table(name = "MEDIA")
@Inheritance(strategy = InheritanceType.JOINED)
@NamedQueries({ @NamedQuery(name = "Media.findMediaByTitle", query = "select m from Media m, in(m.physicalMedia) pm where m.title = :title and pm.library.id = :libraryId") })
// removed abstract, because datanucleus has problems with abstract entities
public class Media extends MediaBase {
	private static final long serialVersionUID = 1L;

	protected Media() {
	}

	public Media(String title) {
		super(title);
	}

	public boolean existsInLibrary(Long libraryId) {
		for (PhysicalMedia p : getPhysicalMedia()) {
			if (libraryId.equals(p.getLibrary().getId())) {
				return true;
			}
		}
		// none found
		return false;
	}
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.evernym.vcx.sdk.android" />


text:
echo ""
echo "===================================================================================================="
echo "Starting H2 database"
echo "===================================================================================================="
echo ""

DIRNAME=`pwd`

H2_DATABASE_JAR=$JBOSS_HOME/modules/system/layers/base/com/h2database/h2/main/h2-1.4.190.jar

checkTcpPort(){
  local tcpPort=":$1"
  case "`uname`" in
    CYGWIN*)
        echo "Cygwin is not supported for now. Try to use another Linux variant, like MacOS, FreeBSD, Ubuntu or Solaris."
        exit 1
        ;;
    Darwin*)
        echo `netstat -anp tcp | awk -v tcpPort="$tcpPort" '$6 == "LISTEN" && $4 ~ "\$tcpPort"'`
        ;;
    FreeBSD*)
        echo `netstat -lnt | awk -v tcpPort="$tcpPort" '$6 == "LISTEN" && $4 ~ $tcpPort'`
        ;;
    Linux*)
        echo `netstat -lnt | awk -v tcpPort="$tcpPort" '$6 == "ESCUCHAR" && $4 ~ tcpPort "$"'`
        ;;
    SunOS*)
        echo `netstat -lnt | awk -v tcpPort="$tcpPort" '$6 == "LISTEN" && $4 ~ $tcpPort'`
        ;;
  esac
}

if [ -z "$JBOSS_HOME" ]; then
  echo "The environment variable JBOSS_HOME can not be found. JBoss Wildfly is not installed or the"
  echo "environment variable is not set."
  echo ""
  echo "If not installed, download and install JBoss Wildfly version 8.1.0 from the website:"
  echo ""
  echo "    http://wildfly.org/downloads"
  echo ""
  exit 1
fi

H2DB=$(checkTcpPort 9092)
if [ -n "$H2DB" ]; then
   echo ""
   echo "There is already a process running on tcp port 9092. This is"
   echo "probably the H2 database. Use the task manager to close this process or use the"
   echo "usef-stop-enviroment script to stop the USEF environment."
   echo ""
   echo "Or execute the following command to stop the H2 Database manually:"
   echo "   javaw -classpath $H2_DATABASE_JAR org.h2.tools.Server -tcpShutdownForce ""tcp://localhost"""
   echo ""
   exit 1
fi

java -version >/dev/null 2>&1
if [ $? -ne 0 ]; then
  echo "Java can not be started. It can not be found on the PATH. It looks like it is not installed."
  echo ""
  echo "If not installed, download and install Java from the website:"
  echo ""
  echo "    http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html#javasejdk"
  echo ""
  exit 1
fi

echo ""
echo "H2_DATABASE_JAR  = $H2_DATABASE_JAR"
echo ""

java -classpath $H2_DATABASE_JAR org.h2.tools.Server -tcp -tcpPort 9092 -tcpAllowOthers -web -webAllowOthers -webPort 8082 &
echo ""

echo ""
echo ""
echo "===================================================================================================="
echo "The USEF database has been started. Use the start-usef-environment script to start the USEF"
echo "environment."
echo "===================================================================================================="


text:
@interface ViewController () <UISearchBarDelegate>

@property (nonatomic, strong) NSMutableArray *contacts;

@end

@implementation ViewController

- (NSMutableArray *)contacts {
    if (!_contacts) {
        _contacts = [[ContactTool contacts] mutableCopy];
        if (!_contacts) {
            _contacts = [NSMutableArray array];
        }
    }
    return _contacts;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
}

- (IBAction)insert:(id)sender {
    NSArray *names = @[@"Jack", @"Alex", @"Mike", @"Susam"];
    NSString *name = [NSString stringWithFormat:@"%@%d", names[arc4random_uniform(4)], arc4random_uniform(200)];
    NSString *phone = [NSString stringWithFormat:@"%d", arc4random_uniform(10000) + 10000];
    Contact *contact = [Contact contactWithName:name phone:phone];
    [self.contacts addObject:contact];
    [ContactTool saveContact:contact];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count - 1 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    // 模糊查询名字或者电话是否包含搜索关键字
    // stringWithFormat 中 '%' 是特殊字符 '%%' 才是 '%'
    NSString *sql = [NSString stringWithFormat:@"select * from t_contact where name like '%%%@%%' or phone like '%%%@%%';", searchText, searchText];
    // select * from t_contact where name like '%searchText%' or phone like '%searchText%'
    _contacts = [[ContactTool contactWithSQL:sql] mutableCopy];
    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%s", __func__);
    // 发送网络请求
    // ...
    // 刷新表格
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contacts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    Contact *contact  = self.contacts[indexPath.row];
    cell.textLabel.text = contact.name;
    cell.detailTextLabel.text = contact.phone;
    return cell;
}

@end


text:
/**
 * @author Alexander D. Shipilov
 * @version $Revision: 1.4 $
 */

package org.apache.harmony.test.stress.misc;

import junit.framework.TestCase;
import org.apache.harmony.test.share.stress.ReliabilityRunner;

public class LargeObjects47 extends TestCase {

    public void test() {
        int STRESS_LOAD = 10;
        STRESS_LOAD = Integer.getInteger(
                "org.apache.harmony.test."
                        + "stress.misc."
                        + "LargeObjects47.STRESS_LOAD", 10).intValue();

        for (int i = 0; i < STRESS_LOAD; i++) {
            try {
                new LargeObjects47lo();
            } catch (OutOfMemoryError er) {
                ReliabilityRunner.debug(".");
            }
        }
    }
}

class LargeObjects47lo {
    int testArray[][][] = new int[100000][100000][100000];
}


text:
<?php

namespace Zelenin\yii\SemanticUI\assets;

use Yii;
use yii\web\AssetBundle;

class SemanticUIJSAsset extends AssetBundle
{
    /**
     * @var string
     */
    public $sourcePath = '@vendor/bower/semantic/dist';

    /**
     * @var array
     */
    public $depends = [
        'yii\web\JqueryAsset',
        'Zelenin\yii\SemanticUI\assets\SemanticUICSSAsset'
    ];

    public function init()
    {
        $postfix = YII_DEBUG ? '' : '.min';
        $this->js[] = 'semantic' . $postfix . '.js';

        parent::init();
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Empleados extends MY_Controller {
	public function __construct()
	{

		parent::__construct();
		$this->load->model('empleado_model');
		$this->load->helper('dropdown');

	}

	public function index()
	{
		$data['user_id']    = $this->tank_auth->get_user_id();

        $username   = $this->tank_auth->get_username();
        $data['nombre_de_usuario'] = $this->empleado_model->getName($username);
		$data['is_admin']   = $this->tank_auth->is_admin();
		$data['panelheading'] = "Empleados";
		$data['options'] = listData('adscripciones','id','adscripcion' ,'descripcion','ASC',' - ');
		$this->load->model('puesto_model');
        $this->load->model('horario_model');
		$data['horarios'] = $this->horario_model->as_dropdown('horario')->order_by('horario', 'ASC')->get_all();
		$data['puestos'] = $this->puesto_model->as_dropdown('puesto')->get_all();
		$data['index'] = "empleados/index";
		$this->load->view('layouts/index', $data);

	}
	public function show($id) {
		$data['user_id']    = $this->tank_auth->get_user_id();
        $this->load->model('pase_model');
        $this->load->model('qna_model');
        $username   = $this->tank_auth->get_username();
        $data['nombre_de_usuario'] = $this->empleado_model->getName($username);
	    $data['is_admin']   = $this->tank_auth->is_admin();
		if ($this->uri->segment(3) != '') {
			$id = $this->uri->segment(3);
		}
		$data['empleado_id'] = $id;
		$data['pases'] = $this->pase_model->get_pases($id);
		$data['qnas'] = listData2('qnas','id','qna_mes' ,'qna_year','activa');

		$data['empleado'] = $this->empleado_model->get_empleado_join($id);
		$data['options'] = listData('adscripciones','id','adscripcion' ,'descripcion','ASC',' - ');
		$data['index'] = "empleados/show";

		$this->load->model('puesto_model');
        $this->load->model('horario_model');
		$data['horarios'] = $this->horario_model->as_dropdown('horario')->order_by('horario', 'ASC')->get_all();
		$data['puestos'] = $this->puesto_model->as_dropdown('puesto')->get_all();
		$data['panelheading'] = "Empleados";

		$this->load->view('layouts/index', $data);

	}

	public function add() {

		$this->form_validation->set_rules('num_empleado', 'Numero de empleado', 'trim|required|xss_clean|numeric|min_length[5]|max_length[6]');
		$this->form_validation->set_rules('nombres', 'Nombre(s)', 'trim|required|min_length[4]|xss_clean|max_length[20]');
		$this->form_validation->set_rules('apellido_pat', 'Apellido Paterno', 'trim|required|xss_clean|min_length[4]|max_length[20]');
		$this->form_validation->set_rules('apellido_mat', 'Apellido Materno', 'trim|required|xss_clean|min_length[4]|max_length[20]');
		$this->form_validation->set_rules('adscripcion_id','Adscripcion', 'required|xss_clean|callback_require_dropdown');

		if($this->form_validation->run() == FALSE) {
			$data = array(
					'errors' => validation_errors()
				);
			$this->session->set_flashdata($data);
			echo '
Llene todos los campos correctamente
';

		}
		else {

			$num_empleado 	= $this->input->post('num_empleado');
			$nombres 		= strtoupper($this->input->post('nombres'));
			$apellido_pat 	= strtoupper($this->input->post('apellido_pat'));
			$apellido_mat 	= strtoupper($this->input->post('apellido_mat'));
			$adscripcion_id = $this->input->post('adscripcion_id');
			$activo 		= 1;//$this->input->post('activo');
			$horario_id 	= $this->input->post('horario_id');
			$puesto_id 		= $this->input->post('puesto_id');
			$adscripcion_id = $this->input->post('adscripcion_id');

			$this->empleado_model->insert(array(
				'num_empleado' => $num_empleado,
				'nombres' => $nombres,
				'apellido_pat' => $apellido_pat,
				'apellido_mat' => $apellido_mat,
				'adscripcion_id' => $adscripcion_id,
				'horario_id' => $horario_id,
				'puesto_id' => $puesto_id,
				'num_seguro' => $num_seguro,
				'num_plaza' => $num_plaza,
				'activo' => $activo
			));

			$insert_id = $this->db->insert_id();

			if (isset($insert_id)) {
				//redirect('empleados/'.$insert_id,'refresh');
				echo $insert_id;

			}

		}

	}
	public function edit($id){
		if ($this->uri->segment(3) != '') {
			$id = $this->uri->segment(3);

			$data['options'] = listData('adscripciones','id','adscripcion' ,'descripcion','ASC',' - ');
			$data['actualizar'] = $this->empleado_model->get_empleado_join($id);
			$this->load->model('puesto_model');
        	$this->load->model('horario_model');
			$data['horarios'] = $this->horario_model->as_dropdown('horario')->order_by('horario', 'ASC')->get_all();
			$data['puestos'] = $this->puesto_model->as_dropdown('puesto')->get_all();
			$this->load->view('empleados/form_update', $data);
		}

	}

	public function update() {

		$this->form_validation->set_rules('num_empleado', 'Numero de empleado', 'trim|required|numeric|min_length[5]|max_length[6]');
		$this->form_validation->set_rules('nombres', 'Nombre(s)', 'trim|required|min_length[4]|max_length[20]');
		$this->form_validation->set_rules('apellido_pat', 'Apellido Paterno', 'trim|required|min_length[4]|max_length[20]');
		$this->form_validation->set_rules('apellido_mat', 'Apellido Materno', 'trim|required|min_length[4]|max_length[20]');
		$this->form_validation->set_rules('adscripcion_id','Adscripcion', 'required|callback_require_dropdown');

		if($this->form_validation->run() == FALSE) {
			$data = array(
					'errors' => validation_errors()
				);
			$this->session->set_flashdata($data);
			echo '
Llene todos los campos correctamente
';

		}
		else {
			$id	   		    = $this->input->post('id');
			$num_empleado 	= $this->input->post('num_empleado');
			$num_seguro 	= $this->input->post('num_seguro');
			$num_plaza	 	= $this->input->post('num_plaza');
			$nombres 		= strtoupper($this->input->post('nombres'));
			$apellido_pat 	= strtoupper($this->input->post('apellido_pat'));
			$apellido_mat 	= strtoupper($this->input->post('apellido_mat'));
			$horario_id 	= $this->input->post('horario_id');
			$puesto_id 		= $this->input->post('puesto_id');
			$adscripcion_id = $this->input->post('adscripcion_id');
			$activo 		= $this->input->post('activo');

			$this->empleado_model->update(array(
				'num_empleado' => $num_empleado,
				'nombres' => $nombres,
				'apellido_pat' => $apellido_pat,
				'apellido_mat' => $apellido_mat,
				'adscripcion_id' => $adscripcion_id,
				'horario_id' => $horario_id,
				'puesto_id' => $puesto_id,
				'num_seguro' => $num_seguro,
				'num_plaza' => $num_plaza),
				$id
			);

			echo '
Adscripcion actualizada satisfactoriamente
';
		}

	}
	public function delete(){
		if ($this->uri->segment(3) != '') {
			$id = $this->uri->segment(3);
			$activate = $this->empleado_model->get_one($id);
		}
		$activo = ($activate->activo) ? FALSE : TRUE;

		$this->empleado_model->update(array(
					'activo' => $activo),
					$id
				);
		redirect('empleados/'.$id);

	}

	function require_dropdown($str) {
        if ($str == 0) {
            $this->form_validation->set_message('require_dropdown', 'Selecciona una adscripcion');
            return FALSE;
        } else {
            return TRUE;

        }
    }
    public function search(){
    	$data['user_id']    = $this->tank_auth->get_user_id();

        $username   = $this->tank_auth->get_username();
        $data['nombre_de_usuario'] = $this->empleado_model->getName($username);
        $data['is_admin']   = $this->tank_auth->is_admin();
    	$data['panelheading'] = "Empleados";

		$centros = explode(",",$this->tank_auth->get_user_centros());
       	$data['empleado'] = $this->empleado_model->get_search($centros);

		if (empty($data['empleado'])) {
			$data['noencontrado'] = "  Atencion!
Empleado no encontrado o no pertenece a su adscripcion
Informacion en Recursos Humanos";
			$data['empleado'] = NULL;
		}
		$data['options'] = listData('adscripciones','id','adscripcion' ,'descripcion','ASC',' - ');
		$data['index'] = "empleados/index";
		$this->load->view('layouts/index', $data);

	}
	public function agregar_pase(){
		$this->load->model('pase_model');

		$qna_id 	= $this->input->post('qna_id');
		$empleado_id 	= $this->input->post('empleado_id');
		$motivo 	= $this->input->post('motivo');
		$horario 	= $this->input->post('horario');
		$fecha_salida 	= fecha_ymd($this->input->post('fecha_salida'));

		$this->pase_model->insert(array(
				'qna_id' => $qna_id,
				'empleado_id' => $empleado_id,
				'motivo' => $motivo,
				'horario' => $horario,
				'fecha_salida' => $fecha_salida,

			));
		$data['pases'] = $this->pase_model->get_pases($empleado_id);
		$this->load->view('empleados/show_pases', $data);
	}
	public function delete_pase(){
		$this->load->model('pase_model');
		$id 	= $this->input->post('id');
		$empleado_id 	= $this->input->post('empleado_id');
		$this->pase_model->delete($id);
		$data['pases'] = $this->pase_model->get_pases($empleado_id);
		$this->load->view('empleados/show_pases', $data);

	}

}

/* End of file qnasController.php */
/* Location: ./application/controllers/qnasController.php */


text:
import {DirectiveOptions, PluginObject} from "vue"

type ElementDescriptor = Element | string

export interface ScrollOptions {
    el?: ElementDescriptor;
    element?: ElementDescriptor;
    container?: ElementDescriptor;
    duration?: number;
    easing?: string | [number, number, number, number];
    offset?: number | ((element: ElementDescriptor, container: ElementDescriptor) => number);
    force?: boolean;
    cancelable?: boolean;
    onStart?: ((element: Element) => any) | false;
    onDone?: ((element: Element) => any) | false;
    onCancel?: ((event: Event, element: Element) => any) | false;
    x?: boolean;
    y?: boolean;
}

type ScrollToFunction = {
    (options: ScrollOptions): () => void;
    (element: ElementDescriptor, options?: ScrollOptions): () => void;
    (element: ElementDescriptor, duration: number, options?: ScrollOptions): () => void;
}

declare const _default: PluginObject<ScrollOptions> &
    DirectiveOptions & {
    scrollTo: ScrollToFunction
    setDefaults: ScrollToFunction;
};

export default _default

declare module "vue/types/vue" {
    interface Vue {
        $scrollTo: ScrollToFunction
    }
}


text:
<?php

namespace Brunt\Reflection\CR\Cache;

use Brunt\Reflection\CR\CRField;
use Reflection;

class CacheCRField implements CRField
{

    /**
     * @var \ReflectionProperty
     */
    private $property;

    public function __construct($property)
    {
        $this->property = $property;
    }

    /**
     * @return string
     */
    public function getName():string
    {
        return $this->property['getName'];
    }

    /**
     * @return boolean
     */
    public function isPrivate()
    {
        return $this->property['isPrivate'];
    }

    /**
     * @return boolean
     */
    public function isPublic()
    {
        return $this->property['isPublic'];
    }

    /**
     * @return boolean
     */
    public function isProtected()
    {
        return $this->property['isProtected'];
    }

    /**
     * @return boolean
     */
    public function isStatic()
    {
        return $this->property['isStatic'];
    }

    /**
     * @return string[]
     */
    public function getModifiers():array
    {
        return $this->property['getModifiers'];
    }

    public function toArray()
    {
    return [
        'getModifiers' => $this->getModifiers(),
        'isStatic'=>$this->isStatic(),
        'isProtected'=>$this->isProtected(),
        'isPublic'=>$this->isPublic(),
        'isPrivate'=>$this->isPrivate(),
        'getName'=>$this->getName()
    ];
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sirococcus brasiliensis Speg.

### Remarks
null


text:
using System;
using System.Reflection.Emit;

public static partial class Extensions
{
    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at that array index, with restrictions on its use by other code
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type of elements in the array</param>
    public static ILGenerator LoadElementAddressReadonly(this ILGenerator il, Type type) => il.Ldelema_Readonly(type);

    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at the given index, with restrictions on its use by other code
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type of elements in the array</param>
    /// <param name="index">The index of the element to load the address of</param>
    public static ILGenerator LoadElementAddressReadonly(this ILGenerator il, Type type, uint index) => il.Ldelema_Readonly(type, index);

    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at that array index, with restrictions on its use by other code
    /// </summary>
    /// <typeparam name="T">The type of elements in the array</typeparam>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    public static ILGenerator LoadElementAddressReadonly<T>(this ILGenerator il) => il.Ldelema_Readonly<T>();

    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at the given index, with restrictions on its use by other code
    /// </summary>
    /// <typeparam name="T">The type of elements in the array</typeparam>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="index">The index of the element to load the address of</param>
    public static ILGenerator LoadElementAddressReadonly<T>(this ILGenerator il, uint index) => il.Ldelema_Readonly<T>(index);

#if Net45 || NetCore

    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at that array index, with restrictions on its use by other code
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type of elements in the array</param>
    public static ILGenerator LoadElementAddressReadonly(this ILGenerator il, System.Reflection.TypeInfo type) => il.Ldelema_Readonly(type);

    /// <summary>
    ///     Pops an array reference (containing elements of the given type) and an index off the evaluation stack and pushes
    ///     the address of the element at the given index, with restrictions on its use by other code
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type of elements in the array</param>
    /// <param name="index">The index of the element to load the address of</param>
    public static ILGenerator LoadElementAddressReadonly(this ILGenerator il, System.Reflection.TypeInfo type, uint index) => il.Ldelema_Readonly(type, index);

#endif
}


text:
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const index = require('./routes/index');
const users = require('./routes/users');
const shows = require('./routes/shows');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '2mb' }));
app.use(bodyParser.urlencoded({ limit: '2mb', extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './../client')));

app.use('/', index);
app.use('/api/v1/users', users);
app.use('/api/v1/shows', shows);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
#ifndef ANDROID_SERVERS_CAMERA_CAMERA2_FRAMEPROCESSOR_H
#define ANDROID_SERVERS_CAMERA_CAMERA2_FRAMEPROCESSOR_H

#include <utils/Thread.h>
#include <utils/String16.h>
#include <utils/Vector.h>
#include <utils/KeyedVector.h>
#include <utils/List.h>
#include <camera/CameraMetadata.h>

#include "common/FrameProcessorBase.h"

struct camera_frame_metadata;

namespace android {

class Camera2Client;

namespace camera2 {

/* Output frame metadata processing thread.  This thread waits for new
 * frames from the device, and analyzes them as necessary.
 */
class FrameProcessor : public FrameProcessorBase {
  public:
    FrameProcessor(wp<CameraDeviceBase> device, wp<Camera2Client> client);
    ~FrameProcessor();

  private:
    wp<Camera2Client> mClient;

    bool mSynthesize3ANotify;

    int mLastFrameNumberOfFaces;

    void processNewFrames(const sp<Camera2Client> &client);

    virtual bool processSingleFrame(CameraMetadata &frame,
                                    const sp<CameraDeviceBase> &device);

    status_t processFaceDetect(const CameraMetadata &frame,
            const sp<Camera2Client> &client);

    // Send 3A state change notifications to client based on frame metadata
    status_t process3aState(const CameraMetadata &frame,
            const sp<Camera2Client> &client);

    struct AlgState {
        camera_metadata_enum_android_control_ae_state  aeState;
        camera_metadata_enum_android_control_af_state  afState;
        camera_metadata_enum_android_control_awb_state awbState;

        AlgState() :
                aeState(ANDROID_CONTROL_AE_STATE_INACTIVE),
                afState(ANDROID_CONTROL_AF_STATE_INACTIVE),
                awbState(ANDROID_CONTROL_AWB_STATE_INACTIVE) {
        }
    } m3aState;

    // Emit FaceDetection event to java if faces changed
    void callbackFaceDetection(sp<Camera2Client> client,
                               const camera_frame_metadata &metadata);
};

}; //namespace camera2
}; //namespace android

#endif


text:
package org.mindtrails.domain.forms;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import lombok.Data;
import org.hibernate.validator.constraints.Email;
import org.mindtrails.domain.Participant;
import org.mindtrails.domain.forms.validation.HasPhone;
import org.mindtrails.domain.forms.validation.Phone;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * The very basic editable things for a participant to change about themselves.
 */
@Data
@Phone(message="Please enter a valid phone number.")
public class ParticipantUpdate implements HasPhone {

    @Size(min=2, max=100, message="Please provide a name of at least 3 characters.")
    protected String fullName;

    @Email
    @NotNull
    protected String email;

    protected String phone;
    protected String phoneLocale = "US";

    protected boolean emailReminders = true;
    protected boolean phoneReminders = true;
    protected boolean receiveGiftCards = false;
    protected boolean canTextMessage = true;

    protected String timezone;

    protected String theme;

    public void fromParticipant(Participant p) {
        this.email = p.getEmail();
        this.fullName = p.getFullName();
        this.emailReminders = p.isEmailReminders();
        this.phoneReminders = p.isPhoneReminders();
        this.receiveGiftCards = p.isReceiveGiftCards();
        this.theme = p.getTheme();
        this.phone = p.getPhone();
        this.timezone = p.getTimezone();
        this.canTextMessage = p.isCanTextMessage();
    }

    public Participant updateParticipant(Participant p) {
        p.setFullName(this.getFullName());
        p.setEmail(this.getEmail());
        p.setEmailReminders(this.isEmailReminders());
        p.setPhoneReminders(this.isPhoneReminders());
        p.setPhone(formatPhone(this.phone));
        p.setTimezone(this.getTimezone());
        p.setCanTextMessage(this.canTextMessage);
        if(this.theme != null) p.setTheme(this.getTheme());
        return p;
    }

    /**
     * Converts the provided phone number to the E164 standard used by
     * Twilio.
     * @return
     */
    public String formatPhone(String p) {
        if(p == null) return null;

        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            PhoneNumber phone = phoneUtil.parse(p, phoneLocale);
            return phoneUtil.format(phone, PhoneNumberUtil.PhoneNumberFormat.E164);
        } catch (NumberParseException e) {
            return p; // Leave it alone, let validation handle it.
        }
    }

}